loader.go 20 KB

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