1
0

backend.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package azure
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "net/http"
  19. "strconv"
  20. "strings"
  21. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  22. "github.com/Azure/go-autorest/autorest/to"
  23. "github.com/compose-spec/compose-go/cli"
  24. "github.com/compose-spec/compose-go/types"
  25. "github.com/pkg/errors"
  26. "github.com/sirupsen/logrus"
  27. "github.com/docker/api/azure/convert"
  28. "github.com/docker/api/azure/login"
  29. "github.com/docker/api/backend"
  30. "github.com/docker/api/compose"
  31. "github.com/docker/api/containers"
  32. apicontext "github.com/docker/api/context"
  33. "github.com/docker/api/context/cloud"
  34. "github.com/docker/api/context/store"
  35. "github.com/docker/api/errdefs"
  36. )
  37. const (
  38. singleContainerName = "single--container--aci"
  39. composeContainerSeparator = "_"
  40. )
  41. // ErrNoSuchContainer is returned when the mentioned container does not exist
  42. var ErrNoSuchContainer = errors.New("no such container")
  43. func init() {
  44. backend.Register("aci", "aci", service, getCloudService)
  45. }
  46. func service(ctx context.Context) (backend.Service, error) {
  47. contextStore := store.ContextStore(ctx)
  48. currentContext := apicontext.CurrentContext(ctx)
  49. var aciContext store.AciContext
  50. if err := contextStore.GetEndpoint(currentContext, &aciContext); err != nil {
  51. return nil, err
  52. }
  53. return getAciAPIService(aciContext), nil
  54. }
  55. func getCloudService() (cloud.Service, error) {
  56. service, err := login.NewAzureLoginService()
  57. if err != nil {
  58. return nil, err
  59. }
  60. return &aciCloudService{
  61. loginService: service,
  62. }, nil
  63. }
  64. func getAciAPIService(aciCtx store.AciContext) *aciAPIService {
  65. return &aciAPIService{
  66. aciContainerService: &aciContainerService{
  67. ctx: aciCtx,
  68. },
  69. aciComposeService: &aciComposeService{
  70. ctx: aciCtx,
  71. },
  72. }
  73. }
  74. type aciAPIService struct {
  75. *aciContainerService
  76. *aciComposeService
  77. }
  78. func (a *aciAPIService) ContainerService() containers.Service {
  79. return a.aciContainerService
  80. }
  81. func (a *aciAPIService) ComposeService() compose.Service {
  82. return a.aciComposeService
  83. }
  84. type aciContainerService struct {
  85. ctx store.AciContext
  86. }
  87. func (cs *aciContainerService) List(ctx context.Context, _ bool) ([]containers.Container, error) {
  88. groupsClient, err := getContainerGroupsClient(cs.ctx.SubscriptionID)
  89. if err != nil {
  90. return nil, err
  91. }
  92. var containerGroups []containerinstance.ContainerGroup
  93. result, err := groupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
  94. if err != nil {
  95. return []containers.Container{}, err
  96. }
  97. for result.NotDone() {
  98. containerGroups = append(containerGroups, result.Values()...)
  99. if err := result.NextWithContext(ctx); err != nil {
  100. return []containers.Container{}, err
  101. }
  102. }
  103. var res []containers.Container
  104. for _, containerGroup := range containerGroups {
  105. group, err := groupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
  106. if err != nil {
  107. return []containers.Container{}, err
  108. }
  109. for _, container := range *group.Containers {
  110. var containerID string
  111. // don't list sidecar container
  112. if *container.Name == convert.ComposeDNSSidecarName {
  113. continue
  114. }
  115. if *container.Name == singleContainerName {
  116. containerID = *containerGroup.Name
  117. } else {
  118. containerID = *containerGroup.Name + composeContainerSeparator + *container.Name
  119. }
  120. status := "Unknown"
  121. if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
  122. status = *container.InstanceView.CurrentState.State
  123. }
  124. res = append(res, containers.Container{
  125. ID: containerID,
  126. Image: *container.Image,
  127. Status: status,
  128. Ports: convert.ToPorts(group.IPAddress, *container.Ports),
  129. })
  130. }
  131. }
  132. return res, nil
  133. }
  134. func (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  135. if strings.Contains(r.ID, composeContainerSeparator) {
  136. return errors.New(fmt.Sprintf("invalid container name. ACI container name cannot include %q", composeContainerSeparator))
  137. }
  138. project, err := convert.ContainerToComposeProject(r, singleContainerName)
  139. if err != nil {
  140. return err
  141. }
  142. logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
  143. groupDefinition, err := convert.ToContainerGroup(cs.ctx, project)
  144. if err != nil {
  145. return err
  146. }
  147. return createACIContainers(ctx, cs.ctx, groupDefinition)
  148. }
  149. func (cs *aciContainerService) Stop(ctx context.Context, containerName string, timeout *uint32) error {
  150. return errdefs.ErrNotImplemented
  151. }
  152. func getGroupAndContainerName(containerID string) (groupName string, containerName string) {
  153. tokens := strings.Split(containerID, composeContainerSeparator)
  154. groupName = tokens[0]
  155. if len(tokens) > 1 {
  156. containerName = tokens[len(tokens)-1]
  157. groupName = containerID[:len(containerID)-(len(containerName)+1)]
  158. } else {
  159. containerName = singleContainerName
  160. }
  161. return groupName, containerName
  162. }
  163. func (cs *aciContainerService) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {
  164. groupName, containerAciName := getGroupAndContainerName(name)
  165. containerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)
  166. if err != nil {
  167. return err
  168. }
  169. return exec(
  170. context.Background(),
  171. *containerExecResponse.WebSocketURI,
  172. *containerExecResponse.Password,
  173. reader,
  174. writer,
  175. )
  176. }
  177. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  178. groupName, containerAciName := getGroupAndContainerName(containerName)
  179. var tail *int32
  180. if req.Follow {
  181. return streamLogs(ctx, cs.ctx, groupName, containerAciName, req.Writer)
  182. }
  183. if req.Tail != "all" {
  184. reqTail, err := strconv.Atoi(req.Tail)
  185. if err != nil {
  186. return err
  187. }
  188. i32 := int32(reqTail)
  189. tail = &i32
  190. }
  191. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName, tail)
  192. if err != nil {
  193. return err
  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. groupName, containerName := getGroupAndContainerName(containerID)
  200. if groupName != containerID {
  201. msg := "cannot delete service %q from compose application %q, you can delete the entire compose app with docker compose down --project-name %s"
  202. return errors.New(fmt.Sprintf(msg, containerName, groupName, groupName))
  203. }
  204. cg, err := deleteACIContainerGroup(ctx, cs.ctx, groupName)
  205. if err != nil {
  206. return err
  207. }
  208. if cg.StatusCode == http.StatusNoContent {
  209. return ErrNoSuchContainer
  210. }
  211. return err
  212. }
  213. func (cs *aciContainerService) Inspect(ctx context.Context, containerID string) (containers.Container, error) {
  214. groupName, containerName := getGroupAndContainerName(containerID)
  215. cg, err := getACIContainerGroup(ctx, cs.ctx, groupName)
  216. if err != nil {
  217. return containers.Container{}, err
  218. }
  219. if cg.StatusCode == http.StatusNoContent {
  220. return containers.Container{}, ErrNoSuchContainer
  221. }
  222. var cc containerinstance.Container
  223. var found = false
  224. for _, c := range *cg.Containers {
  225. if to.String(c.Name) == containerName {
  226. cc = c
  227. found = true
  228. break
  229. }
  230. }
  231. if !found {
  232. return containers.Container{}, ErrNoSuchContainer
  233. }
  234. return convert.ContainerGroupToContainer(containerID, cg, cc)
  235. }
  236. type aciComposeService struct {
  237. ctx store.AciContext
  238. }
  239. func (cs *aciComposeService) Up(ctx context.Context, opts cli.ProjectOptions) error {
  240. project, err := cli.ProjectFromOptions(&opts)
  241. if err != nil {
  242. return err
  243. }
  244. logrus.Debugf("Up on project with name %q\n", project.Name)
  245. groupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)
  246. if err != nil {
  247. return err
  248. }
  249. return createOrUpdateACIContainers(ctx, cs.ctx, groupDefinition)
  250. }
  251. func (cs *aciComposeService) Down(ctx context.Context, opts cli.ProjectOptions) error {
  252. var project types.Project
  253. if opts.Name != "" {
  254. project = types.Project{Name: opts.Name}
  255. } else {
  256. fullProject, err := cli.ProjectFromOptions(&opts)
  257. if err != nil {
  258. return err
  259. }
  260. project = *fullProject
  261. }
  262. logrus.Debugf("Down on project with name %q\n", project.Name)
  263. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  264. if err != nil {
  265. return err
  266. }
  267. if cg.StatusCode == http.StatusNoContent {
  268. return ErrNoSuchContainer
  269. }
  270. return err
  271. }
  272. type aciCloudService struct {
  273. loginService login.AzureLoginService
  274. }
  275. func (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {
  276. return cs.loginService.Login(ctx, params[login.TenantIDLoginParam])
  277. }
  278. func (cs *aciCloudService) CreateContextData(ctx context.Context, params map[string]string) (interface{}, string, error) {
  279. contextHelper := newContextCreateHelper()
  280. return contextHelper.createContextData(ctx, params)
  281. }