backend.go 7.5 KB

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