cloudformation.go 15 KB

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