set.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /*
  2. Copyright 2014 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 config
  14. import (
  15. "encoding/base64"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "reflect"
  20. "strings"
  21. "github.com/renstrom/dedent"
  22. "github.com/spf13/cobra"
  23. "k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
  24. "k8s.io/kubernetes/pkg/util/flag"
  25. )
  26. const (
  27. cannotHaveStepsAfterError = "Cannot have steps after %v. %v are remaining"
  28. additionStepRequiredUnlessUnsettingError = "Must have additional steps after %v unless you are unsetting it"
  29. )
  30. type setOptions struct {
  31. configAccess clientcmd.ConfigAccess
  32. propertyName string
  33. propertyValue string
  34. setRawBytes flag.Tristate
  35. }
  36. var set_long = dedent.Dedent(`
  37. Sets an individual value in a kubeconfig file
  38. PROPERTY_NAME is a dot delimited name where each token represents either an attribute name or a map key. Map keys may not contain dots.
  39. PROPERTY_VALUE is the new value you wish to set. Binary fields such as 'certificate-authority-data' expect a base64 encoded string unless the --set-raw-bytes flag is used.`)
  40. func NewCmdConfigSet(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
  41. options := &setOptions{configAccess: configAccess}
  42. cmd := &cobra.Command{
  43. Use: "set PROPERTY_NAME PROPERTY_VALUE",
  44. Short: "Sets an individual value in a kubeconfig file",
  45. Long: set_long,
  46. Run: func(cmd *cobra.Command, args []string) {
  47. if !options.complete(cmd) {
  48. return
  49. }
  50. err := options.run()
  51. if err != nil {
  52. fmt.Fprintf(out, "%v\n", err)
  53. } else {
  54. fmt.Fprintf(out, "property %q set.\n", options.propertyName)
  55. }
  56. },
  57. }
  58. f := cmd.Flags().VarPF(&options.setRawBytes, "set-raw-bytes", "", "When writing a []byte PROPERTY_VALUE, write the given string directly without base64 decoding.")
  59. f.NoOptDefVal = "true"
  60. return cmd
  61. }
  62. func (o setOptions) run() error {
  63. err := o.validate()
  64. if err != nil {
  65. return err
  66. }
  67. config, err := o.configAccess.GetStartingConfig()
  68. if err != nil {
  69. return err
  70. }
  71. steps, err := newNavigationSteps(o.propertyName)
  72. if err != nil {
  73. return err
  74. }
  75. setRawBytes := false
  76. if o.setRawBytes.Provided() {
  77. setRawBytes = o.setRawBytes.Value()
  78. }
  79. err = modifyConfig(reflect.ValueOf(config), steps, o.propertyValue, false, setRawBytes)
  80. if err != nil {
  81. return err
  82. }
  83. if err := clientcmd.ModifyConfig(o.configAccess, *config, false); err != nil {
  84. return err
  85. }
  86. return nil
  87. }
  88. func (o *setOptions) complete(cmd *cobra.Command) bool {
  89. endingArgs := cmd.Flags().Args()
  90. if len(endingArgs) != 2 {
  91. cmd.Help()
  92. return false
  93. }
  94. o.propertyValue = endingArgs[1]
  95. o.propertyName = endingArgs[0]
  96. return true
  97. }
  98. func (o setOptions) validate() error {
  99. if len(o.propertyValue) == 0 {
  100. return errors.New("you cannot use set to unset a property")
  101. }
  102. if len(o.propertyName) == 0 {
  103. return errors.New("you must specify a property")
  104. }
  105. return nil
  106. }
  107. func modifyConfig(curr reflect.Value, steps *navigationSteps, propertyValue string, unset bool, setRawBytes bool) error {
  108. currStep := steps.pop()
  109. actualCurrValue := curr
  110. if curr.Kind() == reflect.Ptr {
  111. actualCurrValue = curr.Elem()
  112. }
  113. switch actualCurrValue.Kind() {
  114. case reflect.Map:
  115. if !steps.moreStepsRemaining() && !unset {
  116. return fmt.Errorf("can't set a map to a value: %v", actualCurrValue)
  117. }
  118. mapKey := reflect.ValueOf(currStep.stepValue)
  119. mapValueType := curr.Type().Elem().Elem()
  120. if !steps.moreStepsRemaining() && unset {
  121. actualCurrValue.SetMapIndex(mapKey, reflect.Value{})
  122. return nil
  123. }
  124. currMapValue := actualCurrValue.MapIndex(mapKey)
  125. needToSetNewMapValue := currMapValue.Kind() == reflect.Invalid
  126. if needToSetNewMapValue {
  127. currMapValue = reflect.New(mapValueType.Elem()).Elem().Addr()
  128. actualCurrValue.SetMapIndex(mapKey, currMapValue)
  129. }
  130. err := modifyConfig(currMapValue, steps, propertyValue, unset, setRawBytes)
  131. if err != nil {
  132. return err
  133. }
  134. return nil
  135. case reflect.String:
  136. if steps.moreStepsRemaining() {
  137. return fmt.Errorf("can't have more steps after a string. %v", steps)
  138. }
  139. actualCurrValue.SetString(propertyValue)
  140. return nil
  141. case reflect.Slice:
  142. if steps.moreStepsRemaining() {
  143. return fmt.Errorf("can't have more steps after bytes. %v", steps)
  144. }
  145. innerKind := actualCurrValue.Type().Elem().Kind()
  146. if innerKind != reflect.Uint8 {
  147. return fmt.Errorf("unrecognized slice type. %v", innerKind)
  148. }
  149. if unset {
  150. actualCurrValue.Set(reflect.Zero(actualCurrValue.Type()))
  151. return nil
  152. }
  153. if setRawBytes {
  154. actualCurrValue.SetBytes([]byte(propertyValue))
  155. } else {
  156. val, err := base64.StdEncoding.DecodeString(propertyValue)
  157. if err != nil {
  158. return fmt.Errorf("error decoding input value: %v", err)
  159. }
  160. actualCurrValue.SetBytes(val)
  161. }
  162. return nil
  163. case reflect.Bool:
  164. if steps.moreStepsRemaining() {
  165. return fmt.Errorf("can't have more steps after a bool. %v", steps)
  166. }
  167. boolValue, err := toBool(propertyValue)
  168. if err != nil {
  169. return err
  170. }
  171. actualCurrValue.SetBool(boolValue)
  172. return nil
  173. case reflect.Struct:
  174. for fieldIndex := 0; fieldIndex < actualCurrValue.NumField(); fieldIndex++ {
  175. currFieldValue := actualCurrValue.Field(fieldIndex)
  176. currFieldType := actualCurrValue.Type().Field(fieldIndex)
  177. currYamlTag := currFieldType.Tag.Get("json")
  178. currFieldTypeYamlName := strings.Split(currYamlTag, ",")[0]
  179. if currFieldTypeYamlName == currStep.stepValue {
  180. thisMapHasNoValue := (currFieldValue.Kind() == reflect.Map && currFieldValue.IsNil())
  181. if thisMapHasNoValue {
  182. newValue := reflect.MakeMap(currFieldValue.Type())
  183. currFieldValue.Set(newValue)
  184. if !steps.moreStepsRemaining() && unset {
  185. return nil
  186. }
  187. }
  188. if !steps.moreStepsRemaining() && unset {
  189. // if we're supposed to unset the value or if the value is a map that doesn't exist, create a new value and overwrite
  190. newValue := reflect.New(currFieldValue.Type()).Elem()
  191. currFieldValue.Set(newValue)
  192. return nil
  193. }
  194. return modifyConfig(currFieldValue.Addr(), steps, propertyValue, unset, setRawBytes)
  195. }
  196. }
  197. return fmt.Errorf("unable to locate path %#v under %v", currStep, actualCurrValue)
  198. }
  199. panic(fmt.Errorf("unrecognized type: %v", actualCurrValue))
  200. }