backend.go 7.1 KB

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