backend.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. err := verifyExecCommand(command)
  165. if err != nil {
  166. return err
  167. }
  168. groupName, containerAciName := getGroupAndContainerName(name)
  169. containerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)
  170. if err != nil {
  171. return err
  172. }
  173. return exec(
  174. context.Background(),
  175. *containerExecResponse.WebSocketURI,
  176. *containerExecResponse.Password,
  177. reader,
  178. writer,
  179. )
  180. }
  181. func verifyExecCommand(command string) error {
  182. tokens := strings.Split(command, " ")
  183. if len(tokens) > 1 {
  184. return errors.New("ACI exec command does not accept arguments to the command. " +
  185. "Only the binary should be specified")
  186. }
  187. return nil
  188. }
  189. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  190. groupName, containerAciName := getGroupAndContainerName(containerName)
  191. var tail *int32
  192. if req.Follow {
  193. return streamLogs(ctx, cs.ctx, groupName, containerAciName, req.Writer)
  194. }
  195. if req.Tail != "all" {
  196. reqTail, err := strconv.Atoi(req.Tail)
  197. if err != nil {
  198. return err
  199. }
  200. i32 := int32(reqTail)
  201. tail = &i32
  202. }
  203. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName, tail)
  204. if err != nil {
  205. return err
  206. }
  207. _, err = fmt.Fprint(req.Writer, logs)
  208. return err
  209. }
  210. func (cs *aciContainerService) Delete(ctx context.Context, containerID string, _ bool) error {
  211. groupName, containerName := getGroupAndContainerName(containerID)
  212. if groupName != containerID {
  213. msg := "cannot delete service %q from compose application %q, you can delete the entire compose app with docker compose down --project-name %s"
  214. return errors.New(fmt.Sprintf(msg, containerName, groupName, groupName))
  215. }
  216. cg, err := deleteACIContainerGroup(ctx, cs.ctx, groupName)
  217. if err != nil {
  218. return err
  219. }
  220. if cg.StatusCode == http.StatusNoContent {
  221. return ErrNoSuchContainer
  222. }
  223. return err
  224. }
  225. func (cs *aciContainerService) Inspect(ctx context.Context, containerID string) (containers.Container, error) {
  226. groupName, containerName := getGroupAndContainerName(containerID)
  227. cg, err := getACIContainerGroup(ctx, cs.ctx, groupName)
  228. if err != nil {
  229. return containers.Container{}, err
  230. }
  231. if cg.StatusCode == http.StatusNoContent {
  232. return containers.Container{}, ErrNoSuchContainer
  233. }
  234. var cc containerinstance.Container
  235. var found = false
  236. for _, c := range *cg.Containers {
  237. if to.String(c.Name) == containerName {
  238. cc = c
  239. found = true
  240. break
  241. }
  242. }
  243. if !found {
  244. return containers.Container{}, ErrNoSuchContainer
  245. }
  246. return convert.ContainerGroupToContainer(containerID, cg, cc)
  247. }
  248. type aciComposeService struct {
  249. ctx store.AciContext
  250. }
  251. func (cs *aciComposeService) Up(ctx context.Context, opts cli.ProjectOptions) error {
  252. project, err := cli.ProjectFromOptions(&opts)
  253. if err != nil {
  254. return err
  255. }
  256. logrus.Debugf("Up on project with name %q\n", project.Name)
  257. groupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)
  258. if err != nil {
  259. return err
  260. }
  261. return createOrUpdateACIContainers(ctx, cs.ctx, groupDefinition)
  262. }
  263. func (cs *aciComposeService) Down(ctx context.Context, opts cli.ProjectOptions) error {
  264. var project types.Project
  265. if opts.Name != "" {
  266. project = types.Project{Name: opts.Name}
  267. } else {
  268. fullProject, err := cli.ProjectFromOptions(&opts)
  269. if err != nil {
  270. return err
  271. }
  272. project = *fullProject
  273. }
  274. logrus.Debugf("Down on project with name %q\n", project.Name)
  275. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  276. if err != nil {
  277. return err
  278. }
  279. if cg.StatusCode == http.StatusNoContent {
  280. return ErrNoSuchContainer
  281. }
  282. return err
  283. }
  284. type aciCloudService struct {
  285. loginService login.AzureLoginService
  286. }
  287. func (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {
  288. return cs.loginService.Login(ctx, params[login.TenantIDLoginParam])
  289. }
  290. func (cs *aciCloudService) CreateContextData(ctx context.Context, params map[string]string) (interface{}, string, error) {
  291. contextHelper := newContextCreateHelper()
  292. return contextHelper.createContextData(ctx, params)
  293. }