backend.go 14 KB

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