func addServiceAccount(c *k8sclient.Client, f *cmdutil.Factory, name string) (Result, error) { ns, _, e := f.DefaultNamespace() if e != nil { util.Fatal("No default namespace") return Failure, e } sas := c.ServiceAccounts(ns) _, err := sas.Get(name) if err != nil { sa := kapi.ServiceAccount{ ObjectMeta: kapi.ObjectMeta{ Name: name, Labels: map[string]string{ "provider": "fabric8.io", }, }, } _, err = sas.Create(&sa) } r := Success if err != nil { r = Failure } return r, err }
func RunStop(f cmdutil.Factory, cmd *cobra.Command, args []string, out io.Writer, options *resource.FilenameOptions) error { cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). ResourceTypeOrNameArgs(false, args...). FilenameParam(enforceNamespace, options). SelectorParam(cmdutil.GetFlagString(cmd, "selector")). SelectAllParam(cmdutil.GetFlagBool(cmd, "all")). Flatten(). Do() if r.Err() != nil { return r.Err() } shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" gracePeriod := cmdutil.GetFlagInt(cmd, "grace-period") waitForDeletion := false if gracePeriod == 0 { // To preserve backwards compatibility, but prevent accidental data loss, we convert --grace-period=0 // into --grace-period=1 and wait until the object is successfully deleted. gracePeriod = 1 waitForDeletion = true } return ReapResult(r, f, out, false, cmdutil.GetFlagBool(cmd, "ignore-not-found"), cmdutil.GetFlagDuration(cmd, "timeout"), gracePeriod, waitForDeletion, shortOutput, mapper, false) }
func getMapperAndResult(f cmdutil.Factory, args []string, options *resource.FilenameOptions) (meta.RESTMapper, *resource.Mapper, *resource.Result, string, error) { cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return nil, nil, nil, "", err } mapper, typer := f.Object() resourceMapper := &resource.Mapper{ ObjectTyper: typer, RESTMapper: mapper, ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), // NB: we use `f.Decoder(false)` to get a plain deserializer for // the resourceMapper, since it's used to read in edits and // we don't want to convert into the internal version when // reading in edits (this would cause us to potentially try to // compare two different GroupVersions). Decoder: f.Decoder(false), } r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, options). ResourceTypeOrNameArgs(true, args...). ContinueOnError(). Flatten(). Latest(). Do() err = r.Err() if err != nil { return nil, nil, nil, "", err } return mapper, resourceMapper, r, cmdNamespace, err }
func RunStop(f *cmdutil.Factory, cmd *cobra.Command, args []string, out io.Writer, options *StopOptions) error { cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } cmdTenant, enforceTenant, err := f.DefaultTenant() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). TenantParam(cmdTenant).DefaultTenant(). ResourceTypeOrNameArgs(false, args...). FilenameParam(enforceTenant, enforceNamespace, options.Filenames...). SelectorParam(cmdutil.GetFlagString(cmd, "selector")). SelectAllParam(cmdutil.GetFlagBool(cmd, "all")). Flatten(). Do() if r.Err() != nil { return r.Err() } shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" return ReapResult(r, f, out, false, cmdutil.GetFlagBool(cmd, "ignore-not-found"), cmdutil.GetFlagDuration(cmd, "timeout"), cmdutil.GetFlagInt(cmd, "grace-period"), shortOutput, mapper) }
func NewCmdRoutes(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "routes", Short: "Creates any missing Routes for services", Long: `Creates any missing Route resources for Services which need to be exposed remotely`, PreRun: func(cmd *cobra.Command, args []string) { showBanner() }, Run: func(cmd *cobra.Command, args []string) { c, cfg := client.NewClient(f) oc, _ := client.NewOpenShiftClient(cfg) ns, _, err := f.DefaultNamespace() if err != nil { util.Fatal("No default namespace") printResult("Get default namespace", Failure, err) } else { util.Info("Creating a persistent volume for your ") util.Success(string(util.TypeOfMaster(c))) util.Info(" installation at ") util.Success(cfg.Host) util.Info(" in namespace ") util.Successf("%s\n\n", ns) domain := cmd.Flags().Lookup(domainFlag).Value.String() err := createRoutesForDomain(ns, domain, c, oc, f) printError("Create Routes", err) } }, } cmd.PersistentFlags().StringP(domainFlag, "", defaultDomain(), "The domain to put the created routes inside") return cmd }
func NewCmdVolumes(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "volumes", Short: "Creates a persisent volume for any pending persistance volume claims", Long: `Creates a persisent volume for any pending persistance volume claims`, PreRun: func(cmd *cobra.Command, args []string) { showBanner() }, Run: func(cmd *cobra.Command, args []string) { c, _ := client.NewClient(f) ns, _, err := f.DefaultNamespace() if err != nil { util.Fatal("No default namespace") } else { found, pendingClaimNames := findPendingPVS(c, ns) if found { createPV(c, ns, pendingClaimNames, cmd) } } }, } cmd.PersistentFlags().String(sshCommandFlag, "", "the ssh command to run commands inside the VM of the single node cluster") return cmd }
func (o *DeleteOptions) Complete(f cmdutil.Factory, out, errOut io.Writer, args []string) error { cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } // Set up client based support. mapper, typer, err := f.UnstructuredObject() if err != nil { return err } o.Mapper = mapper r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.UnstructuredClientForMapping), unstructured.UnstructuredJSONScheme). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, &o.FilenameOptions). SelectorParam(o.Selector). SelectAllParam(o.DeleteAll). ResourceTypeOrNameArgs(false, args...).RequireObject(false). Flatten(). Do() err = r.Err() if err != nil { return err } o.Result = r o.f = f // Set up writer o.Out = out o.ErrOut = errOut return nil }
func validateRouter(c *k8sclient.Client, f *cmdutil.Factory) (Result, error) { ns, _, err := f.DefaultNamespace() if err != nil { return Failure, err } requirement, err := labels.NewRequirement("router", labels.EqualsOperator, kutil.NewStringSet("router")) if err != nil { return Failure, err } label := labels.LabelSelector{*requirement} rc, err := c.ReplicationControllers(ns).List(label) if err != nil { util.Fatalf("Failed to get PersistentVolumeClaims, %s in namespace %s\n", err, ns) } if rc != nil { items := rc.Items if len(items) > 0 { return Success, err } } //util.Fatalf("No router running in namespace %s\n", ns) // TODO lets create a router return Failure, err }
// Complete assigns the SelectorOptions from args. func (o *SelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string, out io.Writer) error { o.local = cmdutil.GetFlagBool(cmd, "local") o.all = cmdutil.GetFlagBool(cmd, "all") o.record = cmdutil.GetRecordFlag(cmd) o.dryrun = cmdutil.GetDryRunFlag(cmd) cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } o.changeCause = f.Command() mapper, _ := f.Object() o.mapper = mapper o.encoder = f.JSONEncoder() o.builder = f.NewBuilder(). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, &o.fileOptions). Flatten() o.PrintObject = func(obj runtime.Object) error { return f.PrintObject(cmd, mapper, obj, o.out) } o.ClientForMapping = func(mapping *meta.RESTMapping) (resource.RESTClient, error) { return f.ClientForMapping(mapping) } o.resources, o.selector, err = getResourcesAndSelector(args) return err }
func execute(f cmdutil.Factory, cmd *cobra.Command, options *ExecOptions) error { if len(options.Namespace) == 0 { namespace, _, err := f.DefaultNamespace() if err != nil { return err } options.Namespace = namespace } container := cmdutil.GetFlagString(cmd, "container") if len(container) > 0 { options.ContainerName = container } config, err := f.ClientConfig() if err != nil { return err } options.Config = config clientset, err := f.ClientSet() if err != nil { return err } options.PodClient = clientset.Core() if err := options.Validate(); err != nil { return err } if err := options.Run(); err != nil { return err } return nil }
func (o *ResourcesOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { o.f = f o.Mapper, o.Typer = f.Object() o.UpdatePodSpecForObject = f.UpdatePodSpecForObject o.Encoder = f.JSONEncoder() o.ShortOutput = cmdutil.GetFlagString(cmd, "output") == "name" o.Record = cmdutil.GetRecordFlag(cmd) o.ChangeCause = f.Command() o.PrintObject = f.PrintObject o.Cmd = cmd cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } builder := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). //FilenameParam(enforceNamespace, o.Filenames...). FilenameParam(enforceNamespace, &o.FilenameOptions). Flatten() if !o.Local { builder = builder. SelectorParam(o.Selector). ResourceTypeOrNameArgs(o.All, args...). Latest() } o.Infos, err = builder.Do().Infos() if err != nil { return err } return nil }
func (o *PauseConfig) CompletePause(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error { if len(args) == 0 && cmdutil.IsFilenameEmpty(o.Filenames) { return cmdutil.UsageError(cmd, cmd.Use) } o.Mapper, o.Typer = f.Object() o.Encoder = f.JSONEncoder() o.Pauser = f.Pauser o.Out = out cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } r := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, &o.FilenameOptions). ResourceTypeOrNameArgs(true, args...). ContinueOnError(). Latest(). Flatten(). Do() err = r.Err() if err != nil { return err } o.Infos, err = r.Infos() if err != nil { return err } return nil }
// Complete completes all the required options for port-forward cmd. func (o *PortForwardOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, args []string, cmdOut io.Writer, cmdErr io.Writer) error { var err error o.PodName = cmdutil.GetFlagString(cmd, "pod") if len(o.PodName) == 0 && len(args) == 0 { return cmdutil.UsageError(cmd, "POD is required for port-forward") } if len(o.PodName) != 0 { printDeprecationWarning("port-forward POD", "-p POD") o.Ports = args } else { o.PodName = args[0] o.Ports = args[1:] } o.Namespace, _, err = f.DefaultNamespace() if err != nil { return err } o.Client, err = f.Client() if err != nil { return err } o.Config, err = f.ClientConfig() if err != nil { return err } o.StopChannel = make(chan struct{}, 1) o.ReadyChannel = make(chan struct{}) return nil }
// 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 (o *LogsOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { switch len(args) { case 0: return cmdutil.UsageError(cmd, "POD is required for log") case 1: o.PodName = args[0] case 2: o.PodName = args[0] o.ContainerName = args[1] default: return cmdutil.UsageError(cmd, "log POD [CONTAINER]") } var err error o.PodNamespace, _, err = f.DefaultNamespace() if err != nil { return err } o.Client, err = f.Client() if err != nil { return err } return nil }
func NewCmdVolume(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "volume", Short: "Creates a persisent volume for fabric8 apps needing persistent disk", Long: `Creates a persisent volume so that the PersistentVolumeClaims in fabric8 apps can be satisfied when creating fabric8 apps`, PreRun: func(cmd *cobra.Command, args []string) { showBanner() }, Run: func(cmd *cobra.Command, args []string) { c, cfg := client.NewClient(f) ns, _, err := f.DefaultNamespace() if err != nil { util.Fatal("No default namespace") printResult("Get default namespace", Failure, err) } else { util.Info("Creating a persistent volume for your ") util.Success(string(util.TypeOfMaster(c))) util.Info(" installation at ") util.Success(cfg.Host) util.Info(" in namespace ") util.Successf("%s\n\n", ns) r, err := createPersistentVolume(cmd, ns, c, f) printResult("Create PersistentVolume", r, err) } }, } cmd.PersistentFlags().StringP(hostPathFlag, "", "", "Defines the host folder on which to define a persisent volume for single node setups") cmd.PersistentFlags().StringP(nameFlag, "", "fabric8", "The name of the PersistentVolume to create") return cmd }
// Complete fills CreateBasicAuthSecretOptions fields with data and checks for mutual exclusivity // between flags from different option groups. func (o *CreateBasicAuthSecretOptions) Complete(f *kcmdutil.Factory, args []string) error { if len(args) != 1 { return errors.New("must have exactly one argument: secret name") } o.SecretName = args[0] if o.PromptForPassword { if len(o.Password) != 0 { return errors.New("must provide either --prompt or --password flag") } if !term.IsTerminal(o.Reader) { return errors.New("provided reader is not a terminal") } o.Password = cmdutil.PromptForPasswordString(o.Reader, o.Out, "Password: "******"password must be provided") } } if f != nil { client, err := f.Client() if err != nil { return err } namespace, _, err := f.DefaultNamespace() if err != nil { return err } o.SecretsInterface = client.Secrets(namespace) } return nil }
func NewCmdIngress(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "ingress", Short: "Creates any missing Ingress resources for services", Long: `Creates any missing Ingress resources for Services which are of type LoadBalancer`, PreRun: func(cmd *cobra.Command, args []string) { showBanner() }, Run: func(cmd *cobra.Command, args []string) { c, cfg := client.NewClient(f) ns, _, err := f.DefaultNamespace() if err != nil { util.Fatal("No default namespace") printResult("Get default namespace", Failure, err) } else { domain := cmd.Flags().Lookup(domainFlag).Value.String() util.Info("Setting up ingress on your ") util.Success(string(util.TypeOfMaster(c))) util.Info(" installation at ") util.Success(cfg.Host) util.Info(" in namespace ") util.Successf("%s at domain %s\n\n", ns, domain) err := createIngressForDomain(ns, domain, c, f) printError("Create Ingress", err) } }, } cmd.PersistentFlags().StringP(domainFlag, "", defaultDomain(), "The domain to put the created routes inside") return cmd }
func (o *PauseConfig) CompletePause(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error { if len(args) == 0 && len(o.Filenames) == 0 { return cmdutil.UsageError(cmd, cmd.Use) } o.Mapper, o.Typer = f.Object() o.PauseObject = f.PauseObject o.Out = out cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } infos, err := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, o.Filenames...). ResourceTypeOrNameArgs(true, args...). SingleResourceType(). Latest(). Do().Infos() if err != nil { return err } if len(infos) != 1 { return fmt.Errorf("rollout pause is only supported on individual resources - %d resources were found", len(infos)) } o.Info = infos[0] return nil }
func (o *UndoOptions) CompleteUndo(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error { if len(args) == 0 && len(o.Filenames) == 0 { return cmdutil.UsageError(cmd, "Required resource not specified.") } o.ToRevision = cmdutil.GetFlagInt64(cmd, "to-revision") o.Mapper, o.Typer = f.Object(false) o.Out = out cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } infos, err := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, o.Recursive, o.Filenames...). ResourceTypeOrNameArgs(true, args...). Latest(). Flatten(). Do(). Infos() if err != nil { return err } if len(infos) != 1 { return fmt.Errorf("rollout undo is only supported on individual resources - %d resources were found", len(infos)) } o.Info = infos[0] o.Rollbacker, err = f.Rollbacker(o.Info.ResourceMapping()) return err }
func NewCmdPull(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "pull [templateNames]", Short: "Pulls the docker images for the given templates", Long: `Performs a docker pull on all the docker images referenced in the given templates to preload the local docker registry with images`, PreRun: func(cmd *cobra.Command, args []string) { showBanner() }, Run: func(cmd *cobra.Command, args []string) { if len(args) < 1 { util.Error("No template names specified!") cmd.Usage() } else { _, cfg := client.NewClient(f) oc, _ := client.NewOpenShiftClient(cfg) ns, _, err := f.DefaultNamespace() if err != nil { util.Fatal("No default namespace") } else { for _, template := range args { util.Info("Downloading docker images for template ") util.Success(template) util.Info("\n\n") r, err := downloadTemplateDockerImages(cmd, ns, oc, f, template) printResult("Download Docker images", r, err) } } } }, } return cmd }
// NewCmdService looks up the external service address and opens the URL // Credits: https://github.com/kubernetes/minikube/blob/v0.9.0/cmd/minikube/cmd/service.go func NewCmdService(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "service", Short: "Opens the specified Kubernetes service in your browser", Long: `Opens the specified Kubernetes service in your browser`, Run: func(cmd *cobra.Command, args []string) { c, _ := client.NewClient(f) ns := cmd.Flags().Lookup(namespaceCommandFlag).Value.String() if ns == "" { ns, _, _ = f.DefaultNamespace() } printURL := cmd.Flags().Lookup(urlCommandFlag).Value.String() == "true" retry := cmd.Flags().Lookup(retryFlag).Value.String() == "true" if len(args) == 1 { openService(ns, args[0], c, printURL, retry) } else { util.Fatalf("Please choose a service, found %v arguments\n", len(args)) } }, } cmd.PersistentFlags().StringP(namespaceCommandFlag, "n", "default", "The service namespace") cmd.PersistentFlags().BoolP(urlCommandFlag, "u", false, "Display the kubernetes service exposed URL in the CLI instead of opening it in the default browser") cmd.PersistentFlags().Bool(retryFlag, true, "Retries to find the service if its not available just yet") return cmd }
func RunHistory(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string, options *HistoryOptions) error { if len(args) == 0 && len(options.Filenames) == 0 { return cmdutil.UsageError(cmd, "Required resource not specified.") } revisionDetail := cmdutil.GetFlagInt64(cmd, "revision") mapper, typer := f.Object(false) cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, options.Recursive, options.Filenames...). ResourceTypeOrNameArgs(true, args...). ContinueOnError(). Latest(). Flatten(). Do() err = r.Err() if err != nil { return err } err = r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } mapping := info.ResourceMapping() historyViewer, err := f.HistoryViewer(mapping) if err != nil { return err } historyInfo, err := historyViewer.History(info.Namespace, info.Name) if err != nil { return err } if revisionDetail > 0 { // Print details of a specific revision template, ok := historyInfo.RevisionToTemplate[revisionDetail] if !ok { return fmt.Errorf("unable to find revision %d of %s %q", revisionDetail, mapping.Resource, info.Name) } fmt.Fprintf(out, "%s %q revision %d\n", mapping.Resource, info.Name, revisionDetail) kubectl.DescribePodTemplate(template, out) } else { // Print all revisions formattedOutput, printErr := kubectl.PrintRolloutHistory(historyInfo, mapping.Resource, info.Name) if printErr != nil { return printErr } fmt.Fprintf(out, "%s\n", formattedOutput) } return nil }) return err }
// RunLog retrieves a pod log func RunLog(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, p *logParams) error { if len(os.Args) > 1 && os.Args[1] == "log" { printDeprecationWarning("logs", "log") } 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 } // [-c CONTAINER] container := p.containerName if len(container) == 0 { // [CONTAINER] (container as arg not flag) is supported as legacy behavior. See PR #10519 for more details. if len(args) == 1 { if len(pod.Spec.Containers) != 1 { podContainersNames := []string{} for _, container := range pod.Spec.Containers { podContainersNames = append(podContainersNames, container.Name) } return fmt.Errorf("Pod %s has the following containers: %s; please specify the container to print logs for with -c", pod.ObjectMeta.Name, strings.Join(podContainersNames, ", ")) } container = pod.Spec.Containers[0].Name } else { container = args[1] } } follow := false if cmdutil.GetFlagBool(cmd, "follow") { follow = true } previous := false if cmdutil.GetFlagBool(cmd, "previous") { previous = true } return handleLog(client, namespace, podID, container, follow, previous, out) }
func RunCreate(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, options *CreateOptions) error { schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir")) if err != nil { return err } cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). Schema(schema). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, options.Filenames...). Flatten(). Do() err = r.Err() if err != nil { return err } count := 0 err = r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { return cmdutil.AddSourceToErr("creating", info.Source, err) } if cmdutil.ShouldRecord(cmd, info) { if err := cmdutil.RecordChangeCause(info.Object, f.Command()); err != nil { return cmdutil.AddSourceToErr("creating", info.Source, err) } } if err := createAndRefresh(info); err != nil { return cmdutil.AddSourceToErr("creating", info.Source, err) } count++ shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" 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 RunReplace(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *ReplaceOptions) error { if len(os.Args) > 1 && os.Args[1] == "update" { printDeprecationWarning("replace", "update") } schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir")) if err != nil { return err } cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } force := cmdutil.GetFlagBool(cmd, "force") if len(options.Filenames) == 0 { return cmdutil.UsageError(cmd, "Must specify --filename to replace") } shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" if force { return forceReplace(f, out, cmd, args, shortOutput, options) } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). Schema(schema). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, options.Filenames...). Flatten(). Do() err = r.Err() if err != nil { return err } return r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } // Serialize the configuration into an annotation. if err := kubectl.UpdateApplyAnnotation(info); err != nil { return err } // Serialize the object with the annotation applied. obj, err := resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, info.Object) if err != nil { return cmdutil.AddSourceToErr("replacing", info.Source, err) } info.Refresh(obj, true) printObjectSpecificMessage(obj, out) cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "replaced") return nil }) }
func RunPortForward(f *cmdutil.Factory, cmd *cobra.Command, args []string, fw portForwarder) error { podName := cmdutil.GetFlagString(cmd, "pod") if len(podName) == 0 && len(args) == 0 { return cmdutil.UsageError(cmd, "POD is required for port-forward") } if len(podName) != 0 { printDeprecationWarning("port-forward POD", "-p POD") } else { podName = args[0] args = args[1:] } 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.Post(). Resource("pods"). Namespace(namespace). Name(pod.Name). SubResource("portforward") return fw.ForwardPorts("POST", req.URL(), config, args, stopCh) }
// Complete adapts from the command line args and factory to the data required. func (o *TaintOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) { namespace, _, err := f.DefaultNamespace() if err != nil { return err } // retrieves resource and taint args from args // also checks args to verify that all resources are specified before taints taintArgs := []string{} metTaintArg := false for _, s := range args { isTaint := strings.Contains(s, "=") || strings.HasSuffix(s, "-") switch { case !metTaintArg && isTaint: metTaintArg = true fallthrough case metTaintArg && isTaint: taintArgs = append(taintArgs, s) case !metTaintArg && !isTaint: o.resources = append(o.resources, s) case metTaintArg && !isTaint: return fmt.Errorf("all resources must be specified before taint changes: %s", s) } } if len(o.resources) < 1 { return fmt.Errorf("one or more resources must be specified as <resource> <name>") } if len(taintArgs) < 1 { return fmt.Errorf("at least one taint update is required") } if o.taintsToAdd, o.taintsToRemove, err = parseTaints(taintArgs); err != nil { return cmdutil.UsageError(cmd, err.Error()) } mapper, typer := f.Object() o.builder = resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). ContinueOnError(). NamespaceParam(namespace).DefaultNamespace() if o.all { o.builder = o.builder.SelectAllParam(o.all).ResourceTypes("node") } else { if len(o.resources) < 2 { return fmt.Errorf("at least one resource name must be specified since 'all' parameter is not set") } o.builder = o.builder.ResourceNames("node", o.resources[1:]...) } o.builder = o.builder.SelectorParam(o.selector). Flatten(). Latest() o.f = f o.out = out o.cmd = cmd return nil }
func (o *LogsOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { containerName := cmdutil.GetFlagString(cmd, "container") switch len(args) { case 0: return cmdutil.UsageError(cmd, "POD is required for logs") case 1: o.ResourceArg = args[0] case 2: if cmd.Flag("container").Changed { return cmdutil.UsageError(cmd, "only one of -c, [CONTAINER] arg is allowed") } o.ResourceArg = args[0] containerName = args[1] default: return cmdutil.UsageError(cmd, "logs POD [-c CONTAINER]") } var err error o.Namespace, _, err = f.DefaultNamespace() if err != nil { return err } logOptions := &api.PodLogOptions{ Container: containerName, Follow: cmdutil.GetFlagBool(cmd, "follow"), Previous: cmdutil.GetFlagBool(cmd, "previous"), Timestamps: cmdutil.GetFlagBool(cmd, "timestamps"), } if sinceTime := cmdutil.GetFlagString(cmd, "since-time"); len(sinceTime) > 0 { t, err := api.ParseRFC3339(sinceTime, unversioned.Now) if err != nil { return err } logOptions.SinceTime = &t } if limit := cmdutil.GetFlagInt64(cmd, "limit-bytes"); limit != 0 { logOptions.LimitBytes = &limit } if tail := cmdutil.GetFlagInt64(cmd, "tail"); tail != -1 { logOptions.TailLines = &tail } if sinceSeconds := cmdutil.GetFlagDuration(cmd, "since"); sinceSeconds != 0 { // round up to the nearest second sec := int64(math.Ceil(float64(sinceSeconds) / float64(time.Second))) logOptions.SinceSeconds = &sec } o.Options = logOptions o.Mapper, o.Typer = f.Object() o.Decoder = f.Decoder(true) o.ClientMapper = resource.ClientMapperFunc(f.ClientForMapping) o.LogsForObject = f.LogsForObject o.Out = out return nil }
func RunDescribe(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *DescribeOptions, describerSettings *kubectl.DescriberSettings) error { selector := cmdutil.GetFlagString(cmd, "selector") cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } if len(args) == 0 && len(options.Filenames) == 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(cmdutil.GetIncludeThirdPartyAPIs(cmd)) r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, options.Recursive, options.Filenames...). SelectorParam(selector). ResourceTypeOrNameArgs(true, args...). Flatten(). Do() err = r.Err() if err != nil { return err } allErrs := []error{} infos, err := r.Infos() if err != nil { if apierrors.IsNotFound(err) && len(args) == 2 { return DescribeMatchingResources(mapper, typer, f, cmdNamespace, args[0], args[1], describerSettings, out, err) } allErrs = append(allErrs, err) } first := true for _, info := range infos { mapping := info.ResourceMapping() describer, err := f.Describer(mapping) if err != nil { allErrs = append(allErrs, err) continue } s, err := describer.Describe(info.Namespace, info.Name, *describerSettings) if err != nil { allErrs = append(allErrs, err) continue } if first { first = false } else { fmt.Fprintf(out, "\n\n") } fmt.Fprint(out, s) } return utilerrors.NewAggregate(allErrs) }