forked from fabric8-services/fabric8-wit
/
deployments_kubeclient.go
1968 lines (1789 loc) · 59.7 KB
/
deployments_kubeclient.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 kubernetes
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"time"
yaml "gopkg.in/yaml.v2"
resource "k8s.io/apimachinery/pkg/api/resource"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
v1 "k8s.io/client-go/pkg/api/v1"
rest "k8s.io/client-go/rest"
"github.com/fabric8-services/fabric8-wit/app"
"github.com/fabric8-services/fabric8-wit/log"
errs "github.com/pkg/errors"
)
// KubeClientConfig holds configuration data needed to create a new KubeClientInterface
// with kubernetes.NewKubeClient
type KubeClientConfig struct {
// Provides URLS for all APIs, and also access tokens
BaseURLProvider
// Kubernetes namespace in the cluster of type 'user'
UserNamespace string
// Timeout used for communicating with Kubernetes and OpenShift API servers,
// a value of zero indicates no timeout
Timeout time.Duration
// Specifies a non-default HTTP transport to use when sending requests to
// Kubernetes and OpenShift API servers
Transport http.RoundTripper
// Provides access to the Kubernetes REST API, uses default implementation if not set
KubeRESTAPIGetter
// Provides access to the metrics API, uses default implementation if not set
MetricsGetter
// Provides access to the OpenShift REST API, uses default implementation if not set
OpenShiftRESTAPIGetter
}
// KubeRESTAPIGetter has a method to access the KubeRESTAPI interface
type KubeRESTAPIGetter interface {
GetKubeRESTAPI(config *KubeClientConfig) (KubeRESTAPI, error)
}
// OpenShiftRESTAPIGetter has a method to access the OpenShiftRESTAPI interface
type OpenShiftRESTAPIGetter interface {
GetOpenShiftRESTAPI(config *KubeClientConfig) (OpenShiftRESTAPI, error)
}
// MetricsGetter has a method to access the Metrics interface
type MetricsGetter interface {
GetMetrics(config *MetricsClientConfig) (Metrics, error)
}
// KubeClientInterface contains configuration and methods for interacting with a Kubernetes cluster
type KubeClientInterface interface {
GetSpace(spaceName string) (*app.SimpleSpace, error)
GetApplication(spaceName string, appName string) (*app.SimpleApp, error)
GetDeployment(spaceName string, appName string, envName string) (*app.SimpleDeployment, error)
ScaleDeployment(spaceName string, appName string, envName string, deployNumber int) (*int, error)
GetDeploymentStats(spaceName string, appName string, envName string,
startTime time.Time) (*app.SimpleDeploymentStats, error)
GetDeploymentStatSeries(spaceName string, appName string, envName string, startTime time.Time,
endTime time.Time, limit int) (*app.SimpleDeploymentStatSeries, error)
DeleteDeployment(spaceName string, appName string, envName string) error
GetEnvironments() ([]*app.SimpleEnvironment, error)
GetEnvironment(envName string) (*app.SimpleEnvironment, error)
GetMetricsClient(envNS string) (Metrics, error)
Close()
}
type kubeClient struct {
config *KubeClientConfig
envMap map[string]string
BaseURLProvider
KubeRESTAPI
metricsMap map[string]Metrics
OpenShiftRESTAPI
MetricsGetter
}
// KubeRESTAPI collects methods that call out to the Kubernetes API server over the network
type KubeRESTAPI interface {
corev1.CoreV1Interface
}
type kubeAPIClient struct {
corev1.CoreV1Interface
restConfig *rest.Config
}
// OpenShiftRESTAPI collects methods that call out to the OpenShift API server over the network
type OpenShiftRESTAPI interface {
GetBuildConfigs(namespace string, labelSelector string) (map[string]interface{}, error)
GetBuilds(namespace string, labelSelector string) (map[string]interface{}, error)
GetDeploymentConfig(namespace string, name string) (map[string]interface{}, error)
DeleteDeploymentConfig(namespace string, name string, opts *metaV1.DeleteOptions) error
GetDeploymentConfigScale(namespace string, name string) (map[string]interface{}, error)
SetDeploymentConfigScale(namespace string, name string, scale map[string]interface{}) error
GetRoutes(namespace string, labelSelector string) (map[string]interface{}, error)
DeleteRoute(namespace string, name string, opts *metaV1.DeleteOptions) error
}
type openShiftAPIClient struct {
config *KubeClientConfig
httpClient *http.Client
}
type deployment struct {
dcUID types.UID
appVersion string
current *v1.ReplicationController
}
type route struct {
host string
path string
tls bool
// Scoring criteria below
hasAdmitted bool
hasAlternateBackends bool
isCustomHost bool
}
// BaseURLProvider provides the BASE URL (minimal path) of several APIs used in Deployments.
// For true multicluster support, every API in this inteface should take an environment namespace name.
// This hasn't been done, because the rest of fabric8 seems to assume the cluster is the same.
// For most uses, the proxy server will hide this issue - but not for metrics/logging and console.
type BaseURLProvider interface {
GetAPIURL() (*string, error)
GetMetricsURL(envNS string) (*string, error)
GetConsoleURL(envNS string) (*string, error)
GetLoggingURL(envNS string, deploymentName string) (*string, error)
GetAPIToken() (*string, error)
GetMetricsToken(envNS string) (*string, error)
}
// ensure kubeClient implements KubeClientInterface
var _ KubeClientInterface = &kubeClient{}
var _ KubeClientInterface = (*kubeClient)(nil)
// Receiver for default implementation of KubeRESTAPIGetter and MetricsGetter
type defaultGetter struct{}
// NewKubeClient creates a KubeClientInterface given a configuration. The returned
// KubeClientInterface must be closed using the Close method, when no longer needed.
func NewKubeClient(config *KubeClientConfig) (KubeClientInterface, error) {
// Use default implementation if no KubernetesGetter is specified
if config.KubeRESTAPIGetter == nil {
config.KubeRESTAPIGetter = &defaultGetter{}
}
// Use default implementation if no OpenShiftGetter is specified
if config.OpenShiftRESTAPIGetter == nil {
config.OpenShiftRESTAPIGetter = &defaultGetter{}
}
kubeAPI, err := config.GetKubeRESTAPI(config)
if err != nil {
return nil, errs.WithStack(err)
}
osAPI, err := config.GetOpenShiftRESTAPI(config)
if err != nil {
return nil, errs.WithStack(err)
}
// Use default implementation if no MetricsGetter is specified
if config.MetricsGetter == nil {
config.MetricsGetter = &defaultGetter{}
}
// Get environments from config map
envMap, err := getEnvironmentsFromConfigMap(kubeAPI, config.UserNamespace)
if err != nil {
return nil, errs.WithStack(err)
}
kubeClient := &kubeClient{
config: config,
envMap: envMap,
BaseURLProvider: config,
KubeRESTAPI: kubeAPI,
OpenShiftRESTAPI: osAPI,
metricsMap: make(map[string]Metrics),
MetricsGetter: config.MetricsGetter,
}
return kubeClient, nil
}
func (*defaultGetter) GetKubeRESTAPI(config *KubeClientConfig) (KubeRESTAPI, error) {
url, err := config.GetAPIURL()
if err != nil {
return nil, err
}
token, err := config.GetAPIToken()
if err != nil {
return nil, err
}
restConfig := &rest.Config{
Host: *url,
BearerToken: *token,
Timeout: config.Timeout,
Transport: config.Transport,
}
coreV1Client, err := corev1.NewForConfig(restConfig)
if err != nil {
return nil, errs.WithStack(err)
}
client := &kubeAPIClient{
CoreV1Interface: coreV1Client,
restConfig: restConfig,
}
return client, nil
}
func (*defaultGetter) GetOpenShiftRESTAPI(config *KubeClientConfig) (OpenShiftRESTAPI, error) {
// Equivalent to http.DefaultClient with added timeout and transport
httpClient := &http.Client{
Timeout: config.Timeout,
Transport: config.Transport,
}
client := &openShiftAPIClient{
config: config,
httpClient: httpClient,
}
return client, nil
}
func (*defaultGetter) GetMetrics(config *MetricsClientConfig) (Metrics, error) {
return NewMetricsClient(config)
}
func (kc *kubeClient) GetMetricsClient(envNS string) (Metrics, error) {
if kc.metricsMap[envNS] != nil {
return kc.metricsMap[envNS], nil
}
url, err := kc.GetMetricsURL(envNS)
if err != nil {
return nil, err
}
token, err := kc.GetMetricsToken(envNS)
if err != nil {
return nil, err
}
metricsConfig := &MetricsClientConfig{
MetricsURL: *url,
BearerToken: *token,
}
metrics, err := kc.GetMetrics(metricsConfig)
if err != nil {
return nil, err
}
kc.metricsMap[envNS] = metrics
return metrics, nil
}
// Close releases any resources held by this KubeClientInterface
func (kc *kubeClient) Close() {
// Metrics client needs to be closed to stop Hawkular go-routine from spinning
for _, m := range kc.metricsMap {
m.Close()
}
}
// GetSpace returns a space matching the provided name, containing all applications that belong to it
func (kc *kubeClient) GetSpace(spaceName string) (*app.SimpleSpace, error) {
// Get BuildConfigs within the user namespace that have a matching 'space' label
// This is similar to how pipelines are displayed in fabric8-ui
// https://github.com/fabric8-ui/fabric8-ui/blob/master/src/app/space/create/pipelines/pipelines.component.ts
buildconfigs, err := kc.getBuildConfigsForSpace(spaceName)
if err != nil {
return nil, errs.WithStack(err)
}
// Get all applications in this space using BuildConfig names
apps := []*app.SimpleApp{}
for _, bc := range buildconfigs {
appn, err := kc.GetApplication(spaceName, bc)
if err != nil {
return nil, errs.WithStack(err)
}
apps = append(apps, appn)
}
result := &app.SimpleSpace{
Type: "space",
Attributes: &app.SimpleSpaceAttributes{
Name: spaceName,
Applications: apps,
},
}
return result, nil
}
// GetApplication retrieves an application with the given space and application names, with the status
// of that application's deployment in each environment
func (kc *kubeClient) GetApplication(spaceName string, appName string) (*app.SimpleApp, error) {
// Get all deployments of this app for each environment in this space
deployments := []*app.SimpleDeployment{}
for envName := range kc.envMap {
deployment, err := kc.GetDeployment(spaceName, appName, envName)
if err != nil {
return nil, errs.WithStack(err)
} else if deployment != nil {
deployments = append(deployments, deployment)
}
}
result := &app.SimpleApp{
Type: "application",
Attributes: &app.SimpleAppAttributes{
Name: appName,
Deployments: deployments,
},
ID: appName,
}
return result, nil
}
// ScaleDeployment adjusts the desired number of replicas for a specified application, returning the
// previous number of desired replicas
func (kc *kubeClient) ScaleDeployment(spaceName string, appName string, envName string, deployNumber int) (*int, error) {
envNS, err := kc.getEnvironmentNamespace(envName)
if err != nil {
return nil, errs.WithStack(err)
}
// Deployment Config name does not always match the application name, look up
// DC name using available metadata
dcName, err := kc.getDeploymentConfigNameForApp(envNS, appName, spaceName)
if err != nil {
return nil, err
}
// Look up the Scale for the DeploymentConfig corresponding to the application name in the provided environment
scale, err := kc.GetDeploymentConfigScale(envNS, dcName)
if err != nil {
return nil, errs.WithStack(err)
}
spec, ok := scale["spec"].(map[string]interface{})
if !ok {
log.Error(nil, map[string]interface{}{
"err": err,
"space_name": spaceName,
"application_name": appName,
"environment_name": envName,
}, "invalid deployment config returned from endpoint")
return nil, errs.New("invalid deployment config returned from endpoint: missing 'spec'")
}
replicas, pres := spec["replicas"]
oldReplicas := 0 // replicas property may be missing from spec if set to 0
if pres {
oldReplicasFlt, ok := replicas.(float64)
if !ok {
return nil, errs.New("invalid deployment config returned from endpoint: 'replicas' is not a number")
}
oldReplicas = int(oldReplicasFlt)
}
spec["replicas"] = deployNumber
err = kc.SetDeploymentConfigScale(envNS, dcName, scale)
if err != nil {
return nil, errs.WithStack(err)
}
log.Info(nil, map[string]interface{}{
"space_name": spaceName,
"application_name": appName,
"environment_name": envName,
"old_replica_count": oldReplicas,
"new_replica_count": deployNumber,
}, "scaled deployment to %d replicas", deployNumber)
return &oldReplicas, nil
}
func (oc *openShiftAPIClient) GetDeploymentConfigScale(namespace string, name string) (map[string]interface{}, error) {
dcScalePath := fmt.Sprintf("/oapi/v1/namespaces/%s/deploymentconfigs/%s/scale", namespace, name)
return oc.getResource(dcScalePath, false)
}
func (oc *openShiftAPIClient) SetDeploymentConfigScale(namespace string, name string, scale map[string]interface{}) error {
dcScalePath := fmt.Sprintf("/oapi/v1/namespaces/%s/deploymentconfigs/%s/scale", namespace, name)
return oc.sendResource(dcScalePath, "PUT", scale)
}
func (kc *kubeClient) getApplicationURL(envNS string, deploy *deployment) (*string, error) {
// Get the best route to the application to show to the user
routeURL, err := kc.getBestRoute(envNS, deploy)
if err != nil {
return nil, err
}
var result *string
if routeURL != nil {
route := routeURL.String()
result = &route
}
return result, nil
}
// GetDeployment returns information about the current deployment of an application within a
// particular environment. The application must exist within the provided space.
func (kc *kubeClient) GetDeployment(spaceName string, appName string, envName string) (*app.SimpleDeployment, error) {
envNS, err := kc.getEnvironmentNamespace(envName)
if err != nil {
return nil, errs.WithStack(err)
}
// Get the UID for the current deployment of the app
deploy, err := kc.getCurrentDeployment(spaceName, appName, envNS)
if err != nil {
return nil, errs.WithStack(err)
} else if deploy == nil || deploy.current == nil {
return nil, nil
}
// Get all pods created by this deployment
pods, err := kc.getPods(envNS, deploy.current.UID)
if err != nil {
return nil, errs.WithStack(err)
}
// Get the quota for all pods in the deployment
podsQuota, err := kc.getPodsQuota(pods)
if err != nil {
return nil, err
}
// Get the status of each pod in the deployment
podStats, total := kc.getPodStatus(pods)
// Get related URLs for the deployment
appURL, err := kc.getApplicationURL(envNS, deploy)
if err != nil {
return nil, err
}
consoleURL, err := kc.GetConsoleURL(envNS)
if err != nil {
return nil, err
}
logURL, err := kc.GetLoggingURL(envNS, deploy.current.Name)
if err != nil {
return nil, errs.WithStack(err)
}
var links *app.GenericLinksForDeployment
if consoleURL != nil || appURL != nil || logURL != nil {
links = &app.GenericLinksForDeployment{
Console: consoleURL,
Logs: logURL,
Application: appURL,
}
}
verString := string(deploy.appVersion)
result := &app.SimpleDeployment{
Type: "deployment",
Attributes: &app.SimpleDeploymentAttributes{
Name: envName,
Version: &verString,
Pods: podStats,
PodTotal: &total,
PodsQuota: podsQuota,
},
ID: envName,
Links: links,
}
return result, nil
}
// GetDeploymentStats returns performance metrics of an application for a period of 1 minute
// beyond the specified start time, which are then aggregated into a single data point.
func (kc *kubeClient) GetDeploymentStats(spaceName string, appName string, envName string,
startTime time.Time) (*app.SimpleDeploymentStats, error) {
envNS, err := kc.getEnvironmentNamespace(envName)
if err != nil {
return nil, errs.WithStack(err)
}
// Get the UID for the current deployment of the app
deploy, err := kc.getCurrentDeployment(spaceName, appName, envNS)
if err != nil {
return nil, errs.WithStack(err)
} else if deploy == nil || deploy.current == nil {
return nil, nil
}
// Get pods belonging to current deployment
pods, err := kc.getPods(envNS, deploy.current.UID)
if err != nil {
return nil, errs.WithStack(err)
}
mc, err := kc.GetMetricsClient(envNS)
if err != nil {
return nil, err
}
// Gather the statistics we need about the current deployment
cpuUsage, err := mc.GetCPUMetrics(pods, envNS, startTime)
if err != nil {
return nil, errs.WithStack(err)
}
memoryUsage, err := mc.GetMemoryMetrics(pods, envNS, startTime)
if err != nil {
return nil, errs.WithStack(err)
}
netTxUsage, err := mc.GetNetworkSentMetrics(pods, envNS, startTime)
if err != nil {
return nil, err
}
netRxUsage, err := mc.GetNetworkRecvMetrics(pods, envNS, startTime)
if err != nil {
return nil, err
}
result := &app.SimpleDeploymentStats{
Type: "deploymentstats",
Attributes: &app.SimpleDeploymentStatsAttributes{
Cores: cpuUsage,
Memory: memoryUsage,
NetTx: netTxUsage,
NetRx: netRxUsage,
},
}
return result, nil
}
// GetDeploymentStatSeries returns performance metrics of an application as a time series bounded by
// the provided time range in startTime and endTime. If there are more data points than the
// limit argument, only the newest datapoints within that limit are returned.
func (kc *kubeClient) GetDeploymentStatSeries(spaceName string, appName string, envName string,
startTime time.Time, endTime time.Time, limit int) (*app.SimpleDeploymentStatSeries, error) {
envNS, err := kc.getEnvironmentNamespace(envName)
if err != nil {
return nil, errs.WithStack(err)
}
// Get the UID for the current deployment of the app
deploy, err := kc.getCurrentDeployment(spaceName, appName, envNS)
if err != nil {
return nil, errs.WithStack(err)
} else if deploy == nil || deploy.current == nil {
return nil, nil
}
// Get pods belonging to current deployment
pods, err := kc.getPods(envNS, deploy.current.UID)
if err != nil {
return nil, errs.WithStack(err)
}
mc, err := kc.GetMetricsClient(envNS)
if err != nil {
return nil, err
}
// Get CPU, memory and network metrics for pods in deployment
cpuMetrics, err := mc.GetCPUMetricsRange(pods, envNS, startTime, endTime, limit)
if err != nil {
return nil, errs.WithStack(err)
}
memoryMetrics, err := mc.GetMemoryMetricsRange(pods, envNS, startTime, endTime, limit)
if err != nil {
return nil, errs.WithStack(err)
}
netTxMetrics, err := mc.GetNetworkSentMetricsRange(pods, envNS, startTime, endTime, limit)
if err != nil {
return nil, err
}
netRxMetrics, err := mc.GetNetworkRecvMetricsRange(pods, envNS, startTime, endTime, limit)
if err != nil {
return nil, err
}
// Get the earliest and latest timestamps
minTime, maxTime := getTimestampEndpoints(cpuMetrics, memoryMetrics)
result := &app.SimpleDeploymentStatSeries{
Cores: cpuMetrics,
Memory: memoryMetrics,
NetTx: netTxMetrics,
NetRx: netRxMetrics,
Start: minTime,
End: maxTime,
}
return result, nil
}
func (kc *kubeClient) DeleteDeployment(spaceName string, appName string, envName string) error {
envNS, err := kc.getEnvironmentNamespace(envName)
if err != nil {
return errs.WithStack(err)
}
// Deployment Config name does not always match the application name, look up
// DC name using available metadata
dcName, err := kc.getDeploymentConfigNameForApp(envNS, appName, spaceName)
if err != nil {
return err
}
// Delete routes
err = kc.deleteRoutes(dcName, envNS)
if err != nil {
return err
}
// Delete services
err = kc.deleteServices(dcName, envNS)
if err != nil {
return err
}
// Delete DC (will also delete RCs and pods)
err = kc.deleteDeploymentConfig(spaceName, dcName, envNS)
if err != nil {
return err
}
return nil
}
// GetEnvironments retrieves information on all environments in the cluster
// for the current user
func (kc *kubeClient) GetEnvironments() ([]*app.SimpleEnvironment, error) {
envs := []*app.SimpleEnvironment{}
for envName := range kc.envMap {
env, err := kc.GetEnvironment(envName)
if err != nil {
return nil, errs.WithStack(err)
}
envs = append(envs, env)
}
return envs, nil
}
// GetEnvironment returns information on an environment with the provided name
func (kc *kubeClient) GetEnvironment(envName string) (*app.SimpleEnvironment, error) {
envNS, err := kc.getEnvironmentNamespace(envName)
if err != nil {
return nil, errs.WithStack(err)
}
envStats, err := kc.getResourceQuota(envNS)
if err != nil {
return nil, errs.WithStack(err)
}
env := &app.SimpleEnvironment{
Type: "environment",
Attributes: &app.SimpleEnvironmentAttributes{
Name: &envName,
Quota: envStats,
},
}
return env, nil
}
func getTimestampEndpoints(metricsSeries ...[]*app.TimedNumberTuple) (minTime, maxTime *float64) {
// Metrics arrays are ordered by timestamp, so just check beginning and end
for _, series := range metricsSeries {
if len(series) > 0 {
first := series[0].Time
if minTime == nil || *first < *minTime {
minTime = first
}
last := series[len(series)-1].Time
if maxTime == nil || *last > *maxTime {
maxTime = last
}
}
}
return minTime, maxTime
}
const spaceLabelName = "space"
func (kc *kubeClient) getBuildConfigsForSpace(space string) ([]string, error) {
// BuildConfigs are OpenShift objects, so access REST API using HTTP directly until
// there is a Go client for OpenShift
// BuildConfigs created by fabric8 have a "space" label indicating the space they belong to
escapedSelector := url.QueryEscape(spaceLabelName + "=" + space)
result, err := kc.GetBuildConfigs(kc.config.UserNamespace, escapedSelector)
if err != nil {
return nil, errs.WithStack(err)
}
// Parse build configs from result
kind, ok := result["kind"].(string)
if !ok || kind != "BuildConfigList" {
return nil, errs.New("no build configs returned from endpoint")
}
items, ok := result["items"].([]interface{})
if !ok {
return nil, errs.New("malformed response from endpoint")
}
// Extract the names of the BuildConfigs from the response
buildconfigs := []string{}
for _, item := range items {
bc, ok := item.(map[string]interface{})
if !ok {
return nil, errs.New("malformed build config")
}
metadata, ok := bc["metadata"].(map[string]interface{})
if !ok {
return nil, errs.New("'metadata' object missing from build config")
}
name, ok := metadata["name"].(string)
if !ok || len(name) == 0 {
return nil, errs.New("malformed metadata in build config; 'name' is missing or invalid")
}
buildconfigs = append(buildconfigs, name)
}
return buildconfigs, nil
}
func (oc *openShiftAPIClient) GetBuildConfigs(namespace string, labelSelector string) (map[string]interface{}, error) {
bcURL := fmt.Sprintf("/oapi/v1/namespaces/%s/buildconfigs?labelSelector=%s", namespace, labelSelector)
return oc.getResource(bcURL, false)
}
func getEnvironmentsFromConfigMap(kube KubeRESTAPI, userNamespace string) (map[string]string, error) {
// fabric8 creates a ConfigMap in the user namespace with information on environments
const envConfigMap string = "fabric8-environments"
const providerLabel string = "fabric8"
configmap, err := kube.ConfigMaps(userNamespace).Get(envConfigMap, metaV1.GetOptions{})
if err != nil {
return nil, errs.WithStack(err)
}
// Check that config map has the expected label
if configmap.Labels["provider"] != providerLabel {
return nil, errs.Errorf("unknown or missing provider %s for environments config map in namespace %s", providerLabel, userNamespace)
}
// Parse config map data to construct environments map
envMap := make(map[string]string)
const namespaceProp string = "namespace"
// Config map keys are environment names
for key, value := range configmap.Data {
// Look through value for namespace property
var namespace string
lines := strings.Split(value, "\n")
for _, line := range lines {
if strings.HasPrefix(line, namespaceProp) {
tokens := strings.SplitN(line, ":", 2)
if len(tokens) < 2 {
return nil, errs.New("malformed environments config map")
}
namespace = strings.TrimSpace(tokens[1])
}
}
if len(namespace) == 0 {
return nil, errs.Errorf("no namespace for environment %s in config map", key)
}
envMap[key] = namespace
}
return envMap, nil
}
func (kc *kubeClient) getEnvironmentNamespace(envName string) (string, error) {
envNS, pres := kc.envMap[envName]
if !pres {
return "", errs.Errorf("unknown environment: %s", envName)
}
return envNS, nil
}
// Derived from: https://github.com/fabric8-services/fabric8-tenant/blob/master/openshift/kube_token.go
func (oc *openShiftAPIClient) sendResource(path string, method string, reqBody interface{}) error {
url, err := oc.config.GetAPIURL()
if err != nil {
return err
}
fullURL := strings.TrimSuffix(*url, "/") + path
marshalled, err := json.Marshal(reqBody)
if err != nil {
log.Error(nil, map[string]interface{}{
"err": err,
"url": fullURL,
"request_body": reqBody,
}, "could not marshall %s request", method)
return errs.WithStack(err)
}
req, err := http.NewRequest(method, fullURL, bytes.NewBuffer(marshalled))
if err != nil {
log.Error(nil, map[string]interface{}{
"err": err,
"url": fullURL,
"request_body": reqBody,
}, "could not create %s request", method)
return errs.WithStack(err)
}
token, err := oc.config.GetAPIToken()
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+*token)
resp, err := oc.httpClient.Do(req)
if err != nil {
log.Error(nil, map[string]interface{}{
"err": err,
"url": fullURL,
"request_body": reqBody,
}, "could not perform %s request", method)
return errs.WithStack(err)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error(nil, map[string]interface{}{
"err": err,
"url": fullURL,
"request_body": reqBody,
"response_body": respBody,
}, "could not read response from %s request", method)
return errs.WithStack(err)
}
defer resp.Body.Close()
status := resp.StatusCode
if status != http.StatusOK {
log.Error(nil, map[string]interface{}{
"err": err,
"url": fullURL,
"request_body": reqBody,
"response_body": respBody,
"http_status": status,
}, "failed to %s request due to HTTP error", method)
return errs.Errorf("failed to %s url %s: status code %d", method, fullURL, status)
}
return nil
}
func (kc *kubeClient) getAndParseDeploymentConfig(namespace string, dcName string, space string) (*deployment, error) {
result, err := kc.GetDeploymentConfig(namespace, dcName)
if err != nil {
return nil, errs.WithStack(err)
} else if result == nil {
return nil, nil
}
// Parse deployment config from result
kind, ok := result["kind"].(string)
if !ok || kind != "DeploymentConfig" {
return nil, errs.New("no deployment config returned from endpoint")
}
metadata, ok := result["metadata"].(map[string]interface{})
if !ok {
return nil, errs.Errorf("metadata missing from deployment config %s: %+v", dcName, result)
}
// Check the space label is what we expect
labels, ok := metadata["labels"].(map[string]interface{})
if !ok {
return nil, errs.Errorf("labels missing from deployment config %s: %+v", dcName, metadata)
}
/* FIXME Not all projects will have the space label defined due to the requirement that
* fabric8-maven-plugin is called from the project's POM and not that of its parent.
* This requirement is not always satisfied. For now, we work around the issue by logging
* a warning and waiving the space label check, if missing.
*/
spaceLabel, err := getOptionalStringValue(labels, spaceLabelName)
if err != nil {
return nil, err
}
if len(spaceLabel) == 0 {
log.Warn(nil, map[string]interface{}{
"namespace": namespace,
"dc_name": dcName,
"space": space,
}, "space label missing from deployment config")
} else if spaceLabel != space {
return nil, errs.Errorf("deployment config %s is part of space %s, expected space %s", dcName, spaceLabel, space)
}
// Get UID from deployment config
uid, ok := metadata["uid"].(string)
if !ok || len(uid) == 0 {
return nil, errs.Errorf("malformed metadata in deployment config %s: %+v", dcName, metadata)
}
// Read application version from label
version := labels["version"].(string)
if !ok || len(version) == 0 {
return nil, errs.Errorf("version missing from deployment config %s: %+v", dcName, metadata)
}
dc := &deployment{
dcUID: types.UID(uid),
appVersion: version,
}
return dc, nil
}
func (oc *openShiftAPIClient) GetDeploymentConfig(namespace string, name string) (map[string]interface{}, error) {
dcURL := fmt.Sprintf("/oapi/v1/namespaces/%s/deploymentconfigs/%s", namespace, name)
return oc.getResource(dcURL, true)
}
const buildConfigLabelName = "openshift.io/build-config.name"
const envServicesAnnotationPrefix = "environment.services.fabric8.io"
const envServicesDeploymentVersions = "deploymentVersions"
func (kc *kubeClient) getDeploymentConfigNameForApp(namespace string, appName string, spaceName string) (string, error) {
// Look up builds with config name matching appName, this will be the one created by the launcher
labelSelector := fmt.Sprintf("%s=%s,%s=%s", buildConfigLabelName, appName, spaceLabelName, spaceName)
escapedSelector := url.QueryEscape(labelSelector)
// Builds are located in the user's namespace of type "user"
resp, err := kc.GetBuilds(kc.config.UserNamespace, escapedSelector)
if err != nil {
return "", err
}
// Parse builds from response
kind, ok := resp["kind"].(string)
if !ok || kind != "BuildList" {
return "", errs.New("no builds returned from endpoint")
}
items, ok := resp["items"].([]interface{})
if !ok {
return "", errs.New("malformed response from endpoint")
}
// Look for a matching deployment config within latest completed build
var latestCompletedBuild map[string]interface{}
var latestCompletionTime time.Time
for _, item := range items {
build, ok := item.(map[string]interface{})
if !ok {
return "", errs.New("malformed build object")
}
status, ok := build["status"].(map[string]interface{})
if !ok {
return "", errs.New("status missing from build object")
}
phase, ok := status["phase"].(string)
if ok && phase == "Complete" {
completionTimeStr, ok := status["completionTimestamp"].(string)
if ok {
completionTime, err := time.Parse(time.RFC3339, completionTimeStr)
if err != nil {
return "", errs.Wrapf(err, "build completion time uses an invalid date")
}
if completionTime.After(latestCompletionTime) {
latestCompletedBuild = build
latestCompletionTime = completionTime
}
}
}
}
// Fall back to application name, if we can't find a name in the annotations
result := appName
if latestCompletedBuild != nil {
metadata, ok := latestCompletedBuild["metadata"].(map[string]interface{})
if !ok {
return "", errs.New("metadata missing from build object")
}
annotations, ok := metadata["annotations"].(map[string]interface{})
if ok {
envAnnotationName := fmt.Sprintf(envServicesAnnotationPrefix+"/%s", namespace)
envServices, pres := annotations[envAnnotationName]
if pres {
envServicesStr, ok := envServices.(string)
if !ok {
log.Warn(nil, map[string]interface{}{
"namespace": namespace,
"appName": appName,
"spaceName": spaceName,
"envServices": envServicesStr,
}, "%s annotation does not contain a string", envServicesAnnotationPrefix)
} else {
dcName, err := getNameFromEnvServices([]byte(envServicesStr))
if err != nil {
log.Warn(nil, map[string]interface{}{
"err": err,
"namespace": namespace,
"appName": appName,
"spaceName": spaceName,
"envServices": envServicesStr,
}, "failed to determine Deployment Config name")
} else if len(dcName) > 0 {