create.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 create
  14. import (
  15. "fmt"
  16. "io"
  17. "net/url"
  18. "os"
  19. "runtime"
  20. "strings"
  21. "github.com/spf13/cobra"
  22. "k8s.io/klog"
  23. "k8s.io/apimachinery/pkg/api/meta"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  26. kruntime "k8s.io/apimachinery/pkg/runtime"
  27. "k8s.io/apimachinery/pkg/runtime/schema"
  28. "k8s.io/cli-runtime/pkg/genericclioptions"
  29. "k8s.io/cli-runtime/pkg/printers"
  30. "k8s.io/cli-runtime/pkg/resource"
  31. "k8s.io/client-go/dynamic"
  32. "k8s.io/kubernetes/pkg/kubectl"
  33. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  34. "k8s.io/kubernetes/pkg/kubectl/cmd/util/editor"
  35. "k8s.io/kubernetes/pkg/kubectl/generate"
  36. "k8s.io/kubernetes/pkg/kubectl/scheme"
  37. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  38. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  39. )
  40. // CreateOptions is the commandline options for 'create' sub command
  41. type CreateOptions struct {
  42. PrintFlags *genericclioptions.PrintFlags
  43. RecordFlags *genericclioptions.RecordFlags
  44. DryRun bool
  45. FilenameOptions resource.FilenameOptions
  46. Selector string
  47. EditBeforeCreate bool
  48. Raw string
  49. Recorder genericclioptions.Recorder
  50. PrintObj func(obj kruntime.Object) error
  51. genericclioptions.IOStreams
  52. }
  53. var (
  54. createLong = templates.LongDesc(i18n.T(`
  55. Create a resource from a file or from stdin.
  56. JSON and YAML formats are accepted.`))
  57. createExample = templates.Examples(i18n.T(`
  58. # Create a pod using the data in pod.json.
  59. kubectl create -f ./pod.json
  60. # Create a pod based on the JSON passed into stdin.
  61. cat pod.json | kubectl create -f -
  62. # Edit the data in docker-registry.yaml in JSON then create the resource using the edited data.
  63. kubectl create -f docker-registry.yaml --edit -o json`))
  64. )
  65. // NewCreateOptions returns an initialized CreateOptions instance
  66. func NewCreateOptions(ioStreams genericclioptions.IOStreams) *CreateOptions {
  67. return &CreateOptions{
  68. PrintFlags: genericclioptions.NewPrintFlags("created").WithTypeSetter(scheme.Scheme),
  69. RecordFlags: genericclioptions.NewRecordFlags(),
  70. Recorder: genericclioptions.NoopRecorder{},
  71. IOStreams: ioStreams,
  72. }
  73. }
  74. // NewCmdCreate returns new initialized instance of create sub command
  75. func NewCmdCreate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
  76. o := NewCreateOptions(ioStreams)
  77. cmd := &cobra.Command{
  78. Use: "create -f FILENAME",
  79. DisableFlagsInUseLine: true,
  80. Short: i18n.T("Create a resource from a file or from stdin."),
  81. Long: createLong,
  82. Example: createExample,
  83. Run: func(cmd *cobra.Command, args []string) {
  84. if cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames, o.FilenameOptions.Kustomize) {
  85. ioStreams.ErrOut.Write([]byte("Error: must specify one of -f and -k\n\n"))
  86. defaultRunFunc := cmdutil.DefaultSubCommandRun(ioStreams.ErrOut)
  87. defaultRunFunc(cmd, args)
  88. return
  89. }
  90. cmdutil.CheckErr(o.Complete(f, cmd))
  91. cmdutil.CheckErr(o.ValidateArgs(cmd, args))
  92. cmdutil.CheckErr(o.RunCreate(f, cmd))
  93. },
  94. }
  95. // bind flag structs
  96. o.RecordFlags.AddFlags(cmd)
  97. usage := "to use to create the resource"
  98. cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)
  99. cmdutil.AddValidateFlags(cmd)
  100. cmd.Flags().BoolVar(&o.EditBeforeCreate, "edit", o.EditBeforeCreate, "Edit the API resource before creating")
  101. cmd.Flags().Bool("windows-line-endings", runtime.GOOS == "windows",
  102. "Only relevant if --edit=true. Defaults to the line ending native to your platform.")
  103. cmdutil.AddApplyAnnotationFlags(cmd)
  104. cmdutil.AddDryRunFlag(cmd)
  105. cmd.Flags().StringVarP(&o.Selector, "selector", "l", o.Selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")
  106. cmd.Flags().StringVar(&o.Raw, "raw", o.Raw, "Raw URI to POST to the server. Uses the transport specified by the kubeconfig file.")
  107. o.PrintFlags.AddFlags(cmd)
  108. // create subcommands
  109. cmd.AddCommand(NewCmdCreateNamespace(f, ioStreams))
  110. cmd.AddCommand(NewCmdCreateQuota(f, ioStreams))
  111. cmd.AddCommand(NewCmdCreateSecret(f, ioStreams))
  112. cmd.AddCommand(NewCmdCreateConfigMap(f, ioStreams))
  113. cmd.AddCommand(NewCmdCreateServiceAccount(f, ioStreams))
  114. cmd.AddCommand(NewCmdCreateService(f, ioStreams))
  115. cmd.AddCommand(NewCmdCreateDeployment(f, ioStreams))
  116. cmd.AddCommand(NewCmdCreateClusterRole(f, ioStreams))
  117. cmd.AddCommand(NewCmdCreateClusterRoleBinding(f, ioStreams))
  118. cmd.AddCommand(NewCmdCreateRole(f, ioStreams))
  119. cmd.AddCommand(NewCmdCreateRoleBinding(f, ioStreams))
  120. cmd.AddCommand(NewCmdCreatePodDisruptionBudget(f, ioStreams))
  121. cmd.AddCommand(NewCmdCreatePriorityClass(f, ioStreams))
  122. cmd.AddCommand(NewCmdCreateJob(f, ioStreams))
  123. cmd.AddCommand(NewCmdCreateCronJob(f, ioStreams))
  124. return cmd
  125. }
  126. // ValidateArgs makes sure there is no discrepency in command options
  127. func (o *CreateOptions) ValidateArgs(cmd *cobra.Command, args []string) error {
  128. if len(args) != 0 {
  129. return cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
  130. }
  131. if len(o.Raw) > 0 {
  132. if o.EditBeforeCreate {
  133. return cmdutil.UsageErrorf(cmd, "--raw and --edit are mutually exclusive")
  134. }
  135. if len(o.FilenameOptions.Filenames) != 1 {
  136. return cmdutil.UsageErrorf(cmd, "--raw can only use a single local file or stdin")
  137. }
  138. if strings.Index(o.FilenameOptions.Filenames[0], "http://") == 0 || strings.Index(o.FilenameOptions.Filenames[0], "https://") == 0 {
  139. return cmdutil.UsageErrorf(cmd, "--raw cannot read from a url")
  140. }
  141. if o.FilenameOptions.Recursive {
  142. return cmdutil.UsageErrorf(cmd, "--raw and --recursive are mutually exclusive")
  143. }
  144. if len(o.Selector) > 0 {
  145. return cmdutil.UsageErrorf(cmd, "--raw and --selector (-l) are mutually exclusive")
  146. }
  147. if len(cmdutil.GetFlagString(cmd, "output")) > 0 {
  148. return cmdutil.UsageErrorf(cmd, "--raw and --output are mutually exclusive")
  149. }
  150. if _, err := url.ParseRequestURI(o.Raw); err != nil {
  151. return cmdutil.UsageErrorf(cmd, "--raw must be a valid URL path: %v", err)
  152. }
  153. }
  154. return nil
  155. }
  156. // Complete completes all the required options
  157. func (o *CreateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
  158. var err error
  159. o.RecordFlags.Complete(cmd)
  160. o.Recorder, err = o.RecordFlags.ToRecorder()
  161. if err != nil {
  162. return err
  163. }
  164. o.DryRun = cmdutil.GetDryRunFlag(cmd)
  165. if o.DryRun {
  166. o.PrintFlags.Complete("%s (dry run)")
  167. }
  168. printer, err := o.PrintFlags.ToPrinter()
  169. if err != nil {
  170. return err
  171. }
  172. o.PrintObj = func(obj kruntime.Object) error {
  173. return printer.PrintObj(obj, o.Out)
  174. }
  175. return nil
  176. }
  177. // RunCreate performs the creation
  178. func (o *CreateOptions) RunCreate(f cmdutil.Factory, cmd *cobra.Command) error {
  179. // raw only makes sense for a single file resource multiple objects aren't likely to do what you want.
  180. // the validator enforces this, so
  181. if len(o.Raw) > 0 {
  182. return o.raw(f)
  183. }
  184. if o.EditBeforeCreate {
  185. return RunEditOnCreate(f, o.PrintFlags, o.RecordFlags, o.IOStreams, cmd, &o.FilenameOptions)
  186. }
  187. schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"))
  188. if err != nil {
  189. return err
  190. }
  191. cmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()
  192. if err != nil {
  193. return err
  194. }
  195. r := f.NewBuilder().
  196. Unstructured().
  197. Schema(schema).
  198. ContinueOnError().
  199. NamespaceParam(cmdNamespace).DefaultNamespace().
  200. FilenameParam(enforceNamespace, &o.FilenameOptions).
  201. LabelSelectorParam(o.Selector).
  202. Flatten().
  203. Do()
  204. err = r.Err()
  205. if err != nil {
  206. return err
  207. }
  208. count := 0
  209. err = r.Visit(func(info *resource.Info, err error) error {
  210. if err != nil {
  211. return err
  212. }
  213. if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info.Object, scheme.DefaultJSONEncoder()); err != nil {
  214. return cmdutil.AddSourceToErr("creating", info.Source, err)
  215. }
  216. if err := o.Recorder.Record(info.Object); err != nil {
  217. klog.V(4).Infof("error recording current command: %v", err)
  218. }
  219. if !o.DryRun {
  220. if err := createAndRefresh(info); err != nil {
  221. return cmdutil.AddSourceToErr("creating", info.Source, err)
  222. }
  223. }
  224. count++
  225. return o.PrintObj(info.Object)
  226. })
  227. if err != nil {
  228. return err
  229. }
  230. if count == 0 {
  231. return fmt.Errorf("no objects passed to create")
  232. }
  233. return nil
  234. }
  235. // raw makes a simple HTTP request to the provided path on the server using the default
  236. // credentials.
  237. func (o *CreateOptions) raw(f cmdutil.Factory) error {
  238. restClient, err := f.RESTClient()
  239. if err != nil {
  240. return err
  241. }
  242. var data io.ReadCloser
  243. if o.FilenameOptions.Filenames[0] == "-" {
  244. data = os.Stdin
  245. } else {
  246. data, err = os.Open(o.FilenameOptions.Filenames[0])
  247. if err != nil {
  248. return err
  249. }
  250. }
  251. // TODO post content with stream. Right now it ignores body content
  252. result := restClient.Post().RequestURI(o.Raw).Body(data).Do()
  253. if err := result.Error(); err != nil {
  254. return err
  255. }
  256. body, err := result.Raw()
  257. if err != nil {
  258. return err
  259. }
  260. fmt.Fprintf(o.Out, "%v", string(body))
  261. return nil
  262. }
  263. // RunEditOnCreate performs edit on creation
  264. func RunEditOnCreate(f cmdutil.Factory, printFlags *genericclioptions.PrintFlags, recordFlags *genericclioptions.RecordFlags, ioStreams genericclioptions.IOStreams, cmd *cobra.Command, options *resource.FilenameOptions) error {
  265. editOptions := editor.NewEditOptions(editor.EditBeforeCreateMode, ioStreams)
  266. editOptions.FilenameOptions = *options
  267. editOptions.ValidateOptions = cmdutil.ValidateOptions{
  268. EnableValidation: cmdutil.GetFlagBool(cmd, "validate"),
  269. }
  270. editOptions.PrintFlags = printFlags
  271. editOptions.ApplyAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)
  272. editOptions.RecordFlags = recordFlags
  273. err := editOptions.Complete(f, []string{}, cmd)
  274. if err != nil {
  275. return err
  276. }
  277. return editOptions.Run()
  278. }
  279. // createAndRefresh creates an object from input info and refreshes info with that object
  280. func createAndRefresh(info *resource.Info) error {
  281. obj, err := resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, true, info.Object, nil)
  282. if err != nil {
  283. return err
  284. }
  285. info.Refresh(obj, true)
  286. return nil
  287. }
  288. // NameFromCommandArgs is a utility function for commands that assume the first argument is a resource name
  289. func NameFromCommandArgs(cmd *cobra.Command, args []string) (string, error) {
  290. argsLen := cmd.ArgsLenAtDash()
  291. // ArgsLenAtDash returns -1 when -- was not specified
  292. if argsLen == -1 {
  293. argsLen = len(args)
  294. }
  295. if argsLen != 1 {
  296. return "", cmdutil.UsageErrorf(cmd, "exactly one NAME is required, got %d", argsLen)
  297. }
  298. return args[0], nil
  299. }
  300. // CreateSubcommandOptions is an options struct to support create subcommands
  301. type CreateSubcommandOptions struct {
  302. // PrintFlags holds options necessary for obtaining a printer
  303. PrintFlags *genericclioptions.PrintFlags
  304. // Name of resource being created
  305. Name string
  306. // StructuredGenerator is the resource generator for the object being created
  307. StructuredGenerator generate.StructuredGenerator
  308. // DryRun is true if the command should be simulated but not run against the server
  309. DryRun bool
  310. CreateAnnotation bool
  311. Namespace string
  312. EnforceNamespace bool
  313. Mapper meta.RESTMapper
  314. DynamicClient dynamic.Interface
  315. PrintObj printers.ResourcePrinterFunc
  316. genericclioptions.IOStreams
  317. }
  318. // NewCreateSubcommandOptions returns initialized CreateSubcommandOptions
  319. func NewCreateSubcommandOptions(ioStreams genericclioptions.IOStreams) *CreateSubcommandOptions {
  320. return &CreateSubcommandOptions{
  321. PrintFlags: genericclioptions.NewPrintFlags("created").WithTypeSetter(scheme.Scheme),
  322. IOStreams: ioStreams,
  323. }
  324. }
  325. // Complete completes all the required options
  326. func (o *CreateSubcommandOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string, generator generate.StructuredGenerator) error {
  327. name, err := NameFromCommandArgs(cmd, args)
  328. if err != nil {
  329. return err
  330. }
  331. o.Name = name
  332. o.StructuredGenerator = generator
  333. o.DryRun = cmdutil.GetDryRunFlag(cmd)
  334. o.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)
  335. if o.DryRun {
  336. o.PrintFlags.Complete("%s (dry run)")
  337. }
  338. printer, err := o.PrintFlags.ToPrinter()
  339. if err != nil {
  340. return err
  341. }
  342. o.PrintObj = func(obj kruntime.Object, out io.Writer) error {
  343. return printer.PrintObj(obj, out)
  344. }
  345. o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
  346. if err != nil {
  347. return err
  348. }
  349. o.DynamicClient, err = f.DynamicClient()
  350. if err != nil {
  351. return err
  352. }
  353. o.Mapper, err = f.ToRESTMapper()
  354. if err != nil {
  355. return err
  356. }
  357. return nil
  358. }
  359. // Run executes a create subcommand using the specified options
  360. func (o *CreateSubcommandOptions) Run() error {
  361. obj, err := o.StructuredGenerator.StructuredGenerate()
  362. if err != nil {
  363. return err
  364. }
  365. if !o.DryRun {
  366. // create subcommands have compiled knowledge of things they create, so type them directly
  367. gvks, _, err := scheme.Scheme.ObjectKinds(obj)
  368. if err != nil {
  369. return err
  370. }
  371. gvk := gvks[0]
  372. mapping, err := o.Mapper.RESTMapping(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version)
  373. if err != nil {
  374. return err
  375. }
  376. if err := kubectl.CreateOrUpdateAnnotation(o.CreateAnnotation, obj, scheme.DefaultJSONEncoder()); err != nil {
  377. return err
  378. }
  379. asUnstructured := &unstructured.Unstructured{}
  380. if err := scheme.Scheme.Convert(obj, asUnstructured, nil); err != nil {
  381. return err
  382. }
  383. if mapping.Scope.Name() == meta.RESTScopeNameRoot {
  384. o.Namespace = ""
  385. }
  386. actualObject, err := o.DynamicClient.Resource(mapping.Resource).Namespace(o.Namespace).Create(asUnstructured, metav1.CreateOptions{})
  387. if err != nil {
  388. return err
  389. }
  390. // ensure we pass a versioned object to the printer
  391. obj = actualObject
  392. } else {
  393. if meta, err := meta.Accessor(obj); err == nil && o.EnforceNamespace {
  394. meta.SetNamespace(o.Namespace)
  395. }
  396. }
  397. return o.PrintObj(obj, o.Out)
  398. }