-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathDimensionsSCM.java
More file actions
1573 lines (1453 loc) · 62.2 KB
/
DimensionsSCM.java
File metadata and controls
1573 lines (1453 loc) · 62.2 KB
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 hudson.plugins.dimensionsscm;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.ModelObject;
import hudson.model.Node;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.dimensionsscm.model.StringVarStorage;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.PollingResult.Change;
import hudson.scm.RepositoryBrowser;
import hudson.scm.RepositoryBrowsers;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.security.ACL;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.Scrambler;
import hudson.util.Secret;
import hudson.util.VariableResolver;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.kohsuke.stapler.*;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* An SCM that can poll, browse and update from Dimensions CM.
*/
public class DimensionsSCM extends SCM implements Serializable {
@Extension
public static final DescriptorImpl DM_DESCRIPTOR = new DescriptorImpl();
private static final List<StringVarStorage> EMPTY_STRING_LIST = new ArrayList<StringVarStorage>();
private static final List<StringVarStorage> DEFAULT_FOLDERS = Collections.singletonList(new StringVarStorage("/"));
private transient String jobPasswd;
private transient DimensionsAPI cachedAPI;
private transient DimensionsSCMRepositoryBrowser browser;
private String credentialsId;
private String jobUserName;
private String jobServer;
private String jobDatabase;
private String project;
private Secret jobPasswdSecret;
private Secret certificatePassword;
private Secret remoteCertificatePassword;
private Secret keystorePassword;
private String permissions;
private String eol;
private String jobTimeZone;
private String jobWebUrl;
private String credentialsType;
private String keystorePath;
private String certificateAlias;
private String certificatePath;
private String[] folders;
private String[] pathsToExclude;
private List<StringVarStorage> foldersList;
private List<StringVarStorage> pathsToExcludeList;
private boolean canJobUpdate;
private boolean canJobDelete;
private boolean canJobForce;
private boolean canJobRevert;
private boolean canJobExpand;
private boolean canJobNoMetadata;
private boolean canJobNoTouch;
private boolean secureAgentAuth;
@DataBoundConstructor
public DimensionsSCM(final String project, final String credentialsType, final String userName, final String password,
final String pluginServer, final String userServer, final String keystoreServer,
final String pluginDatabase, final String userDatabase, final String keystoreDatabase,
final String keystorePath, final String certificateAlias,
final String credentialsId, final String certificatePassword, final String keystorePassword,
final String certificatePath, final String remoteCertificatePassword, final boolean secureAgentAuth) {
this.credentialsId = StringUtils.EMPTY;
this.jobUserName = StringUtils.EMPTY;
this.jobPasswdSecret = null;
this.keystorePath = StringUtils.EMPTY;
this.certificateAlias = StringUtils.EMPTY;
this.certificatePassword = null;
this.keystorePassword = null;
this.certificatePath = StringUtils.EMPTY;
this.remoteCertificatePassword = null;
this.secureAgentAuth = false;
this.jobServer = null;
this.jobDatabase = null;
if (Credentials.isUserDefined(credentialsType)) {
this.jobUserName = userName;
this.jobPasswdSecret = Secret.fromString(password);
this.jobServer = userServer;
this.jobDatabase = userDatabase;
} else if (Credentials.isPluginDefined(credentialsType)) {
final UsernamePasswordCredentials credentials = initializeCredentials(credentialsId);
if (credentials != null) {
this.jobUserName = credentials.getUsername();
this.jobPasswdSecret = credentials.getPassword();
}
this.jobServer = pluginServer;
this.jobDatabase = pluginDatabase;
this.credentialsId = credentialsId;
} else if (Credentials.isKeystoreDefined(credentialsType)) {
this.keystorePath = keystorePath;
this.certificateAlias = certificateAlias;
this.secureAgentAuth = secureAgentAuth;
this.jobServer = keystoreServer;
this.jobDatabase = keystoreDatabase;
this.certificatePassword = Secret.fromString(certificatePassword);
this.keystorePassword = Secret.fromString(keystorePassword);
if (this.secureAgentAuth) {
this.certificatePath = certificatePath;
this.remoteCertificatePassword = Secret.fromString(remoteCertificatePassword);
}
}
this.credentialsType = credentialsType;
this.project = Values.textOrElse(project, "${JOB_NAME}");
this.jobPasswd = null; // no longer used in config.xml serialization
this.browser = getDescriptor().getBrowser();
getAPI();
Logger.debug("Starting job for project '" + getProject() + "' "
+ ", connecting to " + getServer() + "-" + getUserName() + ":" + getDatabase());
}
private static DimensionsAPI newDimensionsAPIWithCheck() {
try {
return new DimensionsAPI();
} catch (NoClassDefFoundError e) {
// One of the most common customer issues is not installing the API JAR files, make reporting of this clearer.
final Jenkins jenkins = Jenkins.getInstanceOrNull();
final String path = jenkins != null ? new File(jenkins.getRootDir(),
"plugins/dimensionsscm/WEB-INF/lib").getAbsolutePath() : "$JENKINS_HOME/plugins/dimensionsscm/WEB-INF/lib";
throw (NoClassDefFoundError) new NoClassDefFoundError(e.getMessage() + "\r\n"
+ "//=================================================================================================\r\n"
+ "|| Check the required JAR files (darius.jar, dmclient.jar, dmfile.jar, dmnet.jar) were copied to\r\n"
+ "|| '" + path + "'\r\n"
+ "|| directory as described in the 'Installation' section of the Dimensions Plugin user guide:\r\n"
+ "|| https://github.com/jenkinsci/dimensionsscm-plugin/blob/master/docs/user-guide.md#installation\r\n"
+ "\\\\=================================================================================================\r\n");
}
}
private static UsernamePasswordCredentials initializeCredentials(final String credentialsId) {
UsernamePasswordCredentials credentials = null;
if (credentialsId != null && !credentialsId.isEmpty()) {
Item dummy = null;
credentials = CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
UsernamePasswordCredentials.class, dummy, ACL.SYSTEM,
Collections.<DomainRequirement>emptyList()),
CredentialsMatchers.allOf(
CredentialsMatchers.withId(credentialsId))
);
}
return credentials;
}
public boolean isChecked(final String type) {
boolean isActive = false;
final boolean isPluginDefined = Credentials.isPluginDefined(credentialsType);
final boolean isGlobalDefined = Credentials.isGlobalDefined(credentialsType);
final boolean isUserDefined = Credentials.isUserDefined(credentialsType);
final boolean isKeystoreDefined = Credentials.isKeystoreDefined(credentialsType);
if (Credentials.isPluginDefined(type)) {
isActive = isPluginDefined;
}
if (Credentials.isGlobalDefined(type)) {
isActive = isGlobalDefined;
}
if (Credentials.isKeystoreDefined(type)) {
isActive = isKeystoreDefined;
}
if (Credentials.isUserDefined(type)) {
final boolean isAllNotActive = !isKeystoreDefined && !isPluginDefined && !isGlobalDefined;
//the second part of 'or' needed in case when user updates from plugin version where it was no credential types yet
isActive = isUserDefined || (isAllNotActive && !Values.isNullOrEmpty(jobUserName));
}
return isActive;
}
/**
* The fix for Jenkins SECURITY-595 caused this method to be called by
* Stapler when initializing the corresponding Jelly view.
* That lead to a NoClassDefFoundError, which broke the job configuration
* page. The trivial workaround was to make this method non-public.
* If it needs to be public in future, renaming it may be enough.
*/
DimensionsAPI getAPI() {
DimensionsAPI api = this.cachedAPI;
if (api == null) {
api = newDimensionsAPIWithCheck();
this.cachedAPI = api;
}
return api;
}
/**
* Gets the unexpanded project name for the connection.
*
* @return the project spec
*/
public String getProject() {
return this.project;
}
/**
* Gets the expanded project name for the connection. Any variables in the project value will be expanded.
*
* @return the project spec without a trailing version number (if there is one).
*/
public String getProjectName(final Run<?, ?> run, final TaskListener log) {
final String projectVersion = getProjectVersion(run, log);
final int sc = projectVersion.lastIndexOf(';');
return sc >= 0 ? projectVersion.substring(0, sc) : projectVersion;
}
/**
* Gets selected credentialsId for the project
*/
public String getCredentialsId() {
return Values.textOrElse(this.credentialsId, null);
}
/**
* Gets the expanded project name and version for the connection. Any variables in the project value will be
* expanded.
*
* @return the project spec including its trailing version (if there is one).
*/
public String getProjectVersion(final Run<?, ?> run, final TaskListener log) {
EnvVars env = null;
if (run != null) {
try {
env = run.getEnvironment(log);
} catch (IOException e) {
/* don't expand */
} catch (InterruptedException e) {
/* don't expand */
}
}
String ret;
if (env != null) {
ret = env.expand(this.project);
} else {
ret = this.project;
}
return ret;
}
/**
* Gets the permissions string.
*/
public String getPermissions() {
return this.permissions;
}
/**
* Gets the eol value.
*/
public String getEol() {
return this.eol;
}
/**
* Gets the project paths to monitor.
*/
public List<StringVarStorage> getFolders() {
if (folders != null && folders.length > 0) {
if (foldersList == null) {
foldersList = new ArrayList<StringVarStorage>();
}
foldersList.addAll(Values.convertArrayToList(folders));
folders = null;
}
return foldersList;
}
/**
* Gets paths excluded from monitoring.
*/
public List<StringVarStorage> getPathsToExclude() {
if (pathsToExclude != null && pathsToExclude.length > 0) {
if (pathsToExcludeList == null) {
pathsToExcludeList = new ArrayList<StringVarStorage>();
}
pathsToExcludeList.addAll(Values.convertArrayToList(pathsToExclude));
pathsToExclude = null;
}
return pathsToExcludeList;
}
/**
* Gets the user ID for the connection.
*/
public String getUserName() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getUserName();
}
return Values.textOrElse(this.jobUserName, null);
}
/**
* Gets the password for the connection (not null).
*/
public String getPasswordNN() {
if (jobPasswdSecret == null && jobPasswd != null) {
jobPasswdSecret = Secret.fromString(Scrambler.descramble(jobPasswd));
jobPasswd = null;
}
Secret currentPassword = jobPasswdSecret;
if (Credentials.isGlobalDefined(credentialsType)) {
currentPassword = getDescriptor().getPassword();
}
return currentPassword != null && !currentPassword.getPlainText().isEmpty() ? currentPassword.getEncryptedValue() : StringUtils.EMPTY;
}
/**
* Gets the password for the connection (can be null).
*/
public String getPassword() {
return Values.textOrElse(getPasswordNN(), null);
}
/**
* Gets the certificate password as String.
*/
public String getCertificatePassword() {
final Secret currentPassword = getCertificatePasswordSecret();
return currentPassword != null ? currentPassword.getEncryptedValue() : null;
}
/**
* Gets the certificate password as Secret object.
*/
public Secret getCertificatePasswordSecret() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getCertificatePassword();
}
return certificatePassword;
}
/**
* Gets the keystore password as Secret object.
*/
public Secret getKeystorePasswordSecret() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getKeystorePassword();
}
return keystorePassword;
}
/**
* Gets the keystore password as String.
*/
public String getKeystorePassword() {
final Secret currentPassword = getKeystorePasswordSecret();
return currentPassword != null ? currentPassword.getEncryptedValue() : null;
}
/**
* Gets the remote certificate password as Secret instance.
*/
public Secret getRemoteCertificatePasswordSecret() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getRemoteCertificatePassword();
}
return remoteCertificatePassword;
}
/**
* Gets the remote certificate password as String.
*/
public String getRemoteCertificatePassword() {
final Secret currentPassword = getRemoteCertificatePasswordSecret();
return currentPassword != null ? currentPassword.getEncryptedValue() : null;
}
/**
* Gets the remote certificate path as String.
*/
public String getCertificatePath() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getCertificatePath();
}
return certificatePath;
}
/**
* Check if need perform secure auth for remote.
*
* @return secure auth
*/
public boolean isSecureAgentAuth() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().isSecureAgentAuth();
}
return secureAgentAuth;
}
/**
* Gets the server name for the connection.
*/
public String getServer() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getServer();
}
return this.jobServer;
}
//this getter is needed for snippet generator
public String getUserServer() {
return Credentials.isUserDefined(credentialsType) ? this.jobServer : null;
}
//this getter is needed for snippet generator
public String getPluginServer() {
return Credentials.isPluginDefined(credentialsType) ? this.jobServer : null;
}
//this getter is needed for snippet generator
public String getKeystoreServer() {
return Credentials.isKeystoreDefined(credentialsType) ? this.jobServer : null;
}
/**
* Gets the database name for the connection.
*/
public String getDatabase() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getDatabase();
}
return this.jobDatabase;
}
//this getter is needed for snippet generator
public String getUserDatabase() {
return Credentials.isUserDefined(credentialsType) ? this.jobDatabase : null;
}
//this getter is needed for snippet generator
public String getPluginDatabase() {
return Credentials.isPluginDefined(credentialsType) ? this.jobDatabase : null;
}
//this getter is needed for snippet generator
public String getKeystoreDatabase() {
return Credentials.isKeystoreDefined(credentialsType) ? this.jobDatabase : null;
}
/**
* Gets the time zone for the connection.
*/
public String getTimeZone() {
return this.jobTimeZone;
}
/**
* Gets the web URL for the connection.
*/
public String getWebUrl() {
return this.jobWebUrl;
}
/**
* Gets the credentials type.
*/
public String getCredentialsType() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getCredentialsType();
}
return credentialsType;
}
/**
* Gets the keystore path.
*/
public String getKeystorePath() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getKeystorePath();
}
return Values.textOrElse(this.keystorePath, null);
}
/**
* Gets the certificate alias.
*/
public String getCertificateAlias() {
if (Credentials.isGlobalDefined(credentialsType)) {
return getDescriptor().getCertificateAlias();
}
return Values.textOrElse(this.certificateAlias, null);
}
/**
* Gets the expand flag.
*/
public boolean isCanJobExpand() {
return this.canJobExpand;
}
/**
* Gets the no metadata flag.
*/
public boolean isCanJobNoMetadata() {
return this.canJobNoMetadata;
}
/**
* Gets the no touch flag.
*/
public boolean isCanJobNoTouch() {
return this.canJobNoTouch;
}
/**
* Gets the update flag.
*/
public boolean isCanJobUpdate() {
return this.canJobUpdate;
}
/**
* Gets the delete flag.
*/
public boolean isCanJobDelete() {
return this.canJobDelete;
}
/**
* Gets the force flag.
*/
public boolean isCanJobForce() {
return this.canJobForce;
}
/**
* Gets the revert flag.
*/
public boolean isCanJobRevert() {
return this.canJobRevert;
}
@DataBoundSetter
public void setFolders(final List<StringVarStorage> folders) {
this.foldersList = Values.notBlankOrElseList(folders, DEFAULT_FOLDERS);
}
@DataBoundSetter
public void setPathsToExclude(final List<StringVarStorage> pathsToExclude) {
this.pathsToExcludeList = Values.notBlankOrElseList(pathsToExclude, EMPTY_STRING_LIST);
}
@DataBoundSetter
public void setPermissions(final String permissions) {
this.permissions = canJobUpdate ? Values.textOrElse(permissions, "DEFAULT") : StringUtils.EMPTY;
}
@DataBoundSetter
public void setEol(final String eol) {
this.eol = canJobUpdate ? Values.textOrElse(eol, "DEFAULT") : StringUtils.EMPTY;
}
@DataBoundSetter
public void setTimeZone(final String timeZone) {
this.jobTimeZone = Values.textOrElse(timeZone, getDescriptor().getTimeZone());
}
@DataBoundSetter
public void setWebUrl(final String webUrl) {
this.jobWebUrl = Values.textOrElse(webUrl, getDescriptor().getWebUrl());
}
@DataBoundSetter
public void setCanJobUpdate(final boolean canJobUpdate) {
this.canJobUpdate = Values.hasText(this.jobServer) ? canJobUpdate : getDescriptor().isCanUpdate();
}
@DataBoundSetter
public void setCanJobDelete(final boolean canJobDelete) {
this.canJobDelete = canJobDelete;
}
@DataBoundSetter
public void setCanJobForce(final boolean canJobForce) {
this.canJobForce = canJobForce;
}
@DataBoundSetter
public void setCanJobRevert(final boolean canJobRevert) {
this.canJobRevert = canJobRevert;
}
@DataBoundSetter
public void setCanJobExpand(final boolean canJobExpand) {
this.canJobExpand = canJobUpdate && canJobExpand;
}
@DataBoundSetter
public void setCanJobNoMetadata(final boolean canJobNoMetadata) {
this.canJobNoMetadata = canJobUpdate && canJobNoMetadata;
}
@DataBoundSetter
public void setCanJobNoTouch(final boolean canJobNoTouch) {
this.canJobNoTouch = canJobUpdate && canJobNoTouch;
}
/**
* Does this SCM plugin require a workspace for polling?
* <p>
* {@inheritDoc}
*/
@Override
public boolean requiresWorkspaceForPolling() {
return false;
}
/**
* Does this SCM plugin support polling?
* <p>
* {@inheritDoc}
*/
@Override
public boolean supportsPolling() {
return true;
}
/**
* Build up environment variables for build support.
* <p>
* {@inheritDoc}
*/
@Override
public void buildEnvVars(final AbstractBuild<?, ?> build, final Map<String, String> env) {
// To be implemented when build support put in.
super.buildEnvVars(build, env);
}
@Override
public DimensionsSCMRepositoryBrowser getBrowser() {
return this.browser;
}
@NonNull
@Override
public String getKey() {
return "dimensions " + getUserName() + "@" + getServer() + "/" + getDatabase() + "/" + getProject();
}
@CheckForNull
@Override
public RepositoryBrowser<?> guessBrowser() {
return new DimensionsSCMRepositoryBrowser();
}
/**
* Get build parameters for WorkflowRun
*/
public String getParameterFromBuild(final WorkflowRun build, final String parameterName) {
String parValue = null;
for (ParametersAction parametersAction : build.getActions(ParametersAction.class)) {
ParameterValue parameterValue = parametersAction.getParameter(parameterName);
if (parameterValue != null) {
parValue = String.valueOf(parameterValue.getValue());
break;
}
}
return parValue;
}
/**
* Checkout method for the plugin.
* <p>
* {@inheritDoc}
*/
@Override
public void checkout(@NonNull final Run<?, ?> build, @NonNull final Launcher launcher, @NonNull final FilePath workspace, @NonNull final TaskListener listener,
@CheckForNull final File changelogFile, @CheckForNull final SCMRevisionState baseln) throws IOException, InterruptedException {
if (!isCanJobUpdate()) {
Logger.debug("Skipping checkout - " + this.getClass().getName());
}
Logger.debug("Invoking checkout - " + this.getClass().getName());
// Load other Dimensions plugins if set.
final DimensionsBuildWrapper.DescriptorImpl bwplugin = (DimensionsBuildWrapper.DescriptorImpl)
Jenkins.get().getDescriptor(DimensionsBuildWrapper.class);
final DimensionsBuildNotifier.DescriptorImpl bnplugin = (DimensionsBuildNotifier.DescriptorImpl)
Jenkins.get().getDescriptor(DimensionsBuildNotifier.class);
if (DimensionsChecker.isValidPluginCombination(build, listener)) {
Logger.debug("Plugins are ok");
} else {
listener.fatalError("\n[DIMENSIONS] The plugin combinations you have selected are not valid.");
listener.fatalError("\n[DIMENSIONS] Please review online help to determine valid plugin uses.");
throw new IOException("Error: you have selected wrong plugin combinations.");
}
if (isCanJobUpdate()) {
final DimensionsAPI dmSCM = getAPI();
int version = 2009;
final long key = dmSCM.login(this, build);
if (key > 0L) {
// Get the server version.
Logger.debug("Login worked.");
version = dmSCM.getDmVersion();
if (version == 0) {
version = 2009;
}
dmSCM.logout(key, build);
}
if (!workspace.isRemote()) {
// Running on master...
Logger.debug("Checking if master or slave...");
listener.getLogger().println("[DIMENSIONS] Running checkout on master...");
listener.getLogger().flush();
// Using Java API because this allows the plugin to work on platforms where Dimensions has not
// been ported, e.g. MAC OS, which is what I use.
final CheckOutAPITask task = new CheckOutAPITask(build, this, workspace, listener, version);
workspace.act(task);
} else {
// Running on slave... Have to use the command line as Java API will not work on remote hosts.
// Cannot serialise it...
// VariableResolver does not appear to be serialisable either, so...
Logger.debug("Forced processing as slave...");
String baseline = null;
String request = null;
if (build instanceof AbstractBuild) {
final VariableResolver<String> myResolver = ((AbstractBuild<?, ?>) build).getBuildVariableResolver();
baseline = myResolver.resolve("DM_BASELINE");
request = myResolver.resolve("DM_REQUEST");
} else if (build instanceof WorkflowRun) {
baseline = getParameterFromBuild((WorkflowRun) build, "DM_BASELINE");
request = getParameterFromBuild((WorkflowRun) build, "DM_REQUEST");
}
listener.getLogger().println("[DIMENSIONS] Running checkout on slave...");
listener.getLogger().flush();
if (Credentials.isKeystoreDefined(getCredentialsType())) {
if (StringUtils.isBlank(getCertificatePath())) {
throw new IOException("User certificate path from remote machine must be specified.");
}
if (getRemoteCertificatePasswordSecret() == null) {
throw new IOException("User certificate password from remote machine must be specified.");
}
}
final CheckOutCmdTask task = new CheckOutCmdTask(getUserName(), Secret.decrypt(getPasswordNN()), getDatabase(),
getServer(), getProjectVersion(build, listener), baseline, request, isCanJobDelete(),
isCanJobRevert(), isCanJobForce(), isCanJobExpand(), isCanJobNoMetadata(),
isCanJobNoTouch(), (build.getPreviousBuild() == null), getFolders(), version,
permissions, eol, getCertificatePath(), getRemoteCertificatePasswordSecret(),
isSecureAgentAuth(), workspace, listener);
workspace.act(task);
}
}
generateChangeSet(build, listener, changelogFile);
}
/**
* Generate the changeset.
*/
private void generateChangeSet(final Run<?, ?> build, final TaskListener listener, final File changelogFile) throws IOException {
long key = -1L;
final DimensionsAPI dmSCM = newDimensionsAPIWithCheck();
try {
// When are we building files for?
// Looking for the last successful build and then go forward from there - could use the last build as well.
final Calendar lastBuildCal = (build.getPreviousBuild() != null) ? build.getPreviousBuild().getTimestamp() : null;
// Calendar lastBuildCal = (build.getPreviousNotFailedBuild() != null) ? build.getPreviousNotFailedBuild().getTimestamp() : null;
final Calendar nowDateCal = Calendar.getInstance();
final TimeZone tz = (getTimeZone() != null && getTimeZone().length() > 0) ? TimeZone.getTimeZone(getTimeZone()) : TimeZone.getDefault();
if (getTimeZone() != null && getTimeZone().length() > 0) {
Logger.debug("Job timezone setting is " + getTimeZone());
}
Logger.debug("Log updates between " + (lastBuildCal != null ? DateUtils.getStrDate(lastBuildCal, tz) : "0") + " -> " + DateUtils.getStrDate(nowDateCal, tz) + " (" + tz.getID() + ")");
dmSCM.setLogger(listener.getLogger());
// Connect to Dimensions...
key = dmSCM.login(this, build);
if (key > 0L) {
Logger.debug("Login worked.");
String baseline = null;
String request = null;
if (build instanceof AbstractBuild) {
VariableResolver<String> myResolver = ((AbstractBuild<?, ?>) build).getBuildVariableResolver();
baseline = myResolver.resolve("DM_BASELINE");
request = myResolver.resolve("DM_REQUEST");
} else if (build instanceof WorkflowRun) {
baseline = getParameterFromBuild((WorkflowRun) build, "DM_BASELINE");
request = getParameterFromBuild((WorkflowRun) build, "DM_REQUEST");
}
if (baseline != null) {
baseline = baseline.trim();
baseline = baseline.toUpperCase(Values.ROOT_LOCALE);
}
if (request != null) {
request = request.replaceAll(" ", "");
request = request.toUpperCase(Values.ROOT_LOCALE);
}
Logger.debug("Extra parameters - " + baseline + " " + request);
final List<StringVarStorage> folders = getFolders();
if (baseline != null && baseline.length() == 0) {
baseline = null;
}
if (request != null && request.length() == 0) {
request = null;
}
// Iterate through the project folders and process them in Dimensions.
for (StringVarStorage folderStrg : folders) {
final String folderN = folderStrg.getValue();
final File fileName = new File(folderN);
final FilePath dname = new FilePath(fileName);
Logger.debug("Looking for changes in '" + folderN + "'...");
// Check out the folder.
dmSCM.createChangeSetLogs(key, getProjectName(build, listener), dname, lastBuildCal, nowDateCal,
changelogFile, tz, jobWebUrl, baseline, request);
if (request != null) {
break;
}
}
// Add the changelog file's closing tag.
{
PrintWriter pw = null;
try {
pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(changelogFile, true), "UTF-8"));
pw.println("</changelog>");
pw.flush();
} catch (IOException e) {
throw new IOException(Values.exceptionMessage("Unable to write changelog file: " + changelogFile, e, "no message"), e);
} finally {
if (pw != null) {
pw.close();
}
}
}
}
} catch (Exception e) {
final String message = Values.exceptionMessage("Unable to run changelog callout", e, "no message - try again");
listener.fatalError(message);
Logger.debug(message, e);
throw new IOException(e);
} finally {
dmSCM.logout(key, build);
}
}
/**
* Has the repository had any changes since last build?
* <p>
* {@inheritDoc}
*/
@Override
public SCMRevisionState calcRevisionsFromBuild(final Run<?, ?> build, final FilePath workspace, final Launcher launcher, final TaskListener listener) {
return SCMRevisionState.NONE;
}
/**
* Has the repository had any changes?
* <p>
* {@inheritDoc}
*/
@Override
public PollingResult compareRemoteRevisionWith(final Job<?, ?> project, final Launcher launcher, final FilePath workspace,
final TaskListener listener, final SCMRevisionState baseline) throws IOException, InterruptedException {
// New polling function - to use old polling function for the moment.
final Change change = Change.NONE;
try {
if (pollCMChanges(project, launcher, workspace, listener)) {
return PollingResult.BUILD_NOW;
}
} catch (Exception e) {
/* swallow exception. */
}
return new PollingResult(change);
}
/**
* Okay to clear the area?
* <p>
* {@inheritDoc}
*/
@Override
public boolean processWorkspaceBeforeDeletion(@NonNull final Job<?, ?> project, @NonNull final FilePath workspace, @NonNull final Node node) throws IOException, InterruptedException {
// Not used at the moment, so we have a stub...
return true;
}
/**
* Has the repository had any changes?
* <p>
* {@inheritDoc}
*/
private boolean pollCMChanges(final Job<?, ?> project, final Launcher launcher, final FilePath workspace,
final TaskListener listener) {
boolean bChanged = false;
Logger.debug("Invoking pollChanges - " + this.getClass().getName());
Logger.debug("Checking job - " + project.getName());
long key = -1L;
if (getProject() == null || getProject().length() == 0) {
return false;
}
if (project.getLastBuild() == null) {
Logger.debug("There is no lastBuild, so returning true");
return true;
}
final DimensionsAPI dmSCM = getAPI();
try {
final Calendar lastBuildCal = project.getLastBuild().getTimestamp();
final Calendar nowDateCal = Calendar.getInstance();
final TimeZone tz = (getTimeZone() != null && getTimeZone().length() > 0)
? TimeZone.getTimeZone(getTimeZone()) : TimeZone.getDefault();
if (getTimeZone() != null && getTimeZone().length() > 0) {
Logger.debug("Job timezone setting is " + getTimeZone());
}
Logger.debug("Checking for any updates between " + (lastBuildCal != null
? DateUtils.getStrDate(lastBuildCal, tz) : "0") + " -> " + DateUtils.getStrDate(nowDateCal, tz)
+ " (" + tz.getID() + ")");
dmSCM.setLogger(listener.getLogger());
// Connect to Dimensions...
key = dmSCM.login(this, null);
if (key > 0L) {
List<StringVarStorage> folders = getFolders();
// Iterate through the project folders and process them in Dimensions
for (StringVarStorage folderStrg : folders) {
final String folderN = folderStrg.getValue();
if (bChanged) {
break;
}
final File fileName = new File(folderN);
final FilePath dname = new FilePath(fileName);
if (dmSCM.getPathMatcher() == null) {
dmSCM.setPathMatcher(createPathMatcher());
}
bChanged = dmSCM.hasRepositoryBeenUpdated(key, getProjectName(project.getLastBuild(), listener), dname,
lastBuildCal, nowDateCal, tz);
if (Logger.isDebugEnabled()) {
Logger.debug("Polled folder '" + dname.getRemote() + "' between lastBuild="
+ Values.toString(lastBuildCal) + " and now=" + Values.toString(nowDateCal)
+ " where jobTimeZone=[" + getTimeZone() + "]. "
+ (bChanged ? "Found changes" : "No changes"));
}
}
if (Logger.isDebugEnabled()) {
Logger.debug(bChanged ? "Found changes in at least one of the folders, so returning true"
: "No changes in any of the folders, so returning false");
}
}
} catch (Exception e) {
final String message = Values.exceptionMessage("Unable to run pollChanges callout", e, "no message - try again");
Logger.debug(message, e);
listener.fatalError(message);
bChanged = false;
} finally {
dmSCM.logout(key);
}
return bChanged;
}
/**
* Creates path matcher to ignore changes on certain paths.
*
* @return path matcher
*/
public PathMatcher createPathMatcher() {
final String[] pathToExcludeArr = Values.convertListToArray(getPathsToExclude());
return Values.isNullOrEmpty(pathToExcludeArr) ? new NullPathMatcher()
: new DefaultPathMatcher(pathToExcludeArr, null);
}
/**
* Create a log parser object.