cloudformation.go 17 KB

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