backend.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. // don't list sidecar container
  141. if *container.Name == convert.ComposeDNSSidecarName {
  142. continue
  143. }
  144. if !all && convert.GetStatus(container, group) != statusRunning {
  145. continue
  146. }
  147. containerID := *containerGroup.Name + composeContainerSeparator + *container.Name
  148. if _, ok := group.Tags[singleContainerTag]; ok {
  149. containerID = *containerGroup.Name
  150. }
  151. c := convert.ContainerGroupToContainer(containerID, group, container)
  152. res = append(res, c)
  153. }
  154. }
  155. return res, nil
  156. }
  157. func (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  158. if strings.Contains(r.ID, composeContainerSeparator) {
  159. return errors.New(fmt.Sprintf("invalid container name. ACI container name cannot include %q", composeContainerSeparator))
  160. }
  161. project, err := convert.ContainerToComposeProject(r)
  162. if err != nil {
  163. return err
  164. }
  165. logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
  166. groupDefinition, err := convert.ToContainerGroup(ctx, cs.ctx, project)
  167. if err != nil {
  168. return err
  169. }
  170. addTag(&groupDefinition, singleContainerTag)
  171. return createACIContainers(ctx, cs.ctx, groupDefinition)
  172. }
  173. func addTag(groupDefinition *containerinstance.ContainerGroup, tagName string) {
  174. if groupDefinition.Tags == nil {
  175. groupDefinition.Tags = make(map[string]*string, 1)
  176. }
  177. groupDefinition.Tags[tagName] = to.StringPtr(tagName)
  178. }
  179. func (cs *aciContainerService) Start(ctx context.Context, containerID string) error {
  180. groupName, containerName := getGroupAndContainerName(containerID)
  181. if groupName != containerID {
  182. 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"
  183. return errors.New(fmt.Sprintf(msg, containerName, groupName, groupName))
  184. }
  185. containerGroupsClient, err := login.NewContainerGroupsClient(cs.ctx.SubscriptionID)
  186. if err != nil {
  187. return err
  188. }
  189. future, err := containerGroupsClient.Start(ctx, cs.ctx.ResourceGroup, containerName)
  190. if err != nil {
  191. var aerr autorest.DetailedError
  192. if ok := errors.As(err, &aerr); ok {
  193. if aerr.StatusCode == http.StatusNotFound {
  194. return errdefs.ErrNotFound
  195. }
  196. }
  197. return err
  198. }
  199. return future.WaitForCompletionRef(ctx, containerGroupsClient.Client)
  200. }
  201. func (cs *aciContainerService) Stop(ctx context.Context, containerID string, timeout *uint32) error {
  202. if timeout != nil && *timeout != uint32(0) {
  203. return errors.Errorf("ACI integration does not support setting a timeout to stop a container before killing it.")
  204. }
  205. groupName, containerName := getGroupAndContainerName(containerID)
  206. if groupName != containerID {
  207. msg := "cannot stop service %q from compose application %q, you can stop the entire compose app with docker stop %s"
  208. return errors.New(fmt.Sprintf(msg, containerName, groupName, groupName))
  209. }
  210. return stopACIContainerGroup(ctx, cs.ctx, groupName)
  211. }
  212. func getGroupAndContainerName(containerID string) (string, string) {
  213. tokens := strings.Split(containerID, composeContainerSeparator)
  214. groupName := tokens[0]
  215. containerName := groupName
  216. if len(tokens) > 1 {
  217. containerName = tokens[len(tokens)-1]
  218. groupName = containerID[:len(containerID)-(len(containerName)+1)]
  219. }
  220. return groupName, containerName
  221. }
  222. func (cs *aciContainerService) Exec(ctx context.Context, name string, request containers.ExecRequest) error {
  223. err := verifyExecCommand(request.Command)
  224. if err != nil {
  225. return err
  226. }
  227. groupName, containerAciName := getGroupAndContainerName(name)
  228. containerExecResponse, err := execACIContainer(ctx, cs.ctx, request.Command, groupName, containerAciName)
  229. if err != nil {
  230. return err
  231. }
  232. return exec(
  233. context.Background(),
  234. *containerExecResponse.WebSocketURI,
  235. *containerExecResponse.Password,
  236. request,
  237. )
  238. }
  239. func verifyExecCommand(command string) error {
  240. tokens := strings.Split(command, " ")
  241. if len(tokens) > 1 {
  242. return errors.New("ACI exec command does not accept arguments to the command. " +
  243. "Only the binary should be specified")
  244. }
  245. return nil
  246. }
  247. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  248. groupName, containerAciName := getGroupAndContainerName(containerName)
  249. var tail *int32
  250. if req.Follow {
  251. return streamLogs(ctx, cs.ctx, groupName, containerAciName, req)
  252. }
  253. if req.Tail != "all" {
  254. reqTail, err := strconv.Atoi(req.Tail)
  255. if err != nil {
  256. return err
  257. }
  258. i32 := int32(reqTail)
  259. tail = &i32
  260. }
  261. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName, tail)
  262. if err != nil {
  263. return err
  264. }
  265. _, err = fmt.Fprint(req.Writer, logs)
  266. return err
  267. }
  268. func (cs *aciContainerService) Delete(ctx context.Context, containerID string, request containers.DeleteRequest) error {
  269. groupName, containerName := getGroupAndContainerName(containerID)
  270. if groupName != containerID {
  271. msg := "cannot delete service %q from compose application %q, you can delete the entire compose app with docker compose down --project-name %s"
  272. return errors.New(fmt.Sprintf(msg, containerName, groupName, groupName))
  273. }
  274. if !request.Force {
  275. containerGroupsClient, err := login.NewContainerGroupsClient(cs.ctx.SubscriptionID)
  276. if err != nil {
  277. return err
  278. }
  279. cg, err := containerGroupsClient.Get(ctx, cs.ctx.ResourceGroup, groupName)
  280. if err != nil {
  281. if cg.StatusCode == http.StatusNotFound {
  282. return errdefs.ErrNotFound
  283. }
  284. return err
  285. }
  286. for _, container := range *cg.Containers {
  287. status := convert.GetStatus(container, cg)
  288. if status == statusRunning {
  289. return errdefs.ErrForbidden
  290. }
  291. }
  292. }
  293. cg, err := deleteACIContainerGroup(ctx, cs.ctx, groupName)
  294. // Delete returns `StatusNoContent` if the group is not found
  295. if cg.StatusCode == http.StatusNoContent {
  296. return errdefs.ErrNotFound
  297. }
  298. if err != nil {
  299. return err
  300. }
  301. return err
  302. }
  303. func (cs *aciContainerService) Inspect(ctx context.Context, containerID string) (containers.Container, error) {
  304. groupName, containerName := getGroupAndContainerName(containerID)
  305. cg, err := getACIContainerGroup(ctx, cs.ctx, groupName)
  306. if err != nil {
  307. return containers.Container{}, err
  308. }
  309. if cg.StatusCode == http.StatusNoContent {
  310. return containers.Container{}, errdefs.ErrNotFound
  311. }
  312. var cc containerinstance.Container
  313. var found = false
  314. for _, c := range *cg.Containers {
  315. if to.String(c.Name) == containerName {
  316. cc = c
  317. found = true
  318. break
  319. }
  320. }
  321. if !found {
  322. return containers.Container{}, errdefs.ErrNotFound
  323. }
  324. return convert.ContainerGroupToContainer(containerID, cg, cc), nil
  325. }
  326. type aciComposeService struct {
  327. ctx store.AciContext
  328. }
  329. func (cs *aciComposeService) Up(ctx context.Context, project *types.Project) error {
  330. logrus.Debugf("Up on project with name %q\n", project.Name)
  331. groupDefinition, err := convert.ToContainerGroup(ctx, cs.ctx, *project)
  332. addTag(&groupDefinition, composeContainerTag)
  333. if err != nil {
  334. return err
  335. }
  336. return createOrUpdateACIContainers(ctx, cs.ctx, groupDefinition)
  337. }
  338. func (cs *aciComposeService) Emulate(context.Context, *cli.ProjectOptions) error {
  339. return errdefs.ErrNotImplemented
  340. }
  341. func (cs *aciComposeService) Down(ctx context.Context, project string) error {
  342. logrus.Debugf("Down on project with name %q\n", project)
  343. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project)
  344. if err != nil {
  345. return err
  346. }
  347. if cg.StatusCode == http.StatusNoContent {
  348. return errdefs.ErrNotFound
  349. }
  350. return err
  351. }
  352. func (cs *aciComposeService) Ps(ctx context.Context, project string) ([]compose.ServiceStatus, error) {
  353. return nil, errdefs.ErrNotImplemented
  354. }
  355. func (cs *aciComposeService) Logs(ctx context.Context, project string, w io.Writer) error {
  356. return errdefs.ErrNotImplemented
  357. }
  358. func (cs *aciComposeService) Convert(ctx context.Context, project *types.Project) ([]byte, error) {
  359. return nil, errdefs.ErrNotImplemented
  360. }
  361. type aciCloudService struct {
  362. loginService login.AzureLoginServiceAPI
  363. }
  364. func (cs *aciCloudService) Login(ctx context.Context, params interface{}) error {
  365. opts, ok := params.(LoginParams)
  366. if !ok {
  367. return errors.New("Could not read azure LoginParams struct from generic parameter")
  368. }
  369. if opts.ClientID != "" {
  370. return cs.loginService.LoginServicePrincipal(opts.ClientID, opts.ClientSecret, opts.TenantID)
  371. }
  372. return cs.loginService.Login(ctx, opts.TenantID)
  373. }
  374. func (cs *aciCloudService) Logout(ctx context.Context) error {
  375. return cs.loginService.Logout(ctx)
  376. }
  377. func (cs *aciCloudService) CreateContextData(ctx context.Context, params interface{}) (interface{}, string, error) {
  378. contextHelper := newContextCreateHelper()
  379. createOpts := params.(ContextParams)
  380. return contextHelper.createContextData(ctx, createOpts)
  381. }