cloudformation.go 17 KB

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