convert.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. "encoding/json"
  16. "fmt"
  17. "os"
  18. "path/filepath"
  19. "sort"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/docker/compose-cli/ecs/secrets"
  24. ecsapi "github.com/aws/aws-sdk-go/service/ecs"
  25. "github.com/awslabs/goformation/v4/cloudformation"
  26. "github.com/awslabs/goformation/v4/cloudformation/ecs"
  27. "github.com/compose-spec/compose-go/types"
  28. "github.com/docker/cli/opts"
  29. "github.com/joho/godotenv"
  30. )
  31. const secretsInitContainerImage = "docker/ecs-secrets-sidecar:1.0"
  32. const searchDomainInitContainerImage = "docker/ecs-searchdomain-sidecar:1.0"
  33. func (b *ecsAPIService) createTaskDefinition(project *types.Project, service types.ServiceConfig, resources awsResources) (*ecs.TaskDefinition, error) {
  34. cpu, mem, err := toLimits(service)
  35. if err != nil {
  36. return nil, err
  37. }
  38. _, memReservation := toContainerReservation(service)
  39. credential := getRepoCredentials(service)
  40. logConfiguration := getLogConfiguration(service, project)
  41. var (
  42. initContainers []ecs.TaskDefinition_ContainerDefinition
  43. volumes []ecs.TaskDefinition_Volume
  44. mounts []ecs.TaskDefinition_MountPoint
  45. )
  46. if len(service.Secrets) > 0 {
  47. secretsVolume, secretsMount, secretsSideCar, err := createSecretsSideCar(project, service, logConfiguration)
  48. if err != nil {
  49. return nil, err
  50. }
  51. initContainers = append(initContainers, secretsSideCar)
  52. volumes = append(volumes, secretsVolume)
  53. mounts = append(mounts, secretsMount)
  54. }
  55. initContainers = append(initContainers, ecs.TaskDefinition_ContainerDefinition{
  56. Name: fmt.Sprintf("%s_ResolvConf_InitContainer", normalizeResourceName(service.Name)),
  57. Image: searchDomainInitContainerImage,
  58. Essential: false,
  59. Command: []string{b.Region + ".compute.internal", project.Name + ".local"},
  60. LogConfiguration: logConfiguration,
  61. })
  62. var dependencies []ecs.TaskDefinition_ContainerDependency
  63. for _, c := range initContainers {
  64. dependencies = append(dependencies, ecs.TaskDefinition_ContainerDependency{
  65. Condition: ecsapi.ContainerConditionSuccess,
  66. ContainerName: c.Name,
  67. })
  68. }
  69. for _, v := range service.Volumes {
  70. n := fmt.Sprintf("%sAccessPoint", normalizeResourceName(v.Source))
  71. volumes = append(volumes, ecs.TaskDefinition_Volume{
  72. EFSVolumeConfiguration: &ecs.TaskDefinition_EFSVolumeConfiguration{
  73. AuthorizationConfig: &ecs.TaskDefinition_AuthorizationConfig{
  74. AccessPointId: cloudformation.Ref(n),
  75. IAM: "ENABLED",
  76. },
  77. FilesystemId: resources.filesystems[v.Source].ID(),
  78. TransitEncryption: "ENABLED",
  79. },
  80. Name: v.Source,
  81. })
  82. mounts = append(mounts, ecs.TaskDefinition_MountPoint{
  83. ContainerPath: v.Target,
  84. ReadOnly: v.ReadOnly,
  85. SourceVolume: v.Source,
  86. })
  87. }
  88. pairs, err := createEnvironment(project, service)
  89. if err != nil {
  90. return nil, err
  91. }
  92. var reservations *types.Resource
  93. if service.Deploy != nil && service.Deploy.Resources.Reservations != nil {
  94. reservations = service.Deploy.Resources.Reservations
  95. }
  96. containers := append(initContainers, ecs.TaskDefinition_ContainerDefinition{
  97. Command: service.Command,
  98. DisableNetworking: service.NetworkMode == "none",
  99. DependsOnProp: dependencies,
  100. DnsSearchDomains: service.DNSSearch,
  101. DnsServers: service.DNS,
  102. DockerSecurityOptions: service.SecurityOpt,
  103. EntryPoint: service.Entrypoint,
  104. Environment: pairs,
  105. Essential: true,
  106. ExtraHosts: toHostEntryPtr(service.ExtraHosts),
  107. FirelensConfiguration: nil,
  108. HealthCheck: toHealthCheck(service.HealthCheck),
  109. Hostname: service.Hostname,
  110. Image: service.Image,
  111. Interactive: false,
  112. Links: nil,
  113. LinuxParameters: toLinuxParameters(service),
  114. LogConfiguration: logConfiguration,
  115. MemoryReservation: memReservation,
  116. MountPoints: mounts,
  117. Name: service.Name,
  118. PortMappings: toPortMappings(service.Ports),
  119. Privileged: service.Privileged,
  120. PseudoTerminal: service.Tty,
  121. ReadonlyRootFilesystem: service.ReadOnly,
  122. RepositoryCredentials: credential,
  123. ResourceRequirements: toTaskResourceRequirements(reservations),
  124. StartTimeout: 0,
  125. StopTimeout: durationToInt(service.StopGracePeriod),
  126. SystemControls: toSystemControls(service.Sysctls),
  127. Ulimits: toUlimits(service.Ulimits),
  128. User: service.User,
  129. VolumesFrom: nil,
  130. WorkingDirectory: service.WorkingDir,
  131. })
  132. launchType := ecsapi.LaunchTypeFargate
  133. if requireEC2(service) {
  134. launchType = ecsapi.LaunchTypeEc2
  135. }
  136. return &ecs.TaskDefinition{
  137. ContainerDefinitions: containers,
  138. Cpu: cpu,
  139. Family: fmt.Sprintf("%s-%s", project.Name, service.Name),
  140. IpcMode: service.Ipc,
  141. Memory: mem,
  142. NetworkMode: ecsapi.NetworkModeAwsvpc, // FIXME could be set by service.NetworkMode, Fargate only supports network mode ‘awsvpc’.
  143. PidMode: service.Pid,
  144. PlacementConstraints: toPlacementConstraints(service.Deploy),
  145. ProxyConfiguration: nil,
  146. RequiresCompatibilities: []string{
  147. launchType,
  148. },
  149. Volumes: volumes,
  150. }, nil
  151. }
  152. func toTaskResourceRequirements(reservations *types.Resource) []ecs.TaskDefinition_ResourceRequirement {
  153. if reservations == nil {
  154. return nil
  155. }
  156. var requirements []ecs.TaskDefinition_ResourceRequirement
  157. for _, r := range reservations.GenericResources {
  158. if r.DiscreteResourceSpec.Kind == "gpus" {
  159. requirements = append(requirements, ecs.TaskDefinition_ResourceRequirement{
  160. Type: ecsapi.ResourceTypeGpu,
  161. Value: fmt.Sprint(r.DiscreteResourceSpec.Value),
  162. })
  163. }
  164. }
  165. return requirements
  166. }
  167. func createSecretsSideCar(project *types.Project, service types.ServiceConfig, logConfiguration *ecs.TaskDefinition_LogConfiguration) (
  168. ecs.TaskDefinition_Volume,
  169. ecs.TaskDefinition_MountPoint,
  170. ecs.TaskDefinition_ContainerDefinition,
  171. error) {
  172. initContainerName := fmt.Sprintf("%s_Secrets_InitContainer", normalizeResourceName(service.Name))
  173. secretsVolume := ecs.TaskDefinition_Volume{
  174. Name: "secrets",
  175. }
  176. secretsMount := ecs.TaskDefinition_MountPoint{
  177. ContainerPath: "/run/secrets/",
  178. ReadOnly: true,
  179. SourceVolume: "secrets",
  180. }
  181. var (
  182. args []secrets.Secret
  183. taskSecrets []ecs.TaskDefinition_Secret
  184. )
  185. for _, s := range service.Secrets {
  186. secretConfig := project.Secrets[s.Source]
  187. if s.Target == "" {
  188. s.Target = s.Source
  189. }
  190. taskSecrets = append(taskSecrets, ecs.TaskDefinition_Secret{
  191. Name: s.Target,
  192. ValueFrom: secretConfig.Name,
  193. })
  194. var keys []string
  195. if ext, ok := secretConfig.Extensions[extensionKeys]; ok {
  196. if key, ok := ext.(string); ok {
  197. keys = append(keys, key)
  198. } else {
  199. for _, k := range ext.([]interface{}) {
  200. keys = append(keys, k.(string))
  201. }
  202. }
  203. }
  204. args = append(args, secrets.Secret{
  205. Name: s.Target,
  206. Keys: keys,
  207. })
  208. }
  209. command, err := json.Marshal(args)
  210. if err != nil {
  211. return ecs.TaskDefinition_Volume{}, ecs.TaskDefinition_MountPoint{}, ecs.TaskDefinition_ContainerDefinition{}, err
  212. }
  213. secretsSideCar := ecs.TaskDefinition_ContainerDefinition{
  214. Name: initContainerName,
  215. Image: secretsInitContainerImage,
  216. Command: []string{string(command)},
  217. Essential: false, // FIXME this will be ignored, see https://github.com/awslabs/goformation/issues/61#issuecomment-625139607
  218. LogConfiguration: logConfiguration,
  219. MountPoints: []ecs.TaskDefinition_MountPoint{
  220. {
  221. ContainerPath: "/run/secrets/",
  222. ReadOnly: false,
  223. SourceVolume: "secrets",
  224. },
  225. },
  226. Secrets: taskSecrets,
  227. }
  228. return secretsVolume, secretsMount, secretsSideCar, nil
  229. }
  230. func createEnvironment(project *types.Project, service types.ServiceConfig) ([]ecs.TaskDefinition_KeyValuePair, error) {
  231. environment := map[string]*string{}
  232. for _, f := range service.EnvFile {
  233. if !filepath.IsAbs(f) {
  234. f = filepath.Join(project.WorkingDir, f)
  235. }
  236. if _, err := os.Stat(f); os.IsNotExist(err) {
  237. return nil, err
  238. }
  239. file, err := os.Open(f)
  240. if err != nil {
  241. return nil, err
  242. }
  243. defer file.Close() // nolint:errcheck
  244. env, err := godotenv.Parse(file)
  245. if err != nil {
  246. return nil, err
  247. }
  248. for k, v := range env {
  249. environment[k] = &v
  250. }
  251. }
  252. for k, v := range service.Environment {
  253. environment[k] = v
  254. }
  255. var pairs []ecs.TaskDefinition_KeyValuePair
  256. for k, v := range environment {
  257. name := k
  258. var value string
  259. if v != nil {
  260. value = *v
  261. }
  262. pairs = append(pairs, ecs.TaskDefinition_KeyValuePair{
  263. Name: name,
  264. Value: value,
  265. })
  266. }
  267. //order env keys for idempotence between calls
  268. //to avoid unnecessary resource recreations on CloudFormation
  269. sort.Slice(pairs, func(i, j int) bool {
  270. return pairs[i].Name < pairs[j].Name
  271. })
  272. return pairs, nil
  273. }
  274. func getLogConfiguration(service types.ServiceConfig, project *types.Project) *ecs.TaskDefinition_LogConfiguration {
  275. options := map[string]string{
  276. "awslogs-region": cloudformation.Ref("AWS::Region"),
  277. "awslogs-group": cloudformation.Ref("LogGroup"),
  278. "awslogs-stream-prefix": project.Name,
  279. }
  280. if service.Logging != nil {
  281. for k, v := range service.Logging.Options {
  282. if strings.HasPrefix(k, "awslogs-") {
  283. options[k] = v
  284. }
  285. }
  286. }
  287. logConfiguration := &ecs.TaskDefinition_LogConfiguration{
  288. LogDriver: ecsapi.LogDriverAwslogs,
  289. Options: options,
  290. }
  291. return logConfiguration
  292. }
  293. func toSystemControls(sysctls types.Mapping) []ecs.TaskDefinition_SystemControl {
  294. sys := []ecs.TaskDefinition_SystemControl{}
  295. for k, v := range sysctls {
  296. sys = append(sys, ecs.TaskDefinition_SystemControl{
  297. Namespace: k,
  298. Value: v,
  299. })
  300. }
  301. return sys
  302. }
  303. const miB = 1024 * 1024
  304. func toLimits(service types.ServiceConfig) (string, string, error) {
  305. mem, cpu, err := getConfiguredLimits(service)
  306. if err != nil {
  307. return "", "", err
  308. }
  309. if requireEC2(service) {
  310. // just return configured limits expressed in Mb and CPU units
  311. var cpuLimit, memLimit string
  312. if cpu > 0 {
  313. cpuLimit = fmt.Sprint(cpu)
  314. }
  315. if mem > 0 {
  316. memLimit = fmt.Sprint(mem / miB)
  317. }
  318. return cpuLimit, memLimit, nil
  319. }
  320. // All possible cpu/mem values for Fargate
  321. fargateCPUToMem := map[int64][]types.UnitBytes{
  322. 256: {512, 1024, 2048},
  323. 512: {1024, 2048, 3072, 4096},
  324. 1024: {2048, 3072, 4096, 5120, 6144, 7168, 8192},
  325. 2048: {4096, 5120, 6144, 7168, 8192, 9216, 10240, 11264, 12288, 13312, 14336, 15360, 16384},
  326. 4096: {8192, 9216, 10240, 11264, 12288, 13312, 14336, 15360, 16384, 17408, 18432, 19456, 20480, 21504, 22528, 23552, 24576, 25600, 26624, 27648, 28672, 29696, 30720},
  327. }
  328. cpuLimit := "256"
  329. memLimit := "512"
  330. if mem == 0 && cpu == 0 {
  331. return cpuLimit, memLimit, nil
  332. }
  333. var cpus []int64
  334. for k := range fargateCPUToMem {
  335. cpus = append(cpus, k)
  336. }
  337. sort.Slice(cpus, func(i, j int) bool { return cpus[i] < cpus[j] })
  338. for _, fargateCPU := range cpus {
  339. options := fargateCPUToMem[fargateCPU]
  340. if cpu <= fargateCPU {
  341. for _, m := range options {
  342. if mem <= m*miB {
  343. cpuLimit = strconv.FormatInt(fargateCPU, 10)
  344. memLimit = strconv.FormatInt(int64(m), 10)
  345. return cpuLimit, memLimit, nil
  346. }
  347. }
  348. }
  349. }
  350. return "", "", fmt.Errorf("the resources requested are not supported by ECS/Fargate")
  351. }
  352. func getConfiguredLimits(service types.ServiceConfig) (types.UnitBytes, int64, error) {
  353. if service.Deploy == nil {
  354. return 0, 0, nil
  355. }
  356. limits := service.Deploy.Resources.Limits
  357. if limits == nil {
  358. return 0, 0, nil
  359. }
  360. if limits.NanoCPUs == "" {
  361. return limits.MemoryBytes, 0, nil
  362. }
  363. v, err := opts.ParseCPUs(limits.NanoCPUs)
  364. if err != nil {
  365. return 0, 0, err
  366. }
  367. return limits.MemoryBytes, v / 1e6, nil
  368. }
  369. func toContainerReservation(service types.ServiceConfig) (string, int) {
  370. cpuReservation := ".0"
  371. memReservation := 0
  372. if service.Deploy == nil {
  373. return cpuReservation, memReservation
  374. }
  375. reservations := service.Deploy.Resources.Reservations
  376. if reservations == nil {
  377. return cpuReservation, memReservation
  378. }
  379. return reservations.NanoCPUs, int(reservations.MemoryBytes / miB)
  380. }
  381. func toPlacementConstraints(deploy *types.DeployConfig) []ecs.TaskDefinition_TaskDefinitionPlacementConstraint {
  382. if deploy == nil || deploy.Placement.Constraints == nil || len(deploy.Placement.Constraints) == 0 {
  383. return nil
  384. }
  385. pl := []ecs.TaskDefinition_TaskDefinitionPlacementConstraint{}
  386. for _, c := range deploy.Placement.Constraints {
  387. pl = append(pl, ecs.TaskDefinition_TaskDefinitionPlacementConstraint{
  388. Expression: c,
  389. Type: "",
  390. })
  391. }
  392. return pl
  393. }
  394. func toPortMappings(ports []types.ServicePortConfig) []ecs.TaskDefinition_PortMapping {
  395. if len(ports) == 0 {
  396. return nil
  397. }
  398. m := []ecs.TaskDefinition_PortMapping{}
  399. for _, p := range ports {
  400. m = append(m, ecs.TaskDefinition_PortMapping{
  401. ContainerPort: int(p.Target),
  402. HostPort: int(p.Published),
  403. Protocol: p.Protocol,
  404. })
  405. }
  406. return m
  407. }
  408. func toUlimits(ulimits map[string]*types.UlimitsConfig) []ecs.TaskDefinition_Ulimit {
  409. if len(ulimits) == 0 {
  410. return nil
  411. }
  412. u := []ecs.TaskDefinition_Ulimit{}
  413. for k, v := range ulimits {
  414. u = append(u, ecs.TaskDefinition_Ulimit{
  415. Name: k,
  416. SoftLimit: v.Soft,
  417. HardLimit: v.Hard,
  418. })
  419. }
  420. return u
  421. }
  422. func toLinuxParameters(service types.ServiceConfig) *ecs.TaskDefinition_LinuxParameters {
  423. return &ecs.TaskDefinition_LinuxParameters{
  424. Capabilities: toKernelCapabilities(service.CapAdd, service.CapDrop),
  425. Devices: nil,
  426. InitProcessEnabled: service.Init != nil && *service.Init,
  427. MaxSwap: 0,
  428. // FIXME SharedMemorySize: service.ShmSize,
  429. Swappiness: 0,
  430. Tmpfs: toTmpfs(service.Tmpfs),
  431. }
  432. }
  433. func toTmpfs(tmpfs types.StringList) []ecs.TaskDefinition_Tmpfs {
  434. if tmpfs == nil || len(tmpfs) == 0 {
  435. return nil
  436. }
  437. o := []ecs.TaskDefinition_Tmpfs{}
  438. for _, path := range tmpfs {
  439. o = append(o, ecs.TaskDefinition_Tmpfs{
  440. ContainerPath: path,
  441. Size: 100, // size is required on ECS, unlimited by the compose spec
  442. })
  443. }
  444. return o
  445. }
  446. func toKernelCapabilities(add []string, drop []string) *ecs.TaskDefinition_KernelCapabilities {
  447. if len(add) == 0 && len(drop) == 0 {
  448. return nil
  449. }
  450. return &ecs.TaskDefinition_KernelCapabilities{
  451. Add: add,
  452. Drop: drop,
  453. }
  454. }
  455. func toHealthCheck(check *types.HealthCheckConfig) *ecs.TaskDefinition_HealthCheck {
  456. if check == nil {
  457. return nil
  458. }
  459. retries := 0
  460. if check.Retries != nil {
  461. retries = int(*check.Retries)
  462. }
  463. return &ecs.TaskDefinition_HealthCheck{
  464. Command: check.Test,
  465. Interval: durationToInt(check.Interval),
  466. Retries: retries,
  467. StartPeriod: durationToInt(check.StartPeriod),
  468. Timeout: durationToInt(check.Timeout),
  469. }
  470. }
  471. func durationToInt(interval *types.Duration) int {
  472. if interval == nil {
  473. return 0
  474. }
  475. v := int(time.Duration(*interval).Seconds())
  476. return v
  477. }
  478. func toHostEntryPtr(hosts types.HostsList) []ecs.TaskDefinition_HostEntry {
  479. if hosts == nil || len(hosts) == 0 {
  480. return nil
  481. }
  482. e := []ecs.TaskDefinition_HostEntry{}
  483. for _, h := range hosts {
  484. parts := strings.SplitN(h, ":", 2) // FIXME this should be handled by compose-go
  485. e = append(e, ecs.TaskDefinition_HostEntry{
  486. Hostname: parts[0],
  487. IpAddress: parts[1],
  488. })
  489. }
  490. return e
  491. }
  492. func getRepoCredentials(service types.ServiceConfig) *ecs.TaskDefinition_RepositoryCredentials {
  493. if value, ok := service.Extensions[extensionPullCredentials]; ok {
  494. return &ecs.TaskDefinition_RepositoryCredentials{CredentialsParameter: value.(string)}
  495. }
  496. return nil
  497. }
  498. func requireEC2(s types.ServiceConfig) bool {
  499. return gpuRequirements(s) > 0
  500. }
  501. func gpuRequirements(s types.ServiceConfig) int64 {
  502. if deploy := s.Deploy; deploy != nil {
  503. if reservations := deploy.Resources.Reservations; reservations != nil {
  504. for _, resource := range reservations.GenericResources {
  505. if resource.DiscreteResourceSpec.Kind == "gpus" {
  506. return resource.DiscreteResourceSpec.Value
  507. }
  508. }
  509. }
  510. }
  511. return 0
  512. }