本文整理汇总了Golang中k8s/io/kubernetes/pkg/kubectl.MakeLabels函数的典型用法代码示例。如果您正苦于以下问题:Golang MakeLabels函数的具体用法?Golang MakeLabels怎么用?Golang MakeLabels使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MakeLabels函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestLabelsForObject
func TestLabelsForObject(t *testing.T) {
f := NewFactory(nil)
tests := []struct {
name string
object runtime.Object
expected string
err error
}{
{
name: "successful re-use of labels",
object: &api.Service{
ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", Labels: map[string]string{"svc": "test"}},
TypeMeta: unversioned.TypeMeta{Kind: "Service", APIVersion: "v1"},
},
expected: "svc=test",
err: nil,
},
{
name: "empty labels",
object: &api.Service{
ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", Labels: map[string]string{}},
TypeMeta: unversioned.TypeMeta{Kind: "Service", APIVersion: "v1"},
},
expected: "",
err: nil,
},
{
name: "nil labels",
object: &api.Service{
ObjectMeta: api.ObjectMeta{Name: "zen", Namespace: "test", Labels: nil},
TypeMeta: unversioned.TypeMeta{Kind: "Service", APIVersion: "v1"},
},
expected: "",
err: nil,
},
}
for _, test := range tests {
gotLabels, err := f.LabelsForObject(test.object)
if err != test.err {
t.Fatalf("%s: Error mismatch: Expected %v, got %v", test.name, test.err, err)
}
got := kubectl.MakeLabels(gotLabels)
if test.expected != got {
t.Fatalf("%s: Labels mismatch! Expected %s, got %s", test.name, test.expected, got)
}
}
}
示例2: NewFactory
// NewFactory creates a factory with the default Kubernetes resources defined
// if optionalClientConfig is nil, then flags will be bound to a new clientcmd.ClientConfig.
// if optionalClientConfig is not nil, then this factory will make use of it.
func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory {
mapper := kubectl.ShortcutExpander{RESTMapper: registered.RESTMapper()}
flags := pflag.NewFlagSet("", pflag.ContinueOnError)
flags.SetNormalizeFunc(utilflag.WarnWordSepNormalizeFunc) // Warn for "_" flags
clientConfig := optionalClientConfig
if optionalClientConfig == nil {
clientConfig = DefaultClientConfig(flags)
}
clients := NewClientCache(clientConfig)
return &Factory{
clients: clients,
flags: flags,
Object: func() (meta.RESTMapper, runtime.ObjectTyper) {
cfg, err := clientConfig.ClientConfig()
CheckErr(err)
cmdApiVersion := unversioned.GroupVersion{}
if cfg.GroupVersion != nil {
cmdApiVersion = *cfg.GroupVersion
}
outputRESTMapper := kubectl.OutputVersionMapper{RESTMapper: mapper, OutputVersions: []unversioned.GroupVersion{cmdApiVersion}}
// eventually this should allow me choose a group priority based on the order of the discovery doc, for now hardcode a given order
priorityRESTMapper := meta.PriorityRESTMapper{
Delegate: outputRESTMapper,
ResourcePriority: []unversioned.GroupVersionResource{
{Group: api.GroupName, Version: meta.AnyVersion, Resource: meta.AnyResource},
{Group: extensions.GroupName, Version: meta.AnyVersion, Resource: meta.AnyResource},
{Group: metrics.GroupName, Version: meta.AnyVersion, Resource: meta.AnyResource},
},
KindPriority: []unversioned.GroupVersionKind{
{Group: api.GroupName, Version: meta.AnyVersion, Kind: meta.AnyKind},
{Group: extensions.GroupName, Version: meta.AnyVersion, Kind: meta.AnyKind},
{Group: metrics.GroupName, Version: meta.AnyVersion, Kind: meta.AnyKind},
},
}
return priorityRESTMapper, api.Scheme
},
Client: func() (*client.Client, error) {
return clients.ClientForVersion(nil)
},
ClientConfig: func() (*restclient.Config, error) {
return clients.ClientConfigForVersion(nil)
},
ClientForMapping: func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
mappingVersion := mapping.GroupVersionKind.GroupVersion()
client, err := clients.ClientForVersion(&mappingVersion)
if err != nil {
return nil, err
}
switch mapping.GroupVersionKind.Group {
case api.GroupName:
return client.RESTClient, nil
case autoscaling.GroupName:
return client.AutoscalingClient.RESTClient, nil
case batch.GroupName:
return client.BatchClient.RESTClient, nil
case extensions.GroupName:
return client.ExtensionsClient.RESTClient, nil
}
return nil, fmt.Errorf("unable to get RESTClient for resource '%s'", mapping.Resource)
},
Describer: func(mapping *meta.RESTMapping) (kubectl.Describer, error) {
mappingVersion := mapping.GroupVersionKind.GroupVersion()
client, err := clients.ClientForVersion(&mappingVersion)
if err != nil {
return nil, err
}
if describer, ok := kubectl.DescriberFor(mapping.GroupVersionKind.GroupKind(), client); ok {
return describer, nil
}
return nil, fmt.Errorf("no description has been implemented for %q", mapping.GroupVersionKind.Kind)
},
Decoder: func(toInternal bool) runtime.Decoder {
if toInternal {
return api.Codecs.UniversalDecoder()
}
return api.Codecs.UniversalDeserializer()
},
JSONEncoder: func() runtime.Encoder {
return api.Codecs.LegacyCodec(registered.EnabledVersions()...)
},
Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool, wide bool, showAll bool, showLabels bool, absoluteTimestamps bool, columnLabels []string) (kubectl.ResourcePrinter, error) {
return kubectl.NewHumanReadablePrinter(noHeaders, withNamespace, wide, showAll, showLabels, absoluteTimestamps, columnLabels), nil
},
PodSelectorForObject: func(object runtime.Object) (string, error) {
// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
switch t := object.(type) {
case *api.ReplicationController:
return kubectl.MakeLabels(t.Spec.Selector), nil
case *api.Pod:
//.........这里部分代码省略.........
示例3: NewFactory
//.........这里部分代码省略.........
return authenticationreaper.NewGroupReaper(
client.GroupsInterface(oc),
client.ClusterRoleBindingsInterface(oc),
client.RoleBindingsNamespacer(oc),
kclient.SecurityContextConstraintsInterface(kc),
), nil
case buildapi.Kind("BuildConfig"):
oc, _, err := w.Clients()
if err != nil {
return nil, err
}
return buildcmd.NewBuildConfigReaper(oc), nil
}
return kReaperFunc(mapping)
}
kGenerators := w.Factory.Generators
w.Generators = func(cmdName string) map[string]kubectl.Generator {
originGenerators := DefaultGenerators(cmdName)
kubeGenerators := kGenerators(cmdName)
ret := map[string]kubectl.Generator{}
for k, v := range kubeGenerators {
ret[k] = v
}
for k, v := range originGenerators {
ret[k] = v
}
return ret
}
kMapBasedSelectorForObjectFunc := w.Factory.MapBasedSelectorForObject
w.MapBasedSelectorForObject = func(object runtime.Object) (string, error) {
switch t := object.(type) {
case *deployapi.DeploymentConfig:
return kubectl.MakeLabels(t.Spec.Selector), nil
default:
return kMapBasedSelectorForObjectFunc(object)
}
}
kPortsForObjectFunc := w.Factory.PortsForObject
w.PortsForObject = func(object runtime.Object) ([]string, error) {
switch t := object.(type) {
case *deployapi.DeploymentConfig:
return getPorts(t.Spec.Template.Spec), nil
default:
return kPortsForObjectFunc(object)
}
}
kLogsForObjectFunc := w.Factory.LogsForObject
w.LogsForObject = func(object, options runtime.Object) (*restclient.Request, error) {
switch t := object.(type) {
case *deployapi.DeploymentConfig:
dopts, ok := options.(*deployapi.DeploymentLogOptions)
if !ok {
return nil, errors.New("provided options object is not a DeploymentLogOptions")
}
oc, _, err := w.Clients()
if err != nil {
return nil, err
}
return oc.DeploymentLogs(t.Namespace).Get(t.Name, *dopts), nil
case *buildapi.Build:
bopts, ok := options.(*buildapi.BuildLogOptions)
if !ok {
return nil, errors.New("provided options object is not a BuildLogOptions")
}
if bopts.Version != nil {
示例4: NewFactory
//.........这里部分代码省略.........
cfg.GroupVersion = &gv
cfg.APIPath = "/apis"
cfg.Codec = thirdpartyresourcedata.NewCodec(c.ExtensionsClient.RESTClient.Codec(), gvk.Kind)
return restclient.RESTClientFor(cfg)
}
},
Describer: func(mapping *meta.RESTMapping) (kubectl.Describer, error) {
mappingVersion := mapping.GroupVersionKind.GroupVersion()
client, err := clients.ClientForVersion(&mappingVersion)
if err != nil {
return nil, err
}
if describer, ok := kubectl.DescriberFor(mapping.GroupVersionKind.GroupKind(), client); ok {
return describer, nil
}
return nil, fmt.Errorf("no description has been implemented for %q", mapping.GroupVersionKind.Kind)
},
Decoder: func(toInternal bool) runtime.Decoder {
if toInternal {
return api.Codecs.UniversalDecoder()
}
return api.Codecs.UniversalDeserializer()
},
JSONEncoder: func() runtime.Encoder {
return api.Codecs.LegacyCodec(registered.EnabledVersions()...)
},
Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool, wide bool, showAll bool, showLabels bool, absoluteTimestamps bool, columnLabels []string) (kubectl.ResourcePrinter, error) {
return kubectl.NewHumanReadablePrinter(noHeaders, withNamespace, wide, showAll, showLabels, absoluteTimestamps, columnLabels), nil
},
MapBasedSelectorForObject: func(object runtime.Object) (string, error) {
// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
switch t := object.(type) {
case *api.ReplicationController:
return kubectl.MakeLabels(t.Spec.Selector), nil
case *api.Pod:
if len(t.Labels) == 0 {
return "", fmt.Errorf("the pod has no labels and cannot be exposed")
}
return kubectl.MakeLabels(t.Labels), nil
case *api.Service:
if t.Spec.Selector == nil {
return "", fmt.Errorf("the service has no pod selector set")
}
return kubectl.MakeLabels(t.Spec.Selector), nil
case *extensions.Deployment:
// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals
// operator, DoubleEquals operator and In operator with only one element in the set.
if len(t.Spec.Selector.MatchExpressions) > 0 {
return "", fmt.Errorf("couldn't convert expressions - \"%+v\" to map-based selector format", t.Spec.Selector.MatchExpressions)
}
return kubectl.MakeLabels(t.Spec.Selector.MatchLabels), nil
case *extensions.ReplicaSet:
// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals
// operator, DoubleEquals operator and In operator with only one element in the set.
if len(t.Spec.Selector.MatchExpressions) > 0 {
return "", fmt.Errorf("couldn't convert expressions - \"%+v\" to map-based selector format", t.Spec.Selector.MatchExpressions)
}
return kubectl.MakeLabels(t.Spec.Selector.MatchLabels), nil
default:
gvk, err := api.Scheme.ObjectKind(object)
if err != nil {
return "", err
}
return "", fmt.Errorf("cannot extract pod selector from %v", gvk)
}
},
示例5: NewFactory
// NewFactory creates a factory with the default Kubernetes resources defined
// if optionalClientConfig is nil, then flags will be bound to a new clientcmd.ClientConfig.
// if optionalClientConfig is not nil, then this factory will make use of it.
func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory {
mapper := kubectl.ShortcutExpander{RESTMapper: api.RESTMapper}
flags := pflag.NewFlagSet("", pflag.ContinueOnError)
flags.SetNormalizeFunc(util.WarnWordSepNormalizeFunc) // Warn for "_" flags
generators := map[string]kubectl.Generator{
"run/v1": kubectl.BasicReplicationController{},
"run-pod/v1": kubectl.BasicPod{},
"service/v1": kubectl.ServiceGeneratorV1{},
"service/v2": kubectl.ServiceGeneratorV2{},
}
clientConfig := optionalClientConfig
if optionalClientConfig == nil {
clientConfig = DefaultClientConfig(flags)
}
clients := NewClientCache(clientConfig)
return &Factory{
clients: clients,
flags: flags,
generators: generators,
Object: func() (meta.RESTMapper, runtime.ObjectTyper) {
cfg, err := clientConfig.ClientConfig()
CheckErr(err)
cmdApiVersion := cfg.Version
return kubectl.OutputVersionMapper{RESTMapper: mapper, OutputVersion: cmdApiVersion}, api.Scheme
},
Client: func() (*client.Client, error) {
return clients.ClientForVersion("")
},
ClientConfig: func() (*client.Config, error) {
return clients.ClientConfigForVersion("")
},
RESTClient: func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
group, err := api.RESTMapper.GroupForResource(mapping.Resource)
if err != nil {
return nil, err
}
client, err := clients.ClientForVersion(mapping.APIVersion)
if err != nil {
return nil, err
}
switch group {
case "":
return client.RESTClient, nil
case "extensions":
return client.ExtensionsClient.RESTClient, nil
}
return nil, fmt.Errorf("unable to get RESTClient for resource '%s'", mapping.Resource)
},
Describer: func(mapping *meta.RESTMapping) (kubectl.Describer, error) {
group, err := api.RESTMapper.GroupForResource(mapping.Resource)
if err != nil {
return nil, err
}
client, err := clients.ClientForVersion(mapping.APIVersion)
if err != nil {
return nil, err
}
if describer, ok := kubectl.DescriberFor(group, mapping.Kind, client); ok {
return describer, nil
}
return nil, fmt.Errorf("no description has been implemented for %q", mapping.Kind)
},
Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool, wide bool, showAll bool, columnLabels []string) (kubectl.ResourcePrinter, error) {
return kubectl.NewHumanReadablePrinter(noHeaders, withNamespace, wide, showAll, columnLabels), nil
},
PodSelectorForObject: func(object runtime.Object) (string, error) {
// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
switch t := object.(type) {
case *api.ReplicationController:
return kubectl.MakeLabels(t.Spec.Selector), nil
case *api.Pod:
if len(t.Labels) == 0 {
return "", fmt.Errorf("the pod has no labels and cannot be exposed")
}
return kubectl.MakeLabels(t.Labels), nil
case *api.Service:
if t.Spec.Selector == nil {
return "", fmt.Errorf("the service has no pod selector set")
}
return kubectl.MakeLabels(t.Spec.Selector), nil
default:
_, kind, err := api.Scheme.ObjectVersionAndKind(object)
if err != nil {
return "", err
}
return "", fmt.Errorf("cannot extract pod selector from %s", kind)
}
},
PortsForObject: func(object runtime.Object) ([]string, error) {
// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
//.........这里部分代码省略.........
示例6: RunExpose
func RunExpose(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *ExposeOptions) error {
namespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Filenames...).
ResourceTypeOrNameArgs(false, args...).
Flatten().
Do()
infos, err := r.Infos()
if err != nil {
return err
}
if len(infos) > 1 {
return fmt.Errorf("multiple resources provided: %v", args)
}
info := infos[0]
mapping := info.ResourceMapping()
if err := f.CanBeExposed(mapping.Kind); err != nil {
return err
}
// Get the input object
inputObject, err := r.Object()
if err != nil {
return err
}
// Get the generator, setup and validate all required parameters
generatorName := cmdutil.GetFlagString(cmd, "generator")
generator, found := f.Generator(generatorName)
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
}
names := generator.ParamNames()
params := kubectl.MakeParams(cmd, names)
name := info.Name
if len(name) > validation.DNS952LabelMaxLength {
name = name[:validation.DNS952LabelMaxLength]
}
params["default-name"] = name
// For objects that need a pod selector, derive it from the exposed object in case a user
// didn't explicitly specify one via --selector
if s, found := params["selector"]; found && kubectl.IsZero(s) {
s, err := f.PodSelectorForObject(inputObject)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find selectors via --selector flag or introspection: %s", err))
}
params["selector"] = s
}
if cmdutil.GetFlagInt(cmd, "port") < 1 {
noPorts := true
for _, param := range names {
if param.Name == "port" {
noPorts = false
break
}
}
if cmdutil.GetFlagInt(cmd, "port") < 0 && !noPorts {
ports, err := f.PortsForObject(inputObject)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find port via --port flag or introspection: %s", err))
}
switch len(ports) {
case 0:
return cmdutil.UsageError(cmd, "couldn't find port via --port flag or introspection")
case 1:
params["port"] = ports[0]
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("multiple ports to choose from: %v, please explicitly specify a port using the --port flag.", ports))
}
}
}
if cmdutil.GetFlagBool(cmd, "create-external-load-balancer") {
params["create-external-load-balancer"] = "true"
}
if kubectl.IsZero(params["labels"]) {
labels, err := f.LabelsForObject(inputObject)
if err != nil {
return err
}
params["labels"] = kubectl.MakeLabels(labels)
}
if v := cmdutil.GetFlagString(cmd, "type"); v != "" {
params["type"] = v
}
err = kubectl.ValidateParams(names, params)
if err != nil {
return err
}
// Expose new object
object, err := generator.Generate(params)
if err != nil {
//.........这里部分代码省略.........
示例7: NewFactory
//.........这里部分代码省略.........
if mapping.GroupVersionKind.Kind == "Cluster" {
return &kubectl.ClusterDescriber{Interface: fedClientSet}, nil
}
}
clientset, err := clients.ClientSetForVersion(&mappingVersion)
if err != nil {
return nil, err
}
if describer, ok := kubectl.DescriberFor(mapping.GroupVersionKind.GroupKind(), clientset); ok {
return describer, nil
}
return nil, fmt.Errorf("no description has been implemented for %q", mapping.GroupVersionKind.Kind)
},
Decoder: func(toInternal bool) runtime.Decoder {
var decoder runtime.Decoder
if toInternal {
decoder = api.Codecs.UniversalDecoder()
} else {
decoder = api.Codecs.UniversalDeserializer()
}
return thirdpartyresourcedata.NewDecoder(decoder, "")
},
JSONEncoder: func() runtime.Encoder {
return api.Codecs.LegacyCodec(registered.EnabledVersions()...)
},
Printer: func(mapping *meta.RESTMapping, options kubectl.PrintOptions) (kubectl.ResourcePrinter, error) {
return kubectl.NewHumanReadablePrinter(options), nil
},
MapBasedSelectorForObject: func(object runtime.Object) (string, error) {
// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
switch t := object.(type) {
case *api.ReplicationController:
return kubectl.MakeLabels(t.Spec.Selector), nil
case *api.Pod:
if len(t.Labels) == 0 {
return "", fmt.Errorf("the pod has no labels and cannot be exposed")
}
return kubectl.MakeLabels(t.Labels), nil
case *api.Service:
if t.Spec.Selector == nil {
return "", fmt.Errorf("the service has no pod selector set")
}
return kubectl.MakeLabels(t.Spec.Selector), nil
case *extensions.Deployment:
// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals
// operator, DoubleEquals operator and In operator with only one element in the set.
if len(t.Spec.Selector.MatchExpressions) > 0 {
return "", fmt.Errorf("couldn't convert expressions - \"%+v\" to map-based selector format", t.Spec.Selector.MatchExpressions)
}
return kubectl.MakeLabels(t.Spec.Selector.MatchLabels), nil
case *extensions.ReplicaSet:
// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals
// operator, DoubleEquals operator and In operator with only one element in the set.
if len(t.Spec.Selector.MatchExpressions) > 0 {
return "", fmt.Errorf("couldn't convert expressions - \"%+v\" to map-based selector format", t.Spec.Selector.MatchExpressions)
}
return kubectl.MakeLabels(t.Spec.Selector.MatchLabels), nil
default:
gvks, _, err := api.Scheme.ObjectKinds(object)
if err != nil {
return "", err
}
return "", fmt.Errorf("cannot extract pod selector from %v", gvks[0])
}
},
示例8: RunExpose
func RunExpose(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *ExposeOptions) error {
namespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Filenames...).
ResourceTypeOrNameArgs(false, args...).
Flatten().
Do()
infos, err := r.Infos()
if err != nil {
return err
}
if len(infos) > 1 {
return fmt.Errorf("multiple resources provided: %v", args)
}
info := infos[0]
mapping := info.ResourceMapping()
if err := f.CanBeExposed(mapping.Kind); err != nil {
return err
}
// Get the input object
inputObject, err := r.Object()
if err != nil {
return err
}
// Get the generator, setup and validate all required parameters
generatorName := cmdutil.GetFlagString(cmd, "generator")
generator, found := f.Generator(generatorName)
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
}
names := generator.ParamNames()
params := kubectl.MakeParams(cmd, names)
name := info.Name
if len(name) > validation.DNS952LabelMaxLength {
name = name[:validation.DNS952LabelMaxLength]
}
params["default-name"] = name
// For objects that need a pod selector, derive it from the exposed object in case a user
// didn't explicitly specify one via --selector
if s, found := params["selector"]; found && kubectl.IsZero(s) {
s, err := f.PodSelectorForObject(inputObject)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find selectors via --selector flag or introspection: %s", err))
}
params["selector"] = s
}
// For objects that need a port, derive it from the exposed object in case a user
// didn't explicitly specify one via --port
if port, found := params["port"]; found && kubectl.IsZero(port) {
ports, err := f.PortsForObject(inputObject)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find port via --port flag or introspection: %s", err))
}
switch len(ports) {
case 0:
return cmdutil.UsageError(cmd, "couldn't find port via --port flag or introspection")
case 1:
params["port"] = ports[0]
default:
params["ports"] = strings.Join(ports, ",")
}
}
if kubectl.IsZero(params["labels"]) {
labels, err := f.LabelsForObject(inputObject)
if err != nil {
return err
}
params["labels"] = kubectl.MakeLabels(labels)
}
if err = kubectl.ValidateParams(names, params); err != nil {
return err
}
// Generate new object
object, err := generator.Generate(params)
if err != nil {
return err
}
if inline := cmdutil.GetFlagString(cmd, "overrides"); len(inline) > 0 {
object, err = cmdutil.Merge(object, inline, mapping.Kind)
if err != nil {
return err
}
}
resourceMapper := &resource.Mapper{ObjectTyper: typer, RESTMapper: mapper, ClientMapper: f.ClientMapperForCommand()}
info, err = resourceMapper.InfoForObject(object)
if err != nil {
return err
//.........这里部分代码省略.........
示例9: NewFactory
//.........这里部分代码省略.........
return nil, err
}
return client.RESTClient, nil
case "experimental":
client, err := expClients.Client()
if err != nil {
return nil, err
}
return client.RESTClient, nil
}
return nil, fmt.Errorf("unable to get RESTClient for resource '%s'", mapping.Resource)
},
Describer: func(mapping *meta.RESTMapping) (kubectl.Describer, error) {
group, err := api.RESTMapper.GroupForResource(mapping.Resource)
if err != nil {
return nil, err
}
client, expClient, err := getBothClients(group, mapping.APIVersion)
if err != nil {
return nil, err
}
if describer, ok := kubectl.DescriberFor(mapping.Kind, client, expClient); ok {
return describer, nil
}
return nil, fmt.Errorf("no description has been implemented for %q", mapping.Kind)
},
Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool, wide bool, showAll bool, columnLabels []string) (kubectl.ResourcePrinter, error) {
return kubectl.NewHumanReadablePrinter(noHeaders, withNamespace, wide, showAll, columnLabels), nil
},
PodSelectorForObject: func(object runtime.Object) (string, error) {
// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
switch t := object.(type) {
case *api.ReplicationController:
return kubectl.MakeLabels(t.Spec.Selector), nil
case *api.Pod:
if len(t.Labels) == 0 {
return "", fmt.Errorf("the pod has no labels and cannot be exposed")
}
return kubectl.MakeLabels(t.Labels), nil
case *api.Service:
if t.Spec.Selector == nil {
return "", fmt.Errorf("the service has no pod selector set")
}
return kubectl.MakeLabels(t.Spec.Selector), nil
default:
_, kind, err := api.Scheme.ObjectVersionAndKind(object)
if err != nil {
return "", err
}
return "", fmt.Errorf("cannot extract pod selector from %s", kind)
}
},
PortsForObject: func(object runtime.Object) ([]string, error) {
// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
switch t := object.(type) {
case *api.ReplicationController:
return getPorts(t.Spec.Template.Spec), nil
case *api.Pod:
return getPorts(t.Spec), nil
case *api.Service:
return getServicePorts(t.Spec), nil
default:
_, kind, err := api.Scheme.ObjectVersionAndKind(object)
if err != nil {
return nil, err
}
示例10: NewFactory
//.........这里部分代码省略.........
client.RoleBindingsNamespacer(oc),
kclient.SecurityContextConstraintsInterface(kc),
), nil
case userapi.Kind("Group"):
return authenticationreaper.NewGroupReaper(
client.GroupsInterface(oc),
client.ClusterRoleBindingsInterface(oc),
client.RoleBindingsNamespacer(oc),
kclient.SecurityContextConstraintsInterface(kc),
), nil
case buildapi.Kind("BuildConfig"):
return buildreaper.NewBuildConfigReaper(oc), nil
}
return kReaperFunc(mapping)
}
kGenerators := w.Factory.Generators
w.Generators = func(cmdName string) map[string]kubectl.Generator {
originGenerators := DefaultGenerators(cmdName)
kubeGenerators := kGenerators(cmdName)
ret := map[string]kubectl.Generator{}
for k, v := range kubeGenerators {
ret[k] = v
}
for k, v := range originGenerators {
ret[k] = v
}
return ret
}
kMapBasedSelectorForObjectFunc := w.Factory.MapBasedSelectorForObject
w.MapBasedSelectorForObject = func(object runtime.Object) (string, error) {
switch t := object.(type) {
case *deployapi.DeploymentConfig:
return kubectl.MakeLabels(t.Spec.Selector), nil
default:
return kMapBasedSelectorForObjectFunc(object)
}
}
kPortsForObjectFunc := w.Factory.PortsForObject
w.PortsForObject = func(object runtime.Object) ([]string, error) {
switch t := object.(type) {
case *deployapi.DeploymentConfig:
return getPorts(t.Spec.Template.Spec), nil
default:
return kPortsForObjectFunc(object)
}
}
kLogsForObjectFunc := w.Factory.LogsForObject
w.LogsForObject = func(object, options runtime.Object) (*restclient.Request, error) {
oc, _, err := w.Clients()
if err != nil {
return nil, err
}
switch t := object.(type) {
case *deployapi.DeploymentConfig:
dopts, ok := options.(*deployapi.DeploymentLogOptions)
if !ok {
return nil, errors.New("provided options object is not a DeploymentLogOptions")
}
return oc.DeploymentLogs(t.Namespace).Get(t.Name, *dopts), nil
case *buildapi.Build:
bopts, ok := options.(*buildapi.BuildLogOptions)
if !ok {
return nil, errors.New("provided options object is not a BuildLogOptions")
}
示例11: NewFactory
// NewFactory creates an object that holds common methods across all OpenShift commands
func NewFactory(clientConfig kclientcmd.ClientConfig) *Factory {
mapper := ShortcutExpander{kubectl.ShortcutExpander{latest.RESTMapper}}
clients := &clientCache{
clients: make(map[string]*client.Client),
loader: clientConfig,
}
generators := map[string]kubectl.Generator{
"route/v1": routegen.RouteGenerator{},
"run/v1": deploygen.BasicDeploymentConfigController{},
"run-controller/v1": kubectl.BasicReplicationController{},
}
w := &Factory{
Factory: cmdutil.NewFactory(clientConfig),
OpenShiftClientConfig: clientConfig,
clients: clients,
}
w.Object = func() (meta.RESTMapper, runtime.ObjectTyper) {
if cfg, err := clientConfig.ClientConfig(); err == nil {
return kubectl.OutputVersionMapper{mapper, cfg.Version}, api.Scheme
}
return mapper, api.Scheme
}
kRESTClient := w.Factory.RESTClient
w.RESTClient = func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
if latest.OriginKind(mapping.Kind, mapping.APIVersion) {
client, err := clients.ClientForVersion(mapping.APIVersion)
if err != nil {
return nil, err
}
return client.RESTClient, nil
}
return kRESTClient(mapping)
}
// Save original Describer function
kDescriberFunc := w.Factory.Describer
w.Describer = func(mapping *meta.RESTMapping) (kubectl.Describer, error) {
if latest.OriginKind(mapping.Kind, mapping.APIVersion) {
oClient, kClient, err := w.Clients()
if err != nil {
return nil, fmt.Errorf("unable to create client %s: %v", mapping.Kind, err)
}
cfg, err := clients.ClientConfigForVersion(mapping.APIVersion)
if err != nil {
return nil, fmt.Errorf("unable to load a client %s: %v", mapping.Kind, err)
}
describer, ok := describe.DescriberFor(mapping.Kind, oClient, kClient, cfg.Host)
if !ok {
return nil, fmt.Errorf("no description has been implemented for %q", mapping.Kind)
}
return describer, nil
}
return kDescriberFunc(mapping)
}
kScalerFunc := w.Factory.Scaler
w.Scaler = func(mapping *meta.RESTMapping) (kubectl.Scaler, error) {
oc, kc, err := w.Clients()
if err != nil {
return nil, err
}
if mapping.Kind == "DeploymentConfig" {
return deployscaler.NewDeploymentConfigScaler(oc, kc), nil
}
return kScalerFunc(mapping)
}
kReaperFunc := w.Factory.Reaper
w.Reaper = func(mapping *meta.RESTMapping) (kubectl.Reaper, error) {
oc, kc, err := w.Clients()
if err != nil {
return nil, err
}
if mapping.Kind == "DeploymentConfig" {
return deployreaper.NewDeploymentConfigReaper(oc, kc), nil
}
return kReaperFunc(mapping)
}
kGeneratorFunc := w.Factory.Generator
w.Generator = func(name string) (kubectl.Generator, bool) {
if generator, ok := generators[name]; ok {
return generator, true
}
return kGeneratorFunc(name)
}
kPodSelectorForObjectFunc := w.Factory.PodSelectorForObject
w.PodSelectorForObject = func(object runtime.Object) (string, error) {
switch t := object.(type) {
case *deployapi.DeploymentConfig:
return kubectl.MakeLabels(t.Template.ControllerTemplate.Selector), nil
default:
return kPodSelectorForObjectFunc(object)
//.........这里部分代码省略.........
示例12: NewFactory
// NewFactory creates a factory with the default Kubernetes resources defined
// if optionalClientConfig is nil, then flags will be bound to a new clientcmd.ClientConfig.
// if optionalClientConfig is not nil, then this factory will make use of it.
func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory {
mapper := kubectl.ShortcutExpander{RESTMapper: api.RESTMapper}
flags := pflag.NewFlagSet("", pflag.ContinueOnError)
flags.SetNormalizeFunc(util.WarnWordSepNormalizeFunc) // Warn for "_" flags
generators := map[string]kubectl.Generator{
"run/v1": kubectl.BasicReplicationController{},
"run-pod/v1": kubectl.BasicPod{},
"service/v1": kubectl.ServiceGeneratorV1{},
"service/v2": kubectl.ServiceGeneratorV2{},
"horizontalpodautoscaler/v1beta1": kubectl.HorizontalPodAutoscalerV1Beta1{},
}
clientConfig := optionalClientConfig
if optionalClientConfig == nil {
clientConfig = DefaultClientConfig(flags)
}
clients := NewClientCache(clientConfig)
return &Factory{
clients: clients,
flags: flags,
generators: generators,
Object: func() (meta.RESTMapper, runtime.ObjectTyper) {
cfg, err := clientConfig.ClientConfig()
CheckErr(err)
cmdApiVersion := cfg.Version
return kubectl.OutputVersionMapper{RESTMapper: mapper, OutputVersion: cmdApiVersion}, api.Scheme
},
Client: func() (*client.Client, error) {
return clients.ClientForVersion("")
},
ClientConfig: func() (*client.Config, error) {
return clients.ClientConfigForVersion("")
},
RESTClient: func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
group, err := api.RESTMapper.GroupForResource(mapping.Resource)
if err != nil {
return nil, err
}
client, err := clients.ClientForVersion(mapping.APIVersion)
if err != nil {
return nil, err
}
switch group {
case "":
return client.RESTClient, nil
case "extensions":
return client.ExtensionsClient.RESTClient, nil
}
return nil, fmt.Errorf("unable to get RESTClient for resource '%s'", mapping.Resource)
},
Describer: func(mapping *meta.RESTMapping) (kubectl.Describer, error) {
group, err := api.RESTMapper.GroupForResource(mapping.Resource)
if err != nil {
return nil, err
}
client, err := clients.ClientForVersion(mapping.APIVersion)
if err != nil {
return nil, err
}
if describer, ok := kubectl.DescriberFor(group, mapping.Kind, client); ok {
return describer, nil
}
return nil, fmt.Errorf("no description has been implemented for %q", mapping.Kind)
},
Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool, wide bool, showAll bool, columnLabels []string) (kubectl.ResourcePrinter, error) {
return kubectl.NewHumanReadablePrinter(noHeaders, withNamespace, wide, showAll, columnLabels), nil
},
PodSelectorForObject: func(object runtime.Object) (string, error) {
// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
switch t := object.(type) {
case *api.ReplicationController:
return kubectl.MakeLabels(t.Spec.Selector), nil
case *api.Pod:
if len(t.Labels) == 0 {
return "", fmt.Errorf("the pod has no labels and cannot be exposed")
}
return kubectl.MakeLabels(t.Labels), nil
case *api.Service:
if t.Spec.Selector == nil {
return "", fmt.Errorf("the service has no pod selector set")
}
return kubectl.MakeLabels(t.Spec.Selector), nil
default:
_, kind, err := api.Scheme.ObjectVersionAndKind(object)
if err != nil {
return "", err
}
return "", fmt.Errorf("cannot extract pod selector from %s", kind)
}
},
PortsForObject: func(object runtime.Object) ([]string, error) {
//.........这里部分代码省略.........
示例13: NewFactory
//.........这里部分代码省略.........
if mapping.GroupVersionKind.Kind == "Cluster" {
return &kubectl.ClusterDescriber{Interface: fedClientSet}, nil
}
}
client, err := clients.ClientForVersion(&mappingVersion)
if err != nil {
return nil, err
}
if describer, ok := kubectl.DescriberFor(mapping.GroupVersionKind.GroupKind(), client); ok {
return describer, nil
}
return nil, fmt.Errorf("no description has been implemented for %q", mapping.GroupVersionKind.Kind)
},
Decoder: func(toInternal bool) runtime.Decoder {
var decoder runtime.Decoder
if toInternal {
decoder = api.Codecs.UniversalDecoder()
} else {
decoder = api.Codecs.UniversalDeserializer()
}
return thirdpartyresourcedata.NewDecoder(decoder, "")
},
JSONEncoder: func() runtime.Encoder {
return api.Codecs.LegacyCodec(registered.EnabledVersions()...)
},
Printer: func(mapping *meta.RESTMapping, options kubectl.PrintOptions) (kubectl.ResourcePrinter, error) {
return kubectl.NewHumanReadablePrinter(options), nil
},
MapBasedSelectorForObject: func(object runtime.Object) (string, error) {
// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
switch t := object.(type) {
case *api.ReplicationController:
return kubectl.MakeLabels(t.Spec.Selector), nil
case *api.Pod:
if len(t.Labels) == 0 {
return "", fmt.Errorf("the pod has no labels and cannot be exposed")
}
return kubectl.MakeLabels(t.Labels), nil
case *api.Service:
if t.Spec.Selector == nil {
return "", fmt.Errorf("the service has no pod selector set")
}
return kubectl.MakeLabels(t.Spec.Selector), nil
case *extensions.Deployment:
// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals
// operator, DoubleEquals operator and In operator with only one element in the set.
if len(t.Spec.Selector.MatchExpressions) > 0 {
return "", fmt.Errorf("couldn't convert expressions - \"%+v\" to map-based selector format", t.Spec.Selector.MatchExpressions)
}
return kubectl.MakeLabels(t.Spec.Selector.MatchLabels), nil
case *extensions.ReplicaSet:
// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals
// operator, DoubleEquals operator and In operator with only one element in the set.
if len(t.Spec.Selector.MatchExpressions) > 0 {
return "", fmt.Errorf("couldn't convert expressions - \"%+v\" to map-based selector format", t.Spec.Selector.MatchExpressions)
}
return kubectl.MakeLabels(t.Spec.Selector.MatchLabels), nil
default:
gvks, _, err := api.Scheme.ObjectKinds(object)
if err != nil {
return "", err
}
return "", fmt.Errorf("cannot extract pod selector from %v", gvks[0])
}
},
示例14: RunExpose
func RunExpose(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(namespace).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]
// Get the input object
client, err := f.RESTClient(mapping)
if err != nil {
return err
}
inputObject, err := resource.NewHelper(client, mapping).Get(info.Namespace, info.Name)
if err != nil {
return err
}
// Get the generator, setup and validate all required parameters
generatorName := cmdutil.GetFlagString(cmd, "generator")
generator, found := f.Generator(generatorName)
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
}
names := generator.ParamNames()
params := kubectl.MakeParams(cmd, names)
params["default-name"] = info.Name
if s, found := params["selector"]; !found || len(s) == 0 || cmdutil.GetFlagInt(cmd, "port") < 1 {
if len(s) == 0 {
s, err := f.PodSelectorForObject(inputObject)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find selectors via --selector flag or introspection: %s", err))
}
params["selector"] = s
}
noPorts := true
for _, param := range names {
if param.Name == "port" {
noPorts = false
break
}
}
if cmdutil.GetFlagInt(cmd, "port") < 0 && !noPorts {
ports, err := f.PortsForObject(inputObject)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find port via --port flag or introspection: %s", err))
}
switch len(ports) {
case 0:
return cmdutil.UsageError(cmd, "couldn't find port via --port flag or introspection")
case 1:
params["port"] = ports[0]
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("multiple ports to choose from: %v, please explicitly specify a port using the --port flag.", ports))
}
}
}
if cmdutil.GetFlagBool(cmd, "create-external-load-balancer") {
params["create-external-load-balancer"] = "true"
}
if len(params["labels"]) == 0 {
labels, err := f.LabelsForObject(inputObject)
if err != nil {
return err
}
params["labels"] = kubectl.MakeLabels(labels)
}
if v := cmdutil.GetFlagString(cmd, "type"); v != "" {
params["type"] = v
}
err = kubectl.ValidateParams(names, params)
if err != nil {
return err
}
// Expose new object
object, err := generator.Generate(params)
if err != nil {
//.........这里部分代码省略.........
示例15: RunExpose
func RunExpose(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *ExposeOptions) error {
namespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
mapper, typer := f.Object(false)
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Recursive, options.Filenames...).
ResourceTypeOrNameArgs(false, args...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
// Get the generator, setup and validate all required parameters
generatorName := cmdutil.GetFlagString(cmd, "generator")
generators := f.Generators("expose")
generator, found := generators[generatorName]
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
}
names := generator.ParamNames()
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
mapping := info.ResourceMapping()
if err := f.CanBeExposed(mapping.GroupVersionKind.GroupKind()); err != nil {
return err
}
params := kubectl.MakeParams(cmd, names)
name := info.Name
if len(name) > validation.DNS952LabelMaxLength {
name = name[:validation.DNS952LabelMaxLength]
}
params["default-name"] = name
// For objects that need a pod selector, derive it from the exposed object in case a user
// didn't explicitly specify one via --selector
if s, found := params["selector"]; found && kubectl.IsZero(s) {
s, err := f.MapBasedSelectorForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't retrieve selectors via --selector flag or introspection: %s", err))
}
params["selector"] = s
}
// For objects that need a port, derive it from the exposed object in case a user
// didn't explicitly specify one via --port
if port, found := params["port"]; found && kubectl.IsZero(port) {
ports, err := f.PortsForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find port via --port flag or introspection: %s", err))
}
switch len(ports) {
case 0:
return cmdutil.UsageError(cmd, "couldn't find port via --port flag or introspection")
case 1:
params["port"] = ports[0]
default:
params["ports"] = strings.Join(ports, ",")
}
}
// Always try to derive protocols from the exposed object, may use
// different protocols for different ports.
if _, found := params["protocol"]; found {
protocolsMap, err := f.ProtocolsForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find protocol via introspection: %s", err))
}
if protocols := kubectl.MakeProtocols(protocolsMap); !kubectl.IsZero(protocols) {
params["protocols"] = protocols
}
}
if kubectl.IsZero(params["labels"]) {
labels, err := f.LabelsForObject(info.Object)
if err != nil {
return err
}
params["labels"] = kubectl.MakeLabels(labels)
}
if err = kubectl.ValidateParams(names, params); err != nil {
return err
}
// Check for invalid flags used against the present generator.
if err := kubectl.EnsureFlagsValid(cmd, generators, generatorName); err != nil {
return err
}
// Generate new object
//.........这里部分代码省略.........