cloudformation.go 15 KB

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