-
Notifications
You must be signed in to change notification settings - Fork 6
/
common.go
1733 lines (1488 loc) · 64.9 KB
/
common.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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2018 Synopsys, Inc.
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 util
import (
"encoding/json"
"fmt"
"io/ioutil"
"reflect"
"strings"
"time"
alertScheme "github.com/blackducksoftware/synopsysctl/pkg/alert/client/clientset/versioned/scheme"
blackduckScheme "github.com/blackducksoftware/synopsysctl/pkg/blackduck/client/clientset/versioned/scheme"
opssightScheme "github.com/blackducksoftware/synopsysctl/pkg/opssight/client/clientset/versioned/scheme"
horizonapi "github.com/blackducksoftware/horizon/pkg/api"
"github.com/blackducksoftware/horizon/pkg/components"
alertclientset "github.com/blackducksoftware/synopsysctl/pkg/alert/client/clientset/versioned"
"github.com/blackducksoftware/synopsysctl/pkg/api"
alertapi "github.com/blackducksoftware/synopsysctl/pkg/api/alert/v1"
blackduckapi "github.com/blackducksoftware/synopsysctl/pkg/api/blackduck/v1"
opssightapi "github.com/blackducksoftware/synopsysctl/pkg/api/opssight/v1"
hubclientset "github.com/blackducksoftware/synopsysctl/pkg/blackduck/client/clientset/versioned"
opssightclientset "github.com/blackducksoftware/synopsysctl/pkg/opssight/client/clientset/versioned"
routev1 "github.com/openshift/api/route/v1"
securityv1 "github.com/openshift/api/security/v1"
routeclient "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1"
securityclient "github.com/openshift/client-go/security/clientset/versioned/typed/security/v1"
log "github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/api/storage/v1beta1"
apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
const (
// OPENSHIFT denotes to create an OpenShift routes
OPENSHIFT = "OPENSHIFT"
// NONE denotes no exposed service
NONE = "NONE"
// NODEPORT denotes to create a NodePort service
NODEPORT = "NODEPORT"
// LOADBALANCER denotes to create a LoadBalancer service
LOADBALANCER = "LOADBALANCER"
)
// CreateContainer will create the container
func CreateContainer(config *horizonapi.ContainerConfig, envs []*horizonapi.EnvConfig, volumeMounts []*horizonapi.VolumeMountConfig, ports []*horizonapi.PortConfig,
actionConfig *horizonapi.ActionConfig, preStopConfig *horizonapi.ActionConfig, livenessProbeConfigs []*horizonapi.ProbeConfig, readinessProbeConfigs []*horizonapi.ProbeConfig) (*components.Container, error) {
container, err := components.NewContainer(*config)
if err != nil {
return nil, err
}
for _, env := range envs {
container.AddEnv(*env)
}
for _, volumeMount := range volumeMounts {
container.AddVolumeMount(*volumeMount)
}
for _, port := range ports {
container.AddPort(*port)
}
if actionConfig != nil {
container.AddPostStartAction(*actionConfig)
}
// Adds a PreStop if given, originally added to enable graceful pg shutdown
if preStopConfig != nil {
container.AddPreStopAction(*preStopConfig)
}
for _, livenessProbe := range livenessProbeConfigs {
container.AddLivenessProbe(*livenessProbe)
}
for _, readinessProbe := range readinessProbeConfigs {
container.AddReadinessProbe(*readinessProbe)
}
return container, nil
}
// CreateGCEPersistentDiskVolume will create a GCE Persistent disk volume for a pod
func CreateGCEPersistentDiskVolume(volumeName string, diskName string, fsType string) *components.Volume {
gcePersistentDiskVol := components.NewGCEPersistentDiskVolume(horizonapi.GCEPersistentDiskVolumeConfig{
VolumeName: volumeName,
DiskName: diskName,
FSType: fsType,
})
return gcePersistentDiskVol
}
// CreateEmptyDirVolumeWithoutSizeLimit will create a empty directory for a pod
func CreateEmptyDirVolumeWithoutSizeLimit(volumeName string) (*components.Volume, error) {
emptyDirVol, err := components.NewEmptyDirVolume(horizonapi.EmptyDirVolumeConfig{
VolumeName: volumeName,
})
return emptyDirVol, err
}
// CreatePersistentVolumeClaimVolume will create a PVC claim for a pod
func CreatePersistentVolumeClaimVolume(volumeName string, pvcName string) (*components.Volume, error) {
pvcVol := components.NewPVCVolume(horizonapi.PVCVolumeConfig{
PVCName: pvcName,
VolumeName: volumeName,
})
return pvcVol, nil
}
// CreateEmptyDirVolume will create a empty directory for a pod
func CreateEmptyDirVolume(volumeName string, sizeLimit string) (*components.Volume, error) {
emptyDirVol, err := components.NewEmptyDirVolume(horizonapi.EmptyDirVolumeConfig{
VolumeName: volumeName,
SizeLimit: sizeLimit,
})
return emptyDirVol, err
}
// CreateConfigMapVolume will mount the config map for a pod
func CreateConfigMapVolume(volumeName string, mapName string, defaultMode int) (*components.Volume, error) {
configMapVol := components.NewConfigMapVolume(horizonapi.ConfigMapOrSecretVolumeConfig{
VolumeName: volumeName,
DefaultMode: IntToInt32(defaultMode),
MapOrSecretName: mapName,
})
return configMapVol, nil
}
// CreateSecretVolume will mount the secret for a pod
func CreateSecretVolume(volumeName string, secretName string, defaultMode int) (*components.Volume, error) {
secretVol := components.NewSecretVolume(horizonapi.ConfigMapOrSecretVolumeConfig{
VolumeName: volumeName,
DefaultMode: IntToInt32(defaultMode),
MapOrSecretName: secretName,
})
return secretVol, nil
}
// CreatePod will create the pod
func CreatePod(podConfig *PodConfig) (*components.Pod, error) {
name := podConfig.Name
// create pod config
pod := components.NewPod(horizonapi.PodConfig{
Name: name,
FSGID: podConfig.FSGID,
RunAsUser: podConfig.RunAsUser,
RunAsGroup: podConfig.RunAsGroup,
})
// set service account
if len(podConfig.ServiceAccount) > 0 {
pod.Spec.ServiceAccountName = podConfig.ServiceAccount
}
// add volumes
for _, volume := range podConfig.Volumes {
pod.AddVolume(volume)
}
// add labels
pod.AddLabels(podConfig.Labels)
// add pod affinities
for affinityType, podAffinityConfigs := range podConfig.PodAffinityConfigs {
for _, podAffinityConfig := range podAffinityConfigs {
pod.AddPodAffinity(affinityType, *podAffinityConfig)
}
}
// add pod anti affinities
for affinityType, podAntiAffinityConfigs := range podConfig.PodAntiAffinityConfigs {
for _, podAntiAffinityConfig := range podAntiAffinityConfigs {
pod.AddPodAntiAffinity(affinityType, *podAntiAffinityConfig)
}
}
// add node affinities
for affinityType, nodeAffinityConfigs := range podConfig.NodeAffinityConfigs {
for _, nodeAffinityConfig := range nodeAffinityConfigs {
pod.AddNodeAffinity(affinityType, *nodeAffinityConfig)
}
}
// add containers
for _, containerConfig := range podConfig.Containers {
container, err := CreateContainer(containerConfig.ContainerConfig, containerConfig.EnvConfigs, containerConfig.VolumeMounts, containerConfig.PortConfig,
containerConfig.ActionConfig, containerConfig.PreStopConfig, containerConfig.LivenessProbeConfigs, containerConfig.ReadinessProbeConfigs)
if err != nil {
return nil, fmt.Errorf("failed to create the container for pod %s because %+v", name, err)
}
pod.AddContainer(container)
}
// add init containers
for _, initContainerConfig := range podConfig.InitContainers {
initContainer, err := CreateContainer(initContainerConfig.ContainerConfig, initContainerConfig.EnvConfigs, initContainerConfig.VolumeMounts,
initContainerConfig.PortConfig, initContainerConfig.ActionConfig, initContainerConfig.PreStopConfig, initContainerConfig.LivenessProbeConfigs, initContainerConfig.ReadinessProbeConfigs)
if err != nil {
return nil, fmt.Errorf("failed to create the init container for pod %s because %+v", name, err)
}
err = pod.AddInitContainer(initContainer)
if err != nil {
return nil, fmt.Errorf("failed to create the init container for pod %s because %+v", name, err)
}
}
if len(podConfig.ImagePullSecrets) > 0 {
pod.AddImagePullSecrets(podConfig.ImagePullSecrets)
}
return pod, nil
}
// CreateDeployment will create a deployment
func CreateDeployment(deploymentConfig *horizonapi.DeploymentConfig, pod *components.Pod, labels map[string]string, labelSelector map[string]string) *components.Deployment {
deployment := components.NewDeployment(*deploymentConfig)
deployment.Spec.Strategy.Type = appsv1.RecreateDeploymentStrategyType
deployment.AddMatchLabelsSelectors(labelSelector)
deployment.AddLabels(labels)
deployment.AddPod(pod)
return deployment
}
// CreateDeploymentFromContainer will create a deployment with multiple containers inside a pod
func CreateDeploymentFromContainer(deploymentConfig *horizonapi.DeploymentConfig, podConfig *PodConfig, labelSelector map[string]string) (*components.Deployment, error) {
podConfig.Name = deploymentConfig.Name
pod, err := CreatePod(podConfig)
if err != nil {
return nil, fmt.Errorf("unable to create pod for the deployment %s due to %+v", deploymentConfig.Name, err)
}
deployment := CreateDeployment(deploymentConfig, pod, podConfig.Labels, labelSelector)
return deployment, nil
}
// CreateReplicationController will create a replication controller
func CreateReplicationController(replicationControllerConfig *horizonapi.ReplicationControllerConfig, pod *components.Pod, labels map[string]string,
labelSelector map[string]string) *components.ReplicationController {
rc := components.NewReplicationController(*replicationControllerConfig)
rc.AddSelectors(labelSelector)
rc.AddLabels(labels)
rc.AddPod(pod)
return rc
}
// CreateReplicationControllerFromContainer will create a replication controller with multiple containers inside a pod
func CreateReplicationControllerFromContainer(replicationControllerConfig *horizonapi.ReplicationControllerConfig, podConfig *PodConfig, labelSelector map[string]string) (*components.ReplicationController, error) {
podConfig.Name = replicationControllerConfig.Name
pod, err := CreatePod(podConfig)
if err != nil {
return nil, fmt.Errorf("unable to create pod for the replication controller %s due to %+v", replicationControllerConfig.Name, err)
}
rc := CreateReplicationController(replicationControllerConfig, pod, podConfig.Labels, labelSelector)
return rc, nil
}
// CreateService will create the service
func CreateService(name string, selectLabel map[string]string, namespace string, port int32, target int32, serviceType horizonapi.ServiceType, label map[string]string) *components.Service {
svcConfig := horizonapi.ServiceConfig{
Name: name,
Namespace: namespace,
Type: serviceType,
}
mySvc := components.NewService(svcConfig)
myPort := &horizonapi.ServicePortConfig{
Name: fmt.Sprintf("port-%d", port),
Port: port,
TargetPort: fmt.Sprint(target),
Protocol: horizonapi.ProtocolTCP,
}
mySvc.AddPort(*myPort)
mySvc.AddSelectors(selectLabel)
mySvc.AddLabels(label)
return mySvc
}
// CreateServiceWithMultiplePort will create the service with multiple port
func CreateServiceWithMultiplePort(name string, selectLabel map[string]string, namespace string, ports []int32, serviceType horizonapi.ServiceType, label map[string]string) *components.Service {
svcConfig := horizonapi.ServiceConfig{
Name: name,
Namespace: namespace,
Type: serviceType,
}
mySvc := components.NewService(svcConfig)
for _, port := range ports {
myPort := &horizonapi.ServicePortConfig{
Name: fmt.Sprintf("port-%d", port),
Port: port,
TargetPort: fmt.Sprint(port),
Protocol: horizonapi.ProtocolTCP,
}
mySvc.AddPort(*myPort)
}
mySvc.AddSelectors(selectLabel)
mySvc.AddLabels(label)
return mySvc
}
// CreateSecretFromFile will create the secret from file
func CreateSecretFromFile(clientset *kubernetes.Clientset, jsonFile string, namespace string, name string, dataKey string) (*corev1.Secret, error) {
file, err := ioutil.ReadFile(jsonFile)
if err != nil {
log.Panicf("Unable to read the secret file %s due to error: %v\n", jsonFile, err)
}
return clientset.CoreV1().Secrets(namespace).Create(&corev1.Secret{
Type: corev1.SecretTypeOpaque,
StringData: map[string]string{dataKey: string(file)},
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
})
}
// CreateSecret will create the secret
func CreateSecret(clientset *kubernetes.Clientset, namespace string, name string, stringData map[string]string) (*corev1.Secret, error) {
return clientset.CoreV1().Secrets(namespace).Create(&corev1.Secret{
Type: corev1.SecretTypeOpaque,
StringData: stringData,
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
})
}
// GetSecret will create the secret
func GetSecret(clientset *kubernetes.Clientset, namespace string, name string) (*corev1.Secret, error) {
return clientset.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
}
// ListSecrets will list the secret
func ListSecrets(clientset *kubernetes.Clientset, namespace string, labelSelector string) (*corev1.SecretList, error) {
return clientset.CoreV1().Secrets(namespace).List(metav1.ListOptions{LabelSelector: labelSelector})
}
// UpdateSecret updates a secret
func UpdateSecret(clientset *kubernetes.Clientset, namespace string, secret *corev1.Secret) (*corev1.Secret, error) {
return clientset.CoreV1().Secrets(namespace).Update(secret)
}
// DeleteSecret will delete the secret
func DeleteSecret(clientset *kubernetes.Clientset, namespace string, name string) error {
return clientset.CoreV1().Secrets(namespace).Delete(name, &metav1.DeleteOptions{})
}
// GetConfigMap will get the config map
func GetConfigMap(clientset *kubernetes.Clientset, namespace string, name string) (*corev1.ConfigMap, error) {
return clientset.CoreV1().ConfigMaps(namespace).Get(name, metav1.GetOptions{})
}
// ListConfigMaps will list the config map
func ListConfigMaps(clientset *kubernetes.Clientset, namespace string, labelSelector string) (*corev1.ConfigMapList, error) {
return clientset.CoreV1().ConfigMaps(namespace).List(metav1.ListOptions{LabelSelector: labelSelector})
}
// UpdateConfigMap updates a config map
func UpdateConfigMap(clientset *kubernetes.Clientset, namespace string, configMap *corev1.ConfigMap) (*corev1.ConfigMap, error) {
return clientset.CoreV1().ConfigMaps(namespace).Update(configMap)
}
// DeleteConfigMap will delete the config map
func DeleteConfigMap(clientset *kubernetes.Clientset, namespace string, name string) error {
return clientset.CoreV1().ConfigMaps(namespace).Delete(name, &metav1.DeleteOptions{})
}
// CreateNamespace will create the namespace
func CreateNamespace(clientset *kubernetes.Clientset, namespace string) (*corev1.Namespace, error) {
return clientset.CoreV1().Namespaces().Create(&corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: namespace,
},
})
}
// GetNamespace will get the namespace
func GetNamespace(clientset *kubernetes.Clientset, namespace string) (*corev1.Namespace, error) {
return clientset.CoreV1().Namespaces().Get(namespace, metav1.GetOptions{})
}
// ListNamespaces will list the namespace
func ListNamespaces(clientset *kubernetes.Clientset, labelSelector string) (*corev1.NamespaceList, error) {
return clientset.CoreV1().Namespaces().List(metav1.ListOptions{LabelSelector: labelSelector})
}
// UpdateNamespace updates a namespace
func UpdateNamespace(clientset *kubernetes.Clientset, namespace *corev1.Namespace) (*corev1.Namespace, error) {
return clientset.CoreV1().Namespaces().Update(namespace)
}
// DeleteNamespace will delete the namespace
func DeleteNamespace(clientset *kubernetes.Clientset, namespace string) error {
return clientset.CoreV1().Namespaces().Delete(namespace, &metav1.DeleteOptions{})
}
// GetPod will get the input pods corresponding to a namespace
func GetPod(clientset *kubernetes.Clientset, namespace string, name string) (*corev1.Pod, error) {
return clientset.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})
}
// ListPods will get all the pods corresponding to a namespace
func ListPods(clientset *kubernetes.Clientset, namespace string) (*corev1.PodList, error) {
return clientset.CoreV1().Pods(namespace).List(metav1.ListOptions{})
}
// ListPodsWithLabels will get all the pods corresponding to a namespace and labels
func ListPodsWithLabels(clientset *kubernetes.Clientset, namespace string, labelSelector string) (*corev1.PodList, error) {
return clientset.CoreV1().Pods(namespace).List(metav1.ListOptions{LabelSelector: labelSelector})
}
// DeletePod will delete the input pods corresponding to a namespace
func DeletePod(clientset *kubernetes.Clientset, namespace string, name string) error {
propagationPolicy := metav1.DeletePropagationBackground
return clientset.CoreV1().Pods(namespace).Delete(name, &metav1.DeleteOptions{
PropagationPolicy: &propagationPolicy,
})
}
// GetReplicationController will get the replication controller corresponding to a namespace and name
func GetReplicationController(clientset *kubernetes.Clientset, namespace string, name string) (*corev1.ReplicationController, error) {
return clientset.CoreV1().ReplicationControllers(namespace).Get(name, metav1.GetOptions{})
}
// ListReplicationControllers will get the replication controllers corresponding to a namespace
func ListReplicationControllers(clientset *kubernetes.Clientset, namespace string, labelSelector string) (*corev1.ReplicationControllerList, error) {
return clientset.CoreV1().ReplicationControllers(namespace).List(metav1.ListOptions{LabelSelector: labelSelector})
}
// UpdateReplicationController updates the replication controller
func UpdateReplicationController(clientset *kubernetes.Clientset, namespace string, rc *corev1.ReplicationController) (*corev1.ReplicationController, error) {
return clientset.CoreV1().ReplicationControllers(namespace).Update(rc)
}
// DeleteReplicationController will delete the replication controller corresponding to a namespace and name
func DeleteReplicationController(clientset *kubernetes.Clientset, namespace string, name string) error {
propagationPolicy := metav1.DeletePropagationBackground
return clientset.CoreV1().ReplicationControllers(namespace).Delete(name, &metav1.DeleteOptions{
PropagationPolicy: &propagationPolicy,
})
}
// GetDeployment will get the deployment corresponding to a namespace and name
func GetDeployment(clientset *kubernetes.Clientset, namespace string, name string) (*appsv1.Deployment, error) {
return clientset.AppsV1().Deployments(namespace).Get(name, metav1.GetOptions{})
}
// ListDeployments will get all the deployments corresponding to a namespace
func ListDeployments(clientset *kubernetes.Clientset, namespace string, labelSelector string) (*appsv1.DeploymentList, error) {
return clientset.AppsV1().Deployments(namespace).List(metav1.ListOptions{LabelSelector: labelSelector})
}
// UpdateDeployment updates the deployment
func UpdateDeployment(clientset *kubernetes.Clientset, namespace string, deployment *appsv1.Deployment) (*appsv1.Deployment, error) {
return clientset.AppsV1().Deployments(namespace).Update(deployment)
}
// DeleteDeployment will delete the deployment corresponding to a namespace and name
func DeleteDeployment(clientset *kubernetes.Clientset, namespace string, name string) error {
propagationPolicy := metav1.DeletePropagationBackground
return clientset.AppsV1().Deployments(namespace).Delete(name, &metav1.DeleteOptions{
PropagationPolicy: &propagationPolicy,
})
}
// CreatePersistentVolume will create the persistent volume
func CreatePersistentVolume(clientset *kubernetes.Clientset, name string, storageClass string, claimSize string, nfsPath string, nfsServer string) (*corev1.PersistentVolume, error) {
pvQuantity, _ := resource.ParseQuantity(claimSize)
return clientset.CoreV1().PersistentVolumes().Create(&corev1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Namespace: name,
Name: name,
},
Spec: corev1.PersistentVolumeSpec{
Capacity: map[corev1.ResourceName]resource.Quantity{corev1.ResourceStorage: pvQuantity},
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
StorageClassName: storageClass,
PersistentVolumeSource: corev1.PersistentVolumeSource{
NFS: &corev1.NFSVolumeSource{
Path: nfsPath,
Server: nfsServer,
},
},
},
})
}
// DeletePersistentVolume will delete the persistent volume
func DeletePersistentVolume(clientset *kubernetes.Clientset, name string) error {
return clientset.CoreV1().PersistentVolumes().Delete(name, &metav1.DeleteOptions{})
}
// CreatePersistentVolumeClaim will create the persistent volume claim
func CreatePersistentVolumeClaim(name string, namespace string, pvcClaimSize string, storageClass string, accessMode horizonapi.PVCAccessModeType) (*components.PersistentVolumeClaim, error) {
// Workaround so that storageClass does not get set to "", which prevent Kube from using the default storageClass
var class *string
if len(storageClass) == 0 {
class = nil
} else {
class = &storageClass
}
postgresPVC, err := components.NewPersistentVolumeClaim(horizonapi.PVCConfig{
Name: name,
Namespace: namespace,
// VolumeName: createHub.Name,
Size: pvcClaimSize,
Class: class,
})
if err != nil {
return nil, err
}
postgresPVC.AddAccessMode(accessMode)
return postgresPVC, nil
}
// FilterPodByNamePrefixInNamespace will filter the pod based on pod name prefix from a list a pods in a given namespace
func FilterPodByNamePrefixInNamespace(clientset *kubernetes.Clientset, namespace string, prefix string) (*corev1.Pod, error) {
pods, err := ListPods(clientset, namespace)
if err != nil {
return nil, fmt.Errorf("unable to list the pods in namespace %s due to %+v", namespace, err)
}
pod := FilterPodByNamePrefix(pods, prefix)
if pod != nil {
return pod, nil
}
return nil, fmt.Errorf("unable to find the pod with prefix %s", prefix)
}
// FilterPodByNamePrefix will filter the pod based on pod name prefix from a list a pods
func FilterPodByNamePrefix(pods *corev1.PodList, prefix string) *corev1.Pod {
for _, pod := range pods.Items {
if strings.HasPrefix(pod.Name, prefix) {
return &pod
}
}
return nil
}
// GetService will get the service information for the input service name inside the input namespace
func GetService(clientset *kubernetes.Clientset, namespace string, serviceName string) (*corev1.Service, error) {
return clientset.CoreV1().Services(namespace).Get(serviceName, metav1.GetOptions{})
}
// ListServices will list the service information for the input service name inside the input namespace
func ListServices(clientset *kubernetes.Clientset, namespace string, labelSelector string) (*corev1.ServiceList, error) {
return clientset.CoreV1().Services(namespace).List(metav1.ListOptions{LabelSelector: labelSelector})
}
// GetKubeService will get the kubernetes service
func GetKubeService(namespace string, name string, labels map[string]string, selector map[string]string, port int32, target string, serviceType corev1.ServiceType) *corev1.Service {
return &corev1.Service{
TypeMeta: metav1.TypeMeta{
Kind: "Service",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
Labels: labels,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: fmt.Sprintf("port-%d", port),
Port: port,
TargetPort: intstr.Parse(target),
Protocol: corev1.ProtocolTCP,
},
},
Type: serviceType,
Selector: selector,
},
}
}
// CreateKubeService will create the kubernetes service
func CreateKubeService(clientset *kubernetes.Clientset, namespace string, service *corev1.Service) (*corev1.Service, error) {
return clientset.CoreV1().Services(namespace).Create(service)
}
// UpdateService will update the service information for the input service name inside the input namespace
func UpdateService(clientset *kubernetes.Clientset, namespace string, service *corev1.Service) (*corev1.Service, error) {
return clientset.CoreV1().Services(namespace).Update(service)
}
// DeleteService will delete the service information for the input service name inside the input namespace
func DeleteService(clientset *kubernetes.Clientset, namespace string, name string) error {
return clientset.CoreV1().Services(namespace).Delete(name, &metav1.DeleteOptions{})
}
// GetServiceEndPoint will get the service endpoint information for the input service name inside the input namespace
func GetServiceEndPoint(clientset *kubernetes.Clientset, namespace string, serviceName string) (*corev1.Endpoints, error) {
return clientset.CoreV1().Endpoints(namespace).Get(serviceName, metav1.GetOptions{})
}
// ListStorageClasses will list all the storageClass in the cluster
func ListStorageClasses(clientset *kubernetes.Clientset) (*v1beta1.StorageClassList, error) {
return clientset.StorageV1beta1().StorageClasses().List(metav1.ListOptions{})
}
// GetPVC will get the PVC for the given name
func GetPVC(clientset *kubernetes.Clientset, namespace string, name string) (*corev1.PersistentVolumeClaim, error) {
return clientset.CoreV1().PersistentVolumeClaims(namespace).Get(name, metav1.GetOptions{})
}
// ListPVCs will list the PVC for the given label selector
func ListPVCs(clientset *kubernetes.Clientset, namespace string, labelSelector string) (*corev1.PersistentVolumeClaimList, error) {
return clientset.CoreV1().PersistentVolumeClaims(namespace).List(metav1.ListOptions{LabelSelector: labelSelector})
}
// UpdatePVC will update the pvc information for the input pvc name inside the input namespace
func UpdatePVC(clientset *kubernetes.Clientset, namespace string, pvc *corev1.PersistentVolumeClaim) (*corev1.PersistentVolumeClaim, error) {
return clientset.CoreV1().PersistentVolumeClaims(namespace).Update(pvc)
}
// DeletePVC will delete the PVC information for the input pvc name inside the input namespace
func DeletePVC(clientset *kubernetes.Clientset, namespace string, name string) error {
return clientset.CoreV1().PersistentVolumeClaims(namespace).Delete(name, &metav1.DeleteOptions{})
}
// CreateBlackduck will create hub in the cluster
func CreateBlackduck(blackduckClientset *hubclientset.Clientset, namespace string, createHub *blackduckapi.Blackduck) (*blackduckapi.Blackduck, error) {
result := &blackduckapi.Blackduck{}
req := blackduckClientset.SynopsysV1().RESTClient().Post().Resource("blackducks").Body(createHub)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
err := req.Do().Into(result)
return result, err
}
// GetBlackduck will get hubs in the cluster
func GetBlackduck(blackduckClientset *hubclientset.Clientset, namespace string, name string, options metav1.GetOptions) (*blackduckapi.Blackduck, error) {
result := &blackduckapi.Blackduck{}
req := blackduckClientset.SynopsysV1().RESTClient().Get().Resource("blackducks").Name(name).VersionedParams(&options, blackduckScheme.ParameterCodec)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
err := req.Do().Into(result)
return result, err
}
// ListBlackduck gets all blackducks
func ListBlackduck(blackduckClientset *hubclientset.Clientset, namespace string, opts metav1.ListOptions) (*blackduckapi.BlackduckList, error) {
result := &blackduckapi.BlackduckList{}
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
req := blackduckClientset.SynopsysV1().RESTClient().Get().Resource("blackducks").VersionedParams(&opts, blackduckScheme.ParameterCodec).Timeout(timeout)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
err := req.Do().Into(result)
return result, err
}
// UpdateBlackduck will update Blackduck in the cluster
func UpdateBlackduck(blackduckClientset *hubclientset.Clientset, blackduck *blackduckapi.Blackduck) (*blackduckapi.Blackduck, error) {
result := &blackduckapi.Blackduck{}
req := blackduckClientset.SynopsysV1().RESTClient().Put().Resource("blackducks").Body(blackduck).Name(blackduck.Name)
if len(blackduck.Namespace) > 0 {
req = req.Namespace(blackduck.Namespace)
}
err := req.Do().Into(result)
return result, err
}
// UpdateBlackducks will update a set of Blackducks in the cluster
func UpdateBlackducks(clientSet *hubclientset.Clientset, blackduckCRDs []blackduckapi.Blackduck) error {
for _, crd := range blackduckCRDs {
_, err := UpdateBlackduck(clientSet, &crd)
if err != nil {
return err
}
}
return nil
}
// DeleteBlackduck will delete Blackduck in the cluster
func DeleteBlackduck(blackduckClientset *hubclientset.Clientset, name string, namespace string, options *metav1.DeleteOptions) error {
req := blackduckClientset.SynopsysV1().RESTClient().Delete().Resource("blackducks").Name(name).Body(options)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
return req.Do().Error()
}
// CreateOpsSight will create opsSight in the cluster
func CreateOpsSight(opssightClientset *opssightclientset.Clientset, namespace string, opssight *opssightapi.OpsSight) (*opssightapi.OpsSight, error) {
result := &opssightapi.OpsSight{}
req := opssightClientset.SynopsysV1().RESTClient().Post().Resource("opssights").Body(opssight)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
err := req.Do().Into(result)
return result, err
}
// ListOpsSights will list all opssights in the cluster
func ListOpsSights(opssightClientset *opssightclientset.Clientset, namespace string, opts metav1.ListOptions) (*opssightapi.OpsSightList, error) {
result := &opssightapi.OpsSightList{}
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
req := opssightClientset.SynopsysV1().RESTClient().Get().Resource("opssights").VersionedParams(&opts, opssightScheme.ParameterCodec).Timeout(timeout)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
err := req.Do().Into(result)
return result, err
}
// GetOpsSight will get OpsSight in the cluster
func GetOpsSight(opssightClientset *opssightclientset.Clientset, namespace string, name string, options metav1.GetOptions) (*opssightapi.OpsSight, error) {
result := &opssightapi.OpsSight{}
req := opssightClientset.SynopsysV1().RESTClient().Get().Resource("opssights").Name(name).VersionedParams(&options, opssightScheme.ParameterCodec)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
err := req.Do().Into(result)
return result, err
}
// GetOpsSights gets all opssights
func GetOpsSights(clientSet *opssightclientset.Clientset) (*opssightapi.OpsSightList, error) {
return clientSet.SynopsysV1().OpsSights(metav1.NamespaceAll).List(metav1.ListOptions{})
}
// UpdateOpsSight will update OpsSight in the cluster
func UpdateOpsSight(opssightClientset *opssightclientset.Clientset, namespace string, opssight *opssightapi.OpsSight) (*opssightapi.OpsSight, error) {
result := &opssightapi.OpsSight{}
req := opssightClientset.SynopsysV1().RESTClient().Put().Resource("opssights").Body(opssight).Name(opssight.Name)
if len(opssight.Namespace) > 0 {
req = req.Namespace(opssight.Namespace)
}
err := req.Do().Into(result)
return result, err
}
// UpdateOpsSights will update a set of OpsSights in the cluster
func UpdateOpsSights(clientSet *opssightclientset.Clientset, opsSightCRDs []opssightapi.OpsSight) error {
for _, crd := range opsSightCRDs {
_, err := UpdateOpsSight(clientSet, crd.Spec.Namespace, &crd)
if err != nil {
return err
}
}
return nil
}
// DeleteOpsSight will delete OpsSight in the cluster
func DeleteOpsSight(clientSet *opssightclientset.Clientset, name string, namespace string, options *metav1.DeleteOptions) error {
req := clientSet.SynopsysV1().RESTClient().Delete().Resource("opssights").Name(name).Body(options)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
return req.Do().Error()
}
// CreateAlert will create alert in the cluster
func CreateAlert(alertClientset *alertclientset.Clientset, namespace string, createAlert *alertapi.Alert) (*alertapi.Alert, error) {
result := &alertapi.Alert{}
req := alertClientset.SynopsysV1().RESTClient().Post().Resource("alerts").Body(createAlert)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
err := req.Do().Into(result)
return result, err
}
// ListAlerts will list all alerts in the cluster
func ListAlerts(clientSet *alertclientset.Clientset, namespace string, opts metav1.ListOptions) (*alertapi.AlertList, error) {
result := &alertapi.AlertList{}
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
req := clientSet.SynopsysV1().RESTClient().Get().Resource("alerts").VersionedParams(&opts, alertScheme.ParameterCodec).Timeout(timeout)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
err := req.Do().Into(result)
return result, err
}
// GetAlert will get Alert in the cluster
func GetAlert(clientSet *alertclientset.Clientset, namespace string, name string, options metav1.GetOptions) (*alertapi.Alert, error) {
result := &alertapi.Alert{}
req := clientSet.SynopsysV1().RESTClient().Get().Resource("alerts").Name(name).VersionedParams(&options, alertScheme.ParameterCodec)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
err := req.Do().Into(result)
return result, err
}
// GetAlerts gets all alerts
func GetAlerts(clientSet *alertclientset.Clientset) (*alertapi.AlertList, error) {
return clientSet.SynopsysV1().Alerts(metav1.NamespaceAll).List(metav1.ListOptions{})
}
// UpdateAlert will update an Alert in the cluster
func UpdateAlert(clientSet *alertclientset.Clientset, namespace string, alert *alertapi.Alert) (*alertapi.Alert, error) {
result := &alertapi.Alert{}
req := clientSet.SynopsysV1().RESTClient().Put().Resource("alerts").Body(alert).Name(alert.Name)
if len(alert.Namespace) > 0 {
req = req.Namespace(alert.Namespace)
}
err := req.Do().Into(result)
return result, err
}
// UpdateAlerts will update a set of Alerts in the cluster
func UpdateAlerts(clientSet *alertclientset.Clientset, alertCRDs []alertapi.Alert) error {
for _, crd := range alertCRDs {
_, err := UpdateAlert(clientSet, crd.Spec.Namespace, &crd)
if err != nil {
return err
}
}
return nil
}
// DeleteAlert will delete Alert in the cluster
func DeleteAlert(clientSet *alertclientset.Clientset, name string, namespace string, options *metav1.DeleteOptions) error {
req := clientSet.SynopsysV1().RESTClient().Delete().Resource("alerts").Name(name).Body(options)
if len(namespace) > 0 {
req = req.Namespace(namespace)
}
return req.Do().Error()
}
// ListHubPV will list all the persistent volumes attached to each hub in the cluster
func ListHubPV(hubClientset *hubclientset.Clientset, namespace string) (map[string]string, error) {
var pvList map[string]string
pvList = make(map[string]string)
hubs, err := ListBlackduck(hubClientset, namespace, metav1.ListOptions{})
if err != nil {
log.Errorf("unable to list the hubs due to %+v", err)
return pvList, err
}
for _, hub := range hubs.Items {
if hub.Spec.PersistentStorage {
pvList[hub.Name] = fmt.Sprintf("%s (%s)", hub.Name, hub.Status.PVCVolumeName["blackduck-postgres"])
}
}
return pvList, nil
}
// CreateServiceAccount creates a service account
func CreateServiceAccount(namespace string, name string) *components.ServiceAccount {
serviceAccount := components.NewServiceAccount(horizonapi.ServiceAccountConfig{
Name: name,
Namespace: namespace,
})
return serviceAccount
}
// GetServiceAccount get a service account
func GetServiceAccount(clientset *kubernetes.Clientset, namespace string, name string) (*corev1.ServiceAccount, error) {
return clientset.CoreV1().ServiceAccounts(namespace).Get(name, metav1.GetOptions{})
}
// ListServiceAccounts list a service account
func ListServiceAccounts(clientset *kubernetes.Clientset, namespace string, labelSelector string) (*corev1.ServiceAccountList, error) {
return clientset.CoreV1().ServiceAccounts(namespace).List(metav1.ListOptions{LabelSelector: labelSelector})
}
// UpdateServiceAccount updates a service account
func UpdateServiceAccount(clientset *kubernetes.Clientset, namespace string, serviceAccount *corev1.ServiceAccount) (*corev1.ServiceAccount, error) {
return clientset.CoreV1().ServiceAccounts(namespace).Update(serviceAccount)
}
// DeleteServiceAccount delete a service account
func DeleteServiceAccount(clientset *kubernetes.Clientset, namespace string, name string) error {
return clientset.CoreV1().ServiceAccounts(namespace).Delete(name, &metav1.DeleteOptions{})
}
// CreateClusterRoleBinding creates a cluster role binding
func CreateClusterRoleBinding(namespace string, name string, serviceAccountName string, clusterRoleAPIGroup string, clusterRoleKind string, clusterRoleName string) *components.ClusterRoleBinding {
clusterRoleBinding := components.NewClusterRoleBinding(horizonapi.ClusterRoleBindingConfig{
Name: name,
APIVersion: "rbac.authorization.k8s.io/v1",
})
clusterRoleBinding.AddSubject(horizonapi.SubjectConfig{
Kind: "ServiceAccount",
Name: serviceAccountName,
Namespace: namespace,
})
clusterRoleBinding.AddRoleRef(horizonapi.RoleRefConfig{
APIGroup: clusterRoleAPIGroup,
Kind: clusterRoleKind,
Name: clusterRoleName,
})
return clusterRoleBinding
}
// GetClusterRoleBinding get a cluster role
func GetClusterRoleBinding(clientset *kubernetes.Clientset, name string) (*rbacv1.ClusterRoleBinding, error) {
return clientset.RbacV1().ClusterRoleBindings().Get(name, metav1.GetOptions{})
}
// ListClusterRoleBindings list a cluster role binding
func ListClusterRoleBindings(clientset *kubernetes.Clientset, labelSelector string) (*rbacv1.ClusterRoleBindingList, error) {
return clientset.RbacV1().ClusterRoleBindings().List(metav1.ListOptions{LabelSelector: labelSelector})
}
// UpdateClusterRoleBinding updates the cluster role binding
func UpdateClusterRoleBinding(clientset *kubernetes.Clientset, clusterRoleBinding *rbacv1.ClusterRoleBinding) (*rbacv1.ClusterRoleBinding, error) {
return clientset.RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
}
// DeleteClusterRoleBinding delete a cluster role binding
func DeleteClusterRoleBinding(clientset *kubernetes.Clientset, name string) error {
return clientset.RbacV1().ClusterRoleBindings().Delete(name, &metav1.DeleteOptions{})
}
// IsClusterRoleBindingSubjectNamespaceExist checks whether the namespace is already exist in the subject of cluster role binding
func IsClusterRoleBindingSubjectNamespaceExist(subjects []rbacv1.Subject, namespace string) bool {