本文整理匯總了Golang中k8s/io/kubernetes/pkg/client/unversioned.Discovery函數的典型用法代碼示例。如果您正苦於以下問題:Golang Discovery函數的具體用法?Golang Discovery怎麽用?Golang Discovery使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Discovery函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: contactOthers
// Find all sibling pods in the service and post to their /write handler.
func contactOthers(state *State) {
const waitTimeout = 2 * time.Minute
defer state.doneContactingPeers()
client, err := client.NewInCluster()
if err != nil {
log.Fatalf("Unable to create client; error: %v\n", err)
}
// Double check that that worked by getting the server version.
if v, err := client.Discovery().ServerVersion(); err != nil {
log.Fatalf("Unable to get server version: %v\n", err)
} else {
log.Printf("Server version: %#v\n", v)
}
for start := time.Now(); time.Since(start) < waitTimeout; time.Sleep(5 * time.Second) {
eps := getWebserverEndpoints(client)
if eps.Len() >= *peerCount {
break
}
state.Logf("%v/%v has %v endpoints, which is less than %v as expected. Waiting for all endpoints to come up.", *namespace, *service, len(eps), *peerCount)
}
// Do this repeatedly, in case there's some propagation delay with getting
// newly started pods into the endpoints list.
for i := 0; i < 15; i++ {
eps := getWebserverEndpoints(client)
for ep := range eps {
state.Logf("Attempting to contact %s", ep)
contactSingle(ep, state)
}
time.Sleep(5 * time.Second)
}
}
示例2: contactOthers
// Find all sibling pods in the service and post to their /write handler.
func contactOthers(state *State) {
sleepTime := 5 * time.Second
// In large cluster getting all endpoints is pretty expensive.
// Thus, we will limit ourselves to send on average at most 10 such
// requests per second
if sleepTime < time.Duration(*peerCount/10)*time.Second {
sleepTime = time.Duration(*peerCount/10) * time.Second
}
timeout := 5 * time.Minute
// Similarly we need to bump timeout so that it is reasonable in large
// clusters.
if timeout < time.Duration(*peerCount)*time.Second {
timeout = time.Duration(*peerCount) * time.Second
}
defer state.doneContactingPeers()
config, err := restclient.InClusterConfig()
if err != nil {
log.Fatalf("Unable to create config; error: %v\n", err)
}
config.ContentType = "application/vnd.kubernetes.protobuf"
client, err := client.New(config)
if err != nil {
log.Fatalf("Unable to create client; error: %v\n", err)
}
// Double check that that worked by getting the server version.
if v, err := client.Discovery().ServerVersion(); err != nil {
log.Fatalf("Unable to get server version: %v\n", err)
} else {
log.Printf("Server version: %#v\n", v)
}
for start := time.Now(); time.Since(start) < timeout; time.Sleep(sleepTime) {
eps := getWebserverEndpoints(client)
if eps.Len() >= *peerCount {
break
}
state.Logf("%v/%v has %v endpoints (%v), which is less than %v as expected. Waiting for all endpoints to come up.", *namespace, *service, len(eps), eps.List(), *peerCount)
}
// Do this repeatedly, in case there's some propagation delay with getting
// newly started pods into the endpoints list.
for i := 0; i < 15; i++ {
eps := getWebserverEndpoints(client)
for ep := range eps {
state.Logf("Attempting to contact %s", ep)
contactSingle(ep, state)
}
time.Sleep(sleepTime)
}
}
示例3: contactOthers
// Find all sibling pods in the service and post to their /write handler.
func contactOthers(state *State) {
defer state.doneContactingPeers()
client, err := client.NewInCluster()
if err != nil {
log.Fatalf("Unable to create client; error: %v\n", err)
}
// Double check that that worked by getting the server version.
if v, err := client.Discovery().ServerVersion(); err != nil {
log.Fatalf("Unable to get server version: %v\n", err)
} else {
log.Printf("Server version: %#v\n", v)
}
// Do this repeatedly, in case there's some propagation delay with getting
// newly started pods into the endpoints list.
for i := 0; i < 15; i++ {
endpoints, err := client.Endpoints(*namespace).Get(*service)
if err != nil {
state.Logf("Unable to read the endpoints for %v/%v: %v; will try again.", *namespace, *service, err)
time.Sleep(time.Duration(1+rand.Intn(10)) * time.Second)
}
eps := sets.String{}
for _, ss := range endpoints.Subsets {
for _, a := range ss.Addresses {
for _, p := range ss.Ports {
eps.Insert(fmt.Sprintf("http://%s:%d", a.IP, p.Port))
}
}
}
for ep := range eps {
state.Logf("Attempting to contact %s", ep)
contactSingle(ep, state)
}
time.Sleep(5 * time.Second)
}
}
示例4: TestClient
func TestClient(t *testing.T) {
_, s := framework.RunAMaster(t)
defer s.Close()
ns := api.NamespaceDefault
framework.DeleteAllEtcdKeys()
client := client.NewOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}})
info, err := client.Discovery().ServerVersion()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if e, a := version.Get(), *info; !reflect.DeepEqual(e, a) {
t.Errorf("expected %#v, got %#v", e, a)
}
pods, err := client.Pods(ns).List(api.ListOptions{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(pods.Items) != 0 {
t.Errorf("expected no pods, got %#v", pods)
}
// get a validation error
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
GenerateName: "test",
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "test",
},
},
},
}
got, err := client.Pods(ns).Create(pod)
if err == nil {
t.Fatalf("unexpected non-error: %v", got)
}
// get a created pod
pod.Spec.Containers[0].Image = "an-image"
got, err = client.Pods(ns).Create(pod)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got.Name == "" {
t.Errorf("unexpected empty pod Name %v", got)
}
// pod is shown, but not scheduled
pods, err = client.Pods(ns).List(api.ListOptions{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(pods.Items) != 1 {
t.Errorf("expected one pod, got %#v", pods)
}
actual := pods.Items[0]
if actual.Name != got.Name {
t.Errorf("expected pod %#v, got %#v", got, actual)
}
if actual.Spec.NodeName != "" {
t.Errorf("expected pod to be unscheduled, got %#v", actual)
}
}
示例5: NewFactory
//.........這裏部分代碼省略.........
mappingVersion := mapping.GroupVersionKind.GroupVersion()
client, err := clients.ClientForVersion(&mappingVersion)
if err != nil {
return nil, err
}
return kubectl.RollbackerFor(mapping.GroupVersionKind.GroupKind(), client)
},
Validator: func(validate bool, cacheDir string) (validation.Schema, error) {
if validate {
client, err := clients.ClientForVersion(nil)
if err != nil {
return nil, err
}
dir := cacheDir
if len(dir) > 0 {
version, err := client.ServerVersion()
if err != nil {
return nil, err
}
dir = path.Join(cacheDir, version.String())
}
return &clientSwaggerSchema{
c: client,
cacheDir: dir,
mapper: api.RESTMapper,
}, nil
}
return validation.NullSchema{}, nil
},
SwaggerSchema: func(gvk unversioned.GroupVersionKind) (*swagger.ApiDeclaration, error) {
version := gvk.GroupVersion()
client, err := clients.ClientForVersion(&version)
if err != nil {
return nil, err
}
return client.Discovery().SwaggerSchema(version)
},
DefaultNamespace: func() (string, bool, error) {
return clientConfig.Namespace()
},
Generators: func(cmdName string) map[string]kubectl.Generator {
return DefaultGenerators(cmdName)
},
CanBeExposed: func(kind unversioned.GroupKind) error {
switch kind {
case api.Kind("ReplicationController"), api.Kind("Service"), api.Kind("Pod"), extensions.Kind("Deployment"), extensions.Kind("ReplicaSet"):
// nothing to do here
default:
return fmt.Errorf("cannot expose a %s", kind)
}
return nil
},
CanBeAutoscaled: func(kind unversioned.GroupKind) error {
switch kind {
case api.Kind("ReplicationController"), extensions.Kind("Deployment"), extensions.Kind("ReplicaSet"):
// nothing to do here
default:
return fmt.Errorf("cannot autoscale a %v", kind)
}
return nil
},
AttachablePodForObject: func(object runtime.Object) (*api.Pod, error) {
client, err := clients.ClientForVersion(nil)
if err != nil {
return nil, err
}
switch t := object.(type) {
case *api.ReplicationController:
selector := labels.SelectorFromSet(t.Spec.Selector)
pod, _, err := GetFirstPod(client, t.Namespace, selector)
return pod, err
case *extensions.Deployment:
selector, err := unversioned.LabelSelectorAsSelector(t.Spec.Selector)
if err != nil {
return nil, fmt.Errorf("invalid label selector: %v", err)
}
pod, _, err := GetFirstPod(client, t.Namespace, selector)
return pod, err
case *extensions.Job:
selector, err := unversioned.LabelSelectorAsSelector(t.Spec.Selector)
if err != nil {
return nil, fmt.Errorf("invalid label selector: %v", err)
}
pod, _, err := GetFirstPod(client, t.Namespace, selector)
return pod, err
case *api.Pod:
return t, nil
default:
gvk, err := api.Scheme.ObjectKind(object)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("cannot attach to %v: not implemented", gvk)
}
},
EditorEnvs: func() []string {
return []string{"KUBE_EDITOR", "EDITOR"}
},
}
}
示例6: Run
func Run(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *cobra.Command, args []string, argsLenAtDash int) error {
if len(os.Args) > 1 && os.Args[1] == "run-container" {
printDeprecationWarning("run", "run-container")
}
// Let kubectl run follow rules for `--`, see #13004 issue
if len(args) == 0 || argsLenAtDash == 0 {
return cmdutil.UsageError(cmd, "NAME is required for run")
}
interactive := cmdutil.GetFlagBool(cmd, "stdin")
tty := cmdutil.GetFlagBool(cmd, "tty")
if tty && !interactive {
return cmdutil.UsageError(cmd, "-i/--stdin is required for containers with -t/--tty=true")
}
replicas := cmdutil.GetFlagInt(cmd, "replicas")
if interactive && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("-i/--stdin requires that replicas is 1, found %d", replicas))
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
restartPolicy, err := getRestartPolicy(cmd, interactive)
if err != nil {
return err
}
if restartPolicy != api.RestartPolicyAlways && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("--restart=%s requires that --replicas=1, found %d", restartPolicy, replicas))
}
generatorName := cmdutil.GetFlagString(cmd, "generator")
if len(generatorName) == 0 {
client, err := f.Client()
if err != nil {
return err
}
resourcesList, err := client.Discovery().ServerResources()
if err != nil {
// this cover the cases where old servers do not expose discovery
resourcesList = nil
}
if restartPolicy == api.RestartPolicyAlways {
if contains(resourcesList, v1beta1.SchemeGroupVersion.WithResource("deployments")) {
generatorName = "deployment/v1beta1"
} else {
generatorName = "run/v1"
}
} else {
if contains(resourcesList, batchv1.SchemeGroupVersion.WithResource("jobs")) {
generatorName = "job/v1"
} else if contains(resourcesList, v1beta1.SchemeGroupVersion.WithResource("jobs")) {
generatorName = "job/v1beta1"
} else {
generatorName = "run-pod/v1"
}
}
}
generators := f.Generators("run")
generator, found := generators[generatorName]
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
}
names := generator.ParamNames()
params := kubectl.MakeParams(cmd, names)
params["name"] = args[0]
if len(args) > 1 {
params["args"] = args[1:]
}
params["env"] = cmdutil.GetFlagStringSlice(cmd, "env")
obj, _, mapper, mapping, err := createGeneratedObject(f, cmd, generator, names, params, cmdutil.GetFlagString(cmd, "overrides"), namespace)
if err != nil {
return err
}
if cmdutil.GetFlagBool(cmd, "expose") {
serviceGenerator := cmdutil.GetFlagString(cmd, "service-generator")
if len(serviceGenerator) == 0 {
return cmdutil.UsageError(cmd, fmt.Sprintf("No service generator specified"))
}
if err := generateService(f, cmd, args, serviceGenerator, params, namespace, cmdOut); err != nil {
return err
}
}
attachFlag := cmd.Flags().Lookup("attach")
attach := cmdutil.GetFlagBool(cmd, "attach")
if !attachFlag.Changed && interactive {
attach = true
}
remove := cmdutil.GetFlagBool(cmd, "rm")
if !attach && remove {
return cmdutil.UsageError(cmd, "--rm should only be used for attached containers")
}
//.........這裏部分代碼省略.........
示例7: 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,
// If discoverDynamicAPIs is true, make API calls to the discovery service to find APIs that
// have been dynamically added to the apiserver
Object: func(discoverDynamicAPIs bool) (meta.RESTMapper, runtime.ObjectTyper) {
cfg, err := clientConfig.ClientConfig()
CheckErr(err)
cmdApiVersion := unversioned.GroupVersion{}
if cfg.GroupVersion != nil {
cmdApiVersion = *cfg.GroupVersion
}
if discoverDynamicAPIs {
client, err := clients.ClientForVersion(&unversioned.GroupVersion{Version: "v1"})
CheckErr(err)
versions, gvks, err := GetThirdPartyGroupVersions(client.Discovery())
CheckErr(err)
if len(versions) > 0 {
priorityMapper, ok := mapper.RESTMapper.(meta.PriorityRESTMapper)
if !ok {
CheckErr(fmt.Errorf("expected PriorityMapper, saw: %v", mapper.RESTMapper))
return nil, nil
}
multiMapper, ok := priorityMapper.Delegate.(meta.MultiRESTMapper)
if !ok {
CheckErr(fmt.Errorf("unexpected type: %v", mapper.RESTMapper))
return nil, nil
}
groupsMap := map[string][]unversioned.GroupVersion{}
for _, version := range versions {
groupsMap[version.Group] = append(groupsMap[version.Group], version)
}
for group, versionList := range groupsMap {
preferredExternalVersion := versionList[0]
thirdPartyMapper, err := kubectl.NewThirdPartyResourceMapper(versionList, getGroupVersionKinds(gvks, group))
CheckErr(err)
accessor := meta.NewAccessor()
groupMeta := apimachinery.GroupMeta{
GroupVersion: preferredExternalVersion,
GroupVersions: versionList,
RESTMapper: thirdPartyMapper,
SelfLinker: runtime.SelfLinker(accessor),
InterfacesFor: makeInterfacesFor(versionList),
}
CheckErr(registered.RegisterGroup(groupMeta))
registered.AddThirdPartyAPIGroupVersions(versionList...)
multiMapper = append(meta.MultiRESTMapper{thirdPartyMapper}, multiMapper...)
}
priorityMapper.Delegate = multiMapper
// Re-assign to the RESTMapper here because priorityMapper is actually a copy, so if we
// don't re-assign, the above assignement won't actually update mapper.RESTMapper
mapper.RESTMapper = priorityMapper
}
}
outputRESTMapper := kubectl.OutputVersionMapper{RESTMapper: mapper, OutputVersions: []unversioned.GroupVersion{cmdApiVersion}}
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) {
gvk := mapping.GroupVersionKind
mappingVersion := mapping.GroupVersionKind.GroupVersion()
c, err := clients.ClientForVersion(&mappingVersion)
//.........這裏部分代碼省略.........
示例8: Run
func Run(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *cobra.Command, args []string, argsLenAtDash int) error {
if len(os.Args) > 1 && os.Args[1] == "run-container" {
printDeprecationWarning("run", "run-container")
}
// Let kubectl run follow rules for `--`, see #13004 issue
if len(args) == 0 || argsLenAtDash == 0 {
return cmdutil.UsageError(cmd, "NAME is required for run")
}
// validate image name
imageName := cmdutil.GetFlagString(cmd, "image")
validImageRef := reference.ReferenceRegexp.MatchString(imageName)
if !validImageRef {
return fmt.Errorf("Invalid image name %q: %v", imageName, reference.ErrReferenceInvalidFormat)
}
interactive := cmdutil.GetFlagBool(cmd, "stdin")
tty := cmdutil.GetFlagBool(cmd, "tty")
if tty && !interactive {
return cmdutil.UsageError(cmd, "-i/--stdin is required for containers with -t/--tty=true")
}
replicas := cmdutil.GetFlagInt(cmd, "replicas")
if interactive && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("-i/--stdin requires that replicas is 1, found %d", replicas))
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
restartPolicy, err := getRestartPolicy(cmd, interactive)
if err != nil {
return err
}
if restartPolicy != api.RestartPolicyAlways && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("--restart=%s requires that --replicas=1, found %d", restartPolicy, replicas))
}
if err := verifyImagePullPolicy(cmd); err != nil {
return err
}
generatorName := cmdutil.GetFlagString(cmd, "generator")
schedule := cmdutil.GetFlagString(cmd, "schedule")
if len(schedule) != 0 && len(generatorName) == 0 {
generatorName = "scheduledjob/v2alpha1"
}
if len(generatorName) == 0 {
client, err := f.Client()
if err != nil {
return err
}
resourcesList, err := client.Discovery().ServerResources()
// ServerResources ignores errors for old servers do not expose discovery
if err != nil {
return fmt.Errorf("failed to discover supported resources: %v", err)
}
switch restartPolicy {
case api.RestartPolicyAlways:
if contains(resourcesList, v1beta1.SchemeGroupVersion.WithResource("deployments")) {
generatorName = "deployment/v1beta1"
} else {
generatorName = "run/v1"
}
case api.RestartPolicyOnFailure:
if contains(resourcesList, batchv1.SchemeGroupVersion.WithResource("jobs")) {
generatorName = "job/v1"
} else if contains(resourcesList, v1beta1.SchemeGroupVersion.WithResource("jobs")) {
generatorName = "job/v1beta1"
} else {
generatorName = "run-pod/v1"
}
case api.RestartPolicyNever:
generatorName = "run-pod/v1"
}
}
generators := f.Generators("run")
generator, found := generators[generatorName]
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
}
names := generator.ParamNames()
params := kubectl.MakeParams(cmd, names)
params["name"] = args[0]
if len(args) > 1 {
params["args"] = args[1:]
}
params["env"] = cmdutil.GetFlagStringSlice(cmd, "env")
obj, _, mapper, mapping, err := createGeneratedObject(f, cmd, generator, names, params, cmdutil.GetFlagString(cmd, "overrides"), namespace)
if err != nil {
return err
}
if cmdutil.GetFlagBool(cmd, "expose") {
serviceGenerator := cmdutil.GetFlagString(cmd, "service-generator")
if len(serviceGenerator) == 0 {
return cmdutil.UsageError(cmd, fmt.Sprintf("No service generator specified"))
//.........這裏部分代碼省略.........
示例9: NewFactory
//.........這裏部分代碼省略.........
return kubectl.ReaperFor(mapping.GroupVersionKind.GroupKind(), client)
},
HistoryViewer: func(mapping *meta.RESTMapping) (kubectl.HistoryViewer, error) {
mappingVersion := mapping.GroupVersionKind.GroupVersion()
client, err := clients.ClientForVersion(&mappingVersion)
clientset := clientset.FromUnversionedClient(client)
if err != nil {
return nil, err
}
return kubectl.HistoryViewerFor(mapping.GroupVersionKind.GroupKind(), clientset)
},
Rollbacker: func(mapping *meta.RESTMapping) (kubectl.Rollbacker, error) {
mappingVersion := mapping.GroupVersionKind.GroupVersion()
client, err := clients.ClientForVersion(&mappingVersion)
if err != nil {
return nil, err
}
return kubectl.RollbackerFor(mapping.GroupVersionKind.GroupKind(), client)
},
Validator: func(validate bool, cacheDir string) (validation.Schema, error) {
if validate {
client, err := clients.ClientForVersion(nil)
if err != nil {
return nil, err
}
dir := cacheDir
if len(dir) > 0 {
version, err := client.ServerVersion()
if err != nil {
return nil, err
}
dir = path.Join(cacheDir, version.String())
}
return &clientSwaggerSchema{
c: client,
cacheDir: dir,
mapper: api.RESTMapper,
}, nil
}
return validation.NullSchema{}, nil
},
SwaggerSchema: func(gvk unversioned.GroupVersionKind) (*swagger.ApiDeclaration, error) {
version := gvk.GroupVersion()
client, err := clients.ClientForVersion(&version)
if err != nil {
return nil, err
}
return client.Discovery().SwaggerSchema(version)
},
DefaultNamespace: func() (string, bool, error) {
return clientConfig.Namespace()
},
Generators: func(cmdName string) map[string]kubectl.Generator {
return DefaultGenerators(cmdName)
},
CanBeExposed: func(kind unversioned.GroupKind) error {
switch kind {
case api.Kind("ReplicationController"), api.Kind("Service"), api.Kind("Pod"), extensions.Kind("Deployment"):
// nothing to do here
default:
return fmt.Errorf("cannot expose a %s", kind)
}
return nil
},
CanBeAutoscaled: func(kind unversioned.GroupKind) error {
switch kind {
case api.Kind("ReplicationController"), extensions.Kind("Deployment"):
// nothing to do here
default:
return fmt.Errorf("cannot autoscale a %v", kind)
}
return nil
},
AttachablePodForObject: func(object runtime.Object) (*api.Pod, error) {
client, err := clients.ClientForVersion(nil)
if err != nil {
return nil, err
}
switch t := object.(type) {
case *api.ReplicationController:
return GetFirstPod(client, t.Namespace, t.Spec.Selector)
case *extensions.Deployment:
return GetFirstPod(client, t.Namespace, t.Spec.Selector)
case *extensions.Job:
return GetFirstPod(client, t.Namespace, t.Spec.Selector.MatchLabels)
case *api.Pod:
return t, nil
default:
gvk, err := api.Scheme.ObjectKind(object)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("cannot attach to %v: not implemented", gvk)
}
},
EditorEnvs: func() []string {
return []string{"KUBE_EDITOR", "EDITOR"}
},
}
}
示例10: 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,
// If discoverDynamicAPIs is true, make API calls to the discovery service to find APIs that
// have been dynamically added to the apiserver
Object: func(discoverDynamicAPIs bool) (meta.RESTMapper, runtime.ObjectTyper) {
cfg, err := clientConfig.ClientConfig()
checkErrWithPrefix("failed to get client config: ", err)
cmdApiVersion := unversioned.GroupVersion{}
if cfg.GroupVersion != nil {
cmdApiVersion = *cfg.GroupVersion
}
if discoverDynamicAPIs {
client, err := clients.ClientForVersion(&unversioned.GroupVersion{Version: "v1"})
checkErrWithPrefix("failed to find client for version v1: ", err)
var versions []unversioned.GroupVersion
var gvks []unversioned.GroupVersionKind
retries := 3
for i := 0; i < retries; i++ {
versions, gvks, err = GetThirdPartyGroupVersions(client.Discovery())
// Retry if we got a NotFound error, because user may delete
// a thirdparty group when the GetThirdPartyGroupVersions is
// running.
if err == nil || !apierrors.IsNotFound(err) {
break
}
}
checkErrWithPrefix("failed to get third-party group versions: ", err)
if len(versions) > 0 {
priorityMapper, ok := mapper.RESTMapper.(meta.PriorityRESTMapper)
if !ok {
CheckErr(fmt.Errorf("expected PriorityMapper, saw: %v", mapper.RESTMapper))
return nil, nil
}
multiMapper, ok := priorityMapper.Delegate.(meta.MultiRESTMapper)
if !ok {
CheckErr(fmt.Errorf("unexpected type: %v", mapper.RESTMapper))
return nil, nil
}
groupsMap := map[string][]unversioned.GroupVersion{}
for _, version := range versions {
groupsMap[version.Group] = append(groupsMap[version.Group], version)
}
for group, versionList := range groupsMap {
preferredExternalVersion := versionList[0]
thirdPartyMapper, err := kubectl.NewThirdPartyResourceMapper(versionList, getGroupVersionKinds(gvks, group))
checkErrWithPrefix("failed to create third party resource mapper: ", err)
accessor := meta.NewAccessor()
groupMeta := apimachinery.GroupMeta{
GroupVersion: preferredExternalVersion,
GroupVersions: versionList,
RESTMapper: thirdPartyMapper,
SelfLinker: runtime.SelfLinker(accessor),
InterfacesFor: makeInterfacesFor(versionList),
}
checkErrWithPrefix("failed to register group: ", registered.RegisterGroup(groupMeta))
registered.AddThirdPartyAPIGroupVersions(versionList...)
multiMapper = append(meta.MultiRESTMapper{thirdPartyMapper}, multiMapper...)
}
priorityMapper.Delegate = multiMapper
// Reassign to the RESTMapper here because priorityMapper is actually a copy, so if we
// don't reassign, the above assignement won't actually update mapper.RESTMapper
mapper.RESTMapper = priorityMapper
}
}
outputRESTMapper := kubectl.OutputVersionMapper{RESTMapper: mapper, OutputVersions: []unversioned.GroupVersion{cmdApiVersion}}
priorityRESTMapper := meta.PriorityRESTMapper{
Delegate: outputRESTMapper,
}
// TODO: this should come from registered versions
groups := []string{api.GroupName, autoscaling.GroupName, extensions.GroupName, federation.GroupName, batch.GroupName}
// set a preferred version
for _, group := range groups {
gvs := registered.EnabledVersionsForGroup(group)
if len(gvs) == 0 {
continue
}
priorityRESTMapper.ResourcePriority = append(priorityRESTMapper.ResourcePriority, unversioned.GroupVersionResource{Group: group, Version: gvs[0].Version, Resource: meta.AnyResource})
priorityRESTMapper.KindPriority = append(priorityRESTMapper.KindPriority, unversioned.GroupVersionKind{Group: group, Version: gvs[0].Version, Kind: meta.AnyKind})
}
//.........這裏部分代碼省略.........