loader.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. // LoadServices produces a ServiceConfig map from a compose file Dict
  268. // the servicesDict is not validated if directly used. Use Load() to enable validation
  269. func LoadServices(servicesDict types.Dict, workingDir string) ([]types.ServiceConfig, error) {
  270. var services []types.ServiceConfig
  271. for name, serviceDef := range servicesDict {
  272. serviceConfig, err := LoadService(name, serviceDef.(types.Dict), workingDir)
  273. if err != nil {
  274. return nil, err
  275. }
  276. services = append(services, *serviceConfig)
  277. }
  278. return services, nil
  279. }
  280. // LoadService produces a single ServiceConfig from a compose file Dict
  281. // the serviceDict is not validated if directly used. Use Load() to enable validation
  282. func LoadService(name string, serviceDict types.Dict, workingDir string) (*types.ServiceConfig, error) {
  283. serviceConfig := &types.ServiceConfig{}
  284. if err := transform(serviceDict, serviceConfig); err != nil {
  285. return nil, err
  286. }
  287. serviceConfig.Name = name
  288. if err := resolveEnvironment(serviceConfig, workingDir); err != nil {
  289. return nil, err
  290. }
  291. if err := resolveVolumePaths(serviceConfig.Volumes, workingDir); err != nil {
  292. return nil, err
  293. }
  294. return serviceConfig, nil
  295. }
  296. func resolveEnvironment(serviceConfig *types.ServiceConfig, workingDir string) error {
  297. environment := make(map[string]string)
  298. if len(serviceConfig.EnvFile) > 0 {
  299. var envVars []string
  300. for _, file := range serviceConfig.EnvFile {
  301. filePath := absPath(workingDir, file)
  302. fileVars, err := runconfigopts.ParseEnvFile(filePath)
  303. if err != nil {
  304. return err
  305. }
  306. envVars = append(envVars, fileVars...)
  307. }
  308. for k, v := range runconfigopts.ConvertKVStringsToMap(envVars) {
  309. environment[k] = v
  310. }
  311. }
  312. for k, v := range serviceConfig.Environment {
  313. environment[k] = v
  314. }
  315. serviceConfig.Environment = environment
  316. return nil
  317. }
  318. func resolveVolumePaths(volumes []string, workingDir string) error {
  319. for i, mapping := range volumes {
  320. parts := strings.SplitN(mapping, ":", 2)
  321. if len(parts) == 1 {
  322. continue
  323. }
  324. if strings.HasPrefix(parts[0], ".") {
  325. parts[0] = absPath(workingDir, parts[0])
  326. }
  327. parts[0] = expandUser(parts[0])
  328. volumes[i] = strings.Join(parts, ":")
  329. }
  330. return nil
  331. }
  332. // TODO: make this more robust
  333. func expandUser(path string) string {
  334. if strings.HasPrefix(path, "~") {
  335. return strings.Replace(path, "~", os.Getenv("HOME"), 1)
  336. }
  337. return path
  338. }
  339. func transformUlimits(data interface{}) (interface{}, error) {
  340. switch value := data.(type) {
  341. case int:
  342. return types.UlimitsConfig{Single: value}, nil
  343. case types.Dict:
  344. ulimit := types.UlimitsConfig{}
  345. ulimit.Soft = value["soft"].(int)
  346. ulimit.Hard = value["hard"].(int)
  347. return ulimit, nil
  348. default:
  349. return data, fmt.Errorf("invalid type %T for ulimits", value)
  350. }
  351. }
  352. // LoadNetworks produces a NetworkConfig map from a compose file Dict
  353. // the source Dict is not validated if directly used. Use Load() to enable validation
  354. func LoadNetworks(source types.Dict) (map[string]types.NetworkConfig, error) {
  355. networks := make(map[string]types.NetworkConfig)
  356. err := transform(source, &networks)
  357. if err != nil {
  358. return networks, err
  359. }
  360. for name, network := range networks {
  361. if network.External.External && network.External.Name == "" {
  362. network.External.Name = name
  363. networks[name] = network
  364. }
  365. }
  366. return networks, nil
  367. }
  368. // LoadVolumes produces a VolumeConfig map from a compose file Dict
  369. // the source Dict is not validated if directly used. Use Load() to enable validation
  370. func LoadVolumes(source types.Dict) (map[string]types.VolumeConfig, error) {
  371. volumes := make(map[string]types.VolumeConfig)
  372. err := transform(source, &volumes)
  373. if err != nil {
  374. return volumes, err
  375. }
  376. for name, volume := range volumes {
  377. if volume.External.External && volume.External.Name == "" {
  378. volume.External.Name = name
  379. volumes[name] = volume
  380. }
  381. }
  382. return volumes, nil
  383. }
  384. // LoadSecrets produces a SecretConfig map from a compose file Dict
  385. // the source Dict is not validated if directly used. Use Load() to enable validation
  386. func LoadSecrets(source types.Dict, workingDir string) (map[string]types.SecretConfig, error) {
  387. secrets := make(map[string]types.SecretConfig)
  388. if err := transform(source, &secrets); err != nil {
  389. return secrets, err
  390. }
  391. for name, secret := range secrets {
  392. if secret.External.External && secret.External.Name == "" {
  393. secret.External.Name = name
  394. secrets[name] = secret
  395. }
  396. if secret.File != "" {
  397. secret.File = absPath(workingDir, secret.File)
  398. }
  399. }
  400. return secrets, nil
  401. }
  402. func absPath(workingDir string, filepath string) string {
  403. if path.IsAbs(filepath) {
  404. return filepath
  405. }
  406. return path.Join(workingDir, filepath)
  407. }
  408. func transformMapStringString(data interface{}) (interface{}, error) {
  409. switch value := data.(type) {
  410. case map[string]interface{}:
  411. return toMapStringString(value), nil
  412. case types.Dict:
  413. return toMapStringString(value), nil
  414. case map[string]string:
  415. return value, nil
  416. default:
  417. return data, fmt.Errorf("invalid type %T for map[string]string", value)
  418. }
  419. }
  420. func transformExternal(data interface{}) (interface{}, error) {
  421. switch value := data.(type) {
  422. case bool:
  423. return map[string]interface{}{"external": value}, nil
  424. case types.Dict:
  425. return map[string]interface{}{"external": true, "name": value["name"]}, nil
  426. case map[string]interface{}:
  427. return map[string]interface{}{"external": true, "name": value["name"]}, nil
  428. default:
  429. return data, fmt.Errorf("invalid type %T for external", value)
  430. }
  431. }
  432. func transformServicePort(data interface{}) (interface{}, error) {
  433. switch entries := data.(type) {
  434. case []interface{}:
  435. // We process the list instead of individual items here.
  436. // The reason is that one entry might be mapped to multiple ServicePortConfig.
  437. // Therefore we take an input of a list and return an output of a list.
  438. ports := []interface{}{}
  439. for _, entry := range entries {
  440. switch value := entry.(type) {
  441. case int:
  442. v, err := toServicePortConfigs(fmt.Sprint(value))
  443. if err != nil {
  444. return data, err
  445. }
  446. ports = append(ports, v...)
  447. case string:
  448. v, err := toServicePortConfigs(value)
  449. if err != nil {
  450. return data, err
  451. }
  452. ports = append(ports, v...)
  453. case types.Dict:
  454. ports = append(ports, value)
  455. case map[string]interface{}:
  456. ports = append(ports, value)
  457. default:
  458. return data, fmt.Errorf("invalid type %T for port", value)
  459. }
  460. }
  461. return ports, nil
  462. default:
  463. return data, fmt.Errorf("invalid type %T for port", entries)
  464. }
  465. }
  466. func transformServiceSecret(data interface{}) (interface{}, error) {
  467. switch value := data.(type) {
  468. case string:
  469. return map[string]interface{}{"source": value}, nil
  470. case types.Dict:
  471. return data, nil
  472. case map[string]interface{}:
  473. return data, nil
  474. default:
  475. return data, fmt.Errorf("invalid type %T for external", value)
  476. }
  477. }
  478. func transformServiceNetworkMap(value interface{}) (interface{}, error) {
  479. if list, ok := value.([]interface{}); ok {
  480. mapValue := map[interface{}]interface{}{}
  481. for _, name := range list {
  482. mapValue[name] = nil
  483. }
  484. return mapValue, nil
  485. }
  486. return value, nil
  487. }
  488. func transformStringOrNumberList(value interface{}) (interface{}, error) {
  489. list := value.([]interface{})
  490. result := make([]string, len(list))
  491. for i, item := range list {
  492. result[i] = fmt.Sprint(item)
  493. }
  494. return result, nil
  495. }
  496. func transformStringList(data interface{}) (interface{}, error) {
  497. switch value := data.(type) {
  498. case string:
  499. return []string{value}, nil
  500. case []interface{}:
  501. return value, nil
  502. default:
  503. return data, fmt.Errorf("invalid type %T for string list", value)
  504. }
  505. }
  506. func transformMappingOrList(mappingOrList interface{}, sep string) map[string]string {
  507. if mapping, ok := mappingOrList.(types.Dict); ok {
  508. return toMapStringString(mapping)
  509. }
  510. if list, ok := mappingOrList.([]interface{}); ok {
  511. result := make(map[string]string)
  512. for _, value := range list {
  513. parts := strings.SplitN(value.(string), sep, 2)
  514. if len(parts) == 1 {
  515. result[parts[0]] = ""
  516. } else {
  517. result[parts[0]] = parts[1]
  518. }
  519. }
  520. return result
  521. }
  522. panic(fmt.Errorf("expected a map or a slice, got: %#v", mappingOrList))
  523. }
  524. func transformShellCommand(value interface{}) (interface{}, error) {
  525. if str, ok := value.(string); ok {
  526. return shellwords.Parse(str)
  527. }
  528. return value, nil
  529. }
  530. func transformHealthCheckTest(data interface{}) (interface{}, error) {
  531. switch value := data.(type) {
  532. case string:
  533. return append([]string{"CMD-SHELL"}, value), nil
  534. case []interface{}:
  535. return value, nil
  536. default:
  537. return value, fmt.Errorf("invalid type %T for healthcheck.test", value)
  538. }
  539. }
  540. func transformSize(value interface{}) (int64, error) {
  541. switch value := value.(type) {
  542. case int:
  543. return int64(value), nil
  544. case string:
  545. return units.RAMInBytes(value)
  546. }
  547. panic(fmt.Errorf("invalid type for size %T", value))
  548. }
  549. func toServicePortConfigs(value string) ([]interface{}, error) {
  550. var portConfigs []interface{}
  551. ports, portBindings, err := nat.ParsePortSpecs([]string{value})
  552. if err != nil {
  553. return nil, err
  554. }
  555. // We need to sort the key of the ports to make sure it is consistent
  556. keys := []string{}
  557. for port := range ports {
  558. keys = append(keys, string(port))
  559. }
  560. sort.Strings(keys)
  561. for _, key := range keys {
  562. // Reuse ConvertPortToPortConfig so that it is consistent
  563. portConfig, err := opts.ConvertPortToPortConfig(nat.Port(key), portBindings)
  564. if err != nil {
  565. return nil, err
  566. }
  567. for _, p := range portConfig {
  568. portConfigs = append(portConfigs, types.ServicePortConfig{
  569. Protocol: string(p.Protocol),
  570. Target: p.TargetPort,
  571. Published: p.PublishedPort,
  572. Mode: string(p.PublishMode),
  573. })
  574. }
  575. }
  576. return portConfigs, nil
  577. }
  578. func toMapStringString(value map[string]interface{}) map[string]string {
  579. output := make(map[string]string)
  580. for key, value := range value {
  581. output[key] = toString(value)
  582. }
  583. return output
  584. }
  585. func toString(value interface{}) string {
  586. if value == nil {
  587. return ""
  588. }
  589. return fmt.Sprint(value)
  590. }