convert.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. limits = service.Deploy.Resources.Reservations
  359. }
  360. if limits == nil {
  361. return 0, 0, nil
  362. }
  363. if limits.NanoCPUs == "" {
  364. return limits.MemoryBytes, 0, nil
  365. }
  366. v, err := opts.ParseCPUs(limits.NanoCPUs)
  367. if err != nil {
  368. return 0, 0, err
  369. }
  370. return limits.MemoryBytes, v / 1e6, nil
  371. }
  372. func toContainerReservation(service types.ServiceConfig) (string, int) {
  373. cpuReservation := ".0"
  374. memReservation := 0
  375. if service.Deploy == nil {
  376. return cpuReservation, memReservation
  377. }
  378. reservations := service.Deploy.Resources.Reservations
  379. if reservations == nil {
  380. return cpuReservation, memReservation
  381. }
  382. return reservations.NanoCPUs, int(reservations.MemoryBytes / miB)
  383. }
  384. func toPlacementConstraints(deploy *types.DeployConfig) []ecs.TaskDefinition_TaskDefinitionPlacementConstraint {
  385. if deploy == nil || deploy.Placement.Constraints == nil || len(deploy.Placement.Constraints) == 0 {
  386. return nil
  387. }
  388. pl := []ecs.TaskDefinition_TaskDefinitionPlacementConstraint{}
  389. for _, c := range deploy.Placement.Constraints {
  390. pl = append(pl, ecs.TaskDefinition_TaskDefinitionPlacementConstraint{
  391. Expression: c,
  392. Type: "",
  393. })
  394. }
  395. return pl
  396. }
  397. func toPortMappings(ports []types.ServicePortConfig) []ecs.TaskDefinition_PortMapping {
  398. if len(ports) == 0 {
  399. return nil
  400. }
  401. m := []ecs.TaskDefinition_PortMapping{}
  402. for _, p := range ports {
  403. m = append(m, ecs.TaskDefinition_PortMapping{
  404. ContainerPort: int(p.Target),
  405. HostPort: int(p.Published),
  406. Protocol: p.Protocol,
  407. })
  408. }
  409. return m
  410. }
  411. func toUlimits(ulimits map[string]*types.UlimitsConfig) []ecs.TaskDefinition_Ulimit {
  412. if len(ulimits) == 0 {
  413. return nil
  414. }
  415. u := []ecs.TaskDefinition_Ulimit{}
  416. for k, v := range ulimits {
  417. u = append(u, ecs.TaskDefinition_Ulimit{
  418. Name: k,
  419. SoftLimit: v.Soft,
  420. HardLimit: v.Hard,
  421. })
  422. }
  423. return u
  424. }
  425. func toLinuxParameters(service types.ServiceConfig) *ecs.TaskDefinition_LinuxParameters {
  426. return &ecs.TaskDefinition_LinuxParameters{
  427. Capabilities: toKernelCapabilities(service.CapAdd, service.CapDrop),
  428. Devices: nil,
  429. InitProcessEnabled: service.Init != nil && *service.Init,
  430. MaxSwap: 0,
  431. // FIXME SharedMemorySize: service.ShmSize,
  432. Swappiness: 0,
  433. Tmpfs: toTmpfs(service.Tmpfs),
  434. }
  435. }
  436. func toTmpfs(tmpfs types.StringList) []ecs.TaskDefinition_Tmpfs {
  437. if tmpfs == nil || len(tmpfs) == 0 {
  438. return nil
  439. }
  440. o := []ecs.TaskDefinition_Tmpfs{}
  441. for _, path := range tmpfs {
  442. o = append(o, ecs.TaskDefinition_Tmpfs{
  443. ContainerPath: path,
  444. Size: 100, // size is required on ECS, unlimited by the compose spec
  445. })
  446. }
  447. return o
  448. }
  449. func toKernelCapabilities(add []string, drop []string) *ecs.TaskDefinition_KernelCapabilities {
  450. if len(add) == 0 && len(drop) == 0 {
  451. return nil
  452. }
  453. return &ecs.TaskDefinition_KernelCapabilities{
  454. Add: add,
  455. Drop: drop,
  456. }
  457. }
  458. func toHealthCheck(check *types.HealthCheckConfig) *ecs.TaskDefinition_HealthCheck {
  459. if check == nil {
  460. return nil
  461. }
  462. retries := 0
  463. if check.Retries != nil {
  464. retries = int(*check.Retries)
  465. }
  466. return &ecs.TaskDefinition_HealthCheck{
  467. Command: check.Test,
  468. Interval: durationToInt(check.Interval),
  469. Retries: retries,
  470. StartPeriod: durationToInt(check.StartPeriod),
  471. Timeout: durationToInt(check.Timeout),
  472. }
  473. }
  474. func durationToInt(interval *types.Duration) int {
  475. if interval == nil {
  476. return 0
  477. }
  478. v := int(time.Duration(*interval).Seconds())
  479. return v
  480. }
  481. func toHostEntryPtr(hosts types.HostsList) []ecs.TaskDefinition_HostEntry {
  482. if hosts == nil || len(hosts) == 0 {
  483. return nil
  484. }
  485. e := []ecs.TaskDefinition_HostEntry{}
  486. for _, h := range hosts {
  487. parts := strings.SplitN(h, ":", 2) // FIXME this should be handled by compose-go
  488. e = append(e, ecs.TaskDefinition_HostEntry{
  489. Hostname: parts[0],
  490. IpAddress: parts[1],
  491. })
  492. }
  493. return e
  494. }
  495. func getRepoCredentials(service types.ServiceConfig) *ecs.TaskDefinition_RepositoryCredentials {
  496. if value, ok := service.Extensions[extensionPullCredentials]; ok {
  497. return &ecs.TaskDefinition_RepositoryCredentials{CredentialsParameter: value.(string)}
  498. }
  499. return nil
  500. }
  501. func requireEC2(s types.ServiceConfig) bool {
  502. return gpuRequirements(s) > 0
  503. }
  504. func gpuRequirements(s types.ServiceConfig) int64 {
  505. if deploy := s.Deploy; deploy != nil {
  506. if reservations := deploy.Resources.Reservations; reservations != nil {
  507. for _, resource := range reservations.GenericResources {
  508. if resource.DiscreteResourceSpec.Kind == "gpus" {
  509. return resource.DiscreteResourceSpec.Value
  510. }
  511. }
  512. for _, device := range reservations.Devices {
  513. if len(device.Capabilities) == 1 && device.Capabilities[0] == "gpu" {
  514. return int64(device.Count)
  515. }
  516. }
  517. }
  518. }
  519. return 0
  520. }