configmap.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package kubectl
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "path"
  19. "strings"
  20. "k8s.io/kubernetes/pkg/api"
  21. "k8s.io/kubernetes/pkg/runtime"
  22. "k8s.io/kubernetes/pkg/util/validation"
  23. )
  24. // ConfigMapGeneratorV1 supports stable generation of a configMap.
  25. type ConfigMapGeneratorV1 struct {
  26. // Name of configMap (required)
  27. Name string
  28. // Type of configMap (optional)
  29. Type string
  30. // FileSources to derive the configMap from (optional)
  31. FileSources []string
  32. // LiteralSources to derive the configMap from (optional)
  33. LiteralSources []string
  34. }
  35. // Ensure it supports the generator pattern that uses parameter injection.
  36. var _ Generator = &ConfigMapGeneratorV1{}
  37. // Ensure it supports the generator pattern that uses parameters specified during construction.
  38. var _ StructuredGenerator = &ConfigMapGeneratorV1{}
  39. // Generate returns a configMap using the specified parameters.
  40. func (s ConfigMapGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
  41. err := ValidateParams(s.ParamNames(), genericParams)
  42. if err != nil {
  43. return nil, err
  44. }
  45. delegate := &ConfigMapGeneratorV1{}
  46. fromFileStrings, found := genericParams["from-file"]
  47. if found {
  48. fromFileArray, isArray := fromFileStrings.([]string)
  49. if !isArray {
  50. return nil, fmt.Errorf("expected []string, found :%v", fromFileStrings)
  51. }
  52. delegate.FileSources = fromFileArray
  53. delete(genericParams, "from-file")
  54. }
  55. fromLiteralStrings, found := genericParams["from-literal"]
  56. if found {
  57. fromLiteralArray, isArray := fromLiteralStrings.([]string)
  58. if !isArray {
  59. return nil, fmt.Errorf("expected []string, found :%v", fromFileStrings)
  60. }
  61. delegate.LiteralSources = fromLiteralArray
  62. delete(genericParams, "from-literal")
  63. }
  64. params := map[string]string{}
  65. for key, value := range genericParams {
  66. strVal, isString := value.(string)
  67. if !isString {
  68. return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
  69. }
  70. params[key] = strVal
  71. }
  72. delegate.Name = params["name"]
  73. delegate.Type = params["type"]
  74. return delegate.StructuredGenerate()
  75. }
  76. // ParamNames returns the set of supported input parameters when using the parameter injection generator pattern.
  77. func (s ConfigMapGeneratorV1) ParamNames() []GeneratorParam {
  78. return []GeneratorParam{
  79. {"name", true},
  80. {"type", false},
  81. {"from-file", false},
  82. {"from-literal", false},
  83. {"force", false},
  84. }
  85. }
  86. // StructuredGenerate outputs a configMap object using the configured fields.
  87. func (s ConfigMapGeneratorV1) StructuredGenerate() (runtime.Object, error) {
  88. if err := s.validate(); err != nil {
  89. return nil, err
  90. }
  91. configMap := &api.ConfigMap{}
  92. configMap.Name = s.Name
  93. configMap.Data = map[string]string{}
  94. if len(s.FileSources) > 0 {
  95. if err := handleConfigMapFromFileSources(configMap, s.FileSources); err != nil {
  96. return nil, err
  97. }
  98. }
  99. if len(s.LiteralSources) > 0 {
  100. if err := handleConfigMapFromLiteralSources(configMap, s.LiteralSources); err != nil {
  101. return nil, err
  102. }
  103. }
  104. return configMap, nil
  105. }
  106. // validate validates required fields are set to support structured generation.
  107. func (s ConfigMapGeneratorV1) validate() error {
  108. if len(s.Name) == 0 {
  109. return fmt.Errorf("name must be specified")
  110. }
  111. return nil
  112. }
  113. // handleConfigMapFromLiteralSources adds the specified literal source
  114. // information into the provided configMap.
  115. func handleConfigMapFromLiteralSources(configMap *api.ConfigMap, literalSources []string) error {
  116. for _, literalSource := range literalSources {
  117. keyName, value, err := parseLiteralSource(literalSource)
  118. if err != nil {
  119. return err
  120. }
  121. err = addKeyFromLiteralToConfigMap(configMap, keyName, value)
  122. if err != nil {
  123. return err
  124. }
  125. }
  126. return nil
  127. }
  128. // handleConfigMapFromFileSources adds the specified file source information
  129. // into the provided configMap
  130. func handleConfigMapFromFileSources(configMap *api.ConfigMap, fileSources []string) error {
  131. for _, fileSource := range fileSources {
  132. keyName, filePath, err := parseFileSource(fileSource)
  133. if err != nil {
  134. return err
  135. }
  136. info, err := os.Stat(filePath)
  137. if err != nil {
  138. switch err := err.(type) {
  139. case *os.PathError:
  140. return fmt.Errorf("error reading %s: %v", filePath, err.Err)
  141. default:
  142. return fmt.Errorf("error reading %s: %v", filePath, err)
  143. }
  144. }
  145. if info.IsDir() {
  146. if strings.Contains(fileSource, "=") {
  147. return fmt.Errorf("cannot give a key name for a directory path.")
  148. }
  149. fileList, err := ioutil.ReadDir(filePath)
  150. if err != nil {
  151. return fmt.Errorf("error listing files in %s: %v", filePath, err)
  152. }
  153. for _, item := range fileList {
  154. itemPath := path.Join(filePath, item.Name())
  155. if item.Mode().IsRegular() {
  156. keyName = item.Name()
  157. err = addKeyFromFileToConfigMap(configMap, keyName, itemPath)
  158. if err != nil {
  159. return err
  160. }
  161. }
  162. }
  163. } else {
  164. err = addKeyFromFileToConfigMap(configMap, keyName, filePath)
  165. if err != nil {
  166. return err
  167. }
  168. }
  169. }
  170. return nil
  171. }
  172. // addKeyFromFileToConfigMap adds a key with the given name to a ConfigMap, populating
  173. // the value with the content of the given file path, or returns an error.
  174. func addKeyFromFileToConfigMap(configMap *api.ConfigMap, keyName, filePath string) error {
  175. data, err := ioutil.ReadFile(filePath)
  176. if err != nil {
  177. return err
  178. }
  179. return addKeyFromLiteralToConfigMap(configMap, keyName, string(data))
  180. }
  181. // addKeyFromLiteralToConfigMap adds the given key and data to the given config map,
  182. // returning an error if the key is not valid or if the key already exists.
  183. func addKeyFromLiteralToConfigMap(configMap *api.ConfigMap, keyName, data string) error {
  184. // Note, the rules for ConfigMap keys are the exact same as the ones for SecretKeys.
  185. if errs := validation.IsConfigMapKey(keyName); len(errs) != 0 {
  186. return fmt.Errorf("%q is not a valid key name for a ConfigMap: %s", keyName, strings.Join(errs, ";"))
  187. }
  188. if _, entryExists := configMap.Data[keyName]; entryExists {
  189. return fmt.Errorf("cannot add key %s, another key by that name already exists: %v.", keyName, configMap.Data)
  190. }
  191. configMap.Data[keyName] = data
  192. return nil
  193. }