-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
controller.go
411 lines (353 loc) · 11.8 KB
/
controller.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*
* This file is part of the KubeVirt project
*
* 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.
*
* Copyright 2017 Red Hat, Inc.
*
*/
package controller
import (
"context"
"fmt"
"runtime/debug"
"strings"
"time"
k8sv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
v1 "kubevirt.io/api/core/v1"
"kubevirt.io/client-go/log"
cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
)
const (
// BurstReplicas is the maximum amount of requests in a row for CRUD operations on resources by controllers,
// to avoid unintentional DoS
BurstReplicas uint = 250
)
// NewListWatchFromClient creates a new ListWatch from the specified client, resource, kubevirtNamespace and field selector.
func NewListWatchFromClient(c cache.Getter, resource string, namespace string, fieldSelector fields.Selector, labelSelector labels.Selector) *cache.ListWatch {
listFunc := func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = fieldSelector.String()
options.LabelSelector = labelSelector.String()
return c.Get().
Namespace(namespace).
Resource(resource).
VersionedParams(&options, metav1.ParameterCodec).
Do(context.Background()).
Get()
}
watchFunc := func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = fieldSelector.String()
options.LabelSelector = labelSelector.String()
options.Watch = true
return c.Get().
Namespace(namespace).
Resource(resource).
VersionedParams(&options, metav1.ParameterCodec).
Watch(context.Background())
}
return &cache.ListWatch{ListFunc: listFunc, WatchFunc: watchFunc}
}
func HandlePanic() {
if r := recover(); r != nil {
// Ignoring error - There is nothing to do, if logging fails
_ = log.Log.Level(log.FATAL).Log("stacktrace", debug.Stack(), "msg", r)
}
}
func NewResourceEventHandlerFuncsForWorkqueue(queue workqueue.RateLimitingInterface) cache.ResourceEventHandlerFuncs {
return cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := KeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
UpdateFunc: func(old interface{}, new interface{}) {
key, err := KeyFunc(new)
if err == nil {
queue.Add(key)
}
},
DeleteFunc: func(obj interface{}) {
key, err := KeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
}
}
func MigrationKey(migration *v1.VirtualMachineInstanceMigration) string {
return fmt.Sprintf("%v/%v", migration.ObjectMeta.Namespace, migration.ObjectMeta.Name)
}
func VirtualMachineInstanceKey(vmi *v1.VirtualMachineInstance) string {
return fmt.Sprintf("%v/%v", vmi.ObjectMeta.Namespace, vmi.ObjectMeta.Name)
}
func VirtualMachineKey(vm *v1.VirtualMachine) string {
return fmt.Sprintf("%v/%v", vm.ObjectMeta.Namespace, vm.ObjectMeta.Name)
}
func PodKey(pod *k8sv1.Pod) string {
return fmt.Sprintf("%v/%v", pod.Namespace, pod.Name)
}
func DataVolumeKey(dataVolume *cdiv1.DataVolume) string {
return fmt.Sprintf("%v/%v", dataVolume.Namespace, dataVolume.Name)
}
func VirtualMachineInstanceKeys(vmis []*v1.VirtualMachineInstance) []string {
keys := []string{}
for _, vmi := range vmis {
keys = append(keys, VirtualMachineInstanceKey(vmi))
}
return keys
}
func VirtualMachineKeys(vms []*v1.VirtualMachine) []string {
keys := []string{}
for _, vm := range vms {
keys = append(keys, VirtualMachineKey(vm))
}
return keys
}
func HasFinalizer(object metav1.Object, finalizer string) bool {
for _, f := range object.GetFinalizers() {
if f == finalizer {
return true
}
}
return false
}
func RemoveFinalizer(object metav1.Object, finalizer string) {
filtered := []string{}
for _, f := range object.GetFinalizers() {
if f != finalizer {
filtered = append(filtered, f)
}
}
object.SetFinalizers(filtered)
}
func AddFinalizer(object metav1.Object, finalizer string) {
if HasFinalizer(object, finalizer) {
return
}
object.SetFinalizers(append(object.GetFinalizers(), finalizer))
}
func ObservedLatestApiVersionAnnotation(object metav1.Object) bool {
annotations := object.GetAnnotations()
if annotations == nil {
return false
}
version, ok := annotations[v1.ControllerAPILatestVersionObservedAnnotation]
if !ok || version != v1.ApiLatestVersion {
return false
}
return true
}
func SetLatestApiVersionAnnotation(object metav1.Object) {
annotations := object.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
annotations[v1.ControllerAPILatestVersionObservedAnnotation] = v1.ApiLatestVersion
annotations[v1.ControllerAPIStorageVersionObservedAnnotation] = v1.ApiStorageVersion
object.SetAnnotations(annotations)
}
func ApplyVolumeRequestOnVMISpec(vmiSpec *v1.VirtualMachineInstanceSpec, request *v1.VirtualMachineVolumeRequest) *v1.VirtualMachineInstanceSpec {
if request.AddVolumeOptions != nil {
alreadyAdded := false
for _, volume := range vmiSpec.Volumes {
if volume.Name == request.AddVolumeOptions.Name {
alreadyAdded = true
break
}
}
if !alreadyAdded {
newVolume := v1.Volume{
Name: request.AddVolumeOptions.Name,
}
if request.AddVolumeOptions.VolumeSource.PersistentVolumeClaim != nil {
pvcSource := request.AddVolumeOptions.VolumeSource.PersistentVolumeClaim.DeepCopy()
pvcSource.Hotpluggable = true
newVolume.VolumeSource.PersistentVolumeClaim = pvcSource
} else if request.AddVolumeOptions.VolumeSource.DataVolume != nil {
dvSource := request.AddVolumeOptions.VolumeSource.DataVolume.DeepCopy()
dvSource.Hotpluggable = true
newVolume.VolumeSource.DataVolume = dvSource
}
vmiSpec.Volumes = append(vmiSpec.Volumes, newVolume)
if request.AddVolumeOptions.Disk != nil {
newDisk := request.AddVolumeOptions.Disk.DeepCopy()
newDisk.Name = request.AddVolumeOptions.Name
vmiSpec.Domain.Devices.Disks = append(vmiSpec.Domain.Devices.Disks, *newDisk)
}
}
} else if request.RemoveVolumeOptions != nil {
newVolumesList := []v1.Volume{}
newDisksList := []v1.Disk{}
for _, volume := range vmiSpec.Volumes {
if volume.Name != request.RemoveVolumeOptions.Name {
newVolumesList = append(newVolumesList, volume)
}
}
for _, disk := range vmiSpec.Domain.Devices.Disks {
if disk.Name != request.RemoveVolumeOptions.Name {
newDisksList = append(newDisksList, disk)
}
}
vmiSpec.Volumes = newVolumesList
vmiSpec.Domain.Devices.Disks = newDisksList
}
return vmiSpec
}
func CurrentVMIPod(vmi *v1.VirtualMachineInstance, podIndexer cache.Indexer) (*k8sv1.Pod, error) {
// current pod is the most recent pod created on the current VMI node
// OR the most recent pod created if no VMI node is set.
// Get all pods from the namespace
objs, err := podIndexer.ByIndex(cache.NamespaceIndex, vmi.Namespace)
if err != nil {
return nil, err
}
pods := []*k8sv1.Pod{}
for _, obj := range objs {
pod := obj.(*k8sv1.Pod)
pods = append(pods, pod)
}
var curPod *k8sv1.Pod = nil
for _, pod := range pods {
if !IsControlledBy(pod, vmi) {
continue
}
if vmi.Status.NodeName != "" &&
vmi.Status.NodeName != pod.Spec.NodeName {
// This pod isn't scheduled to the current node.
// This can occur during the initial migration phases when
// a new target node is being prepared for the VMI.
continue
}
if curPod == nil || curPod.CreationTimestamp.Before(&pod.CreationTimestamp) {
curPod = pod
}
}
return curPod, nil
}
func VMIActivePodsCount(vmi *v1.VirtualMachineInstance, vmiPodIndexer cache.Indexer) int {
objs, err := vmiPodIndexer.ByIndex(cache.NamespaceIndex, vmi.Namespace)
if err != nil {
return 0
}
running := 0
for _, obj := range objs {
pod := obj.(*k8sv1.Pod)
if pod.Status.Phase == k8sv1.PodSucceeded || pod.Status.Phase == k8sv1.PodFailed {
// not interested in terminated pods
continue
} else if !IsControlledBy(pod, vmi) {
// not interested pods not associated with the vmi
continue
}
running++
}
return running
}
func GeneratePatchBytes(ops []string) []byte {
return []byte(fmt.Sprintf("[%s]", strings.Join(ops, ", ")))
}
func SetVMIPhaseTransitionTimestamp(oldVMI *v1.VirtualMachineInstance, newVMI *v1.VirtualMachineInstance) {
if oldVMI.Status.Phase != newVMI.Status.Phase {
for _, transitionTimeStamp := range newVMI.Status.PhaseTransitionTimestamps {
if transitionTimeStamp.Phase == newVMI.Status.Phase {
// already exists.
return
}
}
now := metav1.NewTime(time.Now())
newVMI.Status.PhaseTransitionTimestamps = append(newVMI.Status.PhaseTransitionTimestamps, v1.VirtualMachineInstancePhaseTransitionTimestamp{
Phase: newVMI.Status.Phase,
PhaseTransitionTimestamp: now,
})
}
}
func SetVMIMigrationPhaseTransitionTimestamp(oldVMIMigration *v1.VirtualMachineInstanceMigration, newVMIMigration *v1.VirtualMachineInstanceMigration) {
if oldVMIMigration.Status.Phase != newVMIMigration.Status.Phase {
for _, transitionTimeStamp := range newVMIMigration.Status.PhaseTransitionTimestamps {
if transitionTimeStamp.Phase == newVMIMigration.Status.Phase {
// already exists.
return
}
}
now := metav1.NewTime(time.Now())
newVMIMigration.Status.PhaseTransitionTimestamps = append(newVMIMigration.Status.PhaseTransitionTimestamps, v1.VirtualMachineInstanceMigrationPhaseTransitionTimestamp{
Phase: newVMIMigration.Status.Phase,
PhaseTransitionTimestamp: now,
})
}
}
func SetSourcePod(migration *v1.VirtualMachineInstanceMigration, vmi *v1.VirtualMachineInstance, podIndexer cache.Indexer) {
if migration.Status.Phase != v1.MigrationPending {
return
}
sourcePod, err := CurrentVMIPod(vmi, podIndexer)
if err != nil {
log.Log.Object(vmi).Reason(err).Warning("migration source pod not found")
}
if sourcePod != nil {
if migration.Status.MigrationState == nil {
migration.Status.MigrationState = &v1.VirtualMachineInstanceMigrationState{}
}
migration.Status.MigrationState.SourcePod = sourcePod.Name
}
}
func VMIHasHotplugVolumes(vmi *v1.VirtualMachineInstance) bool {
for _, volumeStatus := range vmi.Status.VolumeStatus {
if volumeStatus.HotplugVolume != nil {
return true
}
}
for _, volume := range vmi.Spec.Volumes {
if volume.DataVolume != nil && volume.DataVolume.Hotpluggable {
return true
}
if volume.PersistentVolumeClaim != nil && volume.PersistentVolumeClaim.Hotpluggable {
return true
}
}
return false
}
func vmiHasCondition(vmi *v1.VirtualMachineInstance, conditionType v1.VirtualMachineInstanceConditionType) bool {
vmiConditionManager := NewVirtualMachineInstanceConditionManager()
return vmiConditionManager.HasCondition(vmi, conditionType)
}
func VMIHasHotplugCPU(vmi *v1.VirtualMachineInstance) bool {
return vmiHasCondition(vmi, v1.VirtualMachineInstanceVCPUChange)
}
func VMIHasHotplugMemory(vmi *v1.VirtualMachineInstance) bool {
return vmiHasCondition(vmi, v1.VirtualMachineInstanceMemoryChange)
}
func AttachmentPods(ownerPod *k8sv1.Pod, podIndexer cache.Indexer) ([]*k8sv1.Pod, error) {
objs, err := podIndexer.ByIndex(cache.NamespaceIndex, ownerPod.Namespace)
if err != nil {
return nil, err
}
attachmentPods := []*k8sv1.Pod{}
for _, obj := range objs {
pod := obj.(*k8sv1.Pod)
ownerRef := GetControllerOf(pod)
if ownerRef == nil || ownerRef.UID != ownerPod.UID {
continue
}
attachmentPods = append(attachmentPods, pod)
}
return attachmentPods, nil
}