backend.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. projectVolumes, serviceConfigVolumes, err := convert.GetRunVolumes(r.Volumes)
  135. if err != nil {
  136. return err
  137. }
  138. project := compose.Project{
  139. Name: r.ID,
  140. Config: types.Config{
  141. Services: []types.ServiceConfig{
  142. {
  143. Name: singleContainerName,
  144. Image: r.Image,
  145. Ports: ports,
  146. Labels: r.Labels,
  147. Volumes: serviceConfigVolumes,
  148. },
  149. },
  150. Volumes: projectVolumes,
  151. },
  152. }
  153. logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
  154. groupDefinition, err := convert.ToContainerGroup(cs.ctx, project)
  155. if err != nil {
  156. return err
  157. }
  158. return createACIContainers(ctx, cs.ctx, groupDefinition)
  159. }
  160. func (cs *aciContainerService) Stop(ctx context.Context, containerName string, timeout *uint32) error {
  161. return errdefs.ErrNotImplemented
  162. }
  163. func getGroupAndContainerName(containerID string) (groupName string, containerName string) {
  164. tokens := strings.Split(containerID, "_")
  165. groupName = tokens[0]
  166. if len(tokens) > 1 {
  167. containerName = tokens[len(tokens)-1]
  168. groupName = containerID[:len(containerID)-(len(containerName)+1)]
  169. } else {
  170. containerName = singleContainerName
  171. }
  172. return groupName, containerName
  173. }
  174. func (cs *aciContainerService) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {
  175. groupName, containerAciName := getGroupAndContainerName(name)
  176. containerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)
  177. if err != nil {
  178. return err
  179. }
  180. return exec(
  181. context.Background(),
  182. *containerExecResponse.WebSocketURI,
  183. *containerExecResponse.Password,
  184. reader,
  185. writer,
  186. )
  187. }
  188. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  189. groupName, containerAciName := getGroupAndContainerName(containerName)
  190. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName)
  191. if err != nil {
  192. return err
  193. }
  194. if req.Tail != "all" {
  195. tail, err := strconv.Atoi(req.Tail)
  196. if err != nil {
  197. return err
  198. }
  199. lines := strings.Split(logs, "\n")
  200. // If asked for less lines than exist, take only those lines
  201. if tail <= len(lines) {
  202. logs = strings.Join(lines[len(lines)-tail:], "\n")
  203. }
  204. }
  205. _, err = fmt.Fprint(req.Writer, logs)
  206. return err
  207. }
  208. func (cs *aciContainerService) Delete(ctx context.Context, containerID string, _ bool) error {
  209. cg, err := deleteACIContainerGroup(ctx, cs.ctx, containerID)
  210. if err != nil {
  211. return err
  212. }
  213. if cg.StatusCode == http.StatusNoContent {
  214. return ErrNoSuchContainer
  215. }
  216. return err
  217. }
  218. type aciComposeService struct {
  219. ctx store.AciContext
  220. }
  221. func (cs *aciComposeService) Up(ctx context.Context, opts compose.ProjectOptions) error {
  222. project, err := compose.ProjectFromOptions(&opts)
  223. if err != nil {
  224. return err
  225. }
  226. logrus.Debugf("Up on project with name %q\n", project.Name)
  227. groupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)
  228. if err != nil {
  229. return err
  230. }
  231. return createACIContainers(ctx, cs.ctx, groupDefinition)
  232. }
  233. func (cs *aciComposeService) Down(ctx context.Context, opts compose.ProjectOptions) error {
  234. project, err := compose.ProjectFromOptions(&opts)
  235. if err != nil {
  236. return err
  237. }
  238. logrus.Debugf("Down on project with name %q\n", project.Name)
  239. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  240. if err != nil {
  241. return err
  242. }
  243. if cg.StatusCode == http.StatusNoContent {
  244. return ErrNoSuchContainer
  245. }
  246. return err
  247. }
  248. type aciCloudService struct {
  249. loginService login.AzureLoginService
  250. }
  251. func (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {
  252. return cs.loginService.Login(ctx)
  253. }