cloudformation.go 15 KB

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