backend.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 aci
  14. import (
  15. "context"
  16. "fmt"
  17. "net/http"
  18. "strconv"
  19. "strings"
  20. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  21. "github.com/Azure/go-autorest/autorest"
  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. ecstypes "github.com/docker/ecs-plugin/pkg/compose"
  28. "github.com/docker/api/aci/convert"
  29. "github.com/docker/api/aci/login"
  30. "github.com/docker/api/backend"
  31. "github.com/docker/api/compose"
  32. "github.com/docker/api/containers"
  33. apicontext "github.com/docker/api/context"
  34. "github.com/docker/api/context/cloud"
  35. "github.com/docker/api/context/store"
  36. "github.com/docker/api/errdefs"
  37. )
  38. const (
  39. backendType = store.AciContextType
  40. singleContainerTag = "docker-single-container"
  41. composeContainerTag = "docker-compose-application"
  42. composeContainerSeparator = "_"
  43. statusUnknown = "Unknown"
  44. statusRunning = "Running"
  45. )
  46. // ContextParams options for creating ACI context
  47. type ContextParams struct {
  48. Description string
  49. Location string
  50. SubscriptionID string
  51. ResourceGroup string
  52. }
  53. // LoginParams azure login options
  54. type LoginParams struct {
  55. TenantID string
  56. ClientID string
  57. ClientSecret string
  58. }
  59. // Validate returns an error if options are not used properly
  60. func (opts LoginParams) Validate() error {
  61. if opts.ClientID != "" || opts.ClientSecret != "" {
  62. if opts.ClientID == "" || opts.ClientSecret == "" || opts.TenantID == "" {
  63. return errors.New("for Service Principal login, 3 options must be specified: --client-id, --client-secret and --tenant-id")
  64. }
  65. }
  66. return nil
  67. }
  68. func init() {
  69. backend.Register(backendType, backendType, service, getCloudService)
  70. }
  71. func service(ctx context.Context) (backend.Service, error) {
  72. contextStore := store.ContextStore(ctx)
  73. currentContext := apicontext.CurrentContext(ctx)
  74. var aciContext store.AciContext
  75. if err := contextStore.GetEndpoint(currentContext, &aciContext); err != nil {
  76. return nil, err
  77. }
  78. return getAciAPIService(aciContext), nil
  79. }
  80. func getCloudService() (cloud.Service, error) {
  81. service, err := login.NewAzureLoginService()
  82. if err != nil {
  83. return nil, err
  84. }
  85. return &aciCloudService{
  86. loginService: service,
  87. }, nil
  88. }
  89. func getAciAPIService(aciCtx store.AciContext) *aciAPIService {
  90. return &aciAPIService{
  91. aciContainerService: &aciContainerService{
  92. ctx: aciCtx,
  93. },
  94. aciComposeService: &aciComposeService{
  95. ctx: aciCtx,
  96. },
  97. }
  98. }
  99. type aciAPIService struct {
  100. *aciContainerService
  101. *aciComposeService
  102. }
  103. func (a *aciAPIService) ContainerService() containers.Service {
  104. return a.aciContainerService
  105. }
  106. func (a *aciAPIService) ComposeService() compose.Service {
  107. return a.aciComposeService
  108. }
  109. type aciContainerService struct {
  110. ctx store.AciContext
  111. }
  112. func (cs *aciContainerService) List(ctx context.Context, all bool) ([]containers.Container, error) {
  113. groupsClient, err := login.NewContainerGroupsClient(cs.ctx.SubscriptionID)
  114. if err != nil {
  115. return nil, err
  116. }
  117. var containerGroups []containerinstance.ContainerGroup
  118. result, err := groupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
  119. if err != nil {
  120. return []containers.Container{}, err
  121. }
  122. for result.NotDone() {
  123. containerGroups = append(containerGroups, result.Values()...)
  124. if err := result.NextWithContext(ctx); err != nil {
  125. return []containers.Container{}, err
  126. }
  127. }
  128. var res []containers.Container
  129. for _, containerGroup := range containerGroups {
  130. group, err := groupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
  131. if err != nil {
  132. return []containers.Container{}, err
  133. }
  134. if group.Containers == nil || len(*group.Containers) < 1 {
  135. return []containers.Container{}, fmt.Errorf("no containers found in ACI container group %s", *containerGroup.Name)
  136. }
  137. for _, container := range *group.Containers {
  138. // don't list sidecar container
  139. if *container.Name == convert.ComposeDNSSidecarName {
  140. continue
  141. }
  142. if !all && getStatus(container) != statusRunning {
  143. continue
  144. }
  145. containerID := *containerGroup.Name + composeContainerSeparator + *container.Name
  146. if _, ok := group.Tags[singleContainerTag]; ok {
  147. containerID = *containerGroup.Name
  148. }
  149. c := getContainer(containerID, group.IPAddress, container)
  150. res = append(res, c)
  151. }
  152. }
  153. return res, nil
  154. }
  155. func getContainer(containerID string, ipAddress *containerinstance.IPAddress, container containerinstance.Container) containers.Container {
  156. status := getStatus(container)
  157. return containers.Container{
  158. ID: containerID,
  159. Image: *container.Image,
  160. Status: status,
  161. Ports: convert.ToPorts(ipAddress, *container.Ports),
  162. }
  163. }
  164. func getStatus(container containerinstance.Container) string {
  165. status := statusUnknown
  166. if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
  167. status = *container.InstanceView.CurrentState.State
  168. }
  169. return status
  170. }
  171. func (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  172. if strings.Contains(r.ID, composeContainerSeparator) {
  173. return errors.New(fmt.Sprintf("invalid container name. ACI container name cannot include %q", composeContainerSeparator))
  174. }
  175. project, err := convert.ContainerToComposeProject(r)
  176. if err != nil {
  177. return err
  178. }
  179. logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
  180. groupDefinition, err := convert.ToContainerGroup(ctx, cs.ctx, project)
  181. if err != nil {
  182. return err
  183. }
  184. addTag(&groupDefinition, singleContainerTag)
  185. return createACIContainers(ctx, cs.ctx, groupDefinition)
  186. }
  187. func addTag(groupDefinition *containerinstance.ContainerGroup, tagName string) {
  188. if groupDefinition.Tags == nil {
  189. groupDefinition.Tags = make(map[string]*string, 1)
  190. }
  191. groupDefinition.Tags[tagName] = to.StringPtr(tagName)
  192. }
  193. func (cs *aciContainerService) Start(ctx context.Context, containerID string) error {
  194. groupName, containerName := getGroupAndContainerName(containerID)
  195. if groupName != containerID {
  196. msg := "cannot start specified service %q from compose application %q, you can update and restart the entire compose app with docker compose up --project-name %s"
  197. return errors.New(fmt.Sprintf(msg, containerName, groupName, groupName))
  198. }
  199. containerGroupsClient, err := login.NewContainerGroupsClient(cs.ctx.SubscriptionID)
  200. if err != nil {
  201. return err
  202. }
  203. future, err := containerGroupsClient.Start(ctx, cs.ctx.ResourceGroup, containerName)
  204. if err != nil {
  205. var aerr autorest.DetailedError
  206. if ok := errors.As(err, &aerr); ok {
  207. if aerr.StatusCode == http.StatusNotFound {
  208. return errdefs.ErrNotFound
  209. }
  210. }
  211. return err
  212. }
  213. return future.WaitForCompletionRef(ctx, containerGroupsClient.Client)
  214. }
  215. func (cs *aciContainerService) Stop(ctx context.Context, containerID string, timeout *uint32) error {
  216. if timeout != nil && *timeout != uint32(0) {
  217. return errors.Errorf("ACI integration does not support setting a timeout to stop a container before killing it.")
  218. }
  219. groupName, containerName := getGroupAndContainerName(containerID)
  220. if groupName != containerID {
  221. msg := "cannot stop service %q from compose application %q, you can stop the entire compose app with docker stop %s"
  222. return errors.New(fmt.Sprintf(msg, containerName, groupName, groupName))
  223. }
  224. return stopACIContainerGroup(ctx, cs.ctx, groupName)
  225. }
  226. func getGroupAndContainerName(containerID string) (string, string) {
  227. tokens := strings.Split(containerID, composeContainerSeparator)
  228. groupName := tokens[0]
  229. containerName := groupName
  230. if len(tokens) > 1 {
  231. containerName = tokens[len(tokens)-1]
  232. groupName = containerID[:len(containerID)-(len(containerName)+1)]
  233. }
  234. return groupName, containerName
  235. }
  236. func (cs *aciContainerService) Exec(ctx context.Context, name string, request containers.ExecRequest) error {
  237. err := verifyExecCommand(request.Command)
  238. if err != nil {
  239. return err
  240. }
  241. groupName, containerAciName := getGroupAndContainerName(name)
  242. containerExecResponse, err := execACIContainer(ctx, cs.ctx, request.Command, groupName, containerAciName)
  243. if err != nil {
  244. return err
  245. }
  246. return exec(
  247. context.Background(),
  248. *containerExecResponse.WebSocketURI,
  249. *containerExecResponse.Password,
  250. request,
  251. )
  252. }
  253. func verifyExecCommand(command string) error {
  254. tokens := strings.Split(command, " ")
  255. if len(tokens) > 1 {
  256. return errors.New("ACI exec command does not accept arguments to the command. " +
  257. "Only the binary should be specified")
  258. }
  259. return nil
  260. }
  261. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  262. groupName, containerAciName := getGroupAndContainerName(containerName)
  263. var tail *int32
  264. if req.Follow {
  265. return streamLogs(ctx, cs.ctx, groupName, containerAciName, req)
  266. }
  267. if req.Tail != "all" {
  268. reqTail, err := strconv.Atoi(req.Tail)
  269. if err != nil {
  270. return err
  271. }
  272. i32 := int32(reqTail)
  273. tail = &i32
  274. }
  275. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName, tail)
  276. if err != nil {
  277. return err
  278. }
  279. _, err = fmt.Fprint(req.Writer, logs)
  280. return err
  281. }
  282. func (cs *aciContainerService) Delete(ctx context.Context, containerID string, request containers.DeleteRequest) error {
  283. groupName, containerName := getGroupAndContainerName(containerID)
  284. if groupName != containerID {
  285. msg := "cannot delete service %q from compose application %q, you can delete the entire compose app with docker compose down --project-name %s"
  286. return errors.New(fmt.Sprintf(msg, containerName, groupName, groupName))
  287. }
  288. if !request.Force {
  289. containerGroupsClient, err := login.NewContainerGroupsClient(cs.ctx.SubscriptionID)
  290. if err != nil {
  291. return err
  292. }
  293. cg, err := containerGroupsClient.Get(ctx, cs.ctx.ResourceGroup, groupName)
  294. if err != nil {
  295. if cg.StatusCode == http.StatusNotFound {
  296. return errdefs.ErrNotFound
  297. }
  298. return err
  299. }
  300. for _, container := range *cg.Containers {
  301. status := statusUnknown
  302. if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
  303. status = *container.InstanceView.CurrentState.State
  304. }
  305. if status == statusRunning {
  306. return errdefs.ErrForbidden
  307. }
  308. }
  309. }
  310. cg, err := deleteACIContainerGroup(ctx, cs.ctx, groupName)
  311. // Delete returns `StatusNoContent` if the group is not found
  312. if cg.StatusCode == http.StatusNoContent {
  313. return errdefs.ErrNotFound
  314. }
  315. if err != nil {
  316. return err
  317. }
  318. return err
  319. }
  320. func (cs *aciContainerService) Inspect(ctx context.Context, containerID string) (containers.Container, error) {
  321. groupName, containerName := getGroupAndContainerName(containerID)
  322. cg, err := getACIContainerGroup(ctx, cs.ctx, groupName)
  323. if err != nil {
  324. return containers.Container{}, err
  325. }
  326. if cg.StatusCode == http.StatusNoContent {
  327. return containers.Container{}, errdefs.ErrNotFound
  328. }
  329. var cc containerinstance.Container
  330. var found = false
  331. for _, c := range *cg.Containers {
  332. if to.String(c.Name) == containerName {
  333. cc = c
  334. found = true
  335. break
  336. }
  337. }
  338. if !found {
  339. return containers.Container{}, errdefs.ErrNotFound
  340. }
  341. return convert.ContainerGroupToContainer(containerID, cg, cc)
  342. }
  343. type aciComposeService struct {
  344. ctx store.AciContext
  345. }
  346. func (cs *aciComposeService) Up(ctx context.Context, opts cli.ProjectOptions) error {
  347. project, err := cli.ProjectFromOptions(&opts)
  348. if err != nil {
  349. return err
  350. }
  351. logrus.Debugf("Up on project with name %q\n", project.Name)
  352. groupDefinition, err := convert.ToContainerGroup(ctx, cs.ctx, *project)
  353. addTag(&groupDefinition, composeContainerTag)
  354. if err != nil {
  355. return err
  356. }
  357. return createOrUpdateACIContainers(ctx, cs.ctx, groupDefinition)
  358. }
  359. func (cs *aciComposeService) Down(ctx context.Context, opts cli.ProjectOptions) error {
  360. var project types.Project
  361. if opts.Name != "" {
  362. project = types.Project{Name: opts.Name}
  363. } else {
  364. fullProject, err := cli.ProjectFromOptions(&opts)
  365. if err != nil {
  366. return err
  367. }
  368. project = *fullProject
  369. }
  370. logrus.Debugf("Down on project with name %q\n", project.Name)
  371. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  372. if err != nil {
  373. return err
  374. }
  375. if cg.StatusCode == http.StatusNoContent {
  376. return errdefs.ErrNotFound
  377. }
  378. return err
  379. }
  380. func (cs *aciComposeService) Ps(ctx context.Context, opts cli.ProjectOptions) ([]ecstypes.ServiceStatus, error) {
  381. return nil, errdefs.ErrNotImplemented
  382. }
  383. func (cs *aciComposeService) Logs(ctx context.Context, opts cli.ProjectOptions) error {
  384. return errdefs.ErrNotImplemented
  385. }
  386. type aciCloudService struct {
  387. loginService login.AzureLoginServiceAPI
  388. }
  389. func (cs *aciCloudService) Login(ctx context.Context, params interface{}) error {
  390. opts, ok := params.(LoginParams)
  391. if !ok {
  392. return errors.New("Could not read azure LoginParams struct from generic parameter")
  393. }
  394. if opts.ClientID != "" {
  395. return cs.loginService.LoginServicePrincipal(opts.ClientID, opts.ClientSecret, opts.TenantID)
  396. }
  397. return cs.loginService.Login(ctx, opts.TenantID)
  398. }
  399. func (cs *aciCloudService) Logout(ctx context.Context) error {
  400. return cs.loginService.Logout(ctx)
  401. }
  402. func (cs *aciCloudService) CreateContextData(ctx context.Context, params interface{}) (interface{}, string, error) {
  403. contextHelper := newContextCreateHelper()
  404. createOpts := params.(ContextParams)
  405. return contextHelper.createContextData(ctx, createOpts)
  406. }