convert.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 convert
  14. import (
  15. "fmt"
  16. "github.com/spf13/cobra"
  17. "k8s.io/klog"
  18. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. "k8s.io/apimachinery/pkg/runtime/schema"
  21. "k8s.io/cli-runtime/pkg/genericclioptions"
  22. "k8s.io/cli-runtime/pkg/printers"
  23. "k8s.io/cli-runtime/pkg/resource"
  24. scheme "k8s.io/kubernetes/pkg/api/legacyscheme"
  25. api "k8s.io/kubernetes/pkg/apis/core"
  26. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  27. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  28. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  29. "k8s.io/kubernetes/pkg/kubectl/validation"
  30. )
  31. var (
  32. convertLong = templates.LongDesc(i18n.T(`
  33. Convert config files between different API versions. Both YAML
  34. and JSON formats are accepted.
  35. The command takes filename, directory, or URL as input, and convert it into format
  36. of version specified by --output-version flag. If target version is not specified or
  37. not supported, convert to latest version.
  38. The default output will be printed to stdout in YAML format. One can use -o option
  39. to change to output destination.`))
  40. convertExample = templates.Examples(i18n.T(`
  41. # Convert 'pod.yaml' to latest version and print to stdout.
  42. kubectl convert -f pod.yaml
  43. # Convert the live state of the resource specified by 'pod.yaml' to the latest version
  44. # and print to stdout in JSON format.
  45. kubectl convert -f pod.yaml --local -o json
  46. # Convert all files under current directory to latest version and create them all.
  47. kubectl convert -f . | kubectl create -f -`))
  48. )
  49. // ConvertOptions have the data required to perform the convert operation
  50. type ConvertOptions struct {
  51. PrintFlags *genericclioptions.PrintFlags
  52. Printer printers.ResourcePrinter
  53. OutputVersion string
  54. Namespace string
  55. builder func() *resource.Builder
  56. local bool
  57. validator func() (validation.Schema, error)
  58. resource.FilenameOptions
  59. genericclioptions.IOStreams
  60. }
  61. func NewConvertOptions(ioStreams genericclioptions.IOStreams) *ConvertOptions {
  62. return &ConvertOptions{
  63. PrintFlags: genericclioptions.NewPrintFlags("converted").WithTypeSetter(scheme.Scheme).WithDefaultOutput("yaml"),
  64. local: true,
  65. IOStreams: ioStreams,
  66. }
  67. }
  68. // NewCmdConvert creates a command object for the generic "convert" action, which
  69. // translates the config file into a given version.
  70. func NewCmdConvert(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
  71. o := NewConvertOptions(ioStreams)
  72. cmd := &cobra.Command{
  73. Use: "convert -f FILENAME",
  74. DisableFlagsInUseLine: true,
  75. Short: i18n.T("Convert config files between different API versions"),
  76. Long: convertLong,
  77. Example: convertExample,
  78. Run: func(cmd *cobra.Command, args []string) {
  79. cmdutil.CheckErr(o.Complete(f, cmd))
  80. cmdutil.CheckErr(o.RunConvert())
  81. },
  82. }
  83. cmd.Flags().BoolVar(&o.local, "local", o.local, "If true, convert will NOT try to contact api-server but run locally.")
  84. cmd.Flags().StringVar(&o.OutputVersion, "output-version", o.OutputVersion, i18n.T("Output the formatted object with the given group version (for ex: 'extensions/v1beta1')."))
  85. o.PrintFlags.AddFlags(cmd)
  86. cmdutil.AddValidateFlags(cmd)
  87. cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "to need to get converted.")
  88. return cmd
  89. }
  90. // Complete collects information required to run Convert command from command line.
  91. func (o *ConvertOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) (err error) {
  92. err = o.FilenameOptions.RequireFilenameOrKustomize()
  93. if err != nil {
  94. return err
  95. }
  96. o.builder = f.NewBuilder
  97. o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
  98. if err != nil {
  99. return err
  100. }
  101. o.validator = func() (validation.Schema, error) {
  102. return f.Validator(cmdutil.GetFlagBool(cmd, "validate"))
  103. }
  104. // build the printer
  105. o.Printer, err = o.PrintFlags.ToPrinter()
  106. if err != nil {
  107. return err
  108. }
  109. return nil
  110. }
  111. // RunConvert implements the generic Convert command
  112. func (o *ConvertOptions) RunConvert() error {
  113. // Convert must be removed from kubectl, since kubectl can not depend on
  114. // Kubernetes "internal" dependencies. These "internal" dependencies can
  115. // not be removed from convert. Another way to convert a resource is to
  116. // "kubectl apply" it to the cluster, then "kubectl get" at the desired version.
  117. // Another possible solution is to make convert a plugin.
  118. fmt.Fprintf(o.ErrOut, "kubectl convert is DEPRECATED and will be removed in a future version.\nIn order to convert, kubectl apply the object to the cluster, then kubectl get at the desired version.\n")
  119. b := o.builder().
  120. WithScheme(scheme.Scheme).
  121. LocalParam(o.local)
  122. if !o.local {
  123. schema, err := o.validator()
  124. if err != nil {
  125. return err
  126. }
  127. b.Schema(schema)
  128. }
  129. r := b.NamespaceParam(o.Namespace).
  130. ContinueOnError().
  131. FilenameParam(false, &o.FilenameOptions).
  132. Flatten().
  133. Do()
  134. err := r.Err()
  135. if err != nil {
  136. return err
  137. }
  138. singleItemImplied := false
  139. infos, err := r.IntoSingleItemImplied(&singleItemImplied).Infos()
  140. if err != nil {
  141. return err
  142. }
  143. if len(infos) == 0 {
  144. return fmt.Errorf("no objects passed to convert")
  145. }
  146. var specifiedOutputVersion schema.GroupVersion
  147. if len(o.OutputVersion) > 0 {
  148. specifiedOutputVersion, err = schema.ParseGroupVersion(o.OutputVersion)
  149. if err != nil {
  150. return err
  151. }
  152. }
  153. internalEncoder := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
  154. internalVersionJSONEncoder := unstructured.JSONFallbackEncoder{Encoder: internalEncoder}
  155. objects, err := asVersionedObject(infos, !singleItemImplied, specifiedOutputVersion, internalVersionJSONEncoder)
  156. if err != nil {
  157. return err
  158. }
  159. return o.Printer.PrintObj(objects, o.Out)
  160. }
  161. // asVersionedObject converts a list of infos into a single object - either a List containing
  162. // the objects as children, or if only a single Object is present, as that object. The provided
  163. // version will be preferred as the conversion target, but the Object's mapping version will be
  164. // used if that version is not present.
  165. func asVersionedObject(infos []*resource.Info, forceList bool, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) (runtime.Object, error) {
  166. objects, err := asVersionedObjects(infos, specifiedOutputVersion, encoder)
  167. if err != nil {
  168. return nil, err
  169. }
  170. var object runtime.Object
  171. if len(objects) == 1 && !forceList {
  172. object = objects[0]
  173. } else {
  174. object = &api.List{Items: objects}
  175. targetVersions := []schema.GroupVersion{}
  176. if !specifiedOutputVersion.Empty() {
  177. targetVersions = append(targetVersions, specifiedOutputVersion)
  178. }
  179. targetVersions = append(targetVersions, schema.GroupVersion{Group: "", Version: "v1"})
  180. converted, err := tryConvert(scheme.Scheme, object, targetVersions...)
  181. if err != nil {
  182. return nil, err
  183. }
  184. object = converted
  185. }
  186. actualVersion := object.GetObjectKind().GroupVersionKind()
  187. if actualVersion.Version != specifiedOutputVersion.Version {
  188. defaultVersionInfo := ""
  189. if len(actualVersion.Version) > 0 {
  190. defaultVersionInfo = fmt.Sprintf("Defaulting to %q", actualVersion.Version)
  191. }
  192. klog.V(1).Infof("info: the output version specified is invalid. %s\n", defaultVersionInfo)
  193. }
  194. return object, nil
  195. }
  196. // asVersionedObjects converts a list of infos into versioned objects. The provided
  197. // version will be preferred as the conversion target, but the Object's mapping version will be
  198. // used if that version is not present.
  199. func asVersionedObjects(infos []*resource.Info, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) ([]runtime.Object, error) {
  200. objects := []runtime.Object{}
  201. for _, info := range infos {
  202. if info.Object == nil {
  203. continue
  204. }
  205. targetVersions := []schema.GroupVersion{}
  206. // objects that are not part of api.Scheme must be converted to JSON
  207. // TODO: convert to map[string]interface{}, attach to runtime.Unknown?
  208. if !specifiedOutputVersion.Empty() {
  209. if _, _, err := scheme.Scheme.ObjectKinds(info.Object); runtime.IsNotRegisteredError(err) {
  210. // TODO: ideally this would encode to version, but we don't expose multiple codecs here.
  211. data, err := runtime.Encode(encoder, info.Object)
  212. if err != nil {
  213. return nil, err
  214. }
  215. // TODO: Set ContentEncoding and ContentType.
  216. objects = append(objects, &runtime.Unknown{Raw: data})
  217. continue
  218. }
  219. targetVersions = append(targetVersions, specifiedOutputVersion)
  220. } else {
  221. gvks, _, err := scheme.Scheme.ObjectKinds(info.Object)
  222. if err == nil {
  223. for _, gvk := range gvks {
  224. targetVersions = append(targetVersions, scheme.Scheme.PrioritizedVersionsForGroup(gvk.Group)...)
  225. }
  226. }
  227. }
  228. converted, err := tryConvert(scheme.Scheme, info.Object, targetVersions...)
  229. if err != nil {
  230. return nil, err
  231. }
  232. objects = append(objects, converted)
  233. }
  234. return objects, nil
  235. }
  236. // tryConvert attempts to convert the given object to the provided versions in order. This function assumes
  237. // the object is in internal version.
  238. func tryConvert(converter runtime.ObjectConvertor, object runtime.Object, versions ...schema.GroupVersion) (runtime.Object, error) {
  239. var last error
  240. for _, version := range versions {
  241. if version.Empty() {
  242. return object, nil
  243. }
  244. obj, err := converter.ConvertToVersion(object, version)
  245. if err != nil {
  246. last = err
  247. continue
  248. }
  249. return obj, nil
  250. }
  251. return nil, last
  252. }