This repository has been archived by the owner on Oct 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 505
/
DevOpsConnector.java
1550 lines (1337 loc) · 60 KB
/
DevOpsConnector.java
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 2005-2016 Red Hat, Inc.
*
* Red Hat 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 io.fabric8.devops.connector;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.devops.ProjectConfig;
import io.fabric8.devops.ProjectConfigs;
import io.fabric8.devops.ProjectRepositories;
import io.fabric8.gerrit.CreateRepositoryDTO;
import io.fabric8.kubernetes.api.Controller;
import io.fabric8.kubernetes.api.KubernetesHelper;
import io.fabric8.kubernetes.api.ServiceNames;
import io.fabric8.kubernetes.api.builds.Builds;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.letschat.LetsChatClient;
import io.fabric8.letschat.LetsChatKubernetes;
import io.fabric8.letschat.RoomDTO;
import io.fabric8.openshift.api.model.BuildConfig;
import io.fabric8.openshift.api.model.BuildConfigSpec;
import io.fabric8.openshift.api.model.BuildSource;
import io.fabric8.openshift.api.model.GitBuildSource;
import io.fabric8.openshift.client.OpenShiftClient;
import io.fabric8.project.support.GitUtils;
import io.fabric8.repo.git.GitRepoClient;
import io.fabric8.repo.git.GitRepoKubernetes;
import io.fabric8.taiga.ModuleDTO;
import io.fabric8.taiga.ProjectDTO;
import io.fabric8.taiga.TaigaClient;
import io.fabric8.taiga.TaigaKubernetes;
import io.fabric8.taiga.TaigaModule;
import io.fabric8.utils.DomHelper;
import io.fabric8.utils.GitHelpers;
import io.fabric8.utils.IOHelpers;
import io.fabric8.utils.Objects;
import io.fabric8.utils.Strings;
import io.fabric8.utils.Systems;
import io.fabric8.utils.URLUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.annotation.Priority;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.ReaderInterceptorContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.fabric8.kubernetes.api.KubernetesHelper.getOrCreateMetadata;
/**
* Updates a project's connections to its various DevOps resources like issue tracking, chat and jenkins builds
*/
public class DevOpsConnector {
private transient Logger log = LoggerFactory.getLogger(DevOpsConnector.class);
private static final String JSON_MAGIC = ")]}'";
private static final ObjectMapper MAPPER = new ObjectMapper();
private File basedir;
private ProjectConfig projectConfig;
private String username;
private String password;
private String branch;
private String repoName;
private String fullName;
private String gitUrl;
private String secret = Builds.DEFAULT_SECRET;
private String buildImageStream = Builds.DEFAULT_BUILD_IMAGE_STREAM;
private String buildImageTag = Builds.DEFAULT_IMAGE_TAG;
private String s2iCustomBuilderImage = Builds.DEFAULT_CUSTOM_BUILDER_IMAGE;
private String jenkinsJob;
private boolean triggerJenkinsJob = true;
private String jenkinsMonitorView;
private String jenkinsPipelineView;
private String taigaProjectName;
private String taigaProjectSlug;
private String taigaProjectLinkPage = "backlog";
private String taigaProjectLinkLabel = "Backlog";
private String issueTrackerUrl;
private String issueTrackerLabel = "Issues";
private String teamUrl;
private String teamLabel = "Team";
private String releasesUrl;
private String releasesLabel = "Releases";
private String repositoryBrowseLink;
private String repositoryBrowseLabel = "Repository";
private String taigaTeamLinkPage = "team";
private String taigaTeamLinkLabel = "Team";
private boolean taigaAutoCreate = true;
private boolean taigaEnabled = true;
private boolean letschatEnabled = true;
private String letschatRoomLinkLabel = "Room";
private String letschatRoomExpression = "fabric8_${namespace}";
private String flowGitUrl = Systems.getEnvVar("JENKINS_WORKFLOW_GIT_REPOSITORY", "https://github.com/fabric8io/jenkins-workflow-library.git");
private String gerritUser = Systems.getEnvVar("GERRIT_ADMIN_USER", "admin");
private String gerritPwd = Systems.getEnvVar("GERRIT_ADMIN_PWD", "secret");
private String gerritGitInitialCommit = Systems.getEnvVar("GERRIT_INITIAL_COMMIT", "false");
private String gerritGitRepoDesription = Systems.getEnvVar("GERRIT_REPO_DESCRIPTION", "Description of the gerrit git repo");
private boolean recreateMode;
private String namespace = KubernetesHelper.defaultNamespace();
private String projectName;
private String fabric8ConsoleNamespace = KubernetesHelper.defaultNamespace();
private String jenkinsNamespace = KubernetesHelper.defaultNamespace();
private boolean tryLoadConfigFileFromRemoteGit = true;
private boolean modifiedConfig;
private boolean registerWebHooks;
private GitRepoClient gitRepoClient;
private KubernetesClient kubernetes;
private String jenkinsJobUrl;
private ProjectDTO taigaProject;
private TaigaClient taiga;
private String jenkinsJobName;
private String gitSourceSecretName;
private String jenkinsJobTemplate;
private boolean localJenkinsFlow;
@Override
public String toString() {
return "DevOpsConnector{" +
"gitUrl='" + gitUrl + '\'' +
", basedir=" + basedir +
", username='" + username + '\'' +
", branch='" + branch + '\'' +
", repoName='" + repoName + '\'' +
'}';
}
/**
* For a given project this operation will try to update the associated DevOps resources
*
* @throws Exception
*/
public void execute() throws Exception {
loadConfigFile();
KubernetesClient kubernetes = getKubernetes();
String name = projectName;
if (Strings.isNullOrBlank(name)) {
if (projectConfig != null) {
name = projectConfig.getBuildName();
}
if (Strings.isNullOrBlank(name)) {
name = jenkinsJob;
}
if (Strings.isNullOrBlank(name)) {
name = ProjectRepositories.createBuildName(username, repoName);
if (projectConfig != null) {
projectConfig.setBuildName(name);
}
}
}
if (Strings.isNullOrBlank(projectName)) {
projectName = name;
}
Map<String, String> labels = new HashMap<>();
labels.put("user", username);
labels.put("repo", repoName);
getLog().info("build name " + name);
taiga = null;
taigaProject = null;
try {
taiga = createTaiga();
taigaProject = createTaigaProject(taiga);
} catch (Exception e) {
getLog().error("Failed to load or lazily create the Taiga project: " + e, e);
}
getLog().info("taiga " + taiga);
LetsChatClient letschat = null;
try {
letschat = createLetsChat();
} catch (Exception e) {
getLog().error("Failed to load or lazily create the LetsChat client: " + e, e);
}
getLog().info("letschat " + letschat);
/*
* Create Gerrit Git to if isGerritReview is enabled
*/
if (projectConfig != null && projectConfig.hasCodeReview()) {
try {
createGerritRepo(repoName, gerritUser, gerritPwd, gerritGitInitialCommit, gerritGitRepoDesription);
} catch (Exception e) {
getLog().error("Failed to create GerritGit repo : " + e, e);
}
}
Map<String, String> annotations = new HashMap<>();
jenkinsJobUrl = null;
String jenkinsUrl = null;
try {
jenkinsUrl = getJenkinsServiceUrl(true);
if (Strings.isNotBlank(jenkinsUrl)) {
if (Strings.isNotBlank(jenkinsMonitorView)) {
String url = URLUtils.pathJoin(jenkinsUrl, "/view", jenkinsMonitorView);
annotationLink(annotations, "fabric8.link.jenkins.monitor/", url, "Monitor");
}
if (Strings.isNotBlank(jenkinsPipelineView)) {
String url = URLUtils.pathJoin(jenkinsUrl, "/view", jenkinsPipelineView);
annotationLink(annotations, "fabric8.link.jenkins.pipeline/", url, "Pipeline");
}
if (Strings.isNotBlank(name)) {
jenkinsJobUrl = URLUtils.pathJoin(jenkinsUrl, "/job", name);
annotationLink(annotations, "fabric8.link.jenkins.job/", jenkinsJobUrl, "Job");
}
}
} catch (Exception e) {
getLog().warn("Could not find the Jenkins URL!: " + e, e);
}
getLog().info("jenkins " + jenkinsUrl);
if (!annotationLink(annotations, "fabric8.link.issues/", issueTrackerUrl, issueTrackerLabel)) {
String taigaLink = getProjectPageLink(taiga, taigaProject, this.taigaProjectLinkPage);
annotationLink(annotations, "fabric8.link.taiga/", taigaLink, taigaProjectLinkLabel);
}
if (!annotationLink(annotations, "fabric8.link.team/", teamUrl, teamLabel)) {
String taigaTeamLink = getProjectPageLink(taiga, taigaProject, this.taigaTeamLinkPage);
annotationLink(annotations, "fabric8.link.taiga.team/", taigaTeamLink, taigaTeamLinkLabel);
}
annotationLink(annotations, "fabric8.link.releases/", releasesUrl, releasesLabel);
String chatRoomLink = getChatRoomLink(letschat);
annotationLink(annotations, "fabric8.link.letschat.room/", chatRoomLink, letschatRoomLinkLabel);
annotationLink(annotations, "fabric8.link.repository.browse/", repositoryBrowseLink, repositoryBrowseLabel);
ProjectConfigs.defaultEnvironments(projectConfig, namespace);
String consoleUrl = getServiceUrl(ServiceNames.FABRIC8_CONSOLE, namespace, fabric8ConsoleNamespace);
if (projectConfig != null) {
Map<String, String> environments = projectConfig.getEnvironments();
updateEnvironmentConfigMap(environments, kubernetes, annotations, consoleUrl);
}
addLink("Git", getGitUrl());
Controller controller = createController();
OpenShiftClient openShiftClient = controller.getOpenShiftClientOrJenkinshift();
BuildConfig buildConfig = null;
if (openShiftClient != null) {
try {
buildConfig = openShiftClient.buildConfigs().withName(projectName).get();
} catch (Exception e) {
log.error("Failed to load build config for " + namespace + "/" + projectName + ". " + e, e);
}
log.info("Loaded build config for " + namespace + "/" + projectName + " " + buildConfig);
}
// if we have loaded a build config then lets assume its correct!
boolean foundExistingGitUrl = false;
if (buildConfig != null) {
BuildConfigSpec spec = buildConfig.getSpec();
if (spec != null) {
BuildSource source = spec.getSource();
if (source != null) {
GitBuildSource git = source.getGit();
if (git != null) {
gitUrl = git.getUri();
log.info("Loaded existing BuildConfig git url: " + gitUrl);
foundExistingGitUrl = true;
}
LocalObjectReference sourceSecret = source.getSourceSecret();
if (sourceSecret != null) {
gitSourceSecretName = sourceSecret.getName();
}
}
}
if (!foundExistingGitUrl) {
log.warn("Could not find a git url in the loaded BuildConfig: " + buildConfig);
}
log.info("Loaded gitSourceSecretName: " + gitSourceSecretName);
}
log.info("gitUrl is: " + gitUrl);
if (buildConfig == null) {
buildConfig = new BuildConfig();
}
ObjectMeta metadata = getOrCreateMetadata(buildConfig);
metadata.setName(projectName);
metadata.setAnnotations(annotations);
metadata.setLabels(labels);
Builds.configureDefaultBuildConfig(buildConfig, name, gitUrl, foundExistingGitUrl, buildImageStream, buildImageTag, s2iCustomBuilderImage, secret, jenkinsUrl);
try {
getLog().info("About to apply build config: " + new JSONObject(KubernetesHelper.toJson(buildConfig)).toString(4));
controller.applyBuildConfig(buildConfig, "maven");
getLog().info("Created build configuration for " + name + " in namespace: " + controller.getNamespace() + " at " + kubernetes.getMasterUrl());
} catch (Exception e) {
getLog().error("Failed to create BuildConfig for " + KubernetesHelper.toJson(buildConfig) + ". " + e, e);
}
this.jenkinsJobName = name;
if (isRegisterWebHooks()) {
registerWebHooks();
getLog().info("webhooks done");
}
if (modifiedConfig) {
if (basedir == null) {
getLog().error("Could not save updated " + ProjectConfigs.FILE_NAME + " due to missing basedir");
} else {
try {
ProjectConfigs.saveToFolder(basedir, projectConfig, true);
getLog().info("Updated " + ProjectConfigs.FILE_NAME);
} catch (IOException e) {
getLog().error("Could not save updated " + ProjectConfigs.FILE_NAME + ": " + e, e);
}
}
}
}
public void updateEnvironmentConfigMap(Map<String, String> environments, KubernetesClient kubernetes, Map<String, String> annotations, String consoleUrl) {
if (environments != null && !environments.isEmpty()) {
String name = Environments.ENVIRONMENTS_CONFIG_MAP_NAME;
getLog().info("Ensuring ConfigMap " + name + " is populated with enviroments: " + environments);
ConfigMap environmentsConfigMap = Environments.getOrCreateEnvironments(kubernetes);
boolean updatedEnvConfigMap = false;
for (Map.Entry<String, String> entry : environments.entrySet()) {
String label = entry.getKey();
String value = entry.getValue();
String key = value;
annotations.put("fabric8.link.environment." + key + "/label", label);
if (Strings.isNotBlank(consoleUrl)) {
String environmentLink = URLUtils.pathJoin(consoleUrl, "/kubernetes/pods?namespace=" + value);
annotations.put("fabric8.link.environment." + key + "/url", environmentLink);
addLink(label, environmentLink);
}
String dataKey = label.toLowerCase().replace(' ', '-');
boolean updated = Environments.ensureEnvironmentAdded(environmentsConfigMap, dataKey, label, value);
updatedEnvConfigMap = updated || updatedEnvConfigMap;
}
if (updatedEnvConfigMap) {
String ns = kubernetes.getNamespace();
getLog().info("Updating ConfigMap " + name + " with data: " + environmentsConfigMap.getData());
if (KubernetesHelper.getResourceVersion(environmentsConfigMap) == null) {
kubernetes.configMaps().inNamespace(ns).create(environmentsConfigMap);
} else {
try {
kubernetes.configMaps().inNamespace(ns).withName(name).replace(environmentsConfigMap);
} catch (Exception e) {
getLog().error("Failed to update the Environment ConfigMap with data: " + environments + ". Reason: " + e, e);
}
}
} else {
getLog().info("No need to update ConfigMap " + name + " as already has data: " + environmentsConfigMap.getData());
}
}
}
protected String getJenkinsServiceUrl(boolean externalUrl) {
return getServiceUrl(ServiceNames.JENKINS, externalUrl, namespace, jenkinsNamespace);
}
/**
* Looks in the given namespaces for the given service or returns null if it could not be found
*/
protected String getServiceUrl(String serviceName, String... namespaces) {
return getServiceUrl(serviceName, false, namespaces);
}
private String getServiceUrl(String serviceName, boolean serviceExternal, String... namespaces) {
List<String> namespaceList = new ArrayList<>(Arrays.asList(namespaces));
String[] defaults = {KubernetesHelper.defaultNamespace(), "default"};
for (String defaultNamespace : defaults) {
if (namespaceList.contains(defaultNamespace)) {
namespaceList.add(defaultNamespace);
}
}
for (String namespace : namespaceList) {
try {
return KubernetesHelper.getServiceURL(getKubernetes(), serviceName, namespace, "http", serviceExternal);
} catch (Exception e) {
// ignore
}
}
return null;
}
protected boolean annotationLink(Map<String, String> annotations, String annotationPrefix, String issueTrackerUrl, String issueTrackerLabel) {
if (Strings.isNotBlank(issueTrackerUrl)) {
annotations.put(annotationPrefix + "url", issueTrackerUrl);
annotations.put(annotationPrefix + "label", issueTrackerLabel);
addLink(issueTrackerLabel, issueTrackerUrl);
return true;
} else {
return false;
}
}
public void registerWebHooks() {
if (Strings.isNotBlank(jenkinsJobName)) {
jenkinsJobTemplate = createJenkinsJob(jenkinsJobName, jenkinsJobUrl);
getLog().info("created jenkins job");
}
if (Strings.isNotBlank(jenkinsJobUrl) && Strings.isNotBlank(jenkinsJobName)) {
createJenkinsWebhook(jenkinsJobUrl);
}
if (taiga != null && taigaProject != null) {
createTaigaWebhook(taiga, taigaProject);
}
}
public void addLink(String label, String url) {
if (projectConfig == null) {
projectConfig = new ProjectConfig();
}
projectConfig.addLink(label, url);
modifiedConfig = true;
}
public Logger getLog() {
return log;
}
public void setLog(Logger log) {
this.log = log;
}
public KubernetesClient getKubernetes() {
if (kubernetes == null) {
Config config = new ConfigBuilder().withNamespace(namespace).build();
kubernetes = new DefaultKubernetesClient(config);
}
return kubernetes;
}
public GitRepoClient getGitRepoClient() {
if (gitRepoClient == null) {
gitRepoClient = GitRepoKubernetes.createGitRepoClient(getKubernetes(), username, password);
if (gitRepoClient != null) {
if (Strings.isNullOrBlank(username)) {
username = gitRepoClient.getUsername();
}
if (Strings.isNullOrBlank(password)) {
password = gitRepoClient.getPassword();
}
}
}
return gitRepoClient;
}
// Properties
//-------------------------------------------------------------------------
public File getBasedir() {
return basedir;
}
public void setBasedir(File basedir) {
this.basedir = basedir;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getBuildImageStream() {
return buildImageStream;
}
public void setBuildImageStream(String buildImageStream) {
this.buildImageStream = buildImageStream;
}
public String getBuildImageTag() {
return buildImageTag;
}
public void setBuildImageTag(String buildImageTag) {
this.buildImageTag = buildImageTag;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setGitRepoClient(GitRepoClient gitRepoClient) {
this.gitRepoClient = gitRepoClient;
}
public String getGitUrl() {
return gitUrl;
}
public void setGitUrl(String gitUrl) {
this.gitUrl = gitUrl;
}
public String getJenkinsJob() {
return jenkinsJob;
}
public void setJenkinsJob(String jenkinsJob) {
this.jenkinsJob = jenkinsJob;
}
public String getJenkinsMonitorView() {
return jenkinsMonitorView;
}
public void setJenkinsMonitorView(String jenkinsMonitorView) {
this.jenkinsMonitorView = jenkinsMonitorView;
}
public String getJenkinsPipelineView() {
return jenkinsPipelineView;
}
public void setJenkinsPipelineView(String jenkinsPipelineView) {
this.jenkinsPipelineView = jenkinsPipelineView;
}
public void setKubernetes(KubernetesClient kubernetes) {
this.kubernetes = kubernetes;
}
public boolean isTriggerJenkinsJob() {
return triggerJenkinsJob;
}
public void setTriggerJenkinsJob(boolean triggerJenkinsJob) {
this.triggerJenkinsJob = triggerJenkinsJob;
}
public boolean isLetschatEnabled() {
return letschatEnabled;
}
public void setLetschatEnabled(boolean letschatEnabled) {
this.letschatEnabled = letschatEnabled;
}
public String getLetschatRoomExpression() {
return letschatRoomExpression;
}
public void setLetschatRoomExpression(String letschatRoomExpression) {
this.letschatRoomExpression = letschatRoomExpression;
}
public String getLetschatRoomLinkLabel() {
return letschatRoomLinkLabel;
}
public void setLetschatRoomLinkLabel(String letschatRoomLinkLabel) {
this.letschatRoomLinkLabel = letschatRoomLinkLabel;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getFabric8ConsoleNamespace() {
return fabric8ConsoleNamespace;
}
public void setFabric8ConsoleNamespace(String fabric8ConsoleNamespace) {
this.fabric8ConsoleNamespace = fabric8ConsoleNamespace;
}
public String getJenkinsNamespace() {
return jenkinsNamespace;
}
public void setJenkinsNamespace(String jenkinsNamespace) {
this.jenkinsNamespace = jenkinsNamespace;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isRecreateMode() {
return recreateMode;
}
public void setRecreateMode(boolean recreateMode) {
this.recreateMode = recreateMode;
}
public String getRepoName() {
return repoName;
}
public void setRepoName(String repoName) {
this.repoName = repoName;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public boolean isTaigaAutoCreate() {
return taigaAutoCreate;
}
public void setTaigaAutoCreate(boolean taigaAutoCreate) {
this.taigaAutoCreate = taigaAutoCreate;
}
public boolean isTaigaEnabled() {
return taigaEnabled;
}
public void setTaigaEnabled(boolean taigaEnabled) {
this.taigaEnabled = taigaEnabled;
}
public String getTaigaProjectLinkLabel() {
return taigaProjectLinkLabel;
}
public void setTaigaProjectLinkLabel(String taigaProjectLinkLabel) {
this.taigaProjectLinkLabel = taigaProjectLinkLabel;
}
public String getTaigaProjectLinkPage() {
return taigaProjectLinkPage;
}
public void setTaigaProjectLinkPage(String taigaProjectLinkPage) {
this.taigaProjectLinkPage = taigaProjectLinkPage;
}
public String getTaigaProjectName() {
return taigaProjectName;
}
public void setTaigaProjectName(String taigaProjectName) {
this.taigaProjectName = taigaProjectName;
}
public String getTaigaProjectSlug() {
return taigaProjectSlug;
}
public void setTaigaProjectSlug(String taigaProjectSlug) {
this.taigaProjectSlug = taigaProjectSlug;
}
public String getTaigaTeamLinkLabel() {
return taigaTeamLinkLabel;
}
public void setTaigaTeamLinkLabel(String taigaTeamLinkLabel) {
this.taigaTeamLinkLabel = taigaTeamLinkLabel;
}
public String getTaigaTeamLinkPage() {
return taigaTeamLinkPage;
}
public void setTaigaTeamLinkPage(String taigaTeamLinkPage) {
this.taigaTeamLinkPage = taigaTeamLinkPage;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public boolean isTryLoadConfigFileFromRemoteGit() {
return tryLoadConfigFileFromRemoteGit;
}
public void setTryLoadConfigFileFromRemoteGit(boolean tryLoadConfigFileFromRemoteGit) {
this.tryLoadConfigFileFromRemoteGit = tryLoadConfigFileFromRemoteGit;
}
public ProjectConfig getProjectConfig() {
return projectConfig;
}
public void setProjectConfig(ProjectConfig projectConfig) {
this.projectConfig = projectConfig;
}
public void setRegisterWebHooks(boolean registerWebHooks) {
this.registerWebHooks = registerWebHooks;
}
public boolean isRegisterWebHooks() {
return registerWebHooks;
}
public String getIssueTrackerLabel() {
return issueTrackerLabel;
}
public void setIssueTrackerLabel(String issueTrackerLabel) {
this.issueTrackerLabel = issueTrackerLabel;
}
public String getIssueTrackerUrl() {
return issueTrackerUrl;
}
public void setIssueTrackerUrl(String issueTrackerUrl) {
this.issueTrackerUrl = issueTrackerUrl;
}
public String getTeamUrl() {
return teamUrl;
}
public void setTeamUrl(String teamUrl) {
this.teamUrl = teamUrl;
}
public String getTeamLabel() {
return teamLabel;
}
public void setTeamLabel(String teamLabel) {
this.teamLabel = teamLabel;
}
public String getReleasesUrl() {
return releasesUrl;
}
public void setReleasesUrl(String releasesUrl) {
this.releasesUrl = releasesUrl;
}
public String getReleasesLabel() {
return releasesLabel;
}
public void setReleasesLabel(String releasesLabel) {
this.releasesLabel = releasesLabel;
}
public String getRepositoryBrowseLabel() {
return repositoryBrowseLabel;
}
public void setRepositoryBrowseLabel(String repositoryBrowseLabel) {
this.repositoryBrowseLabel = repositoryBrowseLabel;
}
public String getRepositoryBrowseLink() {
return repositoryBrowseLink;
}
public void setRepositoryBrowseLink(String repositoryBrowseLink) {
this.repositoryBrowseLink = repositoryBrowseLink;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
// Implementation methods
//-------------------------------------------------------------------------
protected Controller createController() {
Controller controller = new Controller(getKubernetes());
controller.setNamespace(namespace);
controller.setThrowExceptionOnError(true);
controller.setRecreateMode(recreateMode);
return controller;
}
protected void loadConfigFile() {
if (projectConfig == null) {
GitRepoClient gitRepo = getGitRepoClient();
boolean hasLocalConfig = false;
if (basedir != null && basedir.isDirectory()) {
projectConfig = ProjectConfigs.loadFromFolder(basedir);
if (!projectConfig.isEmpty() || ProjectConfigs.hasConfigFile(basedir)) {
hasLocalConfig = true;
}
}
if (!hasLocalConfig && tryLoadConfigFileFromRemoteGit && Strings.isNotBlank(repoName) && gitRepo != null) {
try {
InputStream input = gitRepo.getRawFile(username, repoName, branch, ProjectConfigs.FILE_NAME);
if (input != null) {
try {
getLog().info("Parsing " + ProjectConfigs.FILE_NAME + " from the git repo " + repoName + " user " + username + " in branch " + branch);
projectConfig = ProjectConfigs.parseProjectConfig(input);
} catch (IOException e) {
getLog().warn("Failed to parse " + ProjectConfigs.FILE_NAME + " from the repo " + repoName + " for user " + username + " branch: " + branch + ". " + e, e);
}
}
} catch (Exception e) {
getLog().warn("Failed to load " + ProjectConfigs.FILE_NAME + " from the repo " + repoName + " for user " + username + " branch: " + branch + ". " + e, e);
}
}
}
if (projectConfig != null) {
String chatRoom = projectConfig.getChatRoom();
if (Strings.isNotBlank(chatRoom)) {
getLog().info("Found chat room: " + chatRoom);
letschatRoomExpression = chatRoom;
}
String issueProjectName = projectConfig.getIssueProjectName();
if (Strings.isNotBlank(issueProjectName)) {
taigaProjectName = issueProjectName;
}
} else {
getLog().info("No fabric8.yml file found for " + basedir);
}
if (Strings.isNullOrBlank(gitUrl)) {
try {
gitUrl = GitHelpers.extractGitUrl(basedir);
} catch (IOException e) {
getLog().warn("Could not load git URL from directory: " + e, e);
}
}
if (Strings.isNullOrBlank(taigaProjectName)) {
taigaProjectName = repoName;
}
if (Strings.isNullOrBlank(taigaProjectSlug)) {
// TODO should we upper case it or anything?
taigaProjectSlug = taigaProjectName;
}
}
protected String getChatRoomLink(LetsChatClient letschat) {
if (letschat != null) {
try {
String url = letschat.getAddress();
String slug = evaluateRoomExpression(letschatRoomExpression);
if (Strings.isNotBlank(url) && Strings.isNotBlank(slug)) {
RoomDTO room = letschat.getOrCreateRoom(slug);
if (room != null) {
String roomId = room.getId();
if (Strings.isNotBlank(roomId)) {
return URLUtils.pathJoin(url, "/#!/room/" + roomId);
}
}
}
} catch (Exception e) {
getLog().error("Failed to get the link to the chat room: " + e, e);
}
}
return null;
}
protected String evaluateRoomExpression(String roomExpresion) {
if (Strings.isNotBlank(roomExpresion)) {
String namespace = KubernetesHelper.defaultNamespace();
String answer = roomExpresion;
answer = replaceExpression(answer, "namespace", namespace);
answer = replaceExpression(answer, "repoName", repoName);
answer = replaceExpression(answer, "username", username);
return answer;
} else {
return null;
}
}
protected String replaceExpression(String text, String key, String value) {
if (Strings.isNotBlank(key) && Strings.isNotBlank(value)) {
String replace = "${" + key + "}";
return text.replace(replace, value);
} else {
return text;
}
}
protected LetsChatClient createLetsChat() {
if (!letschatEnabled) {
return null;
}
KubernetesClient kubernetes = getKubernetes();
LetsChatClient letsChat = LetsChatKubernetes.createLetsChat(kubernetes);
if (letsChat == null) {
getLog().warn("No letschat service availble n kubernetes " + namespace + " on address: " + kubernetes.getMasterUrl());
return null;
}
if (!letsChat.isValid()) {
getLog().warn("No $" + LetsChatKubernetes.LETSCHAT_HUBOT_TOKEN + " environment variable defined so LetsChat support is disabled");
return null;
}
return letsChat;
}
protected TaigaClient createTaiga() {
if (!taigaEnabled) {
return null;
}
TaigaClient taiga = TaigaKubernetes.createTaiga(getKubernetes(), namespace);
if (taiga != null) {