loader.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. package loader
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "reflect"
  7. "regexp"
  8. "sort"
  9. "strings"
  10. "github.com/docker/docker/cli/compose/interpolation"
  11. "github.com/docker/docker/cli/compose/schema"
  12. "github.com/docker/docker/cli/compose/types"
  13. "github.com/docker/docker/opts"
  14. runconfigopts "github.com/docker/docker/runconfig/opts"
  15. "github.com/docker/go-connections/nat"
  16. units "github.com/docker/go-units"
  17. shellwords "github.com/mattn/go-shellwords"
  18. "github.com/mitchellh/mapstructure"
  19. yaml "gopkg.in/yaml.v2"
  20. )
  21. var (
  22. fieldNameRegexp = regexp.MustCompile("[A-Z][a-z0-9]+")
  23. )
  24. // ParseYAML reads the bytes from a file, parses the bytes into a mapping
  25. // structure, and returns it.
  26. func ParseYAML(source []byte) (types.Dict, error) {
  27. var cfg interface{}
  28. if err := yaml.Unmarshal(source, &cfg); err != nil {
  29. return nil, err
  30. }
  31. cfgMap, ok := cfg.(map[interface{}]interface{})
  32. if !ok {
  33. return nil, fmt.Errorf("Top-level object must be a mapping")
  34. }
  35. converted, err := convertToStringKeysRecursive(cfgMap, "")
  36. if err != nil {
  37. return nil, err
  38. }
  39. return converted.(types.Dict), nil
  40. }
  41. // Load reads a ConfigDetails and returns a fully loaded configuration
  42. func Load(configDetails types.ConfigDetails) (*types.Config, error) {
  43. if len(configDetails.ConfigFiles) < 1 {
  44. return nil, fmt.Errorf("No files specified")
  45. }
  46. if len(configDetails.ConfigFiles) > 1 {
  47. return nil, fmt.Errorf("Multiple files are not yet supported")
  48. }
  49. configDict := getConfigDict(configDetails)
  50. if services, ok := configDict["services"]; ok {
  51. if servicesDict, ok := services.(types.Dict); ok {
  52. forbidden := getProperties(servicesDict, types.ForbiddenProperties)
  53. if len(forbidden) > 0 {
  54. return nil, &ForbiddenPropertiesError{Properties: forbidden}
  55. }
  56. }
  57. }
  58. if err := schema.Validate(configDict, schema.Version(configDict)); err != nil {
  59. return nil, err
  60. }
  61. cfg := types.Config{}
  62. if services, ok := configDict["services"]; ok {
  63. servicesConfig, err := interpolation.Interpolate(services.(types.Dict), "service", os.LookupEnv)
  64. if err != nil {
  65. return nil, err
  66. }
  67. servicesList, err := loadServices(servicesConfig, configDetails.WorkingDir)
  68. if err != nil {
  69. return nil, err
  70. }
  71. cfg.Services = servicesList
  72. }
  73. if networks, ok := configDict["networks"]; ok {
  74. networksConfig, err := interpolation.Interpolate(networks.(types.Dict), "network", os.LookupEnv)
  75. if err != nil {
  76. return nil, err
  77. }
  78. networksMapping, err := loadNetworks(networksConfig)
  79. if err != nil {
  80. return nil, err
  81. }
  82. cfg.Networks = networksMapping
  83. }
  84. if volumes, ok := configDict["volumes"]; ok {
  85. volumesConfig, err := interpolation.Interpolate(volumes.(types.Dict), "volume", os.LookupEnv)
  86. if err != nil {
  87. return nil, err
  88. }
  89. volumesMapping, err := loadVolumes(volumesConfig)
  90. if err != nil {
  91. return nil, err
  92. }
  93. cfg.Volumes = volumesMapping
  94. }
  95. if secrets, ok := configDict["secrets"]; ok {
  96. secretsConfig, err := interpolation.Interpolate(secrets.(types.Dict), "secret", os.LookupEnv)
  97. if err != nil {
  98. return nil, err
  99. }
  100. secretsMapping, err := loadSecrets(secretsConfig, configDetails.WorkingDir)
  101. if err != nil {
  102. return nil, err
  103. }
  104. cfg.Secrets = secretsMapping
  105. }
  106. return &cfg, nil
  107. }
  108. // GetUnsupportedProperties returns the list of any unsupported properties that are
  109. // used in the Compose files.
  110. func GetUnsupportedProperties(configDetails types.ConfigDetails) []string {
  111. unsupported := map[string]bool{}
  112. for _, service := range getServices(getConfigDict(configDetails)) {
  113. serviceDict := service.(types.Dict)
  114. for _, property := range types.UnsupportedProperties {
  115. if _, isSet := serviceDict[property]; isSet {
  116. unsupported[property] = true
  117. }
  118. }
  119. }
  120. return sortedKeys(unsupported)
  121. }
  122. func sortedKeys(set map[string]bool) []string {
  123. var keys []string
  124. for key := range set {
  125. keys = append(keys, key)
  126. }
  127. sort.Strings(keys)
  128. return keys
  129. }
  130. // GetDeprecatedProperties returns the list of any deprecated properties that
  131. // are used in the compose files.
  132. func GetDeprecatedProperties(configDetails types.ConfigDetails) map[string]string {
  133. return getProperties(getServices(getConfigDict(configDetails)), types.DeprecatedProperties)
  134. }
  135. func getProperties(services types.Dict, propertyMap map[string]string) map[string]string {
  136. output := map[string]string{}
  137. for _, service := range services {
  138. if serviceDict, ok := service.(types.Dict); ok {
  139. for property, description := range propertyMap {
  140. if _, isSet := serviceDict[property]; isSet {
  141. output[property] = description
  142. }
  143. }
  144. }
  145. }
  146. return output
  147. }
  148. // ForbiddenPropertiesError is returned when there are properties in the Compose
  149. // file that are forbidden.
  150. type ForbiddenPropertiesError struct {
  151. Properties map[string]string
  152. }
  153. func (e *ForbiddenPropertiesError) Error() string {
  154. return "Configuration contains forbidden properties"
  155. }
  156. // TODO: resolve multiple files into a single config
  157. func getConfigDict(configDetails types.ConfigDetails) types.Dict {
  158. return configDetails.ConfigFiles[0].Config
  159. }
  160. func getServices(configDict types.Dict) types.Dict {
  161. if services, ok := configDict["services"]; ok {
  162. if servicesDict, ok := services.(types.Dict); ok {
  163. return servicesDict
  164. }
  165. }
  166. return types.Dict{}
  167. }
  168. func transform(source map[string]interface{}, target interface{}) error {
  169. data := mapstructure.Metadata{}
  170. config := &mapstructure.DecoderConfig{
  171. DecodeHook: mapstructure.ComposeDecodeHookFunc(
  172. transformHook,
  173. mapstructure.StringToTimeDurationHookFunc()),
  174. Result: target,
  175. Metadata: &data,
  176. }
  177. decoder, err := mapstructure.NewDecoder(config)
  178. if err != nil {
  179. return err
  180. }
  181. err = decoder.Decode(source)
  182. // TODO: log unused keys
  183. return err
  184. }
  185. func transformHook(
  186. source reflect.Type,
  187. target reflect.Type,
  188. data interface{},
  189. ) (interface{}, error) {
  190. switch target {
  191. case reflect.TypeOf(types.External{}):
  192. return transformExternal(data)
  193. case reflect.TypeOf(types.HealthCheckTest{}):
  194. return transformHealthCheckTest(data)
  195. case reflect.TypeOf(types.ShellCommand{}):
  196. return transformShellCommand(data)
  197. case reflect.TypeOf(types.StringList{}):
  198. return transformStringList(data)
  199. case reflect.TypeOf(map[string]string{}):
  200. return transformMapStringString(data)
  201. case reflect.TypeOf(types.UlimitsConfig{}):
  202. return transformUlimits(data)
  203. case reflect.TypeOf(types.UnitBytes(0)):
  204. return transformSize(data)
  205. case reflect.TypeOf([]types.ServicePortConfig{}):
  206. return transformServicePort(data)
  207. case reflect.TypeOf(types.ServiceSecretConfig{}):
  208. return transformServiceSecret(data)
  209. case reflect.TypeOf(types.StringOrNumberList{}):
  210. return transformStringOrNumberList(data)
  211. case reflect.TypeOf(map[string]*types.ServiceNetworkConfig{}):
  212. return transformServiceNetworkMap(data)
  213. case reflect.TypeOf(types.MappingWithEquals{}):
  214. return transformMappingOrList(data, "="), nil
  215. case reflect.TypeOf(types.MappingWithColon{}):
  216. return transformMappingOrList(data, ":"), nil
  217. }
  218. return data, nil
  219. }
  220. // keys needs to be converted to strings for jsonschema
  221. // TODO: don't use types.Dict
  222. func convertToStringKeysRecursive(value interface{}, keyPrefix string) (interface{}, error) {
  223. if mapping, ok := value.(map[interface{}]interface{}); ok {
  224. dict := make(types.Dict)
  225. for key, entry := range mapping {
  226. str, ok := key.(string)
  227. if !ok {
  228. return nil, formatInvalidKeyError(keyPrefix, key)
  229. }
  230. var newKeyPrefix string
  231. if keyPrefix == "" {
  232. newKeyPrefix = str
  233. } else {
  234. newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, str)
  235. }
  236. convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix)
  237. if err != nil {
  238. return nil, err
  239. }
  240. dict[str] = convertedEntry
  241. }
  242. return dict, nil
  243. }
  244. if list, ok := value.([]interface{}); ok {
  245. var convertedList []interface{}
  246. for index, entry := range list {
  247. newKeyPrefix := fmt.Sprintf("%s[%d]", keyPrefix, index)
  248. convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix)
  249. if err != nil {
  250. return nil, err
  251. }
  252. convertedList = append(convertedList, convertedEntry)
  253. }
  254. return convertedList, nil
  255. }
  256. return value, nil
  257. }
  258. func formatInvalidKeyError(keyPrefix string, key interface{}) error {
  259. var location string
  260. if keyPrefix == "" {
  261. location = "at top level"
  262. } else {
  263. location = fmt.Sprintf("in %s", keyPrefix)
  264. }
  265. return fmt.Errorf("Non-string key %s: %#v", location, key)
  266. }
  267. func loadServices(servicesDict types.Dict, workingDir string) ([]types.ServiceConfig, error) {
  268. var services []types.ServiceConfig
  269. for name, serviceDef := range servicesDict {
  270. serviceConfig, err := loadService(name, serviceDef.(types.Dict), workingDir)
  271. if err != nil {
  272. return nil, err
  273. }
  274. services = append(services, *serviceConfig)
  275. }
  276. return services, nil
  277. }
  278. func loadService(name string, serviceDict types.Dict, workingDir string) (*types.ServiceConfig, error) {
  279. serviceConfig := &types.ServiceConfig{}
  280. if err := transform(serviceDict, serviceConfig); err != nil {
  281. return nil, err
  282. }
  283. serviceConfig.Name = name
  284. if err := resolveEnvironment(serviceConfig, workingDir); err != nil {
  285. return nil, err
  286. }
  287. if err := resolveVolumePaths(serviceConfig.Volumes, workingDir); err != nil {
  288. return nil, err
  289. }
  290. return serviceConfig, nil
  291. }
  292. func resolveEnvironment(serviceConfig *types.ServiceConfig, workingDir string) error {
  293. environment := make(map[string]string)
  294. if len(serviceConfig.EnvFile) > 0 {
  295. var envVars []string
  296. for _, file := range serviceConfig.EnvFile {
  297. filePath := absPath(workingDir, file)
  298. fileVars, err := runconfigopts.ParseEnvFile(filePath)
  299. if err != nil {
  300. return err
  301. }
  302. envVars = append(envVars, fileVars...)
  303. }
  304. for k, v := range runconfigopts.ConvertKVStringsToMap(envVars) {
  305. environment[k] = v
  306. }
  307. }
  308. for k, v := range serviceConfig.Environment {
  309. environment[k] = v
  310. }
  311. serviceConfig.Environment = environment
  312. return nil
  313. }
  314. func resolveVolumePaths(volumes []string, workingDir string) error {
  315. for i, mapping := range volumes {
  316. parts := strings.SplitN(mapping, ":", 2)
  317. if len(parts) == 1 {
  318. continue
  319. }
  320. if strings.HasPrefix(parts[0], ".") {
  321. parts[0] = absPath(workingDir, parts[0])
  322. }
  323. parts[0] = expandUser(parts[0])
  324. volumes[i] = strings.Join(parts, ":")
  325. }
  326. return nil
  327. }
  328. // TODO: make this more robust
  329. func expandUser(path string) string {
  330. if strings.HasPrefix(path, "~") {
  331. return strings.Replace(path, "~", os.Getenv("HOME"), 1)
  332. }
  333. return path
  334. }
  335. func transformUlimits(data interface{}) (interface{}, error) {
  336. switch value := data.(type) {
  337. case int:
  338. return types.UlimitsConfig{Single: value}, nil
  339. case types.Dict:
  340. ulimit := types.UlimitsConfig{}
  341. ulimit.Soft = value["soft"].(int)
  342. ulimit.Hard = value["hard"].(int)
  343. return ulimit, nil
  344. default:
  345. return data, fmt.Errorf("invalid type %T for ulimits", value)
  346. }
  347. }
  348. func loadNetworks(source types.Dict) (map[string]types.NetworkConfig, error) {
  349. networks := make(map[string]types.NetworkConfig)
  350. err := transform(source, &networks)
  351. if err != nil {
  352. return networks, err
  353. }
  354. for name, network := range networks {
  355. if network.External.External && network.External.Name == "" {
  356. network.External.Name = name
  357. networks[name] = network
  358. }
  359. }
  360. return networks, nil
  361. }
  362. func loadVolumes(source types.Dict) (map[string]types.VolumeConfig, error) {
  363. volumes := make(map[string]types.VolumeConfig)
  364. err := transform(source, &volumes)
  365. if err != nil {
  366. return volumes, err
  367. }
  368. for name, volume := range volumes {
  369. if volume.External.External && volume.External.Name == "" {
  370. volume.External.Name = name
  371. volumes[name] = volume
  372. }
  373. }
  374. return volumes, nil
  375. }
  376. func loadSecrets(source types.Dict, workingDir string) (map[string]types.SecretConfig, error) {
  377. secrets := make(map[string]types.SecretConfig)
  378. if err := transform(source, &secrets); err != nil {
  379. return secrets, err
  380. }
  381. for name, secret := range secrets {
  382. if secret.External.External && secret.External.Name == "" {
  383. secret.External.Name = name
  384. secrets[name] = secret
  385. }
  386. if secret.File != "" {
  387. secret.File = absPath(workingDir, secret.File)
  388. }
  389. }
  390. return secrets, nil
  391. }
  392. func absPath(workingDir string, filepath string) string {
  393. if path.IsAbs(filepath) {
  394. return filepath
  395. }
  396. return path.Join(workingDir, filepath)
  397. }
  398. func transformMapStringString(data interface{}) (interface{}, error) {
  399. switch value := data.(type) {
  400. case map[string]interface{}:
  401. return toMapStringString(value), nil
  402. case types.Dict:
  403. return toMapStringString(value), nil
  404. case map[string]string:
  405. return value, nil
  406. default:
  407. return data, fmt.Errorf("invalid type %T for map[string]string", value)
  408. }
  409. }
  410. func transformExternal(data interface{}) (interface{}, error) {
  411. switch value := data.(type) {
  412. case bool:
  413. return map[string]interface{}{"external": value}, nil
  414. case types.Dict:
  415. return map[string]interface{}{"external": true, "name": value["name"]}, nil
  416. case map[string]interface{}:
  417. return map[string]interface{}{"external": true, "name": value["name"]}, nil
  418. default:
  419. return data, fmt.Errorf("invalid type %T for external", value)
  420. }
  421. }
  422. func transformServicePort(data interface{}) (interface{}, error) {
  423. switch entries := data.(type) {
  424. case []interface{}:
  425. // We process the list instead of individual items here.
  426. // The reason is that one entry might be mapped to multiple ServicePortConfig.
  427. // Therefore we take an input of a list and return an output of a list.
  428. ports := []interface{}{}
  429. for _, entry := range entries {
  430. switch value := entry.(type) {
  431. case int:
  432. v, err := toServicePortConfigs(fmt.Sprint(value))
  433. if err != nil {
  434. return data, err
  435. }
  436. ports = append(ports, v...)
  437. case string:
  438. v, err := toServicePortConfigs(value)
  439. if err != nil {
  440. return data, err
  441. }
  442. ports = append(ports, v...)
  443. case types.Dict:
  444. ports = append(ports, value)
  445. case map[string]interface{}:
  446. ports = append(ports, value)
  447. default:
  448. return data, fmt.Errorf("invalid type %T for port", value)
  449. }
  450. }
  451. return ports, nil
  452. default:
  453. return data, fmt.Errorf("invalid type %T for port", entries)
  454. }
  455. }
  456. func transformServiceSecret(data interface{}) (interface{}, error) {
  457. switch value := data.(type) {
  458. case string:
  459. return map[string]interface{}{"source": value}, nil
  460. case types.Dict:
  461. return data, nil
  462. case map[string]interface{}:
  463. return data, nil
  464. default:
  465. return data, fmt.Errorf("invalid type %T for external", value)
  466. }
  467. }
  468. func transformServiceNetworkMap(value interface{}) (interface{}, error) {
  469. if list, ok := value.([]interface{}); ok {
  470. mapValue := map[interface{}]interface{}{}
  471. for _, name := range list {
  472. mapValue[name] = nil
  473. }
  474. return mapValue, nil
  475. }
  476. return value, nil
  477. }
  478. func transformStringOrNumberList(value interface{}) (interface{}, error) {
  479. list := value.([]interface{})
  480. result := make([]string, len(list))
  481. for i, item := range list {
  482. result[i] = fmt.Sprint(item)
  483. }
  484. return result, nil
  485. }
  486. func transformStringList(data interface{}) (interface{}, error) {
  487. switch value := data.(type) {
  488. case string:
  489. return []string{value}, nil
  490. case []interface{}:
  491. return value, nil
  492. default:
  493. return data, fmt.Errorf("invalid type %T for string list", value)
  494. }
  495. }
  496. func transformMappingOrList(mappingOrList interface{}, sep string) map[string]string {
  497. if mapping, ok := mappingOrList.(types.Dict); ok {
  498. return toMapStringString(mapping)
  499. }
  500. if list, ok := mappingOrList.([]interface{}); ok {
  501. result := make(map[string]string)
  502. for _, value := range list {
  503. parts := strings.SplitN(value.(string), sep, 2)
  504. if len(parts) == 1 {
  505. result[parts[0]] = ""
  506. } else {
  507. result[parts[0]] = parts[1]
  508. }
  509. }
  510. return result
  511. }
  512. panic(fmt.Errorf("expected a map or a slice, got: %#v", mappingOrList))
  513. }
  514. func transformShellCommand(value interface{}) (interface{}, error) {
  515. if str, ok := value.(string); ok {
  516. return shellwords.Parse(str)
  517. }
  518. return value, nil
  519. }
  520. func transformHealthCheckTest(data interface{}) (interface{}, error) {
  521. switch value := data.(type) {
  522. case string:
  523. return append([]string{"CMD-SHELL"}, value), nil
  524. case []interface{}:
  525. return value, nil
  526. default:
  527. return value, fmt.Errorf("invalid type %T for healthcheck.test", value)
  528. }
  529. }
  530. func transformSize(value interface{}) (int64, error) {
  531. switch value := value.(type) {
  532. case int:
  533. return int64(value), nil
  534. case string:
  535. return units.RAMInBytes(value)
  536. }
  537. panic(fmt.Errorf("invalid type for size %T", value))
  538. }
  539. func toServicePortConfigs(value string) ([]interface{}, error) {
  540. var portConfigs []interface{}
  541. ports, portBindings, err := nat.ParsePortSpecs([]string{value})
  542. if err != nil {
  543. return nil, err
  544. }
  545. // We need to sort the key of the ports to make sure it is consistent
  546. keys := []string{}
  547. for port := range ports {
  548. keys = append(keys, string(port))
  549. }
  550. sort.Strings(keys)
  551. for _, key := range keys {
  552. // Reuse ConvertPortToPortConfig so that it is consistent
  553. portConfig, err := opts.ConvertPortToPortConfig(nat.Port(key), portBindings)
  554. if err != nil {
  555. return nil, err
  556. }
  557. for _, p := range portConfig {
  558. portConfigs = append(portConfigs, types.ServicePortConfig{
  559. Protocol: string(p.Protocol),
  560. Target: p.TargetPort,
  561. Published: p.PublishedPort,
  562. Mode: string(p.PublishMode),
  563. })
  564. }
  565. }
  566. return portConfigs, nil
  567. }
  568. func toMapStringString(value map[string]interface{}) map[string]string {
  569. output := make(map[string]string)
  570. for key, value := range value {
  571. output[key] = toString(value)
  572. }
  573. return output
  574. }
  575. func toString(value interface{}) string {
  576. if value == nil {
  577. return ""
  578. }
  579. return fmt.Sprint(value)
  580. }