backend.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. package azure
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/docker/api/context/cloud"
  10. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  11. "github.com/compose-spec/compose-go/types"
  12. "github.com/pkg/errors"
  13. "github.com/sirupsen/logrus"
  14. "github.com/docker/api/azure/convert"
  15. "github.com/docker/api/azure/login"
  16. "github.com/docker/api/backend"
  17. "github.com/docker/api/compose"
  18. "github.com/docker/api/containers"
  19. apicontext "github.com/docker/api/context"
  20. "github.com/docker/api/context/store"
  21. )
  22. const singleContainerName = "single--container--aci"
  23. // ErrNoSuchContainer is returned when the mentioned container does not exist
  24. var ErrNoSuchContainer = errors.New("no such container")
  25. func init() {
  26. backend.Register("aci", "aci", func(ctx context.Context) (backend.Service, error) {
  27. return New(ctx)
  28. })
  29. }
  30. func getter() interface{} {
  31. return &store.AciContext{}
  32. }
  33. // New creates a backend that can manage containers
  34. func New(ctx context.Context) (backend.Service, error) {
  35. currentContext := apicontext.CurrentContext(ctx)
  36. contextStore, err := store.New()
  37. if err != nil {
  38. return nil, err
  39. }
  40. metadata, err := contextStore.Get(currentContext, getter)
  41. if err != nil {
  42. return nil, errors.Wrap(err, "wrong context type")
  43. }
  44. aciContext, _ := metadata.Metadata.Data.(store.AciContext)
  45. auth, _ := login.NewAzureLoginService().NewAuthorizerFromLogin()
  46. containerGroupsClient := containerinstance.NewContainerGroupsClient(aciContext.SubscriptionID)
  47. containerGroupsClient.Authorizer = auth
  48. return getAciAPIService(containerGroupsClient, aciContext), nil
  49. }
  50. func getAciAPIService(cgc containerinstance.ContainerGroupsClient, aciCtx store.AciContext) *aciAPIService {
  51. return &aciAPIService{
  52. aciContainerService: aciContainerService{
  53. containerGroupsClient: cgc,
  54. ctx: aciCtx,
  55. },
  56. aciComposeService: aciComposeService{
  57. ctx: aciCtx,
  58. },
  59. aciCloudService: aciCloudService{
  60. loginService: login.NewAzureLoginService(),
  61. },
  62. }
  63. }
  64. type aciAPIService struct {
  65. aciContainerService
  66. aciComposeService
  67. aciCloudService
  68. }
  69. func (a *aciAPIService) ContainerService() containers.Service {
  70. return &a.aciContainerService
  71. }
  72. func (a *aciAPIService) ComposeService() compose.Service {
  73. return &a.aciComposeService
  74. }
  75. func (a *aciAPIService) CloudService() cloud.Service {
  76. return &a.aciCloudService
  77. }
  78. type aciContainerService struct {
  79. containerGroupsClient containerinstance.ContainerGroupsClient
  80. ctx store.AciContext
  81. }
  82. func (cs *aciContainerService) List(ctx context.Context) ([]containers.Container, error) {
  83. var containerGroups []containerinstance.ContainerGroup
  84. result, err := cs.containerGroupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
  85. if err != nil {
  86. return []containers.Container{}, err
  87. }
  88. for result.NotDone() {
  89. containerGroups = append(containerGroups, result.Values()...)
  90. if err := result.NextWithContext(ctx); err != nil {
  91. return []containers.Container{}, err
  92. }
  93. }
  94. var res []containers.Container
  95. for _, containerGroup := range containerGroups {
  96. group, err := cs.containerGroupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
  97. if err != nil {
  98. return []containers.Container{}, err
  99. }
  100. for _, container := range *group.Containers {
  101. var containerID string
  102. if *container.Name == singleContainerName {
  103. containerID = *containerGroup.Name
  104. } else {
  105. containerID = *containerGroup.Name + "_" + *container.Name
  106. }
  107. status := "Unknown"
  108. if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
  109. status = *container.InstanceView.CurrentState.State
  110. }
  111. res = append(res, containers.Container{
  112. ID: containerID,
  113. Image: *container.Image,
  114. Status: status,
  115. })
  116. }
  117. }
  118. return res, nil
  119. }
  120. func (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  121. var ports []types.ServicePortConfig
  122. for _, p := range r.Ports {
  123. ports = append(ports, types.ServicePortConfig{
  124. Target: p.Destination,
  125. Published: p.Source,
  126. })
  127. }
  128. project := compose.Project{
  129. Name: r.ID,
  130. Config: types.Config{
  131. Services: []types.ServiceConfig{
  132. {
  133. Name: singleContainerName,
  134. Image: r.Image,
  135. Ports: ports,
  136. },
  137. },
  138. },
  139. }
  140. logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
  141. groupDefinition, err := convert.ToContainerGroup(cs.ctx, project)
  142. if err != nil {
  143. return err
  144. }
  145. return createACIContainers(ctx, cs.ctx, groupDefinition)
  146. }
  147. func getGrouNameContainername(containerID string) (groupName string, containerName string) {
  148. tokens := strings.Split(containerID, "_")
  149. groupName = tokens[0]
  150. if len(tokens) > 1 {
  151. containerName = tokens[len(tokens)-1]
  152. groupName = containerID[:len(containerID)-(len(containerName)+1)]
  153. } else {
  154. containerName = singleContainerName
  155. }
  156. return groupName, containerName
  157. }
  158. func (cs *aciContainerService) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {
  159. groupName, containerAciName := getGrouNameContainername(name)
  160. containerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)
  161. if err != nil {
  162. return err
  163. }
  164. return exec(
  165. context.Background(),
  166. *containerExecResponse.WebSocketURI,
  167. *containerExecResponse.Password,
  168. reader,
  169. writer,
  170. )
  171. }
  172. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  173. groupName, containerAciName := getGrouNameContainername(containerName)
  174. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName)
  175. if err != nil {
  176. return err
  177. }
  178. if req.Tail != "all" {
  179. tail, err := strconv.Atoi(req.Tail)
  180. if err != nil {
  181. return err
  182. }
  183. lines := strings.Split(logs, "\n")
  184. // If asked for less lines than exist, take only those lines
  185. if tail <= len(lines) {
  186. logs = strings.Join(lines[len(lines)-tail:], "\n")
  187. }
  188. }
  189. _, err = fmt.Fprint(req.Writer, logs)
  190. return err
  191. }
  192. func (cs *aciContainerService) Delete(ctx context.Context, containerID string, _ bool) error {
  193. cg, err := deleteACIContainerGroup(ctx, cs.ctx, containerID)
  194. if err != nil {
  195. return err
  196. }
  197. if cg.StatusCode == http.StatusNoContent {
  198. return ErrNoSuchContainer
  199. }
  200. return err
  201. }
  202. type aciComposeService struct {
  203. ctx store.AciContext
  204. }
  205. func (cs *aciComposeService) Up(ctx context.Context, opts compose.ProjectOptions) error {
  206. project, err := compose.ProjectFromOptions(&opts)
  207. if err != nil {
  208. return err
  209. }
  210. logrus.Debugf("Up on project with name %q\n", project.Name)
  211. groupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)
  212. if err != nil {
  213. return err
  214. }
  215. return createACIContainers(ctx, cs.ctx, groupDefinition)
  216. }
  217. func (cs *aciComposeService) Down(ctx context.Context, opts compose.ProjectOptions) error {
  218. project, err := compose.ProjectFromOptions(&opts)
  219. if err != nil {
  220. return err
  221. }
  222. logrus.Debugf("Down on project with name %q\n", project.Name)
  223. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  224. if err != nil {
  225. return err
  226. }
  227. if cg.StatusCode == http.StatusNoContent {
  228. return ErrNoSuchContainer
  229. }
  230. return err
  231. }
  232. type aciCloudService struct {
  233. loginService login.AzureLoginService
  234. }
  235. func (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {
  236. return cs.loginService.Login(ctx)
  237. }