// NewCmdScale returns a cobra command with the appropriate configuration and flags to run scale func NewCmdScale(f *cmdutil.Factory, out io.Writer) *cobra.Command { options := &ScaleOptions{} cmd := &cobra.Command{ Use: "scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)", // resize is deprecated Aliases: []string{"resize"}, Short: "Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.", Long: scale_long, Example: scale_example, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" err := RunScale(f, out, cmd, args, shortOutput, options) cmdutil.CheckErr(err) }, } cmd.Flags().String("resource-version", "", "Precondition for resource version. Requires that the current resource version match this value in order to scale.") cmd.Flags().Int("current-replicas", -1, "Precondition for current size. Requires that the current size of the resource match this value in order to scale.") cmd.Flags().Int("replicas", -1, "The new desired number of replicas. Required.") cmd.MarkFlagRequired("replicas") cmd.Flags().Duration("timeout", 0, "The length of time to wait before giving up on a scale operation, zero means don't wait.") cmdutil.AddOutputFlagsForMutation(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) usage := "Filename, directory, or URL to a file identifying the resource to set a new size" kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) cmdutil.AddRecursiveFlag(cmd, &options.Recursive) return cmd }
func NewCmdApply(f *cmdutil.Factory, out io.Writer) *cobra.Command { options := &ApplyOptions{} cmd := &cobra.Command{ Use: "apply -f FILENAME", Short: "Apply a configuration to a resource by filename or stdin", Long: apply_long, Example: apply_example, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(validateArgs(cmd, args)) cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) cmdutil.CheckErr(RunApply(f, cmd, out, options)) }, } usage := "Filename, directory, or URL to file that contains the configuration to apply" kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) cmd.MarkFlagRequired("filename") cmdutil.AddValidateFlags(cmd) cmdutil.AddRecursiveFlag(cmd, &options.Recursive) cmdutil.AddOutputFlagsForMutation(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd }
// NewCmdCreateSecretDockerRegistry is a macro command for creating secrets to work with Docker registries func NewCmdCreateSecretDockerRegistry(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "docker-registry NAME --docker-username=user --docker-password=password --docker-email=email [--docker-server=string] [--from-literal=key1=value1] [--dry-run]", Short: "Create a secret for use with a Docker registry.", Long: secretForDockerRegistryLong, Example: secretForDockerRegistryExample, Run: func(cmd *cobra.Command, args []string) { err := CreateSecretDockerRegistry(f, cmdOut, cmd, args) cmdutil.CheckErr(err) }, } cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddValidateFlags(cmd) cmdutil.AddPrinterFlags(cmd) cmdutil.AddGeneratorFlags(cmd, cmdutil.SecretForDockerRegistryV1GeneratorName) cmd.Flags().String("docker-username", "", "Username for Docker registry authentication") cmd.MarkFlagRequired("docker-username") cmd.Flags().String("docker-password", "", "Password for Docker registry authentication") cmd.MarkFlagRequired("docker-password") cmd.Flags().String("docker-email", "", "Email for Docker registry") cmd.MarkFlagRequired("docker-email") cmd.Flags().String("docker-server", "https://index.docker.io/v1/", "Server location for Docker registry") cmdutil.AddInclude3rdPartyFlags(cmd) return cmd }
func NewCmdRollingUpdate(f *cmdutil.Factory, out io.Writer) *cobra.Command { options := &RollingUpdateOptions{} cmd := &cobra.Command{ Use: "rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC)", // rollingupdate is deprecated. Aliases: []string{"rollingupdate"}, Short: "Perform a rolling update of the given ReplicationController.", Long: rollingUpdate_long, Example: rollingUpdate_example, Run: func(cmd *cobra.Command, args []string) { err := RunRollingUpdate(f, out, cmd, args, options) cmdutil.CheckErr(err) }, } cmd.Flags().Duration("update-period", updatePeriod, `Time to wait between updating pods. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".`) cmd.Flags().Duration("poll-interval", pollInterval, `Time delay between polling for replication controller status after the update. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".`) cmd.Flags().Duration("timeout", timeout, `Max time to wait for a replication controller to update before giving up. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".`) usage := "Filename or URL to file to use to create the new replication controller." kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) cmd.MarkFlagRequired("filename") cmd.Flags().String("image", "", "Image to use for upgrading the replication controller. Must be distinct from the existing image (either new image or new image tag). Can not be used with --filename/-f") cmd.MarkFlagRequired("image") cmd.Flags().String("deployment-label-key", "deployment", "The key to use to differentiate between two different controllers, default 'deployment'. Only relevant when --image is specified, ignored otherwise") cmd.Flags().String("container", "", "Container name which will have its image upgraded. Only relevant when --image is specified, ignored otherwise. Required when using --image on a multi-container pod") cmd.Flags().String("image-pull-policy", "", "Explicit policy for when to pull container images. Required when --image is same as existing image, ignored otherwise.") cmd.Flags().Bool("rollback", false, "If true, this is a request to abort an existing rollout that is partially rolled out. It effectively reverses current and next and runs a rollout") cmdutil.AddDryRunFlag(cmd) cmdutil.AddValidateFlags(cmd) cmdutil.AddPrinterFlags(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd }
func NewCmdClusterInfo(f *cmdutil.Factory, out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "cluster-info", // clusterinfo is deprecated. Aliases: []string{"clusterinfo"}, Short: "Display cluster info", Long: longDescr, Run: func(cmd *cobra.Command, args []string) { err := RunClusterInfo(f, out, cmd) cmdutil.CheckErr(err) }, } cmdutil.AddInclude3rdPartyFlags(cmd) cmd.AddCommand(NewCmdClusterInfoDump(f, out)) return cmd }
// NewCmdCreateServiceAccount is a macro command to create a new service account func NewCmdCreateServiceAccount(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "serviceaccount NAME [--dry-run]", Aliases: []string{"sa"}, Short: "Create a service account with the specified name.", Long: serviceAccountLong, Example: serviceAccountExample, Run: func(cmd *cobra.Command, args []string) { err := CreateServiceAccount(f, cmdOut, cmd, args) cmdutil.CheckErr(err) }, } cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddValidateFlags(cmd) cmdutil.AddPrinterFlags(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) cmdutil.AddGeneratorFlags(cmd, cmdutil.ServiceAccountV1GeneratorName) return cmd }
func NewCmdRun(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "run NAME --image=image [--env=\"key=value\"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [--command] -- [COMMAND] [args...]", // run-container is deprecated Aliases: []string{"run-container"}, Short: "Run a particular image on the cluster.", Long: run_long, Example: run_example, Run: func(cmd *cobra.Command, args []string) { argsLenAtDash := cmd.ArgsLenAtDash() err := Run(f, cmdIn, cmdOut, cmdErr, cmd, args, argsLenAtDash) cmdutil.CheckErr(err) }, } cmdutil.AddPrinterFlags(cmd) addRunFlags(cmd) cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd }
func NewCmdDelete(f *cmdutil.Factory, out io.Writer) *cobra.Command { options := &DeleteOptions{} // retrieve a list of handled resources from printer as valid args validArgs, argAliases := []string{}, []string{} p, err := f.Printer(nil, false, false, false, false, false, false, []string{}) cmdutil.CheckErr(err) if p != nil { validArgs = p.HandledResources() argAliases = kubectl.ResourceAliases(validArgs) } cmd := &cobra.Command{ Use: "delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)])", Short: "Delete resources by filenames, stdin, resources and names, or by resources and label selector.", Long: delete_long, Example: delete_example, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) err := RunDelete(f, out, cmd, args, options) cmdutil.CheckErr(err) }, SuggestFor: []string{"rm"}, ValidArgs: validArgs, ArgAliases: argAliases, } usage := "Filename, directory, or URL to a file containing the resource to delete." kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) cmdutil.AddRecursiveFlag(cmd, &options.Recursive) cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on.") cmd.Flags().Bool("all", false, "[-all] to select all the specified resources.") cmd.Flags().Bool("ignore-not-found", false, "Treat \"resource not found\" as a successful delete. Defaults to \"true\" when --all is specified.") cmd.Flags().Bool("cascade", true, "If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.") cmd.Flags().Int("grace-period", -1, "Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.") cmd.Flags().Bool("now", false, "If true, resources are force terminated without graceful deletion (same as --grace-period=0).") cmd.Flags().Duration("timeout", 0, "The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object") cmdutil.AddOutputFlagsForMutation(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd }
func TestGenerateService(t *testing.T) { tests := []struct { port string args []string serviceGenerator string params map[string]interface{} expectErr bool name string service api.Service expectPOST bool }{ { port: "80", args: []string{"foo"}, serviceGenerator: "service/v2", params: map[string]interface{}{ "name": "foo", }, expectErr: false, name: "basic", service: api.Service{ ObjectMeta: api.ObjectMeta{ Name: "foo", }, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(80), }, }, Selector: map[string]string{ "run": "foo", }, Type: api.ServiceTypeClusterIP, SessionAffinity: api.ServiceAffinityNone, }, }, expectPOST: true, }, { port: "80", args: []string{"foo"}, serviceGenerator: "service/v2", params: map[string]interface{}{ "name": "foo", "labels": "app=bar", }, expectErr: false, name: "custom labels", service: api.Service{ ObjectMeta: api.ObjectMeta{ Name: "foo", Labels: map[string]string{"app": "bar"}, }, Spec: api.ServiceSpec{ Ports: []api.ServicePort{ { Port: 80, Protocol: "TCP", TargetPort: intstr.FromInt(80), }, }, Selector: map[string]string{ "app": "bar", }, Type: api.ServiceTypeClusterIP, SessionAffinity: api.ServiceAffinityNone, }, }, expectPOST: true, }, { expectErr: true, name: "missing port", expectPOST: false, }, { port: "80", args: []string{"foo"}, serviceGenerator: "service/v2", params: map[string]interface{}{ "name": "foo", }, expectErr: false, name: "dry-run", expectPOST: false, }, } for _, test := range tests { sawPOST := false f, tf, codec := NewAPIFactory() tf.ClientConfig = &restclient.Config{ContentConfig: restclient.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} tf.Client = &fake.RESTClient{ Codec: codec, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { switch p, m := req.URL.Path, req.Method; { case test.expectPOST && m == "POST" && p == "/namespaces/namespace/services": sawPOST = true body := objBody(codec, &test.service) data, err := ioutil.ReadAll(req.Body) if err != nil { t.Errorf("unexpected error: %v", err) t.FailNow() } defer req.Body.Close() svc := &api.Service{} if err := runtime.DecodeInto(codec, data, svc); err != nil { t.Errorf("unexpected error: %v", err) t.FailNow() } // Copy things that are defaulted by the system test.service.Annotations = svc.Annotations if !reflect.DeepEqual(&test.service, svc) { t.Errorf("expected:\n%v\nsaw:\n%v\n", &test.service, svc) } return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: body}, nil default: // Ensures no GET is performed when deleting by name t.Errorf("%s: unexpected request: %s %#v\n%#v", test.name, req.Method, req.URL, req) return nil, fmt.Errorf("unexpected request") } }), } cmd := &cobra.Command{} cmd.Flags().String("output", "", "") cmd.Flags().Bool(cmdutil.ApplyAnnotationsFlag, false, "") cmd.Flags().Bool("record", false, "Record current kubectl command in the resource annotation.") cmdutil.AddInclude3rdPartyFlags(cmd) addRunFlags(cmd) if !test.expectPOST { cmd.Flags().Set("dry-run", "true") } if len(test.port) > 0 { cmd.Flags().Set("port", test.port) test.params["port"] = test.port } buff := &bytes.Buffer{} err := generateService(f, cmd, test.args, test.serviceGenerator, test.params, "namespace", buff) if test.expectErr { if err == nil { t.Error("unexpected non-error") } continue } if err != nil { t.Errorf("unexpected error: %v", err) } if test.expectPOST != sawPOST { t.Errorf("expectPost: %v, sawPost: %v", test.expectPOST, sawPOST) } } }