attachablepodforobject.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package polymorphichelpers
  14. import (
  15. "fmt"
  16. "sort"
  17. "time"
  18. corev1 "k8s.io/api/core/v1"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. "k8s.io/cli-runtime/pkg/genericclioptions"
  21. corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
  22. "k8s.io/kubernetes/pkg/kubectl/util/podutils"
  23. )
  24. // attachablePodForObject returns the pod to which to attach given an object.
  25. func attachablePodForObject(restClientGetter genericclioptions.RESTClientGetter, object runtime.Object, timeout time.Duration) (*corev1.Pod, error) {
  26. switch t := object.(type) {
  27. case *corev1.Pod:
  28. return t, nil
  29. }
  30. clientConfig, err := restClientGetter.ToRESTConfig()
  31. if err != nil {
  32. return nil, err
  33. }
  34. clientset, err := corev1client.NewForConfig(clientConfig)
  35. if err != nil {
  36. return nil, err
  37. }
  38. namespace, selector, err := SelectorsForObject(object)
  39. if err != nil {
  40. return nil, fmt.Errorf("cannot attach to %T: %v", object, err)
  41. }
  42. sortBy := func(pods []*corev1.Pod) sort.Interface { return sort.Reverse(podutils.ActivePods(pods)) }
  43. pod, _, err := GetFirstPod(clientset, namespace, selector.String(), timeout, sortBy)
  44. return pod, err
  45. }