/
replicaswatcher.go
173 lines (151 loc) · 4.75 KB
/
replicaswatcher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package runtimeobjects
import (
"context"
"fmt"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
corev1helpers "k8s.io/component-helpers/scheduling/corev1"
"k8s.io/klog/v2"
"k8s.io/perf-tests/clusterloader2/pkg/measurement/util/informer"
)
const (
informerSyncTimeout = time.Minute
)
// ReplicasWatcher is a struct that allows to check a number of replicas at a given time.
// Usage:
// var rw ReplicasWatcher = (...)
//
// if err := rw.Start(stopCh); err != nil {
// panic(err);
// }
//
// // Get number of replicas as needed.
// val = rw.Replicas()
// ...
// val = rw.Replicas()
type ReplicasWatcher interface {
Replicas() int
// Start must block until Replicas() returns a correct value.
Start(stopCh <-chan struct{}) error
}
// ConstReplicas is a ReplicasWatcher implementation that returns a constant value.
type ConstReplicas struct {
ReplicasCount int
}
func (c *ConstReplicas) Replicas() int {
return c.ReplicasCount
}
func (c *ConstReplicas) Start(_ <-chan struct{}) error {
return nil
}
var _ ReplicasWatcher = &ConstReplicas{}
// NodeCounter counts a number of node objects matching nodeSelector and affinity.
type NodeCounter struct {
client clientset.Interface
nodeSelector labels.Selector
affinity *corev1.Affinity
mu sync.Mutex
replicas int
tolerations []corev1.Toleration
}
var _ ReplicasWatcher = &NodeCounter{}
// NewNodeCounter returns a new nodeCounter that return a number of objects matching nodeSelector and affinity.
func NewNodeCounter(client clientset.Interface, nodeSelector labels.Selector, affinity *corev1.Affinity, tolerations []corev1.Toleration) *NodeCounter {
return &NodeCounter{
client: client,
nodeSelector: nodeSelector,
affinity: affinity,
tolerations: tolerations,
}
}
func (n *NodeCounter) Start(stopCh <-chan struct{}) error {
i := informer.NewInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.LabelSelector = n.nodeSelector.String()
return n.client.CoreV1().Nodes().List(context.TODO(), options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.LabelSelector = n.nodeSelector.String()
return n.client.CoreV1().Nodes().Watch(context.TODO(), options)
},
},
func(oldObj, newObj interface{}) {
if err := n.handleObject(oldObj, newObj); err != nil {
klog.Errorf("Error while processing node: %v", err)
}
},
)
// StartAndSync blocks until elements from initial list call are processed.
return informer.StartAndSync(i, stopCh, informerSyncTimeout)
}
func (n *NodeCounter) handleObject(oldObj, newObj interface{}) error {
old, err := n.shouldRun(oldObj)
if err != nil {
return err
}
new, err := n.shouldRun(newObj)
if err != nil {
return err
}
if new == old {
return nil
}
n.mu.Lock()
defer n.mu.Unlock()
if new && !old {
n.replicas++
} else {
n.replicas--
}
return nil
}
func (n *NodeCounter) Replicas() int {
n.mu.Lock()
defer n.mu.Unlock()
return n.replicas
}
func (n *NodeCounter) shouldRun(obj interface{}) (bool, error) {
if obj == nil {
return false, nil
}
node, ok := obj.(*corev1.Node)
if !ok {
return false, fmt.Errorf("unexpected type of obj: %v. got %T, want *corev1.Node", obj, obj)
}
matched, err := podMatchesNodeAffinity(n.affinity, node)
// refer to k8s.io/kubernetes@v1.22.15/pkg/controller/nodelifecycle/node_lifecycle_controller.go:633
// refer to k8s.io/kubernetes@v1.22.15/pkg/controller/daemon/daemon_controller.go:1247
_, hasUntoleratedTaint := corev1helpers.FindMatchingUntoleratedTaint(node.Spec.Taints, n.tolerations, func(t *corev1.Taint) bool {
return t.Effect == corev1.TaintEffectNoExecute || t.Effect == corev1.TaintEffectNoSchedule
})
return !hasUntoleratedTaint && matched, err
}
// GetReplicasOnce starts ReplicasWatcher and gets a number of replicas.
func GetReplicasOnce(rw ReplicasWatcher) (int, error) {
stopCh := make(chan struct{})
defer close(stopCh)
if err := rw.Start(stopCh); err != nil {
return 0, err
}
return rw.Replicas(), nil
}