cloudformation.go 15 KB

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