loader.go 15 KB

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