loader.go 15 KB

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