backend.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package azure
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/docker/api/context/cloud"
  6. "io"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  11. "github.com/Azure/go-autorest/autorest/azure/auth"
  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, _ := auth.NewAuthorizerFromCLI()
  47. containerGroupsClient := containerinstance.NewContainerGroupsClient(aciContext.SubscriptionID)
  48. containerGroupsClient.Authorizer = auth
  49. return getAciAPIService(containerGroupsClient, aciContext), nil
  50. }
  51. func getAciAPIService(cgc containerinstance.ContainerGroupsClient, aciCtx store.AciContext) *aciAPIService {
  52. return &aciAPIService{
  53. aciContainerService: aciContainerService{
  54. containerGroupsClient: cgc,
  55. ctx: aciCtx,
  56. },
  57. aciComposeService: aciComposeService{
  58. containerGroupsClient: cgc,
  59. ctx: aciCtx,
  60. },
  61. aciCloudService: aciCloudService{},
  62. }
  63. }
  64. type aciAPIService struct {
  65. aciContainerService
  66. aciComposeService
  67. aciCloudService
  68. }
  69. func (a *aciAPIService) ContainerService() containers.Service {
  70. return &aciContainerService{
  71. containerGroupsClient: a.aciContainerService.containerGroupsClient,
  72. ctx: a.aciContainerService.ctx,
  73. }
  74. }
  75. func (a *aciAPIService) ComposeService() compose.Service {
  76. return &aciComposeService{
  77. containerGroupsClient: a.aciComposeService.containerGroupsClient,
  78. ctx: a.aciComposeService.ctx,
  79. }
  80. }
  81. func (a *aciAPIService) CloudService() cloud.Service {
  82. return &aciCloudService{}
  83. }
  84. type aciContainerService struct {
  85. containerGroupsClient containerinstance.ContainerGroupsClient
  86. ctx store.AciContext
  87. }
  88. func (cs *aciContainerService) List(ctx context.Context) ([]containers.Container, error) {
  89. var containerGroups []containerinstance.ContainerGroup
  90. result, err := cs.containerGroupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
  91. if err != nil {
  92. return []containers.Container{}, err
  93. }
  94. for result.NotDone() {
  95. containerGroups = append(containerGroups, result.Values()...)
  96. if err := result.NextWithContext(ctx); err != nil {
  97. return []containers.Container{}, err
  98. }
  99. }
  100. var res []containers.Container
  101. for _, containerGroup := range containerGroups {
  102. group, err := cs.containerGroupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
  103. if err != nil {
  104. return []containers.Container{}, err
  105. }
  106. for _, container := range *group.Containers {
  107. var containerID string
  108. if *container.Name == singleContainerName {
  109. containerID = *containerGroup.Name
  110. } else {
  111. containerID = *containerGroup.Name + "_" + *container.Name
  112. }
  113. status := "Unknown"
  114. if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
  115. status = *container.InstanceView.CurrentState.State
  116. }
  117. res = append(res, containers.Container{
  118. ID: containerID,
  119. Image: *container.Image,
  120. Status: status,
  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.Destination,
  131. Published: p.Source,
  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. },
  143. },
  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 getGrouNameContainername(containerID string) (groupName string, containerName string) {
  154. tokens := strings.Split(containerID, "_")
  155. groupName = tokens[0]
  156. if len(tokens) > 1 {
  157. containerName = tokens[len(tokens)-1]
  158. groupName = containerID[:len(containerID)-(len(containerName)+1)]
  159. } else {
  160. containerName = singleContainerName
  161. }
  162. return groupName, containerName
  163. }
  164. func (cs *aciContainerService) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {
  165. groupName, containerAciName := getGrouNameContainername(name)
  166. containerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)
  167. if err != nil {
  168. return err
  169. }
  170. return exec(
  171. context.Background(),
  172. *containerExecResponse.WebSocketURI,
  173. *containerExecResponse.Password,
  174. reader,
  175. writer,
  176. )
  177. }
  178. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  179. groupName, containerAciName := getGrouNameContainername(containerName)
  180. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName)
  181. if err != nil {
  182. return err
  183. }
  184. if req.Tail != "all" {
  185. tail, err := strconv.Atoi(req.Tail)
  186. if err != nil {
  187. return err
  188. }
  189. lines := strings.Split(logs, "\n")
  190. // If asked for less lines than exist, take only those lines
  191. if tail <= len(lines) {
  192. logs = strings.Join(lines[len(lines)-tail:], "\n")
  193. }
  194. }
  195. _, err = fmt.Fprint(req.Writer, logs)
  196. return err
  197. }
  198. func (cs *aciContainerService) Delete(ctx context.Context, containerID string, _ bool) error {
  199. cg, err := deleteACIContainerGroup(ctx, cs.ctx, containerID)
  200. if err != nil {
  201. return err
  202. }
  203. if cg.StatusCode == http.StatusNoContent {
  204. return ErrNoSuchContainer
  205. }
  206. return err
  207. }
  208. type aciComposeService struct {
  209. containerGroupsClient containerinstance.ContainerGroupsClient
  210. ctx store.AciContext
  211. }
  212. func (cs *aciComposeService) Up(ctx context.Context, opts compose.ProjectOptions) error {
  213. project, err := compose.ProjectFromOptions(&opts)
  214. if err != nil {
  215. return err
  216. }
  217. logrus.Debugf("Up on project with name %q\n", project.Name)
  218. groupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)
  219. if err != nil {
  220. return err
  221. }
  222. return createACIContainers(ctx, cs.ctx, groupDefinition)
  223. }
  224. func (cs *aciComposeService) Down(ctx context.Context, opts compose.ProjectOptions) error {
  225. project, err := compose.ProjectFromOptions(&opts)
  226. if err != nil {
  227. return err
  228. }
  229. logrus.Debugf("Down on project with name %q\n", project.Name)
  230. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  231. if err != nil {
  232. return err
  233. }
  234. if cg.StatusCode == http.StatusNoContent {
  235. return ErrNoSuchContainer
  236. }
  237. return err
  238. }
  239. type aciCloudService struct {
  240. }
  241. func (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {
  242. return login.Login()
  243. }