loader.go 16 KB

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