cloudformation.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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 ecs
  14. import (
  15. "context"
  16. "fmt"
  17. "io/ioutil"
  18. "regexp"
  19. "strings"
  20. "github.com/docker/compose-cli/api/compose"
  21. "github.com/docker/compose-cli/api/config"
  22. "github.com/docker/compose-cli/api/errdefs"
  23. ecsapi "github.com/aws/aws-sdk-go/service/ecs"
  24. "github.com/aws/aws-sdk-go/service/elbv2"
  25. cloudmapapi "github.com/aws/aws-sdk-go/service/servicediscovery"
  26. "github.com/awslabs/goformation/v4/cloudformation"
  27. "github.com/awslabs/goformation/v4/cloudformation/ec2"
  28. "github.com/awslabs/goformation/v4/cloudformation/ecs"
  29. "github.com/awslabs/goformation/v4/cloudformation/elasticloadbalancingv2"
  30. "github.com/awslabs/goformation/v4/cloudformation/iam"
  31. "github.com/awslabs/goformation/v4/cloudformation/logs"
  32. "github.com/awslabs/goformation/v4/cloudformation/secretsmanager"
  33. cloudmap "github.com/awslabs/goformation/v4/cloudformation/servicediscovery"
  34. "github.com/cnabio/cnab-to-oci/remotes"
  35. "github.com/compose-spec/compose-go/types"
  36. cliconfig "github.com/docker/cli/cli/config"
  37. "github.com/docker/distribution/reference"
  38. "golang.org/x/sync/errgroup"
  39. "sigs.k8s.io/kustomize/kyaml/yaml"
  40. "sigs.k8s.io/kustomize/kyaml/yaml/merge2"
  41. )
  42. func (b *ecsAPIService) Kill(ctx context.Context, project *types.Project, options compose.KillOptions) error {
  43. return errdefs.ErrNotImplemented
  44. }
  45. func (b *ecsAPIService) Convert(ctx context.Context, project *types.Project, options compose.ConvertOptions) ([]byte, error) {
  46. err := b.resolveServiceImagesDigests(ctx, project)
  47. if err != nil {
  48. return nil, err
  49. }
  50. template, err := b.convert(ctx, project)
  51. if err != nil {
  52. return nil, err
  53. }
  54. bytes, err := marshall(template, options.Format)
  55. if err != nil {
  56. return nil, err
  57. }
  58. x, ok := project.Extensions[extensionCloudFormation]
  59. if !ok {
  60. return bytes, nil
  61. }
  62. if options.Format != "yaml" {
  63. return nil, fmt.Errorf("format %q with overlays is not supported", options.Format)
  64. }
  65. nodes, err := yaml.Parse(string(bytes))
  66. if err != nil {
  67. return nil, err
  68. }
  69. bytes, err = yaml.Marshal(x)
  70. if err != nil {
  71. return nil, err
  72. }
  73. overlay, err := yaml.Parse(string(bytes))
  74. if err != nil {
  75. return nil, err
  76. }
  77. nodes, err = merge2.Merge(overlay, nodes, yaml.MergeOptions{
  78. ListIncreaseDirection: yaml.MergeOptionsListPrepend,
  79. })
  80. if err != nil {
  81. return nil, err
  82. }
  83. s, err := nodes.String()
  84. if err != nil {
  85. return nil, err
  86. }
  87. bytes = []byte(s)
  88. return bytes, err
  89. }
  90. func (b *ecsAPIService) resolveServiceImagesDigests(ctx context.Context, project *types.Project) error {
  91. configFile, err := cliconfig.Load(config.Dir(ctx))
  92. if err != nil {
  93. return err
  94. }
  95. resolver := remotes.CreateResolver(configFile)
  96. eg := errgroup.Group{}
  97. for i, s := range project.Services {
  98. idx := i
  99. service := s
  100. eg.Go(func() error {
  101. named, err := reference.ParseDockerRef(service.Image)
  102. if err != nil {
  103. return err
  104. }
  105. _, desc, err := resolver.Resolve(ctx, named.String())
  106. if err != nil {
  107. return err
  108. }
  109. digested, err := reference.WithDigest(named, desc.Digest)
  110. if err != nil {
  111. return err
  112. }
  113. fmt.Printf("%s resolved to %s\n", service.Image, digested)
  114. service.Image = digested.String()
  115. project.Services[idx] = service
  116. return nil
  117. })
  118. }
  119. return eg.Wait()
  120. }
  121. func (b *ecsAPIService) convert(ctx context.Context, project *types.Project) (*cloudformation.Template, error) {
  122. err := b.checkCompatibility(project)
  123. if err != nil {
  124. return nil, err
  125. }
  126. template := cloudformation.NewTemplate()
  127. resources, err := b.parse(ctx, project, template)
  128. if err != nil {
  129. return nil, err
  130. }
  131. err = b.ensureResources(&resources, project, template)
  132. if err != nil {
  133. return nil, err
  134. }
  135. for name, secret := range project.Secrets {
  136. err := b.createSecret(project, name, secret, template)
  137. if err != nil {
  138. return nil, err
  139. }
  140. }
  141. b.createLogGroup(project, template)
  142. // Private DNS namespace will allow DNS name for the services to be <service>.<project>.local
  143. b.createCloudMap(project, template, resources.vpc)
  144. b.createNFSMountTarget(project, resources, template)
  145. b.createAccessPoints(project, resources, template)
  146. for _, service := range project.Services {
  147. err := b.createService(project, service, template, resources)
  148. if err != nil {
  149. return nil, err
  150. }
  151. err = b.createAutoscalingPolicy(project, resources, template, service)
  152. if err != nil {
  153. return nil, err
  154. }
  155. }
  156. err = b.createCapacityProvider(ctx, project, template, resources)
  157. if err != nil {
  158. return nil, err
  159. }
  160. return template, nil
  161. }
  162. func (b *ecsAPIService) createService(project *types.Project, service types.ServiceConfig, template *cloudformation.Template, resources awsResources) error {
  163. taskExecutionRole := b.createTaskExecutionRole(project, service, template)
  164. taskRole := b.createTaskRole(project, service, template, resources)
  165. definition, err := b.createTaskDefinition(project, service, resources)
  166. if err != nil {
  167. return err
  168. }
  169. definition.ExecutionRoleArn = cloudformation.Ref(taskExecutionRole)
  170. if taskRole != "" {
  171. definition.TaskRoleArn = cloudformation.Ref(taskRole)
  172. }
  173. taskDefinition := fmt.Sprintf("%sTaskDefinition", normalizeResourceName(service.Name))
  174. template.Resources[taskDefinition] = definition
  175. var healthCheck *cloudmap.Service_HealthCheckConfig
  176. serviceRegistry := b.createServiceRegistry(service, template, healthCheck)
  177. var (
  178. dependsOn []string
  179. serviceLB []ecs.Service_LoadBalancer
  180. )
  181. for _, port := range service.Ports {
  182. for net := range service.Networks {
  183. b.createIngress(service, net, port, template, resources)
  184. }
  185. protocol := strings.ToUpper(port.Protocol)
  186. if resources.loadBalancerType == elbv2.LoadBalancerTypeEnumApplication {
  187. // we don't set Https as a certificate must be specified for HTTPS listeners
  188. protocol = elbv2.ProtocolEnumHttp
  189. }
  190. targetGroupName := b.createTargetGroup(project, service, port, template, protocol, resources.vpc)
  191. listenerName := b.createListener(service, port, template, targetGroupName, resources.loadBalancer, protocol)
  192. dependsOn = append(dependsOn, listenerName)
  193. serviceLB = append(serviceLB, ecs.Service_LoadBalancer{
  194. ContainerName: service.Name,
  195. ContainerPort: int(port.Target),
  196. TargetGroupArn: cloudformation.Ref(targetGroupName),
  197. })
  198. }
  199. desiredCount := 1
  200. if service.Deploy != nil && service.Deploy.Replicas != nil {
  201. desiredCount = int(*service.Deploy.Replicas)
  202. }
  203. for dependency := range service.DependsOn {
  204. dependsOn = append(dependsOn, serviceResourceName(dependency))
  205. }
  206. for _, s := range service.Volumes {
  207. dependsOn = append(dependsOn, b.mountTargets(s.Source, resources)...)
  208. }
  209. minPercent, maxPercent, err := computeRollingUpdateLimits(service)
  210. if err != nil {
  211. return err
  212. }
  213. assignPublicIP := ecsapi.AssignPublicIpEnabled
  214. launchType := ecsapi.LaunchTypeFargate
  215. platformVersion := "1.4.0" // LATEST which is set to 1.3.0 (?) which doesn’t allow efs volumes.
  216. if requireEC2(service) {
  217. assignPublicIP = ecsapi.AssignPublicIpDisabled
  218. launchType = ecsapi.LaunchTypeEc2
  219. platformVersion = "" // The platform version must be null when specifying an EC2 launch type
  220. }
  221. template.Resources[serviceResourceName(service.Name)] = &ecs.Service{
  222. AWSCloudFormationDependsOn: dependsOn,
  223. Cluster: resources.cluster.ARN(),
  224. DesiredCount: desiredCount,
  225. DeploymentController: &ecs.Service_DeploymentController{
  226. Type: ecsapi.DeploymentControllerTypeEcs,
  227. },
  228. DeploymentConfiguration: &ecs.Service_DeploymentConfiguration{
  229. MaximumPercent: maxPercent,
  230. MinimumHealthyPercent: minPercent,
  231. },
  232. LaunchType: launchType,
  233. // TODO we miss support for https://github.com/aws/containers-roadmap/issues/631 to select a capacity provider
  234. LoadBalancers: serviceLB,
  235. NetworkConfiguration: &ecs.Service_NetworkConfiguration{
  236. AwsvpcConfiguration: &ecs.Service_AwsVpcConfiguration{
  237. AssignPublicIp: assignPublicIP,
  238. SecurityGroups: resources.serviceSecurityGroups(service),
  239. Subnets: resources.subnetsIDs(),
  240. },
  241. },
  242. PlatformVersion: platformVersion,
  243. PropagateTags: ecsapi.PropagateTagsService,
  244. SchedulingStrategy: ecsapi.SchedulingStrategyReplica,
  245. ServiceRegistries: []ecs.Service_ServiceRegistry{serviceRegistry},
  246. Tags: serviceTags(project, service),
  247. TaskDefinition: cloudformation.Ref(normalizeResourceName(taskDefinition)),
  248. }
  249. return nil
  250. }
  251. const allProtocols = "-1"
  252. func (b *ecsAPIService) createIngress(service types.ServiceConfig, net string, port types.ServicePortConfig, template *cloudformation.Template, resources awsResources) {
  253. protocol := strings.ToUpper(port.Protocol)
  254. if protocol == "" {
  255. protocol = allProtocols
  256. }
  257. ingress := fmt.Sprintf("%s%dIngress", normalizeResourceName(net), port.Target)
  258. template.Resources[ingress] = &ec2.SecurityGroupIngress{
  259. CidrIp: "0.0.0.0/0",
  260. Description: fmt.Sprintf("%s:%d/%s on %s network", service.Name, port.Target, port.Protocol, net),
  261. GroupId: resources.securityGroups[net],
  262. FromPort: int(port.Target),
  263. IpProtocol: protocol,
  264. ToPort: int(port.Target),
  265. }
  266. }
  267. func (b *ecsAPIService) createSecret(project *types.Project, name string, s types.SecretConfig, template *cloudformation.Template) error {
  268. if s.External.External {
  269. return nil
  270. }
  271. sensitiveData, err := ioutil.ReadFile(s.File)
  272. if err != nil {
  273. return err
  274. }
  275. resource := fmt.Sprintf("%sSecret", normalizeResourceName(s.Name))
  276. template.Resources[resource] = &secretsmanager.Secret{
  277. Description: fmt.Sprintf("Secret %s", s.Name),
  278. SecretString: string(sensitiveData),
  279. Tags: projectTags(project),
  280. }
  281. s.Name = cloudformation.Ref(resource)
  282. project.Secrets[name] = s
  283. return nil
  284. }
  285. func (b *ecsAPIService) createLogGroup(project *types.Project, template *cloudformation.Template) {
  286. retention := 0
  287. if v, ok := project.Extensions[extensionRetention]; ok {
  288. retention = v.(int)
  289. }
  290. logGroup := fmt.Sprintf("/docker-compose/%s", project.Name)
  291. template.Resources["LogGroup"] = &logs.LogGroup{
  292. LogGroupName: logGroup,
  293. RetentionInDays: retention,
  294. }
  295. }
  296. func computeRollingUpdateLimits(service types.ServiceConfig) (int, int, error) {
  297. maxPercent := 200
  298. minPercent := 100
  299. if service.Deploy == nil || service.Deploy.UpdateConfig == nil {
  300. return minPercent, maxPercent, nil
  301. }
  302. updateConfig := service.Deploy.UpdateConfig
  303. min, okMin := updateConfig.Extensions[extensionMinPercent]
  304. if okMin {
  305. minPercent = min.(int)
  306. }
  307. max, okMax := updateConfig.Extensions[extensionMaxPercent]
  308. if okMax {
  309. maxPercent = max.(int)
  310. }
  311. if okMin && okMax {
  312. return minPercent, maxPercent, nil
  313. }
  314. if updateConfig.Parallelism != nil {
  315. parallelism := int(*updateConfig.Parallelism)
  316. if service.Deploy.Replicas == nil {
  317. return minPercent, maxPercent,
  318. fmt.Errorf("rolling update configuration require deploy.replicas to be set")
  319. }
  320. replicas := int(*service.Deploy.Replicas)
  321. if replicas < parallelism {
  322. return minPercent, maxPercent,
  323. fmt.Errorf("deploy.replicas (%d) must be greater than deploy.update_config.parallelism (%d)", replicas, parallelism)
  324. }
  325. if !okMin {
  326. minPercent = (replicas - parallelism) * 100 / replicas
  327. }
  328. if !okMax {
  329. maxPercent = (replicas + parallelism) * 100 / replicas
  330. }
  331. }
  332. return minPercent, maxPercent, nil
  333. }
  334. func (b *ecsAPIService) createListener(service types.ServiceConfig, port types.ServicePortConfig,
  335. template *cloudformation.Template,
  336. targetGroupName string, loadBalancer awsResource, protocol string) string {
  337. listenerName := fmt.Sprintf(
  338. "%s%s%dListener",
  339. normalizeResourceName(service.Name),
  340. strings.ToUpper(port.Protocol),
  341. port.Target,
  342. )
  343. //add listener to dependsOn
  344. //https://stackoverflow.com/questions/53971873/the-target-group-does-not-have-an-associated-load-balancer
  345. template.Resources[listenerName] = &elasticloadbalancingv2.Listener{
  346. DefaultActions: []elasticloadbalancingv2.Listener_Action{
  347. {
  348. ForwardConfig: &elasticloadbalancingv2.Listener_ForwardConfig{
  349. TargetGroups: []elasticloadbalancingv2.Listener_TargetGroupTuple{
  350. {
  351. TargetGroupArn: cloudformation.Ref(targetGroupName),
  352. },
  353. },
  354. },
  355. Type: elbv2.ActionTypeEnumForward,
  356. },
  357. },
  358. LoadBalancerArn: loadBalancer.ARN(),
  359. Protocol: protocol,
  360. Port: int(port.Target),
  361. }
  362. return listenerName
  363. }
  364. func (b *ecsAPIService) createTargetGroup(project *types.Project, service types.ServiceConfig, port types.ServicePortConfig, template *cloudformation.Template, protocol string, vpc string) string {
  365. targetGroupName := fmt.Sprintf(
  366. "%s%s%dTargetGroup",
  367. normalizeResourceName(service.Name),
  368. strings.ToUpper(port.Protocol),
  369. port.Published,
  370. )
  371. template.Resources[targetGroupName] = &elasticloadbalancingv2.TargetGroup{
  372. Port: int(port.Target),
  373. Protocol: protocol,
  374. Tags: projectTags(project),
  375. TargetType: elbv2.TargetTypeEnumIp,
  376. VpcId: vpc,
  377. }
  378. return targetGroupName
  379. }
  380. func (b *ecsAPIService) createServiceRegistry(service types.ServiceConfig, template *cloudformation.Template, healthCheck *cloudmap.Service_HealthCheckConfig) ecs.Service_ServiceRegistry {
  381. serviceRegistration := fmt.Sprintf("%sServiceDiscoveryEntry", normalizeResourceName(service.Name))
  382. serviceRegistry := ecs.Service_ServiceRegistry{
  383. RegistryArn: cloudformation.GetAtt(serviceRegistration, "Arn"),
  384. }
  385. template.Resources[serviceRegistration] = &cloudmap.Service{
  386. Description: fmt.Sprintf("%q service discovery entry in Cloud Map", service.Name),
  387. HealthCheckConfig: healthCheck,
  388. HealthCheckCustomConfig: &cloudmap.Service_HealthCheckCustomConfig{
  389. FailureThreshold: 1,
  390. },
  391. Name: service.Name,
  392. NamespaceId: cloudformation.Ref("CloudMap"),
  393. DnsConfig: &cloudmap.Service_DnsConfig{
  394. DnsRecords: []cloudmap.Service_DnsRecord{
  395. {
  396. TTL: 60,
  397. Type: cloudmapapi.RecordTypeA,
  398. },
  399. },
  400. RoutingPolicy: cloudmapapi.RoutingPolicyMultivalue,
  401. },
  402. }
  403. return serviceRegistry
  404. }
  405. func (b *ecsAPIService) createTaskExecutionRole(project *types.Project, service types.ServiceConfig, template *cloudformation.Template) string {
  406. taskExecutionRole := fmt.Sprintf("%sTaskExecutionRole", normalizeResourceName(service.Name))
  407. policies := b.createPolicies(project, service)
  408. template.Resources[taskExecutionRole] = &iam.Role{
  409. AssumeRolePolicyDocument: ecsTaskAssumeRolePolicyDocument,
  410. Policies: policies,
  411. ManagedPolicyArns: []string{
  412. ecsTaskExecutionPolicy,
  413. ecrReadOnlyPolicy,
  414. },
  415. Tags: serviceTags(project, service),
  416. }
  417. return taskExecutionRole
  418. }
  419. func (b *ecsAPIService) createTaskRole(project *types.Project, service types.ServiceConfig, template *cloudformation.Template, resources awsResources) string {
  420. taskRole := fmt.Sprintf("%sTaskRole", normalizeResourceName(service.Name))
  421. rolePolicies := []iam.Role_Policy{}
  422. if roles, ok := service.Extensions[extensionRole]; ok {
  423. rolePolicies = append(rolePolicies, iam.Role_Policy{
  424. PolicyName: fmt.Sprintf("%sPolicy", normalizeResourceName(service.Name)),
  425. PolicyDocument: roles,
  426. })
  427. }
  428. for _, vol := range service.Volumes {
  429. rolePolicies = append(rolePolicies, iam.Role_Policy{
  430. PolicyName: fmt.Sprintf("%s%sVolumeMountPolicy", normalizeResourceName(service.Name), normalizeResourceName(vol.Source)),
  431. PolicyDocument: volumeMountPolicyDocument(vol.Source, resources.filesystems[vol.Source].ARN()),
  432. })
  433. }
  434. managedPolicies := []string{}
  435. if v, ok := service.Extensions[extensionManagedPolicies]; ok {
  436. for _, s := range v.([]interface{}) {
  437. managedPolicies = append(managedPolicies, s.(string))
  438. }
  439. }
  440. if len(rolePolicies) == 0 && len(managedPolicies) == 0 {
  441. return ""
  442. }
  443. template.Resources[taskRole] = &iam.Role{
  444. AssumeRolePolicyDocument: ecsTaskAssumeRolePolicyDocument,
  445. Policies: rolePolicies,
  446. ManagedPolicyArns: managedPolicies,
  447. Tags: serviceTags(project, service),
  448. }
  449. return taskRole
  450. }
  451. func (b *ecsAPIService) createCloudMap(project *types.Project, template *cloudformation.Template, vpc string) {
  452. template.Resources["CloudMap"] = &cloudmap.PrivateDnsNamespace{
  453. Description: fmt.Sprintf("Service Map for Docker Compose project %s", project.Name),
  454. Name: fmt.Sprintf("%s.local", project.Name),
  455. Vpc: vpc,
  456. }
  457. }
  458. func (b *ecsAPIService) createPolicies(project *types.Project, service types.ServiceConfig) []iam.Role_Policy {
  459. var arns []string
  460. if value, ok := service.Extensions[extensionPullCredentials]; ok {
  461. arns = append(arns, value.(string))
  462. }
  463. for _, secret := range service.Secrets {
  464. arns = append(arns, project.Secrets[secret.Source].Name)
  465. }
  466. if len(arns) > 0 {
  467. return []iam.Role_Policy{
  468. {
  469. PolicyDocument: &PolicyDocument{
  470. Statement: []PolicyStatement{
  471. {
  472. Effect: "Allow",
  473. Action: []string{actionGetSecretValue, actionGetParameters, actionDecrypt},
  474. Resource: arns,
  475. },
  476. },
  477. },
  478. PolicyName: fmt.Sprintf("%sGrantAccessToSecrets", service.Name),
  479. },
  480. }
  481. }
  482. return nil
  483. }
  484. func networkResourceName(network string) string {
  485. return fmt.Sprintf("%sNetwork", normalizeResourceName(network))
  486. }
  487. func serviceResourceName(service string) string {
  488. return fmt.Sprintf("%sService", normalizeResourceName(service))
  489. }
  490. func volumeResourceName(service string) string {
  491. return fmt.Sprintf("%sFilesystem", normalizeResourceName(service))
  492. }
  493. func normalizeResourceName(s string) string {
  494. return strings.Title(regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString(s, ""))
  495. }