forked from redhat-developer/odo
/
occlient.go
2131 lines (1876 loc) · 68.3 KB
/
occlient.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
package occlient
import (
taro "archive/tar"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/redhat-developer/odo/pkg/util"
"github.com/fatih/color"
"github.com/golang/glog"
dockerapiv10 "github.com/openshift/api/image/docker10"
"github.com/pkg/errors"
servicecatalogclienset "github.com/kubernetes-incubator/service-catalog/pkg/client/clientset_generated/clientset/typed/servicecatalog/v1beta1"
appsschema "github.com/openshift/client-go/apps/clientset/versioned/scheme"
appsclientset "github.com/openshift/client-go/apps/clientset/versioned/typed/apps/v1"
buildschema "github.com/openshift/client-go/build/clientset/versioned/scheme"
buildclientset "github.com/openshift/client-go/build/clientset/versioned/typed/build/v1"
imageclientset "github.com/openshift/client-go/image/clientset/versioned/typed/image/v1"
projectclientset "github.com/openshift/client-go/project/clientset/versioned/typed/project/v1"
routeclientset "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1"
userclientset "github.com/openshift/client-go/user/clientset/versioned/typed/user/v1"
scv1beta1 "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1"
appsv1 "github.com/openshift/api/apps/v1"
buildv1 "github.com/openshift/api/build/v1"
imagev1 "github.com/openshift/api/image/v1"
projectv1 "github.com/openshift/api/project/v1"
routev1 "github.com/openshift/api/route/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/version"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/client-go/util/retry"
)
const (
ocRequestTimeout = 1 * time.Second
OpenShiftNameSpace = "openshift"
// The length of the string to be generated for names of resources
nameLength = 5
// git repository that will be used for bootstraping
bootstrapperURI = "https://github.com/kadel/bootstrap-supervisored-s2i"
bootstrapperRef = "v0.0.2"
)
// errorMsg is the message for user when invalid configuration error occurs
const errorMsg = `
Please login to your server:
oc login https://mycluster.mydomain.com
`
type Client struct {
kubeClient kubernetes.Interface
imageClient imageclientset.ImageV1Interface
appsClient appsclientset.AppsV1Interface
buildClient buildclientset.BuildV1Interface
projectClient projectclientset.ProjectV1Interface
serviceCatalogClient servicecatalogclienset.ServicecatalogV1beta1Interface
routeClient routeclientset.RouteV1Interface
userClient userclientset.UserV1Interface
kubeConfig clientcmd.ClientConfig
namespace string
}
func New(connectionCheck bool) (*Client, error) {
var client Client
// initialize client-go clients
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
configOverrides := &clientcmd.ConfigOverrides{}
client.kubeConfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)
config, err := client.kubeConfig.ClientConfig()
if err != nil {
return nil, errors.New(err.Error() + errorMsg)
}
kubeClient, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
client.kubeClient = kubeClient
imageClient, err := imageclientset.NewForConfig(config)
if err != nil {
return nil, err
}
client.imageClient = imageClient
appsClient, err := appsclientset.NewForConfig(config)
if err != nil {
return nil, err
}
client.appsClient = appsClient
buildClient, err := buildclientset.NewForConfig(config)
if err != nil {
return nil, err
}
client.buildClient = buildClient
serviceCatalogClient, err := servicecatalogclienset.NewForConfig(config)
if err != nil {
return nil, err
}
client.serviceCatalogClient = serviceCatalogClient
projectClient, err := projectclientset.NewForConfig(config)
if err != nil {
return nil, err
}
client.projectClient = projectClient
routeClient, err := routeclientset.NewForConfig(config)
if err != nil {
return nil, err
}
client.routeClient = routeClient
userClient, err := userclientset.NewForConfig(config)
if err != nil {
return nil, err
}
client.userClient = userClient
namespace, _, err := client.kubeConfig.Namespace()
if err != nil {
return nil, err
}
client.namespace = namespace
// Skip this if connectionCheck is false
if !connectionCheck {
if !isServerUp(config.Host) {
return nil, errors.New("Unable to connect to OpenShift cluster, is it down?")
}
if !client.isLoggedIn() {
return nil, errors.New("Please log in to the cluster")
}
}
return &client, nil
}
// parseImageName parse image reference
// returns (imageNamespace, imageName, tag, digest, error)
// if image is referenced by tag (name:tag) than digest is ""
// if image is referenced by digest (name@digest) than tag is ""
func ParseImageName(image string) (string, string, string, string, error) {
digestParts := strings.Split(image, "@")
if len(digestParts) == 2 {
// image is references digest
// Safe path image name and digest are non empty, else error
if digestParts[0] != "" && digestParts[1] != "" {
// Image name might be fully qualified name of form: Namespace/ImageName
imangeNameParts := strings.Split(digestParts[0], "/")
if len(imangeNameParts) == 2 {
return imangeNameParts[0], imangeNameParts[1], "", digestParts[1], nil
}
return "", imangeNameParts[0], "", digestParts[1], nil
}
} else if len(digestParts) == 1 && digestParts[0] != "" { // Filter out empty image name
tagParts := strings.Split(image, ":")
if len(tagParts) == 2 {
// ":1.0.0 is invalid image name"
if tagParts[0] != "" {
// Image name might be fully qualified name of form: Namespace/ImageName
imangeNameParts := strings.Split(tagParts[0], "/")
if len(imangeNameParts) == 2 {
return imangeNameParts[0], imangeNameParts[1], tagParts[1], "", nil
}
return "", tagParts[0], tagParts[1], "", nil
}
} else if len(tagParts) == 1 {
// Image name might be fully qualified name of form: Namespace/ImageName
imangeNameParts := strings.Split(tagParts[0], "/")
if len(imangeNameParts) == 2 {
return imangeNameParts[0], imangeNameParts[1], "latest", "", nil
}
return "", tagParts[0], "latest", "", nil
}
}
return "", "", "", "", fmt.Errorf("invalid image reference %s", image)
}
// imageWithMetadata mutates the given image. It parses raw DockerImageManifest data stored in the image and
// fills its DockerImageMetadata and other fields.
// Copied from v3.7 github.com/openshift/origin/pkg/image/apis/image/v1/helpers.go
func imageWithMetadata(image *imagev1.Image) error {
// Check if the metadata are already filled in for this image.
meta, hasMetadata := image.DockerImageMetadata.Object.(*dockerapiv10.DockerImage)
if hasMetadata && meta.Size > 0 {
return nil
}
version := image.DockerImageMetadataVersion
if len(version) == 0 {
version = "1.0"
}
obj := &dockerapiv10.DockerImage{}
if len(image.DockerImageMetadata.Raw) != 0 {
if err := json.Unmarshal(image.DockerImageMetadata.Raw, obj); err != nil {
return err
}
image.DockerImageMetadata.Object = obj
}
image.DockerImageMetadataVersion = version
return nil
}
// isLoggedIn checks whether user is logged in or not and returns boolean output
func (c *Client) isLoggedIn() bool {
// ~ indicates current user
// Reference: https://github.com/openshift/origin/blob/master/pkg/oc/cli/cmd/whoami.go#L55
output, err := c.userClient.Users().Get("~", metav1.GetOptions{})
glog.V(4).Infof("isLoggedIn err: %#v \n output: %#v", err, output.Name)
if err != nil {
glog.V(4).Info(errors.Wrap(err, "error running command"))
glog.V(4).Infof("Output is: %v", output)
return false
}
return true
}
// isServerUp returns true if server is up and running
func isServerUp(server string) bool {
u, err := url.Parse(server)
if err != nil {
glog.V(4).Info(errors.Wrap(err, "unable to parse url"))
return false
}
glog.V(4).Infof("Trying to connect to server %v - %v", u.Host)
_, connectionError := net.DialTimeout("tcp", u.Host, time.Duration(ocRequestTimeout))
if connectionError != nil {
glog.V(4).Info(errors.Wrap(connectionError, "unable to connect to server"))
return false
}
glog.V(4).Infof("Server %v is up", server)
return true
}
func (c *Client) GetCurrentProjectName() string {
return c.namespace
}
// GetProjectNames return list of existing projects that user has access to.
func (c *Client) GetProjectNames() ([]string, error) {
projects, err := c.projectClient.Projects().List(metav1.ListOptions{})
if err != nil {
return nil, errors.Wrap(err, "unable to list projects")
}
var projectNames []string
for _, p := range projects.Items {
projectNames = append(projectNames, p.Name)
}
return projectNames, nil
}
func (c *Client) CreateNewProject(name string) error {
projectRequest := &projectv1.ProjectRequest{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
}
_, err := c.projectClient.ProjectRequests().Create(projectRequest)
if err != nil {
return errors.Wrapf(err, "unable to create new project %s", name)
}
return nil
}
func (c *Client) SetCurrentProject(project string) error {
rawConfig, err := c.kubeConfig.RawConfig()
if err != nil {
return errors.Wrapf(err, "unable to switch to %s project", project)
}
rawConfig.Contexts[rawConfig.CurrentContext].Namespace = project
err = clientcmd.ModifyConfig(clientcmd.NewDefaultClientConfigLoadingRules(), rawConfig, true)
if err != nil {
return errors.Wrapf(err, "unable to switch to %s project", project)
}
return nil
}
// addLabelsToArgs adds labels from map to args as a new argument in format that oc requires
// --labels label1=value1,label2=value2
func addLabelsToArgs(labels map[string]string, args []string) []string {
if labels != nil {
var labelsString []string
for key, value := range labels {
labelsString = append(labelsString, fmt.Sprintf("%s=%s", key, value))
}
args = append(args, "--labels")
args = append(args, strings.Join(labelsString, ","))
}
return args
}
// getExposedPortsFromISI parse ImageStreamImage definition and return all exposed ports in form of ContainerPorts structs
func getExposedPortsFromISI(image *imagev1.ImageStreamImage) ([]corev1.ContainerPort, error) {
// file DockerImageMetadata
imageWithMetadata(&image.Image)
var ports []corev1.ContainerPort
for exposedPort := range image.Image.DockerImageMetadata.Object.(*dockerapiv10.DockerImage).ContainerConfig.ExposedPorts {
splits := strings.Split(exposedPort, "/")
if len(splits) != 2 {
return nil, fmt.Errorf("invalid port %s", exposedPort)
}
portNumberI64, err := strconv.ParseInt(splits[0], 10, 32)
if err != nil {
return nil, errors.Wrapf(err, "invalid port number %s", splits[0])
}
portNumber := int32(portNumberI64)
var portProto corev1.Protocol
switch strings.ToUpper(splits[1]) {
case "TCP":
portProto = corev1.ProtocolTCP
case "UDP":
portProto = corev1.ProtocolUDP
default:
return nil, fmt.Errorf("invalid port protocol %s", splits[1])
}
port := corev1.ContainerPort{
Name: fmt.Sprintf("%d-%s", portNumber, strings.ToLower(string(portProto))),
ContainerPort: portNumber,
Protocol: portProto,
}
ports = append(ports, port)
}
return ports, nil
}
// GetImageStreams returns the Image Stream objects in the given namespace
func (c *Client) GetImageStreams(namespace string) ([]imagev1.ImageStream, error) {
imageStreamList, err := c.imageClient.ImageStreams(namespace).List(metav1.ListOptions{})
if err != nil {
return nil, errors.Wrap(err, "unable to list imagestreams")
}
return imageStreamList.Items, nil
}
// GetImageStreamsNames returns the names of the image streams in a given
// namespace
func (c *Client) GetImageStreamsNames(namespace string) ([]string, error) {
imageStreams, err := c.GetImageStreams(namespace)
if err != nil {
return nil, errors.Wrap(err, "unable to get image streams")
}
var names []string
for _, imageStream := range imageStreams {
names = append(names, imageStream.Name)
}
return names, nil
}
// isTagInImageStream takes a imagestream and a tag and checks if the tag is present in the imagestream's status attribute
func isTagInImageStream(is imagev1.ImageStream, imageTag string) bool {
// Loop through the tags in the imagestream's status attribute
for _, tag := range is.Status.Tags {
// look for a matching tag
if tag.Tag == imageTag {
// Return true if found
return true
}
}
// Return false if not found.
return false
}
// GetImageNS returns the imagestream using image details like imageNS, imageName and imageTag
// imageNS can be empty in which case, this function searches currentNamespace on priority. If
// imagestream of required tag not found in current namespace, then searches openshift namespace.
// If not found, error out. If imageNS is not empty string, then, the requested imageNS only is searched
// for requested imagestream
func (c *Client) GetImageStream(imageNS string, imageName string, imageTag string) (*imagev1.ImageStream, error) {
var err error
var imageStream *imagev1.ImageStream
var currentProjectName string
currentProjectName = c.GetCurrentProjectName()
/*
If User has not chosen image NS then,
1. Use image from current NS if available
2. If not 1, use default openshift NS
3. If not 2, return errors from both 1 and 2
else
Use user chosen namespace
If image doesn't exist in user chosen namespace,
error out
else
Proceed
*/
// User has not passed any particular ImageStream
if imageNS == "" {
// First try finding imagestream from current namespace
currentNSImageStream, e := c.imageClient.ImageStreams(currentProjectName).Get(imageName, metav1.GetOptions{})
if e != nil {
err = errors.Wrapf(e, "no match found for : %s in namespace %s", imageName, currentProjectName)
} else {
if isTagInImageStream(*currentNSImageStream, imageTag) {
return currentNSImageStream, nil
}
}
// If not in current namespace, try finding imagestream from openshift namespace
openshiftNSImageStream, e := c.imageClient.ImageStreams(OpenShiftNameSpace).Get(imageName, metav1.GetOptions{})
if e != nil {
// The image is not available in current Namespace.
err = errors.Wrapf(e, "%s\n.no match found for : %s in namespace %s", err.Error(), imageName, OpenShiftNameSpace)
} else {
if isTagInImageStream(*openshiftNSImageStream, imageTag) {
return openshiftNSImageStream, nil
}
}
if e != nil && err != nil {
// Imagestream not found in openshift and current namespaces
return nil, err
}
// Required tag not in openshift and current namespaces
return nil, fmt.Errorf("image stream %s with tag %s not found in openshift and %s namespaces", imageName, imageTag, currentProjectName)
} else {
// Fetch imagestream from requested namespace
imageStream, err = c.imageClient.ImageStreams(imageNS).Get(imageName, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrapf(
err, "no match found for %s in namespace %s", imageName, imageNS,
)
}
if !isTagInImageStream(*imageStream, imageTag) {
return nil, fmt.Errorf("image stream %s with tag %s not found in %s namespaces", imageName, imageTag, currentProjectName)
}
}
return imageStream, nil
}
// GetExposedPorts retruns image namespace and list of ContainerPorts that are exposed by given image
func (c *Client) GetExposedPorts(imageStream *imagev1.ImageStream, imageTag string) ([]corev1.ContainerPort, error) {
var containerPorts []corev1.ContainerPort
glog.V(4).Infof("Checking for exact match of builderImage with ImageStream")
imageNS := imageStream.ObjectMeta.Namespace
imageName := imageStream.ObjectMeta.Name
tagFound := false
for _, tag := range imageStream.Status.Tags {
// look for matching tag
if tag.Tag == imageTag {
tagFound = true
glog.V(4).Infof("Found exact image tag match for %s:%s", imageName, imageTag)
if len(tag.Items) > 0 {
tagDigest := tag.Items[0].Image
imageStreamImageName := fmt.Sprintf("%s@%s", imageName, tagDigest)
// look for imageStreamImage for given tag (reference by digest)
imageStreamImage, err := c.imageClient.ImageStreamImages(imageNS).Get(imageStreamImageName, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrapf(err, "unable to find ImageStreamImage with %s digest", imageStreamImageName)
}
// get ports that are exported by image
containerPorts, err = getExposedPortsFromISI(imageStreamImage)
if err != nil {
return nil, errors.Wrapf(err, "unable to get exported ports from %s:%s image", imageName, imageTag)
}
} else {
return nil, fmt.Errorf("unable to find tag %s for image %s", imageTag, imageName)
}
}
}
if !tagFound {
return nil, fmt.Errorf("unable to find tag %s for image %s", imageTag, imageName)
}
return containerPorts, nil
}
func getAppRootVolumeName(dcName string) string {
return fmt.Sprintf("%s-s2idata", dcName)
}
// NewAppS2I create new application using S2I
// gitUrl is the url of the git repo
// inputPorts is the array containing the string port values
func (c *Client) NewAppS2I(name string, builderImage string, gitUrl string, labels map[string]string, annotations map[string]string, inputPorts []string) error {
imageNS, imageName, imageTag, _, err := ParseImageName(builderImage)
if err != nil {
return errors.Wrap(err, "unable to parse image name")
}
imageStream, err := c.GetImageStream(imageNS, imageName, imageTag)
if err != nil {
return errors.Wrap(err, "Unable to create new app")
}
/*
Set imageNS to the namespace of above fetched imagestream because, the namespace passed here can potentially be emptystring
in which case, GetImageStream function resolves to correct namespace in accordance with priorities in GetImageStream
*/
imageNS = imageStream.ObjectMeta.Namespace
var containerPorts []corev1.ContainerPort
if len(inputPorts) == 0 {
containerPorts, err = c.GetExposedPorts(imageStream, imageTag)
if err != nil {
return errors.Wrapf(err, "unable to get exposed ports for %s:%s", imageName, imageTag)
}
} else {
if err != nil {
return errors.Wrapf(err, "unable to create s2i app for %s", name)
}
imageNS = imageStream.ObjectMeta.Namespace
containerPorts, err = getContainerPortsFromStrings(inputPorts)
if err != nil {
return errors.Wrapf(err, "unable to get container ports from %v", inputPorts)
}
}
// ObjectMetadata are the same for all generated objects
commonObjectMeta := metav1.ObjectMeta{
Name: name,
Labels: labels,
Annotations: annotations,
}
// generate and create ImageStream
is := imagev1.ImageStream{
ObjectMeta: commonObjectMeta,
}
_, err = c.imageClient.ImageStreams(c.namespace).Create(&is)
if err != nil {
return errors.Wrapf(err, "unable to create ImageStream for %s", name)
}
// if gitUrl is not set, error out
if gitUrl == "" {
return errors.New("unable to create buildSource with empty gitUrl")
}
buildSource := buildv1.BuildSource{
Git: &buildv1.GitBuildSource{
URI: gitUrl,
},
Type: buildv1.BuildSourceGit,
}
bc := buildv1.BuildConfig{
ObjectMeta: commonObjectMeta,
Spec: buildv1.BuildConfigSpec{
CommonSpec: buildv1.CommonSpec{
Output: buildv1.BuildOutput{
To: &corev1.ObjectReference{
Kind: "ImageStreamTag",
Name: name + ":latest",
},
},
Source: buildSource,
Strategy: buildv1.BuildStrategy{
SourceStrategy: &buildv1.SourceBuildStrategy{
From: corev1.ObjectReference{
Kind: "ImageStreamTag",
Name: imageName + ":" + imageTag,
Namespace: imageNS,
},
},
},
},
},
}
_, err = c.buildClient.BuildConfigs(c.namespace).Create(&bc)
if err != nil {
return errors.Wrapf(err, "unable to create BuildConfig for %s", name)
}
// generate and create DeploymentConfig
dc := appsv1.DeploymentConfig{
ObjectMeta: commonObjectMeta,
Spec: appsv1.DeploymentConfigSpec{
Replicas: 1,
Selector: map[string]string{
"deploymentconfig": name,
},
Template: &corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"deploymentconfig": name,
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Image: bc.Spec.Output.To.Name,
Name: name,
Ports: containerPorts,
},
},
},
},
Triggers: []appsv1.DeploymentTriggerPolicy{
{
Type: "ConfigChange",
},
{
Type: "ImageChange",
ImageChangeParams: &appsv1.DeploymentTriggerImageChangeParams{
Automatic: true,
ContainerNames: []string{
name,
},
From: corev1.ObjectReference{
Kind: "ImageStreamTag",
Name: bc.Spec.Output.To.Name,
},
},
},
},
},
}
_, err = c.appsClient.DeploymentConfigs(c.namespace).Create(&dc)
if err != nil {
return errors.Wrapf(err, "unable to create DeploymentConfig for %s", name)
}
err = c.CreateService(commonObjectMeta, dc.Spec.Template.Spec.Containers[0].Ports)
if err != nil {
return errors.Wrapf(err, "unable to create Service for %s", name)
}
return nil
}
// BootstrapSupervisoredS2I uses s2i to inject Supervisor into builder image.
// Supervisor keeps pod running (runs as pid1), so you it is possible to trigger assembly script inside running pod,
// and than restart application using Supervisor without need to restart whole container.
// inputPorts is the array containing the string port values
func (c *Client) BootstrapSupervisoredS2I(name string, builderImage string, labels map[string]string, annotations map[string]string, inputPorts []string) error {
imageNS, imageName, imageTag, _, err := ParseImageName(builderImage)
if err != nil {
return errors.Wrap(err, "unable to create new s2i git build ")
}
imageStream, err := c.GetImageStream(imageNS, imageName, imageTag)
if err != nil {
return errors.Wrap(err, "Failed to bootstrap supervisored")
}
/*
Set imageNS to the namespace of above fetched imagestream because, the namespace passed here can potentially be emptystring
in which case, GetImageStream function resolves to correct namespace in accordance with priorities in GetImageStream
*/
imageNS = imageStream.ObjectMeta.Namespace
var containerPorts []corev1.ContainerPort
if len(inputPorts) == 0 {
containerPorts, err = c.GetExposedPorts(imageStream, imageTag)
if err != nil {
return errors.Wrapf(err, "unable to get exposed ports for %s:%s", imageName, imageTag)
}
} else {
if err != nil {
return errors.Wrapf(err, "unable to bootstrap s2i supervisored for %s", name)
}
containerPorts, err = getContainerPortsFromStrings(inputPorts)
if err != nil {
return errors.Wrapf(err, "unable to get container ports from %v", inputPorts)
}
}
// ObjectMetadata are the same for all generated objects
commonObjectMeta := metav1.ObjectMeta{
Name: name,
Labels: labels,
Annotations: annotations,
}
// generate and create ImageStream
is := imagev1.ImageStream{
ObjectMeta: commonObjectMeta,
}
_, err = c.imageClient.ImageStreams(c.namespace).Create(&is)
if err != nil {
return errors.Wrapf(err, "unable to create ImageStream for %s", name)
}
// generate BuildConfig
buildSource := buildv1.BuildSource{
Git: &buildv1.GitBuildSource{
URI: bootstrapperURI,
Ref: bootstrapperRef,
},
Type: buildv1.BuildSourceGit,
}
bc := buildv1.BuildConfig{
ObjectMeta: commonObjectMeta,
Spec: buildv1.BuildConfigSpec{
CommonSpec: buildv1.CommonSpec{
Output: buildv1.BuildOutput{
To: &corev1.ObjectReference{
Kind: "ImageStreamTag",
Name: name + ":latest",
},
},
Source: buildSource,
Strategy: buildv1.BuildStrategy{
SourceStrategy: &buildv1.SourceBuildStrategy{
From: corev1.ObjectReference{
Kind: "ImageStreamTag",
Name: imageName + ":" + imageTag,
Namespace: imageNS,
},
},
},
},
},
}
_, err = c.buildClient.BuildConfigs(c.namespace).Create(&bc)
if err != nil {
return errors.Wrapf(err, "unable to create BuildConfig for %s", name)
}
// generate and create DeploymentConfig
dc := appsv1.DeploymentConfig{
ObjectMeta: commonObjectMeta,
Spec: appsv1.DeploymentConfigSpec{
Replicas: 1,
Selector: map[string]string{
"deploymentconfig": name,
},
Template: &corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"deploymentconfig": name,
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Image: bc.Spec.Output.To.Name,
Name: name,
Ports: containerPorts,
},
},
},
},
Triggers: []appsv1.DeploymentTriggerPolicy{
{
Type: "ConfigChange",
},
{
Type: "ImageChange",
ImageChangeParams: &appsv1.DeploymentTriggerImageChangeParams{
Automatic: true,
ContainerNames: []string{
name,
"copy-files-to-volume",
},
From: corev1.ObjectReference{
Kind: "ImageStreamTag",
Name: bc.Spec.Output.To.Name,
},
},
},
},
},
}
addBootstrapInitContainer(&dc, name)
addBootstrapVolume(&dc, name)
addBootstrapVolumeMount(&dc, name)
_, err = c.appsClient.DeploymentConfigs(c.namespace).Create(&dc)
if err != nil {
return errors.Wrapf(err, "unable to create DeploymentConfig for %s", name)
}
err = c.CreateService(commonObjectMeta, dc.Spec.Template.Spec.Containers[0].Ports)
if err != nil {
return errors.Wrapf(err, "unable to create Service for %s", name)
}
_, err = c.CreatePVC(getAppRootVolumeName(name), "1Gi", labels)
if err != nil {
return errors.Wrapf(err, "unable to create PVC for %s", name)
}
return nil
}
// CreateService generates and creates the service
// commonObjectMeta is the ObjectMeta for the service
// dc is the deploymentConfig to get the container ports
func (c *Client) CreateService(commonObjectMeta metav1.ObjectMeta, containerPorts []corev1.ContainerPort) error {
// generate and create Service
var svcPorts []corev1.ServicePort
for _, containerPort := range containerPorts {
svcPort := corev1.ServicePort{
Name: containerPort.Name,
Port: containerPort.ContainerPort,
Protocol: containerPort.Protocol,
TargetPort: intstr.FromInt(int(containerPort.ContainerPort)),
}
svcPorts = append(svcPorts, svcPort)
}
svc := corev1.Service{
ObjectMeta: commonObjectMeta,
Spec: corev1.ServiceSpec{
Ports: svcPorts,
Selector: map[string]string{
"deploymentconfig": commonObjectMeta.Name,
},
},
}
_, err := c.kubeClient.CoreV1().Services(c.namespace).Create(&svc)
if err != nil {
return errors.Wrapf(err, "unable to create Service for %s", commonObjectMeta.Name)
}
return nil
}
// AddBootstrapInitContainer adds the bootstrap init container to the deployment config
// dc is the deployment config to be updated
// dcName is the name of the deployment config
func addBootstrapInitContainer(dc *appsv1.DeploymentConfig, dcName string) {
dc.Spec.Template.Spec.InitContainers = append(dc.Spec.Template.Spec.InitContainers,
corev1.Container{
Name: "copy-files-to-volume",
Image: dc.Spec.Template.Spec.Containers[0].Image,
Command: []string{
"copy-files-to-volume",
"/opt/app-root",
"/mnt/app-root"},
VolumeMounts: []corev1.VolumeMount{
{
Name: getAppRootVolumeName(dcName),
MountPath: "/mnt",
},
},
})
}
// addBootstrapVolume adds the bootstrap volume to the deployment config
// dc is the deployment config to be updated
// dcName is the name of the deployment config
func addBootstrapVolume(dc *appsv1.DeploymentConfig, dcName string) {
dc.Spec.Template.Spec.Volumes = append(dc.Spec.Template.Spec.Volumes, corev1.Volume{
Name: getAppRootVolumeName(dcName),
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: getAppRootVolumeName(dcName),
},
},
})
}
// addBootstrapVolumeMount mounts the bootstrap volume to the deployment config
// dc is the deployment config to be updated
// dcName is the name of the deployment config
func addBootstrapVolumeMount(dc *appsv1.DeploymentConfig, dcName string) {
for i := range dc.Spec.Template.Spec.Containers {
dc.Spec.Template.Spec.Containers[i].VolumeMounts = append(dc.Spec.Template.Spec.Containers[i].VolumeMounts, corev1.VolumeMount{
Name: getAppRootVolumeName(dcName),
MountPath: "/opt/app-root",
SubPath: "app-root",
})
}
}
// UpdateBuildConfig updates the BuildConfig file
// buildConfigName is the name of the BuildConfig file to be updated
// projectName is the name of the project
// gitUrl equals to the git URL of the source and is equals to "" if the source is of type dir or binary
// annotations contains the annotations for the BuildConfig file
func (c *Client) UpdateBuildConfig(buildConfigName string, projectName string, gitUrl string, annotations map[string]string) error {
// generate BuildConfig
buildSource := buildv1.BuildSource{}
// if gitUrl set change buildSource to git and use given repo
if gitUrl != "" {
buildSource = buildv1.BuildSource{
Git: &buildv1.GitBuildSource{
URI: gitUrl,
},
Type: buildv1.BuildSourceGit,
}
} else {
buildSource = buildv1.BuildSource{
Git: &buildv1.GitBuildSource{
URI: bootstrapperURI,
Ref: bootstrapperRef,
},
Type: buildv1.BuildSourceGit,
}
}
buildConfig, err := c.GetBuildConfigFromName(buildConfigName, projectName)
if err != nil {
return errors.Wrap(err, "unable to get the BuildConfig file")
}
buildConfig.Spec.Source = buildSource
buildConfig.Annotations = annotations
_, err = c.buildClient.BuildConfigs(c.namespace).Update(buildConfig)
if err != nil {
return errors.Wrap(err, "unable to update the component")
}
return nil
}
// UpdateDCAnnotations updates the DeploymentConfig file
// dcName is the name of the DeploymentConfig file to be updated
// annotations contains the annotations for the DeploymentConfig file
func (c *Client) UpdateDCAnnotations(dcName string, annotations map[string]string) error {
dc, err := c.GetDeploymentConfigFromName(dcName, c.namespace)
if err != nil {
return errors.Wrapf(err, "unable to get DeploymentConfig %s", dcName)
}
dc.Annotations = annotations
_, err = c.appsClient.DeploymentConfigs(c.namespace).Update(dc)
if err != nil {
return errors.Wrapf(err, "unable to uDeploymentConfig config %s", dcName)
}
return nil
}
// SetupForSupervisor adds the supervisor to the deployment config
// dcName is the name of the deployment config to be updated
// projectName is the name of the project
// annotations are the updated annotations for the new deployment config
// labels are the labels of the PVC created while setting up the supervisor
func (c *Client) SetupForSupervisor(dcName string, projectName string, annotations map[string]string, labels map[string]string) error {
dc, err := c.GetDeploymentConfigFromName(dcName, projectName)
if err != nil {
return errors.Wrapf(err, "unable to get DeploymentConfig %s", dcName)
}
dc.Annotations = annotations
addBootstrapInitContainer(dc, dcName)
addBootstrapVolume(dc, dcName)
addBootstrapVolumeMount(dc, dcName)
dc, err = c.appsClient.DeploymentConfigs(c.namespace).Update(dc)
if err != nil {
return errors.Wrapf(err, "unable to uDeploymentConfig config %s", dcName)
}
_, err = c.CreatePVC(getAppRootVolumeName(dcName), "1Gi", labels)
if err != nil {
return errors.Wrapf(err, "unable to create PVC for %s", dcName)
}
return nil
}
// CleanupAfterSupervisor removes the supervisor from the deployment config