backend.go 7.6 KB

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