-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathOrganizationFolder.java
1599 lines (1486 loc) · 67.2 KB
/
OrganizationFolder.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
/*
* The MIT License
*
* Copyright 2015 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.branch;
import com.cloudbees.hudson.plugins.folder.AbstractFolderDescriptor;
import com.cloudbees.hudson.plugins.folder.AbstractFolderProperty;
import com.cloudbees.hudson.plugins.folder.ChildNameGenerator;
import com.cloudbees.hudson.plugins.folder.FolderIcon;
import com.cloudbees.hudson.plugins.folder.FolderIconDescriptor;
import com.cloudbees.hudson.plugins.folder.computed.ChildObserver;
import com.cloudbees.hudson.plugins.folder.computed.ComputedFolder;
import com.cloudbees.hudson.plugins.folder.computed.EventOutputStreams;
import com.cloudbees.hudson.plugins.folder.computed.FolderComputation;
import com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger;
import com.cloudbees.hudson.plugins.folder.views.AbstractFolderViewHolder;
import com.thoughtworks.xstream.XStreamException;
import hudson.BulkChange;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.Util;
import hudson.XmlFile;
import hudson.console.ModelHyperlinkNote;
import hudson.model.Action;
import hudson.model.Cause;
import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Items;
import hudson.model.Saveable;
import hudson.model.StreamBuildListener;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.View;
import hudson.model.listeners.SaveableListener;
import hudson.security.ACL;
import hudson.security.Permission;
import hudson.util.DescribableList;
import hudson.util.StreamTaskListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import jenkins.model.TransientActionFactory;
import jenkins.scm.api.SCMEvent;
import jenkins.scm.api.SCMEventListener;
import jenkins.scm.api.SCMHeadEvent;
import jenkins.scm.api.SCMNavigator;
import jenkins.scm.api.SCMNavigatorDescriptor;
import jenkins.scm.api.SCMNavigatorEvent;
import jenkins.scm.api.SCMNavigatorOwner;
import jenkins.scm.api.SCMSource;
import jenkins.scm.api.SCMSourceCriteria;
import jenkins.scm.api.SCMSourceEvent;
import jenkins.scm.api.SCMSourceObserver;
import jenkins.scm.api.SCMSourceOwner;
import jenkins.scm.api.metadata.ObjectMetadataAction;
import net.sf.json.JSONObject;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.jenkins.ui.icon.Icon;
import org.jenkins.ui.icon.IconSet;
import org.jenkins.ui.icon.IconSpec;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.access.AccessDeniedException;
import static hudson.Functions.printStackTrace;
import static jenkins.scm.api.SCMEvent.Type.CREATED;
import static jenkins.scm.api.SCMEvent.Type.UPDATED;
/**
* A folder-like collection of {@link MultiBranchProject}s, one per repository.
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // mistakes in various places
public final class OrganizationFolder extends ComputedFolder<MultiBranchProject<?,?>>
implements SCMNavigatorOwner, IconSpec {
/**
* Our logger.
*/
private static final Logger LOGGER = Logger.getLogger(OrganizationFolder.class.getName());
static final String COMPLETED_PROCESSING_EVENT = "[%tc] Finished processing %s %s event from %s with timestamp %tc, processed in %dms. Matched %d.%n";
/**
* Our navigators.
*/
private final DescribableList<SCMNavigator,SCMNavigatorDescriptor> navigators = new DescribableList<>(this);
/**
* Our project factories.
*/
private final DescribableList<MultiBranchProjectFactory,MultiBranchProjectFactoryDescriptor> projectFactories = new DescribableList<>(this);
/**
* The rules for automatic building of branches.
*
* @since 2.0.12
*/
private DescribableList<BranchBuildStrategy, BranchBuildStrategyDescriptor> buildStrategies = new DescribableList<>(this);
/**
* The branches properties.
*
* @since 2.5.9
*/
private BranchPropertyStrategy strategy;
/**
* The persisted state maintained outside of the config file.
*
* @since 2.0
*/
private transient /*almost final*/ State state = new State(this);
/**
* The navigator digest used to detect if we need to trigger a rescan on save.
*
* @since 2.0
*/
private transient String navDigest;
/**
* The factory digest used to detect if we need to trigger a rescan on save.
*
* @since 2.0
*/
private transient String facDigest;
/**
* The {@link #propertyStrategy} digest used to detect if we need to trigger a rescan on save.
*
* @since 2.5.9
*/
private transient String propsDigest;
/**
* The {@link #buildStrategies} digest used to detect if we need to trigger a rescan on save.
*
* @since 2.0.12
*/
private transient String bbsDigest;
/**
* {@inheritDoc}
*/
public OrganizationFolder(ItemGroup parent, String name) {
super(parent, name);
}
/**
* {@inheritDoc}
*/
@Override
public void onCreatedFromScratch() {
super.onCreatedFromScratch();
if( projectFactories.isEmpty() ) {
for (MultiBranchProjectFactoryDescriptor d : ExtensionList.lookup(MultiBranchProjectFactoryDescriptor.class)) {
MultiBranchProjectFactory f = d.newInstance();
if (f != null) {
projectFactories.add(f);
}
}
}
addTrigger(new PeriodicFolderTrigger("1d"));
try {
addProperty(OrganizationChildTriggersProperty.newDefaultInstance());
addProperty(OrganizationChildOrphanedItemsProperty.newDefaultInstance());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent, name);
navigators.setOwner(this);
projectFactories.setOwner(this);
if (buildStrategies == null) {
buildStrategies = new DescribableList<>(this);
} else {
buildStrategies.setOwner(this);
}
if (!(getFolderViews() instanceof OrganizationFolderViewHolder)) {
resetFolderViews();
}
if (getIcon() == null) {
setIcon(newDefaultFolderIcon());
}
if (getProperties().get(OrganizationChildTriggersProperty.class) == null) {
try {
addProperty(OrganizationChildTriggersProperty.newDefaultInstance());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
if (getProperties().get(OrganizationChildOrphanedItemsProperty.class) == null) {
try {
addProperty(OrganizationChildOrphanedItemsProperty.newDefaultInstance());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
PropertyMigration.applyAll(this);
if (state == null) {
state = new State(this);
}
try {
state.load();
} catch (XStreamException | IOException e) {
LOGGER.log(Level.WARNING, "Could not read persisted state, will be recovered on next index.", e);
state.reset();
}
if (getComputation().getLogFile().isFile()) {
// TODO find a more reliable way to detect if the folder has not been scanned since creation
// Basically we want the first save after a config change to trigger a scan.
// The above condition will cover the very first save, but will not cover the case of the configuration
// being changed *by code not the user*, saved and then Jenkins restarted before the scan occurs.
// Should not be a big deal as periodic scan will pick it up eventually and user can always manually force
// the issue by triggering a manual scan
try {
navDigest = Util.getDigestOf(Items.XSTREAM2.toXML(navigators));
} catch (XStreamException e) {
navDigest = null;
}
try {
facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(projectFactories));
} catch (XStreamException e) {
facDigest = null;
}
try {
propsDigest = Util.getDigestOf(Items.XSTREAM2.toXML(strategy));
} catch (XStreamException e) {
propsDigest = null;
}
try {
bbsDigest = Util.getDigestOf(Items.XSTREAM2.toXML(buildStrategies));
} catch (XStreamException e) {
bbsDigest = null;
}
}
}
@Override
public MultiBranchProject<?, ?> getItem(String name) throws AccessDeniedException {
if (name == null) {
return null;
}
MultiBranchProject<?, ?> item = super.getItem(name);
if (item != null) {
return item;
}
if (name.indexOf('%') != -1) {
String decoded = NameEncoder.decode(name);
item = super.getItem(decoded);
if (item != null) {
return item;
}
// fall through for double decoded call paths // TODO is this necessary
}
return super.getItem(NameEncoder.encode(name));
}
/**
* Returns the child job with the specified project name or {@code null} if no such child job exists.
*
* @param projectName the name of the project.
* @return the child job or {@code null} if no such job exists or if the requesting user does ave permission to
* view it.
* @since 2.0.0
*/
@edu.umd.cs.findbugs.annotations.CheckForNull
public MultiBranchProject<?,?> getItemByProjectName(@NonNull String projectName) {
return super.getItem(NameEncoder.encode(projectName));
}
/**
* @deprecated Directly check {@link List#size} of {@link #getSCMNavigators} if desired.
*/
@Deprecated
public boolean isSingleOrigin() {
return navigators.size() == 1;
}
public DescribableList<SCMNavigator,SCMNavigatorDescriptor> getNavigators() {
return navigators;
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public List<SCMNavigator> getSCMNavigators() {
return navigators;
}
public DescribableList<MultiBranchProjectFactory,MultiBranchProjectFactoryDescriptor> getProjectFactories() {
return projectFactories;
}
/**
* Gets the strategy.
*
* @return the strategy.
* @since 2.5.9
*/
public BranchPropertyStrategy getStrategy() {
return strategy != null ? strategy : new DefaultBranchPropertyStrategy(new BranchProperty[0]);
}
/**
* Sets the branch property strategy.
*
* @param strategy chosen.
* @since 2.5.9
*/
public void setStrategy(BranchPropertyStrategy strategy) {
this.strategy = strategy;
}
/**
* The {@link BranchBuildStrategy}s to apply.
*
* @return The {@link BranchBuildStrategy}s to apply.
* @since 2.0.12
*/
public DescribableList<BranchBuildStrategy, BranchBuildStrategyDescriptor> getBuildStrategies() {
return buildStrategies;
}
/**
* {@inheritDoc}
*/
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, Descriptor.FormException {
super.submit(req, rsp);
JSONObject json = req.getSubmittedForm();
navigators.rebuildHetero(req, json, ExtensionList.lookup(SCMNavigatorDescriptor.class), "navigators");
projectFactories.rebuildHetero(req, json, ExtensionList.lookup(MultiBranchProjectFactoryDescriptor.class), "projectFactories");
buildStrategies.rebuildHetero(req, json, ExtensionList.lookup(BranchBuildStrategyDescriptor.class), "buildStrategies");
strategy = req.bindJSON(BranchPropertyStrategy.class, json.getJSONObject("strategy"));
for (SCMNavigator n : navigators) {
n.afterSave(this);
}
String navDigest;
try {
navDigest = Util.getDigestOf(Items.XSTREAM2.toXML(navigators));
} catch (XStreamException e) {
navDigest = null;
}
String facDigest;
try {
facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(projectFactories));
} catch (XStreamException e) {
facDigest = null;
}
String propsDigest;
try {
propsDigest = Util.getDigestOf(Items.XSTREAM2.toXML(strategy));
} catch (XStreamException e) {
propsDigest = null;
}
String bbsDigest;
try {
bbsDigest = Util.getDigestOf(Items.XSTREAM2.toXML(buildStrategies));
} catch (XStreamException e) {
bbsDigest = null;
}
recalculateAfterSubmitted(!StringUtils.equals(navDigest, this.navDigest));
recalculateAfterSubmitted(!StringUtils.equals(facDigest, this.facDigest));
recalculateAfterSubmitted(!StringUtils.equals(propsDigest, this.propsDigest));
recalculateAfterSubmitted(!StringUtils.equals(bbsDigest, this.bbsDigest));
this.navDigest = navDigest;
this.facDigest = facDigest;
this.propsDigest = propsDigest;
this.bbsDigest = bbsDigest;
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
protected FolderComputation<MultiBranchProject<?, ?>> createComputation(
@CheckForNull FolderComputation<MultiBranchProject<?, ?>> previous) {
return new OrganizationScan(OrganizationFolder.this, previous);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isHasEvents() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isBuildable() {
return super.isBuildable() && !navigators.isEmpty() && !projectFactories.isEmpty();
}
/**
* {@inheritDoc}
*/
@Override
protected void computeChildren(final ChildObserver<MultiBranchProject<?,?>> observer, final TaskListener listener) throws IOException, InterruptedException {
// capture the current digests to prevent unnecessary rescan if re-saving after scan
try {
navDigest = Util.getDigestOf(Items.XSTREAM2.toXML(navigators));
} catch (XStreamException e) {
navDigest = null;
}
try {
facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(projectFactories));
} catch (XStreamException e) {
facDigest = null;
}
try {
bbsDigest = Util.getDigestOf(Items.XSTREAM2.toXML(buildStrategies));
} catch (XStreamException e) {
bbsDigest = null;
}
long start = System.currentTimeMillis();
listener.getLogger().format("[%tc] Starting organization scan...%n", start);
try {
listener.getLogger().format("[%tc] Updating actions...%n", System.currentTimeMillis());
Map<SCMNavigator, List<Action>> navigatorActions = new HashMap<>();
for (SCMNavigator navigator : navigators) {
List<Action> actions;
try {
actions = navigator.fetchActions(this, null, listener);
} catch (IOException e) {
printStackTrace(e, listener.error("[%tc] Could not refresh actions for navigator %s",
System.currentTimeMillis(), navigator));
// preserve previous actions if we have some transient error fetching now (e.g. API rate limit)
actions = Util.fixNull(state.getActions().get(navigator));
}
navigatorActions.put(navigator, actions);
}
// update any persistent actions for the SCMNavigator
if (!navigatorActions.equals(state.getActions())) {
boolean saveProject = false;
for (List<Action> actions : navigatorActions.values()) {
for (Action a : actions) {
// undo any hacks that attached the contributed actions without attribution
saveProject = removeActions(a.getClass()) || saveProject;
}
}
BulkChange bc = new BulkChange(state);
try {
state.setActions(navigatorActions);
try {
bc.commit();
} catch (IOException | RuntimeException e) {
listener.error("[%tc] Could not persist folder level actions",
System.currentTimeMillis());
throw e;
}
if (saveProject) {
try {
save();
} catch (IOException | RuntimeException e) {
listener.error(
"[%tc] Could not persist folder level configuration changes",
System.currentTimeMillis());
throw e;
}
}
} finally {
bc.abort();
}
}
for (SCMNavigator navigator : navigators) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
listener.getLogger().format("[%tc] Consulting %s%n", System.currentTimeMillis(),
navigator.getDescriptor().getDisplayName());
try {
navigator.visitSources(new SCMSourceObserverImpl(listener, observer, navigator, null));
} catch (IOException | InterruptedException | RuntimeException e) {
listener.error("[%tc] Could not fetch sources from navigator %s",
System.currentTimeMillis(), navigator);
throw e;
}
}
} finally {
long end = System.currentTimeMillis();
listener.getLogger().format("[%tc] Finished organization scan. Scan took %s%n", end,
Util.getTimeSpanString(end - start));
}
}
/**
* {@inheritDoc}
*/
@Override
protected AbstractFolderViewHolder newFolderViewHolder() {
return new OrganizationFolderViewHolder(this);
}
/**
* {@inheritDoc}
*/
@Override
protected FolderIcon newDefaultFolderIcon() {
return new MetadataActionFolderIcon();
}
/**
* {@inheritDoc}
*/
@Override
public String getIconClassName() {
String result;
if (navigators.size() == 1) {
result = navigators.get(0).getDescriptor().getIconClassName();
} else {
result = null;
for (int i = 0; i < navigators.size(); i++) {
String iconClassName = navigators.get(i).getDescriptor().getIconClassName();
if (i == 0) {
result = iconClassName;
} else if (!StringUtils.equals(result, iconClassName)) {
result = null;
break;
}
}
}
return result != null ? result : getDescriptor().getIconClassName();
}
/**
* Get the term used in the UI to represent the source for this kind of
* {@link Item}. Must start with a capital letter.
* @return term used in the UI to represent the souce
*/
public String getSourcePronoun() {
Set<String> result = new TreeSet<>();
for (SCMNavigator navigator: navigators) {
String pronoun = Util.fixEmptyAndTrim(navigator.getPronoun());
if (pronoun != null) {
result.add(pronoun);
}
}
return result.isEmpty() ? this.getPronoun() : StringUtils.join(result, " / ");
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public List<SCMSource> getSCMSources() {
Set<SCMSource> result = new HashSet<>();
for (MultiBranchProject<?,?> child : getItems(MultiBranchProject::isBuildable)) {
result.addAll(child.getSCMSources());
}
return new ArrayList<>(result);
}
/**
* {@inheritDoc}
*/
@Override
public SCMSource getSCMSource(String sourceId) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void onSCMSourceUpdated(@NonNull SCMSource source) {
// TODO possibly we should recheck whether this project remains valid
}
/**
* {@inheritDoc}
*/
@Override
public SCMSourceCriteria getSCMSourceCriteria(@NonNull SCMSource source) {
return null;
}
/**
* Will create an specialized view when there are no repositories or branches found, which contain a Jenkinsfile
* or other MARKER file.
*/
@Override
public View getPrimaryView() {
if (!hasVisibleItems()) {
return getWelcomeView();
}
return super.getPrimaryView();
}
/**
* Creates a place-holder view when there's no active repositories indexed.
*
* @return a place-holder view for when there's no active repositories indexed.
*/
protected View getWelcomeView() {
return new OrganizationFolderEmptyView(this);
}
/**
* {@inheritDoc}
*/
@Override
public View getView(String name) {
if (name.equals("Welcome")) {
return getWelcomeView();
} else {
return super.getView(name);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getDescription() {
String description = super.getDescription();
if (StringUtils.isNotBlank(description)) {
return description;
}
ObjectMetadataAction action = getAction(ObjectMetadataAction.class);
if (action != null) {
return action.getObjectDescription();
}
return super.getDescription();
}
/**
* {@inheritDoc}
*/
@Override
public String getDisplayName() {
String displayName = getDisplayNameOrNull();
if (displayName == null) {
ObjectMetadataAction action = getAction(ObjectMetadataAction.class);
if (action != null && StringUtils.isNotBlank(action.getObjectDisplayName())) {
return action.getObjectDisplayName();
}
}
return super.getDisplayName();
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public ACL getACL() {
final ACL acl = super.getACL();
if (getParent() instanceof ComputedFolder<?>) {
return new ACL() {
@Override
public boolean hasPermission2(@NonNull Authentication a, @NonNull Permission permission) {
if (ACL.SYSTEM2.equals(a)) {
return true;
} else if (SUPPRESSED_PERMISSIONS.contains(permission)) {
return false;
} else {
return acl.hasPermission2(a, permission);
}
}
};
} else {
return acl;
}
}
private static final Set<Permission> SUPPRESSED_PERMISSIONS =
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
Item.CONFIGURE, Item.DELETE, View.CONFIGURE, View.CREATE, View.DELETE)));
/**
* Our descriptor
*/
@Extension
@Symbol("organizationFolder")
public static class DescriptorImpl extends AbstractFolderDescriptor {
/**
* {@inheritDoc}
*/
@NonNull
@Override
public String getDisplayName() {
return Messages.OrganizationFolder_DisplayName();
}
/**
* {@inheritDoc}
*/
@Override
public TopLevelItem newInstance(ItemGroup parent, String name) {
return new OrganizationFolder(parent, name);
}
/**
* Used to categorize {@link OrganizationFolder} instances.
*
* @return A string with the category identifier. {@code TopLevelItemDescriptor#getCategoryId()}
*/
@Override
@NonNull
public String getCategoryId() {
return "nested-projects";
}
/**
* Gets all the {@link BranchPropertyStrategyDescriptor} instances applicable to the specified project and source.
*
* @return all the {@link BranchPropertyStrategyDescriptor} instances applicable to the specified project and
* source.
*/
public List<BranchPropertyStrategyDescriptor> propertyStrategyDescriptors() {
return BranchPropertyStrategyDescriptor.all();
}
/**
* A description of this {@link OrganizationFolder}.
*
* @return A string with the description. {@code TopLevelItemDescriptor#getDescription()}.
*/
@Override
@NonNull
public String getDescription() {
return Messages.OrganizationFolder_Description();
}
@Override
public String getIconFilePathPattern() {
return "plugin/branch-api/images/organization-folder.svg";
}
/**
* {@inheritDoc}
*/
@Override
public String getIconClassName() {
return "symbol-business-outline plugin-ionicons-api";
}
/**
* {@inheritDoc}
*/
@Override
public List<FolderIconDescriptor> getIconDescriptors() {
return Collections.singletonList(
Jenkins.get().getDescriptorByType(MetadataActionFolderIcon.DescriptorImpl.class)
);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isIconConfigurable() {
return true;
}
@Override
@NonNull
public final ChildNameGenerator<OrganizationFolder, ? extends TopLevelItem> childNameGenerator() {
return ChildNameGeneratorImpl.INSTANCE;
}
static {
IconSet.icons.addIcon(
new Icon("icon-branch-api-organization-folder icon-sm",
"plugin/branch-api/images/organization-folder.svg",
Icon.ICON_SMALL_STYLE));
IconSet.icons.addIcon(
new Icon("icon-branch-api-organization-folder icon-md",
"plugin/branch-api/images/organization-folder.svg",
Icon.ICON_MEDIUM_STYLE));
IconSet.icons.addIcon(
new Icon("icon-branch-api-organization-folder icon-lg",
"plugin/branch-api/images/organization-folder.svg",
Icon.ICON_LARGE_STYLE));
IconSet.icons.addIcon(
new Icon("icon-branch-api-organization-folder icon-xlg",
"plugin/branch-api/images/organization-folder.svg",
Icon.ICON_XLARGE_STYLE));
}
}
private static class ChildNameGeneratorImpl extends ChildNameGenerator<OrganizationFolder, MultiBranchProject<?,?>> {
private static final ChildNameGeneratorImpl INSTANCE = new ChildNameGeneratorImpl();
@Override
@CheckForNull
public String itemNameFromItem(@NonNull OrganizationFolder parent, @NonNull MultiBranchProject<?, ?> item) {
ProjectNameProperty property = item.getProperties().get(ProjectNameProperty.class);
if (property != null) {
return NameEncoder.encode(property.getName());
}
String idealName = idealNameFromItem(parent, item);
if (idealName != null) {
return NameEncoder.encode(idealName);
}
return null;
}
@Override
@CheckForNull
public String dirNameFromItem(@NonNull OrganizationFolder parent, @NonNull MultiBranchProject<?, ?> item) {
ProjectNameProperty property = item.getProperties().get(ProjectNameProperty.class);
if (property != null) {
return NameMangler.apply(property.getName());
}
String idealName = idealNameFromItem(parent, item);
if (idealName != null) {
return NameMangler.apply(idealName);
}
return null;
}
@Override
@NonNull
public String itemNameFromLegacy(@NonNull OrganizationFolder parent, @NonNull String legacyDirName) {
return NameEncoder.decode(legacyDirName);
}
@Override
@NonNull
public String dirNameFromLegacy(@NonNull OrganizationFolder parent, @NonNull String legacyDirName) {
return NameMangler.apply(NameEncoder.decode(legacyDirName));
}
@Override
public void recordLegacyName(OrganizationFolder parent, MultiBranchProject<?, ?> item, String legacyDirName)
throws IOException {
item.addProperty(new ProjectNameProperty(legacyDirName));
}
}
/**
* Our scan.
*/
public static class OrganizationScan extends FolderComputation<MultiBranchProject<?, ?>> {
public OrganizationScan(OrganizationFolder folder, FolderComputation<MultiBranchProject<?, ?>> previous) {
super(folder, previous);
}
/**
* {@inheritDoc}
*/
@Override
public String getDisplayName() {
return Messages.OrganizationFolder_OrganizationScan_displayName(((OrganizationFolder)getParent()).getSourcePronoun());
}
@Override
public void run() {
long start = System.currentTimeMillis();
try {
super.run();
} finally {
long end = System.currentTimeMillis();
LOGGER.log(Level.INFO, "{0} #{1,time,yyyyMMdd.HHmmss} organization scan action completed: {2} in {3}",
new Object[]{
getParent().getFullName(), start, getResult(), Util.getTimeSpanString(end - start)
}
);
}
}
}
/**
* Listens for events from the SCM event system.
*
* @since 2.0
*/
@Extension
public static class SCMEventListenerImpl extends SCMEventListener {
private final EventOutputStreams globalEvents = createGlobalEvents();
private EventOutputStreams createGlobalEvents() {
File logsDir = new File(Jenkins.get().getRootDir(), "logs");
if (!logsDir.isDirectory() && !logsDir.mkdirs()) {
LOGGER.log(Level.WARNING, "Could not create logs directory: {0}", logsDir);
}
final File eventsFile = new File(logsDir, OrganizationFolder.class.getName() + ".log");
if (!eventsFile.isFile()) {
File oldFile = new File(logsDir.getParent(), eventsFile.getName());
if (oldFile.isFile()) {
if (!oldFile.renameTo(eventsFile)) {
FileUtils.deleteQuietly(oldFile);
}
}
}
return new EventOutputStreams(new EventOutputStreams.OutputFile() {
@NonNull
@Override
public File get() {
return eventsFile;
}
},
250, TimeUnit.MILLISECONDS,
1024,
true,
32 * 1024,
5
);
}
/**
* The {@link TaskListener} for events that we cannot assign to an organization folder.
* @return The {@link TaskListener} for events that we cannot assign to an organization folder.
*/
@Restricted(NoExternalUse.class)
public StreamTaskListener globalEventsListener() {
return new StreamBuildListener(globalEvents.get(), StandardCharsets.UTF_8);
}
/**
* {@inheritDoc}
*/
@Override
public void onSCMHeadEvent(SCMHeadEvent<?> event) {
try (StreamTaskListener global = globalEventsListener()) {
String globalEventDescription = StringUtils.defaultIfBlank(event.description(), event.getClass().getName());
long started = System.currentTimeMillis();
global.getLogger().format("[%tc] Received %s %s event from %s with timestamp %tc%n",
started,
globalEventDescription,
event.getType().name(),
event.getOrigin(), event.getTimestamp());
int matchCount = 0;
if (CREATED == event.getType() || UPDATED == event.getType()) {
try {
for (OrganizationFolder p : Jenkins.get().getAllItems(OrganizationFolder.class)) {
if (!p.isBuildable()) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER,
"{0} {1} {2,date} {2,time}: Ignoring {3} because it is disabled",
new Object[]{
globalEventDescription,
event.getType().name(), event.getTimestamp(), p.getFullName()
}