cloudformation.go 17 KB

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