本文整理汇总了Golang中k8s/io/kubernetes/pkg/kubectl/cmd/util.Factory类的典型用法代码示例。如果您正苦于以下问题:Golang Factory类的具体用法?Golang Factory怎么用?Golang Factory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Factory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: addServiceAccount
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
}
示例2: NewCmdVolumes
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
}
示例3: RunVersion
func RunVersion(f cmdutil.Factory, out io.Writer, cmd *cobra.Command) error {
v := fmt.Sprintf("%#v", version.Get())
if cmdutil.GetFlagBool(cmd, "short") {
v = version.Get().GitVersion
}
fmt.Fprintf(out, "Client Version: %s\n", v)
if cmdutil.GetFlagBool(cmd, "client") {
return nil
}
clientset, err := f.ClientSet()
if err != nil {
return err
}
serverVersion, err := clientset.Discovery().ServerVersion()
if err != nil {
return err
}
v = fmt.Sprintf("%#v", *serverVersion)
if cmdutil.GetFlagBool(cmd, "short") {
v = serverVersion.GitVersion
}
fmt.Fprintf(out, "Server Version: %s\n", v)
return nil
}
示例4: RunStop
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)
}
示例5: popCluster
// popCluster fetches the cluster object with the given name, deletes
// it and returns the deleted cluster object.
func popCluster(f cmdutil.Factory, name string) (*federationapi.Cluster, error) {
// Boilerplate to create the secret in the host cluster.
mapper, typer := f.Object()
gvks, _, err := typer.ObjectKinds(&federationapi.Cluster{})
if err != nil {
return nil, err
}
gvk := gvks[0]
mapping, err := mapper.RESTMapping(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version)
if err != nil {
return nil, err
}
client, err := f.ClientForMapping(mapping)
if err != nil {
return nil, err
}
rh := resource.NewHelper(client, mapping)
obj, err := rh.Get("", name, false)
if isNotFound(err) {
// Cluster isn't registered, there isn't anything to be done here.
return nil, nil
} else if err != nil {
return nil, err
}
cluster, ok := obj.(*federationapi.Cluster)
if !ok {
return nil, fmt.Errorf("unexpected object type: expected \"federation/v1beta1.Cluster\", got %T: obj: %#v", obj, obj)
}
// Remove the cluster resource in the federation API server by
// calling rh.Delete()
return cluster, rh.Delete("", name)
}
示例6: deleteSecret
// deleteSecret deletes the secret with the given name from the host
// cluster.
func deleteSecret(hostFactory cmdutil.Factory, name, namespace string) error {
clientset, err := hostFactory.ClientSet()
if err != nil {
return err
}
return clientset.Core().Secrets(namespace).Delete(name, &api.DeleteOptions{})
}
示例7: NewCmdRoutes
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
}
示例8: RunApiVersions
func RunApiVersions(f *cmdutil.Factory, w 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
}
apiVersions, err := client.ServerAPIVersions()
if err != nil {
fmt.Printf("Couldn't get available api versions from server: %v\n", err)
os.Exit(1)
}
var expAPIVersions *unversioned.APIVersions
expAPIVersions, err = client.Experimental().ServerAPIVersions()
fmt.Fprintf(w, "Available Server Api Versions: %#v\n", *apiVersions)
if err == nil {
fmt.Fprintf(w, "Available Server Experimental Api Versions: %#v\n", *expAPIVersions)
}
return nil
}
示例9: DescribeMatchingResources
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
}
示例10: NewCmdGet
// NewCmdGet creates a command object for the generic "get" action, which
// retrieves one or more resources from a server.
func NewCmdGet(f *cmdutil.Factory, out io.Writer) *cobra.Command {
options := &GetOptions{}
// retrieve a list of handled resources from printer as valid args
validArgs := []string{}
p, err := f.Printer(nil, false, false, false, false, false, false, []string{})
cmdutil.CheckErr(err)
if p != nil {
validArgs = p.HandledResources()
}
cmd := &cobra.Command{
Use: "get [(-o|--output=)json|yaml|wide|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...] (TYPE [NAME | -l label] | TYPE/NAME ...) [flags]",
Short: "Display one or many resources",
Long: get_long,
Example: get_example,
Run: func(cmd *cobra.Command, args []string) {
err := RunGet(f, out, cmd, args, options)
cmdutil.CheckErr(err)
},
ValidArgs: validArgs,
}
cmdutil.AddPrinterFlags(cmd)
cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on")
cmd.Flags().BoolP("watch", "w", false, "After listing/getting the requested object, watch for changes.")
cmd.Flags().Bool("watch-only", false, "Watch for changes to the requested object(s), without listing/getting first.")
cmd.Flags().Bool("all-namespaces", false, "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.")
cmd.Flags().StringSliceP("label-columns", "L", []string{}, "Accepts a comma separated list of labels that are going to be presented as columns. Names are case-sensitive. You can also use multiple flag statements like -L label1 -L label2...")
cmd.Flags().Bool("export", false, "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information.")
usage := "Filename, directory, or URL to a file identifying the resource to get from a server."
kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage)
return cmd
}
示例11: RunExplain
// RunExplain executes the appropriate steps to print a model's documentation
func RunExplain(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return cmdutil.UsageError(cmd, "We accept only this format: explain RESOURCE")
}
client, err := f.Client()
if err != nil {
return err
}
recursive := cmdutil.GetFlagBool(cmd, "recursive")
apiV := cmdutil.GetFlagString(cmd, "api-version")
swagSchema, err := kubectl.GetSwaggerSchema(apiV, client)
if err != nil {
return err
}
mapper, _ := f.Object()
inModel, fieldsPath, err := kubectl.SplitAndParseResourceRequest(args[0], mapper)
if err != nil {
return err
}
return kubectl.PrintModelDescription(inModel, fieldsPath, out, swagSchema, recursive)
}
示例12: ReapResult
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
}
示例13: Complete
// 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: ")
if len(o.Password) == 0 {
return errors.New("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
}
示例14: NewCmdVolume
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
}
示例15: NewCmdIngress
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
}