convert.go 14 KB

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