func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { port := cmdutil.GetFlagInt(cmd, "port") fmt.Fprintf(out, "Starting to serve on localhost:%d", port) clientConfig, err := f.ClientConfig() if err != nil { return err } staticPrefix := cmdutil.GetFlagString(cmd, "www-prefix") if !strings.HasSuffix(staticPrefix, "/") { staticPrefix += "/" } apiProxyPrefix := cmdutil.GetFlagString(cmd, "api-prefix") if !strings.HasSuffix(apiProxyPrefix, "/") { apiProxyPrefix += "/" } server, err := kubectl.NewProxyServer(cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, clientConfig) if err != nil { return err } glog.Fatal(server.Serve(port)) return nil }
func DescribeMatchingResources(mapper meta.RESTMapper, typer runtime.ObjectTyper, describer kubectl.Describer, f *cmdutil.Factory, namespace, rsrc, prefix string, out io.Writer, originalError error) error { r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). NamespaceParam(namespace).DefaultNamespace(). ResourceTypeOrNameArgs(true, rsrc). SingleResourceType(). Flatten(). Do() infos, err := r.Infos() if err != nil { return err } isFound := false for ix := range infos { info := infos[ix] if strings.HasPrefix(info.Name, prefix) { isFound = true s, err := describer.Describe(info.Namespace, info.Name) if err != nil { return err } fmt.Fprintf(out, "%s\n", s) } } if !isFound { return originalError } return nil }
func ReapResult(r *resource.Result, f *cmdutil.Factory, out io.Writer, isDefaultDelete, ignoreNotFound bool, timeout time.Duration, gracePeriod int, shortOutput bool, mapper meta.RESTMapper) error { found := 0 if ignoreNotFound { r = r.IgnoreErrors(errors.IsNotFound) } err := r.Visit(func(info *resource.Info) error { found++ reaper, err := f.Reaper(info.Mapping) if err != nil { // If there is no reaper for this resources and the user didn't explicitly ask for stop. if kubectl.IsNoSuchReaperError(err) && isDefaultDelete { return deleteResource(info, out, shortOutput, mapper) } return cmdutil.AddSourceToErr("reaping", info.Source, err) } var options *api.DeleteOptions if gracePeriod >= 0 { options = api.NewDeleteOptions(int64(gracePeriod)) } if _, err := reaper.Stop(info.Namespace, info.Name, timeout, options); err != nil { return cmdutil.AddSourceToErr("stopping", info.Source, err) } cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "deleted") return nil }) if err != nil { return err } if found == 0 { fmt.Fprintf(out, "No resources found\n") } return nil }
func RunLog(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { if len(args) == 0 { return cmdutil.UsageError(cmd, "POD is required for log") } if len(args) > 2 { return cmdutil.UsageError(cmd, "log POD [CONTAINER]") } namespace, err := f.DefaultNamespace() if err != nil { return err } client, err := f.Client() if err != nil { return err } podID := args[0] pod, err := client.Pods(namespace).Get(podID) if err != nil { return err } var container string if len(args) == 1 { if len(pod.Spec.Containers) != 1 { return fmt.Errorf("POD %s has more than one container; please specify the container to print logs for", pod.ObjectMeta.Name) } container = pod.Spec.Containers[0].Name } else { container = args[1] } follow := false if cmdutil.GetFlagBool(cmd, "follow") { follow = true } readCloser, err := client.RESTClient.Get(). Prefix("proxy"). Resource("nodes"). Name(pod.Spec.Host). Suffix("containerLogs", namespace, podID, container). Param("follow", strconv.FormatBool(follow)). Stream() if err != nil { return err } defer readCloser.Close() _, err = io.Copy(out, readCloser) return err }
func RunApiVersions(f *cmdutil.Factory, out io.Writer) error { if len(os.Args) > 1 && os.Args[1] == "apiversions" { printDeprecationWarning("api-versions", "apiversions") } client, err := f.Client() if err != nil { return err } kubectl.GetApiVersions(out, client) return nil }
func (o *AddSecretOptions) Complete(f *cmdutil.Factory, args []string, typeFlag string) error { if len(args) < 2 { return errors.New("must have service account name and at least one secret name") } o.TargetName = args[0] o.SecretNames = args[1:] loweredTypeFlag := strings.ToLower(typeFlag) switch loweredTypeFlag { case string(PullType): o.Type = PullType case string(MountType): o.Type = MountType default: return fmt.Errorf("unknown for: %v", typeFlag) } var err error o.ClientInterface, err = f.Client() if err != nil { return err } o.Namespace, err = f.DefaultNamespace() if err != nil { return err } o.Mapper, o.Typer = f.Object() o.ClientMapper = f.ClientMapperForCommand() return nil }
func RunVersion(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { if cmdutil.GetFlagBool(cmd, "client") { kubectl.GetClientVersion(out) return nil } client, err := f.Client() if err != nil { return err } kubectl.GetVersion(out, client) return nil }
func RunUpdate(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames util.StringList) error { schema, err := f.Validator() if err != nil { return err } cmdNamespace, err := f.DefaultNamespace() if err != nil { return err } patch := cmdutil.GetFlagString(cmd, "patch") if len(filenames) == 0 && len(patch) == 0 { return cmdutil.UsageError(cmd, "Must specify --filename or --patch to update") } if len(filenames) != 0 && len(patch) != 0 { return cmdutil.UsageError(cmd, "Can not specify both --filename and --patch") } // TODO: Make patching work with -f, updating with patched JSON input files if len(filenames) == 0 { name, err := updateWithPatch(cmd, args, f, patch) if err != nil { return err } fmt.Fprintf(out, "%s\n", name) return nil } if len(filenames) == 0 { return cmdutil.UsageError(cmd, "Must specify --filename to update") } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). Schema(schema). ContinueOnError(). NamespaceParam(cmdNamespace).RequireNamespace(). FilenameParam(filenames...). Flatten(). Do() err = r.Err() if err != nil { return err } return r.Visit(func(info *resource.Info) error { data, err := info.Mapping.Codec.Encode(info.Object) if err != nil { return err } obj, err := resource.NewHelper(info.Client, info.Mapping).Update(info.Namespace, info.Name, true, data) if err != nil { return err } info.Refresh(obj, true) printObjectSpecificMessage(obj, out) fmt.Fprintf(out, "%s/%s\n", info.Mapping.Resource, info.Name) return nil }) }
// NewKubectlCommand creates the `kubectl` command and its nested children. func NewKubectlCommand(f *cmdutil.Factory, in io.Reader, out, err io.Writer) *cobra.Command { // Parent command to which all subcommands are added. cmds := &cobra.Command{ Use: "kubectl", Short: "kubectl controls the Kubernetes cluster manager", Long: `kubectl controls the Kubernetes cluster manager. Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`, Run: runHelp, BashCompletionFunction: bash_completion_func, } f.BindFlags(cmds.PersistentFlags()) // From this point and forward we get warnings on flags that contain "_" separators cmds.SetGlobalNormalizationFunc(util.WarnWordSepNormalizeFunc) cmds.AddCommand(NewCmdGet(f, out)) cmds.AddCommand(NewCmdDescribe(f, out)) cmds.AddCommand(NewCmdCreate(f, out)) cmds.AddCommand(NewCmdReplace(f, out)) cmds.AddCommand(NewCmdPatch(f, out)) cmds.AddCommand(NewCmdDelete(f, out)) cmds.AddCommand(NewCmdNamespace(out)) cmds.AddCommand(NewCmdLog(f, out)) cmds.AddCommand(NewCmdRollingUpdate(f, out)) cmds.AddCommand(NewCmdScale(f, out)) cmds.AddCommand(NewCmdAttach(f, in, out, err)) cmds.AddCommand(NewCmdExec(f, in, out, err)) cmds.AddCommand(NewCmdPortForward(f)) cmds.AddCommand(NewCmdProxy(f, out)) cmds.AddCommand(NewCmdRun(f, out)) cmds.AddCommand(NewCmdStop(f, out)) cmds.AddCommand(NewCmdExposeService(f, out)) cmds.AddCommand(NewCmdLabel(f, out)) cmds.AddCommand(cmdconfig.NewCmdConfig(cmdconfig.NewDefaultPathOptions(), out)) cmds.AddCommand(NewCmdClusterInfo(f, out)) cmds.AddCommand(NewCmdApiVersions(f, out)) cmds.AddCommand(NewCmdVersion(f, out)) return cmds }
func Run(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { if len(os.Args) > 1 && os.Args[1] == "run-container" { printDeprecationWarning("run", "run-container") } if len(args) != 1 { return cmdutil.UsageError(cmd, "NAME is required for run") } namespace, _, err := f.DefaultNamespace() if err != nil { return err } client, err := f.Client() if err != nil { return err } generatorName := cmdutil.GetFlagString(cmd, "generator") generator, found := f.Generator(generatorName) if !found { return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not found.", generator)) } names := generator.ParamNames() params := kubectl.MakeParams(cmd, names) params["name"] = args[0] err = kubectl.ValidateParams(names, params) if err != nil { return err } controller, err := generator.Generate(params) if err != nil { return err } inline := cmdutil.GetFlagString(cmd, "overrides") if len(inline) > 0 { controller, err = cmdutil.Merge(controller, inline, "ReplicationController") if err != nil { return err } } // TODO: extract this flag to a central location, when such a location exists. if !cmdutil.GetFlagBool(cmd, "dry-run") { controller, err = client.ReplicationControllers(namespace).Create(controller.(*api.ReplicationController)) if err != nil { return err } } return f.PrintObject(cmd, controller, out) }
// RunScale executes the scaling func RunScale(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool) error { if len(os.Args) > 1 && os.Args[1] == "resize" { printDeprecationWarning("scale", "resize") } count := cmdutil.GetFlagInt(cmd, "replicas") if count < 0 { return cmdutil.UsageError(cmd, "--replicas=COUNT RESOURCE NAME") } cmdNamespace, _, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). ResourceTypeOrNameArgs(false, args...). Flatten(). Do() err = r.Err() if err != nil { return err } mapping, err := r.ResourceMapping() if err != nil { return err } infos, err := r.Infos() if err != nil { return err } if len(infos) > 1 { return fmt.Errorf("multiple resources provided: %v", args) } info := infos[0] scaler, err := f.Scaler(mapping) if err != nil { return err } resourceVersion := cmdutil.GetFlagString(cmd, "resource-version") currentSize := cmdutil.GetFlagInt(cmd, "current-replicas") precondition := &kubectl.ScalePrecondition{currentSize, resourceVersion} retry := kubectl.NewRetryParams(kubectl.Interval, kubectl.Timeout) waitForReplicas := kubectl.NewRetryParams(kubectl.Interval, kubectl.Timeout) if err := scaler.Scale(info.Namespace, info.Name, uint(count), precondition, retry, waitForReplicas); err != nil { return err } cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "scaled") return nil }
func RunResize(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { count := cmdutil.GetFlagInt(cmd, "replicas") if len(args) != 2 || count < 0 { return cmdutil.UsageError(cmd, "--replicas=COUNT RESOURCE ID") } cmdNamespace, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). ResourceTypeOrNameArgs(false, args...). Flatten(). Do() err = r.Err() if err != nil { return err } mapping, err := r.ResourceMapping() if err != nil { return err } infos, err := r.Infos() if err != nil { return err } info := infos[0] resizer, err := f.Resizer(mapping) if err != nil { return err } resourceVersion := cmdutil.GetFlagString(cmd, "resource-version") currentSize := cmdutil.GetFlagInt(cmd, "current-replicas") precondition := &kubectl.ResizePrecondition{currentSize, resourceVersion} cond := kubectl.ResizeCondition(resizer, precondition, info.Namespace, info.Name, uint(count)) msg := "resized" if err = wait.Poll(retryFrequency, retryTimeout, cond); err != nil { msg = fmt.Sprintf("Failed to resize controller in spite of retrying for %s", retryTimeout) if err != nil { return err } } fmt.Fprintf(out, "%s\n", msg) return nil }
func (o *CreateDockerConfigOptions) Complete(f *cmdutil.Factory, args []string) error { if len(args) != 1 { return errors.New("must have exactly one argument: secret name") } o.SecretName = args[0] client, err := f.Client() if err != nil { return err } o.SecretNamespace, err = f.DefaultNamespace() if err != nil { return err } o.SecretsInterface = client.Secrets(o.SecretNamespace) return nil }
func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { port := cmdutil.GetFlagInt(cmd, "port") clientConfig, err := f.ClientConfig() if err != nil { return err } staticPrefix := cmdutil.GetFlagString(cmd, "www-prefix") if !strings.HasSuffix(staticPrefix, "/") { staticPrefix += "/" } apiProxyPrefix := cmdutil.GetFlagString(cmd, "api-prefix") if !strings.HasSuffix(apiProxyPrefix, "/") { apiProxyPrefix += "/" } filter := &kubectl.FilterServer{ AcceptPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-paths")), RejectPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "reject-paths")), AcceptHosts: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-hosts")), } if cmdutil.GetFlagBool(cmd, "disable-filter") { glog.Warning("Request filter disabled, your proxy is vulnerable to XSRF attacks, please be cautious") filter = nil } server, err := kubectl.NewProxyServer(port, cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, filter, clientConfig) if err != nil { return err } // Separate listening from serving so we can report the bound port // when it is chosen by os (port == 0) l, err := server.Listen() if err != nil { glog.Fatal(err) } fmt.Fprintf(out, "Starting to serve on %s", l.Addr().String()) glog.Fatal(server.ServeOnListener(l)) return nil }
func RunDescribe(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { selector := cmdutil.GetFlagString(cmd, "selector") cmdNamespace, _, err := f.DefaultNamespace() if err != nil { return err } if len(args) == 0 { fmt.Fprint(out, "You must specify the type of resource to describe. ", valid_resources) return cmdutil.UsageError(cmd, "Required resource not specified.") } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam(selector). ResourceTypeOrNameArgs(false, args...). Flatten(). Do() err = r.Err() if err != nil { return err } mapping, err := r.ResourceMapping() if err != nil { return err } describer, err := f.Describer(mapping) if err != nil { return err } infos, err := r.Infos() if err != nil { if apierrors.IsNotFound(err) && len(args) == 2 { return DescribeMatchingResources(mapper, typer, describer, f, cmdNamespace, args[0], args[1], out, err) } return err } for _, info := range infos { s, err := describer.Describe(info.Namespace, info.Name) if err != nil { return err } fmt.Fprintf(out, "%s\n\n", s) } return nil }
func updateWithPatch(cmd *cobra.Command, args []string, f *cmdutil.Factory, patch string) (string, error) { cmdNamespace, err := f.DefaultNamespace() if err != nil { return "", err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). ResourceTypeOrNameArgs(false, args...). Flatten(). Do() err = r.Err() if err != nil { return "", err } mapping, err := r.ResourceMapping() if err != nil { return "", err } client, err := f.RESTClient(mapping) if err != nil { return "", err } infos, err := r.Infos() if err != nil { return "", err } name, namespace := infos[0].Name, infos[0].Namespace helper := resource.NewHelper(client, mapping) obj, err := helper.Get(namespace, name) if err != nil { return "", err } patchedObj, err := cmdutil.Merge(obj, patch, mapping.Kind) if err != nil { return "", err } data, err := helper.Codec.Encode(patchedObj) if err != nil { return "", err } _, err = helper.Update(namespace, name, true, data) return name, err }
func RunReplace(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames util.StringList) error { if os.Args[1] == "update" { printDeprecationWarning("replace", "update") } schema, err := f.Validator() if err != nil { return err } cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } force := cmdutil.GetFlagBool(cmd, "force") if len(filenames) == 0 { return cmdutil.UsageError(cmd, "Must specify --filename to replace") } if force { return forceReplace(f, out, cmd, args, filenames) } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). Schema(schema). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, filenames...). Flatten(). Do() err = r.Err() if err != nil { return err } return r.Visit(func(info *resource.Info) error { data, err := info.Mapping.Codec.Encode(info.Object) if err != nil { return cmdutil.AddSourceToErr("replacing", info.Source, err) } obj, err := resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, data) if err != nil { return cmdutil.AddSourceToErr("replacing", info.Source, err) } info.Refresh(obj, true) printObjectSpecificMessage(obj, out) fmt.Fprintf(out, "%s/%s\n", info.Mapping.Resource, info.Name) return nil }) }
func RunClusterInfo(factory *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { if os.Args[1] == "clusterinfo" { printDeprecationWarning("cluster-info", "clusterinfo") } client, err := factory.ClientConfig() if err != nil { return err } printService(out, "Kubernetes master", client.Host) mapper, typer := factory.Object() cmdNamespace, _, err := factory.DefaultNamespace() if err != nil { return err } // TODO use generalized labels once they are implemented (#341) b := resource.NewBuilder(mapper, typer, factory.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam("kubernetes.io/cluster-service=true"). ResourceTypeOrNameArgs(false, []string{"services"}...). Latest() b.Do().Visit(func(r *resource.Info) error { services := r.Object.(*api.ServiceList).Items for _, service := range services { var link string if len(service.Status.LoadBalancer.Ingress) > 0 { ingress := service.Status.LoadBalancer.Ingress[0] ip := ingress.IP if ip == "" { ip = ingress.Hostname } for _, port := range service.Spec.Ports { link += "http://" + ip + ":" + strconv.Itoa(port.Port) + " " } } else { link = client.Host + "/api/" + client.Version + "/proxy/namespaces/" + service.ObjectMeta.Namespace + "/services/" + service.ObjectMeta.Name } name := service.ObjectMeta.Labels["kubernetes.io/name"] if len(name) == 0 { name = service.ObjectMeta.Name } printService(out, name, link) } return nil }) return nil // TODO consider printing more information about cluster }
// Complete verifies command line arguments and loads data from the command environment func (p *AttachOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, argsIn []string) error { if len(argsIn) == 0 { return cmdutil.UsageError(cmd, "POD is required for attach") } if len(argsIn) > 1 { return cmdutil.UsageError(cmd, fmt.Sprintf("expected a single argument: POD, saw %d: %s", len(argsIn), argsIn)) } p.PodName = argsIn[0] namespace, _, err := f.DefaultNamespace() if err != nil { return err } p.Namespace = namespace config, err := f.ClientConfig() if err != nil { return err } p.Config = config client, err := f.Client() if err != nil { return err } p.Client = client return nil }
func RunCreate(f *cmdutil.Factory, out io.Writer, filenames util.StringList, shortOutput bool) error { schema, err := f.Validator() if err != nil { return err } cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). Schema(schema). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, filenames...). Flatten(). Do() err = r.Err() if err != nil { return err } count := 0 err = r.Visit(func(info *resource.Info) error { data, err := info.Mapping.Codec.Encode(info.Object) if err != nil { return cmdutil.AddSourceToErr("creating", info.Source, err) } obj, err := resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, true, data) if err != nil { return cmdutil.AddSourceToErr("creating", info.Source, err) } count++ info.Refresh(obj, true) if !shortOutput { printObjectSpecificMessage(info.Object, out) } cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "created") return nil }) if err != nil { return err } if count == 0 { return fmt.Errorf("no objects passed to create") } return nil }
func RunDelete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames util.StringList) error { cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, filenames...). SelectorParam(cmdutil.GetFlagString(cmd, "selector")). SelectAllParam(cmdutil.GetFlagBool(cmd, "all")). ResourceTypeOrNameArgs(false, args...).RequireObject(false). Flatten(). Do() err = r.Err() if err != nil { return err } ignoreNotFound := cmdutil.GetFlagBool(cmd, "ignore-not-found") // By default use a reaper to delete all related resources. if cmdutil.GetFlagBool(cmd, "cascade") { return ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, cmdutil.GetFlagDuration(cmd, "timeout"), cmdutil.GetFlagInt(cmd, "grace-period")) } return DeleteResult(r, out, ignoreNotFound) }
// NewCmdCreateDockerConfigSecret creates a command object for making a dockercfg secret func NewCmdCreateDockerConfigSecret(name, fullName string, f *cmdutil.Factory, out io.Writer, newSecretFullName, ocEditFullName string) *cobra.Command { o := &CreateDockerConfigOptions{Out: out} cmd := &cobra.Command{ Use: fmt.Sprintf("%s SECRET_NAME --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL", name), Short: "Create a new dockercfg secret", Long: fmt.Sprintf(createDockercfgLong, fullName, newSecretFullName, ocEditFullName), Run: func(c *cobra.Command, args []string) { if err := o.Complete(f, args); err != nil { cmdutil.CheckErr(err) } if err := o.Validate(); err != nil { cmdutil.CheckErr(err) } if len(cmdutil.GetFlagString(c, "output")) != 0 { secret, err := o.MakeDockerSecret() cmdutil.CheckErr(err) cmdutil.CheckErr(f.PrintObject(c, secret, out)) return } if err := o.CreateDockerSecret(); err != nil { cmdutil.CheckErr(err) } }, } cmd.Flags().StringVar(&o.Username, "docker-username", "", "username for Docker registry authentication") cmd.Flags().StringVar(&o.Password, "docker-password", "", "password for Docker registry authentication") cmd.Flags().StringVar(&o.EmailAddress, "docker-email", "", "email for Docker registry") cmd.Flags().StringVar(&o.RegistryLocation, "docker-server", "https://index.docker.io/v1/", "server location for Docker registry") cmdutil.AddPrinterFlags(cmd) return cmd }
func RunCreate(f *cmdutil.Factory, out io.Writer, filenames util.StringList) error { schema, err := f.Validator() if err != nil { return err } cmdNamespace, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).RequireNamespace(). FilenameParam(filenames...). Flatten(). Do() err = r.Err() if err != nil { return err } count := 0 err = r.Visit(func(info *resource.Info) error { data, err := info.Mapping.Codec.Encode(info.Object) if err != nil { return err } if err := schema.ValidateBytes(data); err != nil { return err } obj, err := resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, true, data) if err != nil { return err } count++ info.Refresh(obj, true) fmt.Fprintf(out, "%s/%s\n", info.Mapping.Resource, info.Name) return nil }) if err != nil { return err } if count == 0 { return fmt.Errorf("no objects passed to create") } return nil }
func RunPortForward(f *cmdutil.Factory, cmd *cobra.Command, args []string) error { podName := cmdutil.GetFlagString(cmd, "pod") if len(podName) == 0 { return cmdutil.UsageError(cmd, "POD is required for exec") } if len(args) < 1 { return cmdutil.UsageError(cmd, "at least 1 PORT is required for port-forward") } namespace, err := f.DefaultNamespace() if err != nil { return err } client, err := f.Client() if err != nil { return err } pod, err := client.Pods(namespace).Get(podName) if err != nil { return err } if pod.Status.Phase != api.PodRunning { glog.Fatalf("Unable to execute command because pod is not running. Current status=%v", pod.Status.Phase) } config, err := f.ClientConfig() if err != nil { return err } signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt) defer signal.Stop(signals) stopCh := make(chan struct{}, 1) go func() { <-signals close(stopCh) }() req := client.RESTClient.Get(). Prefix("proxy"). Resource("nodes"). Name(pod.Spec.Host). Suffix("portForward", namespace, podName) pf, err := portforward.New(req, config, args, stopCh) if err != nil { return err } return pf.ForwardPorts() }
func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { port := cmdutil.GetFlagInt(cmd, "port") fmt.Fprintf(out, "Starting to serve on localhost:%d", port) clientConfig, err := f.ClientConfig() if err != nil { return err } staticPrefix := cmdutil.GetFlagString(cmd, "www-prefix") if !strings.HasSuffix(staticPrefix, "/") { staticPrefix += "/" } apiProxyPrefix := cmdutil.GetFlagString(cmd, "api-prefix") if !strings.HasSuffix(apiProxyPrefix, "/") { apiProxyPrefix += "/" } filter := &kubectl.FilterServer{ AcceptPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-paths")), RejectPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "reject-paths")), AcceptHosts: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-hosts")), } if cmdutil.GetFlagBool(cmd, "disable-filter") { glog.Warning("Request filter disabled, your proxy is vulnerable to XSRF attacks, please be cautious") filter = nil } server, err := kubectl.NewProxyServer(cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, filter, clientConfig) if err != nil { return err } glog.Fatal(server.Serve(port)) return nil }
func RunDescribe(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { cmdNamespace, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). ResourceTypeOrNameArgs(false, args...). Flatten(). Do() err = r.Err() if err != nil { return err } mapping, err := r.ResourceMapping() if err != nil { return err } describer, err := f.Describer(mapping) if err != nil { return err } infos, err := r.Infos() if err != nil { if errors.IsNotFound(err) && len(args) == 2 { return DescribeMatchingResources(mapper, typer, describer, f, cmdNamespace, args[0], args[1], out) } return err } if len(infos) > 1 { return fmt.Errorf("multiple resources provided: %v", args) } info := infos[0] s, err := describer.Describe(info.Namespace, info.Name) if err != nil { return err } fmt.Fprintf(out, "%s\n", s) return nil }
func RunPatch(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool) error { cmdNamespace, _, err := f.DefaultNamespace() if err != nil { return err } patch := cmdutil.GetFlagString(cmd, "patch") if len(patch) == 0 { return cmdutil.UsageError(cmd, "Must specify -p to patch") } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). ResourceTypeOrNameArgs(false, args...). Flatten(). Do() err = r.Err() if err != nil { return err } mapping, err := r.ResourceMapping() if err != nil { return err } client, err := f.RESTClient(mapping) if err != nil { return err } infos, err := r.Infos() if err != nil { return err } name, namespace := infos[0].Name, infos[0].Namespace helper := resource.NewHelper(client, mapping) _, err = helper.Patch(namespace, name, api.StrategicMergePatchType, []byte(patch)) if err != nil { return err } cmdutil.PrintSuccess(mapper, shortOutput, out, "", name, "patched") return nil }
func NewCmdStop(f *cmdutil.Factory, out io.Writer) *cobra.Command { flags := &struct { Filenames util.StringList }{} cmd := &cobra.Command{ Use: "stop (-f FILENAME | RESOURCE (ID | -l label | --all))", Short: "Gracefully shut down a resource by id or filename.", Long: stop_long, Example: stop_example, Run: func(cmd *cobra.Command, args []string) { cmdNamespace, err := f.DefaultNamespace() cmdutil.CheckErr(err) mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).RequireNamespace(). ResourceTypeOrNameArgs(false, args...). FilenameParam(flags.Filenames...). SelectorParam(cmdutil.GetFlagString(cmd, "selector")). SelectAllParam(cmdutil.GetFlagBool(cmd, "all")). Flatten(). Do() cmdutil.CheckErr(r.Err()) r.Visit(func(info *resource.Info) error { reaper, err := f.Reaper(info.Mapping) cmdutil.CheckErr(err) if _, err := reaper.Stop(info.Namespace, info.Name); err != nil { return err } fmt.Fprintf(out, "%s/%s\n", info.Mapping.Resource, info.Name) return nil }) }, } usage := "Filename, directory, or URL to file of resource(s) to be stopped" kubectl.AddJsonFilenameFlag(cmd, &flags.Filenames, usage) cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on") cmd.Flags().Bool("all", false, "[-all] to select all the specified resources") return cmd }
func RunClusterInfo(factory *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { if os.Args[1] == "clusterinfo" { printDeprecationWarning("cluster-info", "clusterinfo") } client, err := factory.ClientConfig() if err != nil { return err } printService(out, "Kubernetes master", client.Host, false) mapper, typer := factory.Object() cmdNamespace, err := factory.DefaultNamespace() if err != nil { return err } // TODO use generalized labels once they are implemented (#341) b := resource.NewBuilder(mapper, typer, factory.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam("kubernetes.io/cluster-service=true"). ResourceTypeOrNameArgs(false, []string{"services"}...). Latest() b.Do().Visit(func(r *resource.Info) error { services := r.Object.(*api.ServiceList).Items for _, service := range services { splittedLink := strings.Split(strings.Split(service.ObjectMeta.SelfLink, "?")[0], "/") // insert "proxy" into the link splittedLink = append(splittedLink, "") copy(splittedLink[4:], splittedLink[3:]) splittedLink[3] = "proxy" link := client.Host + strings.Join(splittedLink, "/") + "/" printService(out, service.ObjectMeta.Labels["name"], link, true) } return nil }) return nil // TODO consider printing more information about cluster }
func RunDescribe(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { cmdNamespace, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). ResourceTypeOrNameArgs(false, args...). Flatten(). Do() err = r.Err() if err != nil { return err } mapping, err := r.ResourceMapping() if err != nil { return err } describer, err := f.Describer(mapping) if err != nil { return err } infos, err := r.Infos() if err != nil { return err } info := infos[0] s, err := describer.Describe(info.Namespace, info.Name) if err != nil { return err } fmt.Fprintf(out, "%s\n", s) return nil }