loader.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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) (map[string]interface{}, 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.(map[string]interface{}), 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.(map[string]interface{}); 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.(map[string]interface{}), "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.(map[string]interface{}), "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.(map[string]interface{}), "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.(map[string]interface{}), "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.(map[string]interface{})
  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 map[string]interface{}, propertyMap map[string]string) map[string]string {
  141. output := map[string]string{}
  142. for _, service := range services {
  143. if serviceDict, ok := service.(map[string]interface{}); 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) map[string]interface{} {
  163. return configDetails.ConfigFiles[0].Config
  164. }
  165. func getServices(configDict map[string]interface{}) map[string]interface{} {
  166. if services, ok := configDict["services"]; ok {
  167. if servicesDict, ok := services.(map[string]interface{}); ok {
  168. return servicesDict
  169. }
  170. }
  171. return map[string]interface{}{}
  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. func convertToStringKeysRecursive(value interface{}, keyPrefix string) (interface{}, error) {
  231. if mapping, ok := value.(map[interface{}]interface{}); ok {
  232. dict := make(map[string]interface{})
  233. for key, entry := range mapping {
  234. str, ok := key.(string)
  235. if !ok {
  236. return nil, formatInvalidKeyError(keyPrefix, key)
  237. }
  238. var newKeyPrefix string
  239. if keyPrefix == "" {
  240. newKeyPrefix = str
  241. } else {
  242. newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, str)
  243. }
  244. convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix)
  245. if err != nil {
  246. return nil, err
  247. }
  248. dict[str] = convertedEntry
  249. }
  250. return dict, nil
  251. }
  252. if list, ok := value.([]interface{}); ok {
  253. var convertedList []interface{}
  254. for index, entry := range list {
  255. newKeyPrefix := fmt.Sprintf("%s[%d]", keyPrefix, index)
  256. convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix)
  257. if err != nil {
  258. return nil, err
  259. }
  260. convertedList = append(convertedList, convertedEntry)
  261. }
  262. return convertedList, nil
  263. }
  264. return value, nil
  265. }
  266. func formatInvalidKeyError(keyPrefix string, key interface{}) error {
  267. var location string
  268. if keyPrefix == "" {
  269. location = "at top level"
  270. } else {
  271. location = fmt.Sprintf("in %s", keyPrefix)
  272. }
  273. return fmt.Errorf("Non-string key %s: %#v", location, key)
  274. }
  275. // LoadServices produces a ServiceConfig map from a compose file Dict
  276. // the servicesDict is not validated if directly used. Use Load() to enable validation
  277. func LoadServices(servicesDict map[string]interface{}, workingDir string, lookupEnv template.Mapping) ([]types.ServiceConfig, error) {
  278. var services []types.ServiceConfig
  279. for name, serviceDef := range servicesDict {
  280. serviceConfig, err := LoadService(name, serviceDef.(map[string]interface{}), workingDir, lookupEnv)
  281. if err != nil {
  282. return nil, err
  283. }
  284. services = append(services, *serviceConfig)
  285. }
  286. return services, nil
  287. }
  288. // LoadService produces a single ServiceConfig from a compose file Dict
  289. // the serviceDict is not validated if directly used. Use Load() to enable validation
  290. func LoadService(name string, serviceDict map[string]interface{}, workingDir string, lookupEnv template.Mapping) (*types.ServiceConfig, error) {
  291. serviceConfig := &types.ServiceConfig{}
  292. if err := transform(serviceDict, serviceConfig); err != nil {
  293. return nil, err
  294. }
  295. serviceConfig.Name = name
  296. if err := resolveEnvironment(serviceConfig, workingDir, lookupEnv); err != nil {
  297. return nil, err
  298. }
  299. resolveVolumePaths(serviceConfig.Volumes, workingDir, lookupEnv)
  300. return serviceConfig, nil
  301. }
  302. func updateEnvironment(environment map[string]*string, vars map[string]*string, lookupEnv template.Mapping) {
  303. for k, v := range vars {
  304. interpolatedV, ok := lookupEnv(k)
  305. if (v == nil || *v == "") && ok {
  306. // lookupEnv is prioritized over vars
  307. environment[k] = &interpolatedV
  308. } else {
  309. environment[k] = v
  310. }
  311. }
  312. }
  313. func resolveEnvironment(serviceConfig *types.ServiceConfig, workingDir string, lookupEnv template.Mapping) error {
  314. environment := make(map[string]*string)
  315. if len(serviceConfig.EnvFile) > 0 {
  316. var envVars []string
  317. for _, file := range serviceConfig.EnvFile {
  318. filePath := absPath(workingDir, file)
  319. fileVars, err := runconfigopts.ParseEnvFile(filePath)
  320. if err != nil {
  321. return err
  322. }
  323. envVars = append(envVars, fileVars...)
  324. }
  325. updateEnvironment(environment,
  326. runconfigopts.ConvertKVStringsToMapWithNil(envVars), lookupEnv)
  327. }
  328. updateEnvironment(environment, serviceConfig.Environment, lookupEnv)
  329. serviceConfig.Environment = environment
  330. return nil
  331. }
  332. func resolveVolumePaths(volumes []types.ServiceVolumeConfig, workingDir string, lookupEnv template.Mapping) {
  333. for i, volume := range volumes {
  334. if volume.Type != "bind" {
  335. continue
  336. }
  337. volume.Source = absPath(workingDir, expandUser(volume.Source, lookupEnv))
  338. volumes[i] = volume
  339. }
  340. }
  341. // TODO: make this more robust
  342. func expandUser(path string, lookupEnv template.Mapping) string {
  343. if strings.HasPrefix(path, "~") {
  344. home, ok := lookupEnv("HOME")
  345. if !ok {
  346. logrus.Warn("cannot expand '~', because the environment lacks HOME")
  347. return path
  348. }
  349. return strings.Replace(path, "~", home, 1)
  350. }
  351. return path
  352. }
  353. func transformUlimits(data interface{}) (interface{}, error) {
  354. switch value := data.(type) {
  355. case int:
  356. return types.UlimitsConfig{Single: value}, nil
  357. case map[string]interface{}:
  358. ulimit := types.UlimitsConfig{}
  359. ulimit.Soft = value["soft"].(int)
  360. ulimit.Hard = value["hard"].(int)
  361. return ulimit, nil
  362. default:
  363. return data, fmt.Errorf("invalid type %T for ulimits", value)
  364. }
  365. }
  366. // LoadNetworks produces a NetworkConfig map from a compose file Dict
  367. // the source Dict is not validated if directly used. Use Load() to enable validation
  368. func LoadNetworks(source map[string]interface{}) (map[string]types.NetworkConfig, error) {
  369. networks := make(map[string]types.NetworkConfig)
  370. err := transform(source, &networks)
  371. if err != nil {
  372. return networks, err
  373. }
  374. for name, network := range networks {
  375. if network.External.External && network.External.Name == "" {
  376. network.External.Name = name
  377. networks[name] = network
  378. }
  379. }
  380. return networks, nil
  381. }
  382. // LoadVolumes produces a VolumeConfig map from a compose file Dict
  383. // the source Dict is not validated if directly used. Use Load() to enable validation
  384. func LoadVolumes(source map[string]interface{}) (map[string]types.VolumeConfig, error) {
  385. volumes := make(map[string]types.VolumeConfig)
  386. err := transform(source, &volumes)
  387. if err != nil {
  388. return volumes, err
  389. }
  390. for name, volume := range volumes {
  391. if volume.External.External {
  392. template := "conflicting parameters \"external\" and %q specified for volume %q"
  393. if volume.Driver != "" {
  394. return nil, fmt.Errorf(template, "driver", name)
  395. }
  396. if len(volume.DriverOpts) > 0 {
  397. return nil, fmt.Errorf(template, "driver_opts", name)
  398. }
  399. if len(volume.Labels) > 0 {
  400. return nil, fmt.Errorf(template, "labels", name)
  401. }
  402. if volume.External.Name == "" {
  403. volume.External.Name = name
  404. volumes[name] = volume
  405. }
  406. }
  407. }
  408. return volumes, nil
  409. }
  410. // LoadSecrets produces a SecretConfig map from a compose file Dict
  411. // the source Dict is not validated if directly used. Use Load() to enable validation
  412. func LoadSecrets(source map[string]interface{}, workingDir string) (map[string]types.SecretConfig, error) {
  413. secrets := make(map[string]types.SecretConfig)
  414. if err := transform(source, &secrets); err != nil {
  415. return secrets, err
  416. }
  417. for name, secret := range secrets {
  418. if secret.External.External && secret.External.Name == "" {
  419. secret.External.Name = name
  420. secrets[name] = secret
  421. }
  422. if secret.File != "" {
  423. secret.File = absPath(workingDir, secret.File)
  424. }
  425. }
  426. return secrets, nil
  427. }
  428. func absPath(workingDir string, filepath string) string {
  429. if path.IsAbs(filepath) {
  430. return filepath
  431. }
  432. return path.Join(workingDir, filepath)
  433. }
  434. func transformMapStringString(data interface{}) (interface{}, error) {
  435. switch value := data.(type) {
  436. case map[string]interface{}:
  437. return toMapStringString(value, false), nil
  438. case map[string]string:
  439. return value, nil
  440. default:
  441. return data, fmt.Errorf("invalid type %T for map[string]string", value)
  442. }
  443. }
  444. func transformExternal(data interface{}) (interface{}, error) {
  445. switch value := data.(type) {
  446. case bool:
  447. return map[string]interface{}{"external": value}, nil
  448. case map[string]interface{}:
  449. return map[string]interface{}{"external": true, "name": value["name"]}, nil
  450. default:
  451. return data, fmt.Errorf("invalid type %T for external", value)
  452. }
  453. }
  454. func transformServicePort(data interface{}) (interface{}, error) {
  455. switch entries := data.(type) {
  456. case []interface{}:
  457. // We process the list instead of individual items here.
  458. // The reason is that one entry might be mapped to multiple ServicePortConfig.
  459. // Therefore we take an input of a list and return an output of a list.
  460. ports := []interface{}{}
  461. for _, entry := range entries {
  462. switch value := entry.(type) {
  463. case int:
  464. v, err := toServicePortConfigs(fmt.Sprint(value))
  465. if err != nil {
  466. return data, err
  467. }
  468. ports = append(ports, v...)
  469. case string:
  470. v, err := toServicePortConfigs(value)
  471. if err != nil {
  472. return data, err
  473. }
  474. ports = append(ports, v...)
  475. case map[string]interface{}:
  476. ports = append(ports, value)
  477. default:
  478. return data, fmt.Errorf("invalid type %T for port", value)
  479. }
  480. }
  481. return ports, nil
  482. default:
  483. return data, fmt.Errorf("invalid type %T for port", entries)
  484. }
  485. }
  486. func transformServiceSecret(data interface{}) (interface{}, error) {
  487. switch value := data.(type) {
  488. case string:
  489. return map[string]interface{}{"source": value}, nil
  490. case map[string]interface{}:
  491. return data, nil
  492. default:
  493. return data, fmt.Errorf("invalid type %T for secret", value)
  494. }
  495. }
  496. func transformServiceVolumeConfig(data interface{}) (interface{}, error) {
  497. switch value := data.(type) {
  498. case string:
  499. return parseVolume(value)
  500. case map[string]interface{}:
  501. return data, nil
  502. default:
  503. return data, fmt.Errorf("invalid type %T for service volume", value)
  504. }
  505. }
  506. func transformServiceNetworkMap(value interface{}) (interface{}, error) {
  507. if list, ok := value.([]interface{}); ok {
  508. mapValue := map[interface{}]interface{}{}
  509. for _, name := range list {
  510. mapValue[name] = nil
  511. }
  512. return mapValue, nil
  513. }
  514. return value, nil
  515. }
  516. func transformStringOrNumberList(value interface{}) (interface{}, error) {
  517. list := value.([]interface{})
  518. result := make([]string, len(list))
  519. for i, item := range list {
  520. result[i] = fmt.Sprint(item)
  521. }
  522. return result, nil
  523. }
  524. func transformStringList(data interface{}) (interface{}, error) {
  525. switch value := data.(type) {
  526. case string:
  527. return []string{value}, nil
  528. case []interface{}:
  529. return value, nil
  530. default:
  531. return data, fmt.Errorf("invalid type %T for string list", value)
  532. }
  533. }
  534. func transformMappingOrList(mappingOrList interface{}, sep string, allowNil bool) interface{} {
  535. switch value := mappingOrList.(type) {
  536. case map[string]interface{}:
  537. return toMapStringString(value, allowNil)
  538. case ([]interface{}):
  539. result := make(map[string]interface{})
  540. for _, value := range value {
  541. parts := strings.SplitN(value.(string), sep, 2)
  542. key := parts[0]
  543. switch {
  544. case len(parts) == 1 && allowNil:
  545. result[key] = nil
  546. case len(parts) == 1 && !allowNil:
  547. result[key] = ""
  548. default:
  549. result[key] = parts[1]
  550. }
  551. }
  552. return result
  553. }
  554. panic(fmt.Errorf("expected a map or a list, got %T: %#v", mappingOrList, mappingOrList))
  555. }
  556. func transformShellCommand(value interface{}) (interface{}, error) {
  557. if str, ok := value.(string); ok {
  558. return shellwords.Parse(str)
  559. }
  560. return value, nil
  561. }
  562. func transformHealthCheckTest(data interface{}) (interface{}, error) {
  563. switch value := data.(type) {
  564. case string:
  565. return append([]string{"CMD-SHELL"}, value), nil
  566. case []interface{}:
  567. return value, nil
  568. default:
  569. return value, fmt.Errorf("invalid type %T for healthcheck.test", value)
  570. }
  571. }
  572. func transformSize(value interface{}) (int64, error) {
  573. switch value := value.(type) {
  574. case int:
  575. return int64(value), nil
  576. case string:
  577. return units.RAMInBytes(value)
  578. }
  579. panic(fmt.Errorf("invalid type for size %T", value))
  580. }
  581. func toServicePortConfigs(value string) ([]interface{}, error) {
  582. var portConfigs []interface{}
  583. ports, portBindings, err := nat.ParsePortSpecs([]string{value})
  584. if err != nil {
  585. return nil, err
  586. }
  587. // We need to sort the key of the ports to make sure it is consistent
  588. keys := []string{}
  589. for port := range ports {
  590. keys = append(keys, string(port))
  591. }
  592. sort.Strings(keys)
  593. for _, key := range keys {
  594. // Reuse ConvertPortToPortConfig so that it is consistent
  595. portConfig, err := opts.ConvertPortToPortConfig(nat.Port(key), portBindings)
  596. if err != nil {
  597. return nil, err
  598. }
  599. for _, p := range portConfig {
  600. portConfigs = append(portConfigs, types.ServicePortConfig{
  601. Protocol: string(p.Protocol),
  602. Target: p.TargetPort,
  603. Published: p.PublishedPort,
  604. Mode: string(p.PublishMode),
  605. })
  606. }
  607. }
  608. return portConfigs, nil
  609. }
  610. func toMapStringString(value map[string]interface{}, allowNil bool) map[string]interface{} {
  611. output := make(map[string]interface{})
  612. for key, value := range value {
  613. output[key] = toString(value, allowNil)
  614. }
  615. return output
  616. }
  617. func toString(value interface{}, allowNil bool) interface{} {
  618. switch {
  619. case value != nil:
  620. return fmt.Sprint(value)
  621. case allowNil:
  622. return nil
  623. default:
  624. return ""
  625. }
  626. }