pod_store.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright 2016 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 utils
  14. import (
  15. "context"
  16. "time"
  17. "k8s.io/api/core/v1"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. "k8s.io/apimachinery/pkg/fields"
  20. "k8s.io/apimachinery/pkg/labels"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/util/wait"
  23. "k8s.io/apimachinery/pkg/watch"
  24. clientset "k8s.io/client-go/kubernetes"
  25. "k8s.io/client-go/tools/cache"
  26. )
  27. // Convenient wrapper around cache.Store that returns list of v1.Pod instead of interface{}.
  28. type PodStore struct {
  29. cache.Store
  30. stopCh chan struct{}
  31. Reflector *cache.Reflector
  32. }
  33. func NewPodStore(c clientset.Interface, namespace string, label labels.Selector, field fields.Selector) (*PodStore, error) {
  34. lw := &cache.ListWatch{
  35. ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
  36. options.LabelSelector = label.String()
  37. options.FieldSelector = field.String()
  38. obj, err := c.CoreV1().Pods(namespace).List(context.TODO(), options)
  39. return runtime.Object(obj), err
  40. },
  41. WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
  42. options.LabelSelector = label.String()
  43. options.FieldSelector = field.String()
  44. return c.CoreV1().Pods(namespace).Watch(context.TODO(), options)
  45. },
  46. }
  47. store := cache.NewStore(cache.MetaNamespaceKeyFunc)
  48. stopCh := make(chan struct{})
  49. reflector := cache.NewReflector(lw, &v1.Pod{}, store, 0)
  50. go reflector.Run(stopCh)
  51. if err := wait.PollImmediate(50*time.Millisecond, 2*time.Minute, func() (bool, error) {
  52. if len(reflector.LastSyncResourceVersion()) != 0 {
  53. return true, nil
  54. }
  55. return false, nil
  56. }); err != nil {
  57. close(stopCh)
  58. return nil, err
  59. }
  60. return &PodStore{Store: store, stopCh: stopCh, Reflector: reflector}, nil
  61. }
  62. func (s *PodStore) List() []*v1.Pod {
  63. objects := s.Store.List()
  64. pods := make([]*v1.Pod, 0)
  65. for _, o := range objects {
  66. pods = append(pods, o.(*v1.Pod))
  67. }
  68. return pods
  69. }
  70. func (s *PodStore) Stop() {
  71. close(s.stopCh)
  72. }