convert.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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"
  32. const searchDomainInitContainerImage = "docker/ecs-searchdomain-sidecar"
  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. return pairs, nil
  268. }
  269. func getLogConfiguration(service types.ServiceConfig, project *types.Project) *ecs.TaskDefinition_LogConfiguration {
  270. options := map[string]string{
  271. "awslogs-region": cloudformation.Ref("AWS::Region"),
  272. "awslogs-group": cloudformation.Ref("LogGroup"),
  273. "awslogs-stream-prefix": project.Name,
  274. }
  275. if service.Logging != nil {
  276. for k, v := range service.Logging.Options {
  277. if strings.HasPrefix(k, "awslogs-") {
  278. options[k] = v
  279. }
  280. }
  281. }
  282. logConfiguration := &ecs.TaskDefinition_LogConfiguration{
  283. LogDriver: ecsapi.LogDriverAwslogs,
  284. Options: options,
  285. }
  286. return logConfiguration
  287. }
  288. func toSystemControls(sysctls types.Mapping) []ecs.TaskDefinition_SystemControl {
  289. sys := []ecs.TaskDefinition_SystemControl{}
  290. for k, v := range sysctls {
  291. sys = append(sys, ecs.TaskDefinition_SystemControl{
  292. Namespace: k,
  293. Value: v,
  294. })
  295. }
  296. return sys
  297. }
  298. const miB = 1024 * 1024
  299. func toLimits(service types.ServiceConfig) (string, string, error) {
  300. mem, cpu, err := getConfiguredLimits(service)
  301. if err != nil {
  302. return "", "", err
  303. }
  304. if requireEC2(service) {
  305. // just return configured limits expressed in Mb and CPU units
  306. var cpuLimit, memLimit string
  307. if cpu > 0 {
  308. cpuLimit = fmt.Sprint(cpu)
  309. }
  310. if mem > 0 {
  311. memLimit = fmt.Sprint(mem / miB)
  312. }
  313. return cpuLimit, memLimit, nil
  314. }
  315. // All possible cpu/mem values for Fargate
  316. fargateCPUToMem := map[int64][]types.UnitBytes{
  317. 256: {512, 1024, 2048},
  318. 512: {1024, 2048, 3072, 4096},
  319. 1024: {2048, 3072, 4096, 5120, 6144, 7168, 8192},
  320. 2048: {4096, 5120, 6144, 7168, 8192, 9216, 10240, 11264, 12288, 13312, 14336, 15360, 16384},
  321. 4096: {8192, 9216, 10240, 11264, 12288, 13312, 14336, 15360, 16384, 17408, 18432, 19456, 20480, 21504, 22528, 23552, 24576, 25600, 26624, 27648, 28672, 29696, 30720},
  322. }
  323. cpuLimit := "256"
  324. memLimit := "512"
  325. if mem == 0 && cpu == 0 {
  326. return cpuLimit, memLimit, nil
  327. }
  328. var cpus []int64
  329. for k := range fargateCPUToMem {
  330. cpus = append(cpus, k)
  331. }
  332. sort.Slice(cpus, func(i, j int) bool { return cpus[i] < cpus[j] })
  333. for _, fargateCPU := range cpus {
  334. options := fargateCPUToMem[fargateCPU]
  335. if cpu <= fargateCPU {
  336. for _, m := range options {
  337. if mem <= m*miB {
  338. cpuLimit = strconv.FormatInt(fargateCPU, 10)
  339. memLimit = strconv.FormatInt(int64(m), 10)
  340. return cpuLimit, memLimit, nil
  341. }
  342. }
  343. }
  344. }
  345. return "", "", fmt.Errorf("the resources requested are not supported by ECS/Fargate")
  346. }
  347. func getConfiguredLimits(service types.ServiceConfig) (types.UnitBytes, int64, error) {
  348. if service.Deploy == nil {
  349. return 0, 0, nil
  350. }
  351. limits := service.Deploy.Resources.Limits
  352. if limits == nil {
  353. return 0, 0, nil
  354. }
  355. if limits.NanoCPUs == "" {
  356. return limits.MemoryBytes, 0, nil
  357. }
  358. v, err := opts.ParseCPUs(limits.NanoCPUs)
  359. if err != nil {
  360. return 0, 0, err
  361. }
  362. return limits.MemoryBytes, v / 1e6, nil
  363. }
  364. func toContainerReservation(service types.ServiceConfig) (string, int) {
  365. cpuReservation := ".0"
  366. memReservation := 0
  367. if service.Deploy == nil {
  368. return cpuReservation, memReservation
  369. }
  370. reservations := service.Deploy.Resources.Reservations
  371. if reservations == nil {
  372. return cpuReservation, memReservation
  373. }
  374. return reservations.NanoCPUs, int(reservations.MemoryBytes / miB)
  375. }
  376. func toPlacementConstraints(deploy *types.DeployConfig) []ecs.TaskDefinition_TaskDefinitionPlacementConstraint {
  377. if deploy == nil || deploy.Placement.Constraints == nil || len(deploy.Placement.Constraints) == 0 {
  378. return nil
  379. }
  380. pl := []ecs.TaskDefinition_TaskDefinitionPlacementConstraint{}
  381. for _, c := range deploy.Placement.Constraints {
  382. pl = append(pl, ecs.TaskDefinition_TaskDefinitionPlacementConstraint{
  383. Expression: c,
  384. Type: "",
  385. })
  386. }
  387. return pl
  388. }
  389. func toPortMappings(ports []types.ServicePortConfig) []ecs.TaskDefinition_PortMapping {
  390. if len(ports) == 0 {
  391. return nil
  392. }
  393. m := []ecs.TaskDefinition_PortMapping{}
  394. for _, p := range ports {
  395. m = append(m, ecs.TaskDefinition_PortMapping{
  396. ContainerPort: int(p.Target),
  397. HostPort: int(p.Published),
  398. Protocol: p.Protocol,
  399. })
  400. }
  401. return m
  402. }
  403. func toUlimits(ulimits map[string]*types.UlimitsConfig) []ecs.TaskDefinition_Ulimit {
  404. if len(ulimits) == 0 {
  405. return nil
  406. }
  407. u := []ecs.TaskDefinition_Ulimit{}
  408. for k, v := range ulimits {
  409. u = append(u, ecs.TaskDefinition_Ulimit{
  410. Name: k,
  411. SoftLimit: v.Soft,
  412. HardLimit: v.Hard,
  413. })
  414. }
  415. return u
  416. }
  417. func toLinuxParameters(service types.ServiceConfig) *ecs.TaskDefinition_LinuxParameters {
  418. return &ecs.TaskDefinition_LinuxParameters{
  419. Capabilities: toKernelCapabilities(service.CapAdd, service.CapDrop),
  420. Devices: nil,
  421. InitProcessEnabled: service.Init != nil && *service.Init,
  422. MaxSwap: 0,
  423. // FIXME SharedMemorySize: service.ShmSize,
  424. Swappiness: 0,
  425. Tmpfs: toTmpfs(service.Tmpfs),
  426. }
  427. }
  428. func toTmpfs(tmpfs types.StringList) []ecs.TaskDefinition_Tmpfs {
  429. if tmpfs == nil || len(tmpfs) == 0 {
  430. return nil
  431. }
  432. o := []ecs.TaskDefinition_Tmpfs{}
  433. for _, path := range tmpfs {
  434. o = append(o, ecs.TaskDefinition_Tmpfs{
  435. ContainerPath: path,
  436. Size: 100, // size is required on ECS, unlimited by the compose spec
  437. })
  438. }
  439. return o
  440. }
  441. func toKernelCapabilities(add []string, drop []string) *ecs.TaskDefinition_KernelCapabilities {
  442. if len(add) == 0 && len(drop) == 0 {
  443. return nil
  444. }
  445. return &ecs.TaskDefinition_KernelCapabilities{
  446. Add: add,
  447. Drop: drop,
  448. }
  449. }
  450. func toHealthCheck(check *types.HealthCheckConfig) *ecs.TaskDefinition_HealthCheck {
  451. if check == nil {
  452. return nil
  453. }
  454. retries := 0
  455. if check.Retries != nil {
  456. retries = int(*check.Retries)
  457. }
  458. return &ecs.TaskDefinition_HealthCheck{
  459. Command: check.Test,
  460. Interval: durationToInt(check.Interval),
  461. Retries: retries,
  462. StartPeriod: durationToInt(check.StartPeriod),
  463. Timeout: durationToInt(check.Timeout),
  464. }
  465. }
  466. func durationToInt(interval *types.Duration) int {
  467. if interval == nil {
  468. return 0
  469. }
  470. v := int(time.Duration(*interval).Seconds())
  471. return v
  472. }
  473. func toHostEntryPtr(hosts types.HostsList) []ecs.TaskDefinition_HostEntry {
  474. if hosts == nil || len(hosts) == 0 {
  475. return nil
  476. }
  477. e := []ecs.TaskDefinition_HostEntry{}
  478. for _, h := range hosts {
  479. parts := strings.SplitN(h, ":", 2) // FIXME this should be handled by compose-go
  480. e = append(e, ecs.TaskDefinition_HostEntry{
  481. Hostname: parts[0],
  482. IpAddress: parts[1],
  483. })
  484. }
  485. return e
  486. }
  487. func getRepoCredentials(service types.ServiceConfig) *ecs.TaskDefinition_RepositoryCredentials {
  488. if value, ok := service.Extensions[extensionPullCredentials]; ok {
  489. return &ecs.TaskDefinition_RepositoryCredentials{CredentialsParameter: value.(string)}
  490. }
  491. return nil
  492. }
  493. func requireEC2(s types.ServiceConfig) bool {
  494. return gpuRequirements(s) > 0
  495. }
  496. func gpuRequirements(s types.ServiceConfig) int64 {
  497. if deploy := s.Deploy; deploy != nil {
  498. if reservations := deploy.Resources.Reservations; reservations != nil {
  499. for _, resource := range reservations.GenericResources {
  500. if resource.DiscreteResourceSpec.Kind == "gpus" {
  501. return resource.DiscreteResourceSpec.Value
  502. }
  503. }
  504. }
  505. }
  506. return 0
  507. }