aboutsummaryrefslogtreecommitdiffstats
path: root/src/k8splugin/plugins/generic/plugin.go
blob: a210f6d6061c5de038f04110cb8133789c338df4 (plain)
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
Copyright 2018 Intel Corporation.
Copyright © 2021 Nokia Bell Labs.
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 main

import (
	"context"
	"fmt"
	logger "log"
	"time"

	appsv1 "k8s.io/api/apps/v1"
	"k8s.io/client-go/kubernetes"

	//appsv1beta1 "k8s.io/api/apps/v1beta1"
	//appsv1beta2 "k8s.io/api/apps/v1beta2"
	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/intstr"

	pkgerrors "github.com/pkg/errors"
	"github.com/prometheus/common/log"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/rest"

	"github.com/onap/multicloud-k8s/src/k8splugin/internal/app"
	"github.com/onap/multicloud-k8s/src/k8splugin/internal/config"
	"github.com/onap/multicloud-k8s/src/k8splugin/internal/helm"
	"github.com/onap/multicloud-k8s/src/k8splugin/internal/plugin"
	"github.com/onap/multicloud-k8s/src/k8splugin/internal/utils"
	cachetools "k8s.io/client-go/tools/cache"
	watchtools "k8s.io/client-go/tools/watch"
)

// Compile time check to see if genericPlugin implements the correct interface
var _ plugin.Reference = genericPlugin{}

// ExportedVariable is what we will look for when calling the generic plugin
var ExportedVariable genericPlugin

type genericPlugin struct {
}

func (g genericPlugin) WatchUntilReady(
	timeout time.Duration,
	ns string,
	res helm.KubernetesResource,
	mapper meta.RESTMapper,
	restClient rest.Interface,
	objType runtime.Object,
	clientSet kubernetes.Interface) error {
	selector, err := fields.ParseSelector(fmt.Sprintf("metadata.name=%s", res.Name))
	if err != nil {
		return err
	}

	mapping, err := mapper.RESTMapping(schema.GroupKind{
		Group: res.GVK.Group,
		Kind:  res.GVK.Kind,
	}, res.GVK.Version)
	if err != nil {
		return pkgerrors.Wrap(err, "Preparing mapper based on GVK")
	}
	lw := cachetools.NewListWatchFromClient(restClient, mapping.Resource.Resource, ns, selector)

	// What we watch for depends on the Kind.
	// - For a Job, we watch for completion.
	// - For all else, we watch until Ready.
	// In the future, we might want to add some special logic for types
	// like Ingress, Volume, etc.
	ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), timeout)
	defer cancel()

	_, err = watchtools.UntilWithSync(ctx, lw, objType, nil, func(e watch.Event) (bool, error) {
		obj := e.Object
		switch e.Type {
		case watch.Added, watch.Modified:
			// For things like a secret or a config map, this is the best indicator
			// we get. We care mostly about jobs, where what we want to see is
			// the status go into a good state.
			logger.Printf("Add/Modify event for %s: %v", res.Name, e.Type)
			switch res.GVK.Kind {
			case "Job":
				return g.waitForJob(obj, res.Name)
			case "Pod":
				return g.waitForPodSuccess(obj, res.Name)
			case "Deployment":
				return g.waitForDeploymentSuccess(obj, res.Name, clientSet)
			case "DaemonSet":
				return g.waitForDaemonSetSuccess(obj, res.Name)
			case "StatefulSet":
				return g.waitForStatefulSetSuccess(obj, res.Name)
			}
			return true, nil
		case watch.Deleted:
			logger.Printf("Deleted event for %s", res.Name)
			return true, nil
		case watch.Error:
			// Handle error and return with an error.
			logger.Printf("Error event for %s", res.Name)
			return true, pkgerrors.New("failed to deploy " + res.Name)
		default:
			return false, nil
		}
	})
	if err != nil {
		logger.Printf("Error in Rss %s", res.Name)
		return err
	} else {
		logger.Printf("Done for %s", res.Name)
		return nil
	}
}

// waitForJob is a helper that waits for a job to complete.
//
// This operates on an event returned from a watcher.
func (g genericPlugin) waitForJob(obj runtime.Object, name string) (bool, error) {
	o, ok := obj.(*batchv1.Job)
	if !ok {
		return true, pkgerrors.New("expected " + name + " to be a *batch.Job, got " + obj.GetObjectKind().GroupVersionKind().Kind)
	}

	for _, c := range o.Status.Conditions {
		if c.Type == batchv1.JobComplete && c.Status == "True" {
			return true, nil
		} else if c.Type == batchv1.JobFailed && c.Status == "True" {
			return true, pkgerrors.New("job failed: " + c.Reason)
		}
	}

	logger.Printf("%s: Jobs active: %d, jobs failed: %d, jobs succeeded: %d", name, o.Status.Active, o.Status.Failed, o.Status.Succeeded)
	return false, nil
}

// waitForPodSuccess is a helper that waits for a pod to complete.
//
// This operates on an event returned from a watcher.
func (g genericPlugin) waitForPodSuccess(obj runtime.Object, name string) (bool, error) {
	o, ok := obj.(*corev1.Pod)
	if !ok {
		return true, pkgerrors.New("expected " + name + " to be a *v1.Pod, got " + obj.GetObjectKind().GroupVersionKind().Kind)
	}

	switch o.Status.Phase {
	case corev1.PodSucceeded:
		logger.Printf("Pod %s succeeded", o.Name)
		return true, nil
	case corev1.PodFailed:
		return true, pkgerrors.New("pod " + o.Name + " failed")
	case corev1.PodPending:
		logger.Printf("Pod %s pending", o.Name)
	case corev1.PodRunning:
		logger.Printf("Pod %s running", o.Name)
	}

	return false, nil
}

// waitForDeploymentSuccess is a helper that waits for a deployment to run.
//
// This operates on an event returned from a watcher.
func (g genericPlugin) waitForDeploymentSuccess(obj runtime.Object, name string, clientSet kubernetes.Interface) (bool, error) {
	o, ok := obj.(*appsv1.Deployment)
	if !ok {
		return true, pkgerrors.New("expected " + name + " to be a *apps.Deployment, got " + obj.GetObjectKind().GroupVersionKind().Kind)
	}

	// If paused deployment will never be ready -> consider ready
	if o.Spec.Paused {
		logger.Printf("Depoyment %s is paused, consider ready", o.Name)
		return true, nil
	}

	// Find RS associated with deployment
	newReplicaSet, err := app.GetNewReplicaSet(o, clientSet.AppsV1())
	if err != nil || newReplicaSet == nil {
		return false, err
	}
	expectedReady := *o.Spec.Replicas - app.MaxUnavailable(*o)
	if !(newReplicaSet.Status.ReadyReplicas >= expectedReady) {
		logger.Printf("Deployment is not ready: %s/%s. %d out of %d expected pods are ready", o.Namespace, o.Name, newReplicaSet.Status.ReadyReplicas, expectedReady)
		return false, nil
	}
	return true, nil
}

// waitForDaemonSetSuccess is a helper that waits for a daemonSet to run.
//
// This operates on an event returned from a watcher.
func (g genericPlugin) waitForDaemonSetSuccess(obj runtime.Object, name string) (bool, error) {
	o, ok := obj.(*appsv1.DaemonSet)
	if !ok {
		return true, pkgerrors.New("expected " + name + " to be a *apps.DaemonSet, got " + obj.GetObjectKind().GroupVersionKind().Kind)
	}

	// If the update strategy is not a rolling update, there will be nothing to wait for
	if o.Spec.UpdateStrategy.Type != appsv1.RollingUpdateDaemonSetStrategyType {
		return true, nil
	}

	// Make sure all the updated pods have been scheduled
	if o.Status.UpdatedNumberScheduled != o.Status.DesiredNumberScheduled {
		logger.Printf("DaemonSet is not ready: %s/%s. %d out of %d expected pods have been scheduled", o.Namespace, o.Name, o.Status.UpdatedNumberScheduled, o.Status.DesiredNumberScheduled)
		return false, nil
	}
	maxUnavailable, err := intstr.GetValueFromIntOrPercent(o.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable, int(o.Status.DesiredNumberScheduled), true)
	if err != nil {
		// If for some reason the value is invalid, set max unavailable to the
		// number of desired replicas. This is the same behavior as the
		// `MaxUnavailable` function in deploymentutil
		maxUnavailable = int(o.Status.DesiredNumberScheduled)
	}

	expectedReady := int(o.Status.DesiredNumberScheduled) - maxUnavailable
	if !(int(o.Status.NumberReady) >= expectedReady) {
		logger.Printf("DaemonSet is not ready: %s/%s. %d out of %d expected pods are ready", o.Namespace, o.Name, o.Status.NumberReady, expectedReady)
		return false, nil
	}
	return true, nil
}

// waitForStatefulSetSuccess is a helper that waits for a statefulSet to run.
//
// This operates on an event returned from a watcher.
func (g genericPlugin) waitForStatefulSetSuccess(obj runtime.Object, name string) (bool, error) {
	o, ok := obj.(*appsv1.StatefulSet)
	if !ok {
		return true, pkgerrors.New("expected " + name + " to be a *apps.StatefulSet, got " + obj.GetObjectKind().GroupVersionKind().Kind)
	}

	// If the update strategy is not a rolling update, there will be nothing to wait for
	if o.Spec.UpdateStrategy.Type != appsv1.RollingUpdateStatefulSetStrategyType {
		return true, nil
	}

	// Dereference all the pointers because StatefulSets like them
	var partition int
	// 1 is the default for replicas if not set
	var replicas = 1
	// For some reason, even if the update strategy is a rolling update, the
	// actual rollingUpdate field can be nil. If it is, we can safely assume
	// there is no partition value
	if o.Spec.UpdateStrategy.RollingUpdate != nil && o.Spec.UpdateStrategy.RollingUpdate.Partition != nil {
		partition = int(*o.Spec.UpdateStrategy.RollingUpdate.Partition)
	}
	if o.Spec.Replicas != nil {
		replicas = int(*o.Spec.Replicas)
	}

	// Because an update strategy can use partitioning, we need to calculate the
	// number of updated replicas we should have. For example, if the replicas
	// is set to 3 and the partition is 2, we'd expect only one pod to be
	// updated
	expectedReplicas := replicas - partition

	// Make sure all the updated pods have been scheduled
	if int(o.Status.UpdatedReplicas) != expectedReplicas {
		logger.Printf("StatefulSet is not ready: %s/%s. %d out of %d expected pods have been scheduled", o.Namespace, o.Name, o.Status.UpdatedReplicas, expectedReplicas)
		return false, nil
	}

	if int(o.Status.ReadyReplicas) != replicas {
		logger.Printf("StatefulSet is not ready: %s/%s. %d out of %d expected pods are ready", o.Namespace, o.Name, o.Status.ReadyReplicas, replicas)
		return false, nil
	}
	return true, nil
}

// Create generic object in a specific Kubernetes cluster
func (g genericPlugin) Create(yamlFilePath string, namespace string, client plugin.KubernetesConnector) (string, error) {
	if namespace == "" {
		namespace = "default"
	}

	//Decode the yaml file to create a runtime.Object
	unstruct := &unstructured.Unstructured{}
	//Ignore the returned obj as we expect the data in unstruct
	_, err := utils.DecodeYAML(yamlFilePath, unstruct)
	if err != nil {
		return "", pkgerrors.Wrap(err, "Decode deployment object error")
	}

	dynClient := client.GetDynamicClient()
	mapper := client.GetMapper()

	gvk := unstruct.GroupVersionKind()
	mapping, err := mapper.RESTMapping(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version)
	if err != nil {
		return "", pkgerrors.Wrap(err, "Mapping kind to resource error")
	}
	if gvk.Kind == "CustomResourceDefinition" {
		//according the helm spec, CRD is created only once, and we raise only warn if we try to do it once more
		resource := helm.KubernetesResource{}
		resource.GVK = gvk
		resource.Name = unstruct.GetName()
		name, err := g.Get(resource, namespace, client)
		if err == nil && name == resource.Name {
			//CRD update is not supported according to Helm spec
			log.Warn(fmt.Sprintf("CRD %s create will be skipped. It already exists", name))
			return name, nil
		}
	}
	//Add the tracking label to all resources created here
	labels := unstruct.GetLabels()
	//Check if labels exist for this object
	if labels == nil {
		labels = map[string]string{}
	}
	labels[config.GetConfiguration().KubernetesLabelName] = client.GetInstanceID()
	unstruct.SetLabels(labels)

	// This checks if the resource we are creating has a podSpec in it
	// Eg: Deployment, StatefulSet, Job etc..
	// If a PodSpec is found, the label will be added to it too.
	plugin.TagPodsIfPresent(unstruct, client.GetInstanceID())

	gvr := mapping.Resource
	var createdObj *unstructured.Unstructured

	switch mapping.Scope.Name() {
	case meta.RESTScopeNameNamespace:
		createdObj, err = dynClient.Resource(gvr).Namespace(namespace).Create(context.TODO(), unstruct, metav1.CreateOptions{})
	case meta.RESTScopeNameRoot:
		createdObj, err = dynClient.Resource(gvr).Create(context.TODO(), unstruct, metav1.CreateOptions{})
	default:
		return "", pkgerrors.New("Got an unknown RESTSCopeName for mapping: " + gvk.String())
	}

	if err != nil {
		return "", pkgerrors.Wrap(err, "Create object error")
	}

	return createdObj.GetName(), nil
}

// Update deployment object in a specific Kubernetes cluster
func (g genericPlugin) Update(yamlFilePath string, namespace string, client plugin.KubernetesConnector) (string, error) {
	if namespace == "" {
		namespace = "default"
	}

	//Decode the yaml file to create a runtime.Object
	unstruct := &unstructured.Unstructured{}
	//Ignore the returned obj as we expect the data in unstruct
	_, err := utils.DecodeYAML(yamlFilePath, unstruct)
	if err != nil {
		return "", pkgerrors.Wrap(err, "Decode deployment object error")
	}

	dynClient := client.GetDynamicClient()
	mapper := client.GetMapper()

	gvk := unstruct.GroupVersionKind()
	mapping, err := mapper.RESTMapping(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version)
	if err != nil {
		return "", pkgerrors.Wrap(err, "Mapping kind to resource error")
	}

	if gvk.Kind == "CustomResourceDefinition" {
		resource := helm.KubernetesResource{}
		resource.GVK = gvk
		resource.Name = unstruct.GetName()
		name, err := g.Get(resource, namespace, client)
		if err == nil && name == resource.Name {
			//CRD update is not supported according to Helm spec
			log.Warn(fmt.Sprintf("CRD %s update will be skipped", name))
			return name, nil
		}
	}

	//Add the tracking label to all resources created here
	labels := unstruct.GetLabels()
	//Check if labels exist for this object
	if labels == nil {
		labels = map[string]string{}
	}
	labels[config.GetConfiguration().KubernetesLabelName] = client.GetInstanceID()
	unstruct.SetLabels(labels)

	// This checks if the resource we are creating has a podSpec in it
	// Eg: Deployment, StatefulSet, Job etc..
	// If a PodSpec is found, the label will be added to it too.
	plugin.TagPodsIfPresent(unstruct, client.GetInstanceID())

	gvr := mapping.Resource
	var updatedObj *unstructured.Unstructured

	switch mapping.Scope.Name() {
	case meta.RESTScopeNameNamespace:
		updatedObj, err = dynClient.Resource(gvr).Namespace(namespace).Update(context.TODO(), unstruct, metav1.UpdateOptions{})
	case meta.RESTScopeNameRoot:
		updatedObj, err = dynClient.Resource(gvr).Update(context.TODO(), unstruct, metav1.UpdateOptions{})
	default:
		return "", pkgerrors.New("Got an unknown RESTSCopeName for mapping: " + gvk.String())
	}

	if err != nil {
		return "", pkgerrors.Wrap(err, "Update object error")
	}

	return updatedObj.GetName(), nil
}

// Get an existing resource hosted in a specific Kubernetes cluster
func (g genericPlugin) Get(resource helm.KubernetesResource,
	namespace string, client plugin.KubernetesConnector) (string, error) {
	if namespace == "" {
		namespace = "default"
	}

	dynClient := client.GetDynamicClient()
	mapper := client.GetMapper()

	mapping, err := mapper.RESTMapping(schema.GroupKind{
		Group: resource.GVK.Group,
		Kind:  resource.GVK.Kind,
	}, resource.GVK.Version)
	if err != nil {
		return "", pkgerrors.Wrap(err, "Mapping kind to resource error")
	}

	gvr := mapping.Resource
	opts := metav1.GetOptions{}
	var unstruct *unstructured.Unstructured
	switch mapping.Scope.Name() {
	case meta.RESTScopeNameNamespace:
		unstruct, err = dynClient.Resource(gvr).Namespace(namespace).Get(context.TODO(), resource.Name, opts)
	case meta.RESTScopeNameRoot:
		unstruct, err = dynClient.Resource(gvr).Get(context.TODO(), resource.Name, opts)
	default:
		return "", pkgerrors.New("Got an unknown RESTSCopeName for mapping: " + resource.GVK.String())
	}

	if err != nil {
		return "", pkgerrors.Wrap(err, "Get object error")
	}

	return unstruct.GetName(), nil
}

// List all existing resources of the GroupVersionKind
// TODO: Implement in seperate patch
func (g genericPlugin) List(gvk schema.GroupVersionKind, namespace string,
	client plugin.KubernetesConnector) ([]helm.KubernetesResource, error) {

	var returnData []helm.KubernetesResource
	return returnData, nil
}

// Delete an existing resource hosted in a specific Kubernetes cluster
func (g genericPlugin) Delete(resource helm.KubernetesResource, namespace string, client plugin.KubernetesConnector) error {
	if namespace == "" {
		namespace = "default"
	}

	dynClient := client.GetDynamicClient()
	mapper := client.GetMapper()

	mapping, err := mapper.RESTMapping(schema.GroupKind{
		Group: resource.GVK.Group,
		Kind:  resource.GVK.Kind,
	}, resource.GVK.Version)
	if err != nil {
		return pkgerrors.Wrap(err, "Mapping kind to resource error")
	}

	gvr := mapping.Resource
	deletePolicy := metav1.DeletePropagationBackground
	opts := metav1.DeleteOptions{
		PropagationPolicy: &deletePolicy,
	}
	if resource.GVK.Kind == "CustomResourceDefinition" {
		//CRD deletion is not supported according to Helm spec
		log.Warn(fmt.Sprintf("CRD %s deletion will be skipped", resource.Name))
		return nil
	}

	switch mapping.Scope.Name() {
	case meta.RESTScopeNameNamespace:
		err = dynClient.Resource(gvr).Namespace(namespace).Delete(context.TODO(), resource.Name, opts)
	case meta.RESTScopeNameRoot:
		err = dynClient.Resource(gvr).Delete(context.TODO(), resource.Name, opts)
	default:
		return pkgerrors.New("Got an unknown RESTSCopeName for mapping: " + resource.GVK.String())
	}

	if err != nil {
		return pkgerrors.Wrap(err, "Delete object error")
	}
	return nil
}