/
ConfigurationAsCode.java
831 lines (728 loc) · 31.8 KB
/
ConfigurationAsCode.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
package io.jenkins.plugins.casc;
import com.google.common.annotations.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Functions;
import hudson.PluginManager;
import hudson.Util;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.ManagementLink;
import hudson.remoting.Which;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.util.FormValidation;
import io.jenkins.plugins.casc.impl.DefaultConfiguratorRegistry;
import io.jenkins.plugins.casc.model.CNode;
import io.jenkins.plugins.casc.model.Mapping;
import io.jenkins.plugins.casc.model.Scalar;
import io.jenkins.plugins.casc.model.Scalar.Format;
import io.jenkins.plugins.casc.model.Sequence;
import io.jenkins.plugins.casc.model.Source;
import io.jenkins.plugins.casc.snakeyaml.DumperOptions;
import io.jenkins.plugins.casc.snakeyaml.emitter.Emitter;
import io.jenkins.plugins.casc.snakeyaml.error.YAMLException;
import io.jenkins.plugins.casc.snakeyaml.nodes.MappingNode;
import io.jenkins.plugins.casc.snakeyaml.nodes.Node;
import io.jenkins.plugins.casc.snakeyaml.nodes.NodeTuple;
import io.jenkins.plugins.casc.snakeyaml.nodes.ScalarNode;
import io.jenkins.plugins.casc.snakeyaml.nodes.SequenceNode;
import io.jenkins.plugins.casc.snakeyaml.nodes.Tag;
import io.jenkins.plugins.casc.snakeyaml.resolver.Resolver;
import io.jenkins.plugins.casc.snakeyaml.serializer.Serializer;
import io.jenkins.plugins.casc.yaml.YamlSource;
import io.jenkins.plugins.casc.yaml.YamlUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import jenkins.model.GlobalConfiguration;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.lang.Klass;
import org.kohsuke.stapler.verb.POST;
import static io.jenkins.plugins.casc.SchemaGeneration.writeJSONSchema;
import static io.jenkins.plugins.casc.snakeyaml.DumperOptions.FlowStyle.BLOCK;
import static io.jenkins.plugins.casc.snakeyaml.DumperOptions.ScalarStyle.DOUBLE_QUOTED;
import static io.jenkins.plugins.casc.snakeyaml.DumperOptions.ScalarStyle.LITERAL;
import static io.jenkins.plugins.casc.snakeyaml.DumperOptions.ScalarStyle.PLAIN;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
/**
* {@linkplain #configure() Main entry point of the logic}.
*
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@Extension
public class ConfigurationAsCode extends ManagementLink {
public static final String CASC_JENKINS_CONFIG_PROPERTY = "casc.jenkins.config";
public static final String CASC_JENKINS_CONFIG_ENV = "CASC_JENKINS_CONFIG";
public static final String DEFAULT_JENKINS_YAML_PATH = "jenkins.yaml";
public static final String YAML_FILES_PATTERN = "glob:**.{yml,yaml,YAML,YML}";
private static final Logger LOGGER = Logger.getLogger(ConfigurationAsCode.class.getName());
@Inject
private DefaultConfiguratorRegistry registry;
private long lastTimeLoaded;
private List<String> sources = Collections.emptyList();
@CheckForNull
@Override
public String getIconFileName() {
return "/plugin/configuration-as-code/img/logo-head.svg";
}
@CheckForNull
@Override
public String getDisplayName() {
return "Configuration as Code";
}
@CheckForNull
@Override
public String getUrlName() {
return "configuration-as-code";
}
@Override
public String getDescription() {
return "Reload your configuration or update configuration source";
}
public Date getLastTimeLoaded() {
return new Date(lastTimeLoaded);
}
public List<String> getSources() {
return sources;
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReload(StaplerRequest request, StaplerResponse response) throws Exception {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
configure();
response.sendRedirect("");
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReplace(StaplerRequest request, StaplerResponse response) throws Exception {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String newSource = request.getParameter("_.newSource");
String normalizedSource = Util.fixEmptyAndTrim(newSource);
File file = new File(Util.fixNull(normalizedSource));
if (file.exists() || ConfigurationAsCode.isSupportedURI(normalizedSource)) {
List<String> candidatePaths = Collections.singletonList(normalizedSource);
List<YamlSource> candidates = getConfigFromSources(candidatePaths);
if (canApplyFrom(candidates)) {
sources = candidatePaths;
configureWith(getConfigFromSources(getSources()));
CasCGlobalConfig config = GlobalConfiguration.all().get(CasCGlobalConfig.class);
if (config != null) {
config.setConfigurationPath(normalizedSource);
config.save();
}
LOGGER.log(Level.FINE, "Replace configuration with: " + normalizedSource);
} else {
LOGGER.log(Level.WARNING, "Provided sources could not be applied");
// todo: show message in UI
}
} else {
LOGGER.log(Level.FINE, "No such source exists, applying default");
// May be do nothing instead?
configure();
}
response.sendRedirect("");
}
private boolean canApplyFrom(List<YamlSource> yamlSources) {
try {
checkWith(yamlSources);
return true;
} catch (ConfiguratorException e) {
// ignore and return false
}
return false;
}
@POST
@Restricted(NoExternalUse.class)
public FormValidation doCheckNewSource(@QueryParameter String newSource) {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
String normalizedSource = Util.fixEmptyAndTrim(newSource);
File file = new File(Util.fixNull(normalizedSource));
if (normalizedSource == null) {
return FormValidation.ok(); // empty, do nothing
}
if (!file.exists() && !ConfigurationAsCode.isSupportedURI(normalizedSource)) {
return FormValidation.error("Configuration cannot be applied. File or URL cannot be parsed or do not exist.");
}
List<YamlSource> yamlSources = Collections.emptyList();
try {
List<String> sources = Collections.singletonList(normalizedSource);
yamlSources = getConfigFromSources(sources);
final Map<Source, String> issues = checkWith(yamlSources);
final JSONArray errors = collectProblems(issues, "error");
if (!errors.isEmpty()) {
return FormValidation.error(errors.toString());
}
final JSONArray warnings = collectProblems(issues, "warning");
if (!warnings.isEmpty()) {
return FormValidation.warning(warnings.toString());
}
return FormValidation.okWithMarkup("The configuration can be applied");
} catch (ConfiguratorException | IllegalArgumentException e) {
return FormValidation.error(e, e.getCause() == null ? e.getMessage() : e.getCause().getMessage());
} finally {
closeSources(yamlSources);
}
}
private JSONArray collectProblems(Map<Source, String> issues, String severity) {
final JSONArray problems = new JSONArray();
issues.entrySet().stream().map(e -> new JSONObject().accumulate("line", e.getKey().line).accumulate(severity, e.getValue()))
.forEach(problems::add);
return problems;
}
private void appendSources(List<YamlSource> sources, String source) throws ConfiguratorException {
if (isSupportedURI(source)) {
sources.add(YamlSource.of(source));
} else {
sources.addAll(configs(source).stream()
.map(YamlSource::of)
.collect(toList()));
}
}
private List<YamlSource> getConfigFromSources(List<String> newSources) throws ConfiguratorException {
List<YamlSource> sources = new ArrayList<>();
for (String p : newSources) {
appendSources(sources, p);
}
return sources;
}
/**
* Defaults to use a file in the current working directory with the name 'jenkins.yaml'
*
* Add the environment variable CASC_JENKINS_CONFIG to override the default. Accepts single file or a directory.
* If a directory is detected, we scan for all .yml and .yaml files
*
* @throws Exception when the file provided cannot be found or parsed
*/
@Restricted(NoExternalUse.class)
@Initializer(after = InitMilestone.EXTENSIONS_AUGMENTED, before = InitMilestone.JOB_LOADED)
public static void init() throws Exception {
detectVaultPluginMissing();
get().configure();
}
/**
* Main entry point to start configuration process.
* @throws ConfiguratorException Configuration error
*/
public void configure() throws ConfiguratorException {
configureWith(getStandardConfigSources());
}
private List<YamlSource> getStandardConfigSources() throws ConfiguratorException {
List<YamlSource> configs = new ArrayList<>();
List<String> standardConfig = getStandardConfig();
for (String p : standardConfig) {
appendSources(configs, p);
}
sources = Collections.unmodifiableList(standardConfig);
return configs;
}
private List<String> getStandardConfig() {
List<String> configParameters = getBundledCasCURIs();
CasCGlobalConfig casc = GlobalConfiguration.all().get(CasCGlobalConfig.class);
String cascPath = casc != null ? casc.getConfigurationPath() : null;
String configParameter = System.getProperty(
CASC_JENKINS_CONFIG_PROPERTY,
System.getenv(CASC_JENKINS_CONFIG_ENV)
);
// We prefer to rely on environment variable over global config
if (StringUtils.isNotBlank(cascPath) && StringUtils.isBlank(configParameter)) {
configParameter = cascPath;
}
if (configParameter == null) {
String fullPath = Jenkins.getInstance().getRootDir() + File.separator + DEFAULT_JENKINS_YAML_PATH;
if (Files.exists(Paths.get(fullPath))) {
configParameter = fullPath;
}
}
if (configParameter != null) {
// Add external config parameter
configParameters.add(configParameter);
}
if (configParameters.isEmpty()) {
LOGGER.log(Level.FINE, "No configuration set nor default config file");
}
return configParameters;
}
@Restricted(NoExternalUse.class)
public List<String> getBundledCasCURIs() {
final String cascFile = "/WEB-INF/" + DEFAULT_JENKINS_YAML_PATH;
final String cascDirectory = "/WEB-INF/" + DEFAULT_JENKINS_YAML_PATH + ".d/";
List<String> res = new ArrayList<>();
final ServletContext servletContext = Jenkins.getInstance().servletContext;
try {
URL bundled = servletContext.getResource(cascFile);
if (bundled != null) {
res.add(bundled.toString());
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load " + cascFile, e);
}
PathMatcher matcher = FileSystems.getDefault().getPathMatcher(YAML_FILES_PATTERN);
Set<String> resources = servletContext.getResourcePaths(cascDirectory);
if (resources!=null) {
// sort to execute them in a deterministic order
for (String cascItem : new TreeSet<>(resources)) {
try {
URL bundled = servletContext.getResource(cascItem);
if (bundled != null && matcher.matches(new File(bundled.getPath()).toPath())) {
res.add(bundled.toString());
} //TODO: else do some handling?
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to execute " + res, e);
}
}
}
return res;
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doCheck(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
final Map<Source, String> issues = checkWith(YamlSource.of(req));
res.setContentType("application/json");
final JSONArray warnings = new JSONArray();
issues.entrySet().stream().map(e -> new JSONObject().accumulate("line", e.getKey().line).accumulate("warning", e.getValue()))
.forEach(warnings::add);
warnings.write(res.getWriter());
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doApply(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
configureWith(YamlSource.of(req));
}
/**
* Export live jenkins instance configuration as Yaml
* @throws Exception
*/
@RequirePOST
@Restricted(NoExternalUse.class)
public void doExport(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
res.setContentType("application/x-yaml; charset=utf-8");
res.addHeader("Content-Disposition", "attachment; filename=jenkins.yaml");
export(res.getOutputStream());
}
/**
* Export JSONSchema to URL
* @throws Exception
*/
@Restricted(NoExternalUse.class)
public void doSchema(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
res.setContentType("application/json; charset=utf-8");
res.getWriter().print(writeJSONSchema());
}
@RequirePOST
@Restricted(NoExternalUse.class)
public void doViewExport(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
export(out);
req.setAttribute("export", out.toString(StandardCharsets.UTF_8.name()));
req.getView(this, "viewExport.jelly").forward(req, res);
}
@Restricted(NoExternalUse.class)
public void doReference(StaplerRequest req, StaplerResponse res) throws Exception {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
req.getView(this, "reference.jelly").forward(req, res);
}
@Restricted(NoExternalUse.class)
public void export(OutputStream out) throws Exception {
final List<NodeTuple> tuples = new ArrayList<>();
final ConfigurationContext context = new ConfigurationContext(registry);
for (RootElementConfigurator root : RootElementConfigurator.all()) {
final CNode config = root.describe(root.getTargetComponent(context), context);
final Node valueNode = toYaml(config);
if (valueNode == null) continue;
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, root.getName(), null, null, PLAIN),
valueNode));
}
MappingNode root = new MappingNode(Tag.MAP, tuples, BLOCK);
try (Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
serializeYamlNode(root, writer);
} catch (IOException e) {
throw new YAMLException(e);
}
}
@VisibleForTesting
@Restricted(NoExternalUse.class)
public static void serializeYamlNode(Node root, Writer writer) throws IOException {
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(BLOCK);
options.setDefaultScalarStyle(PLAIN);
options.setSplitLines(true);
options.setPrettyFlow(true);
Serializer serializer = new Serializer(new Emitter(writer, options), new Resolver(),
options, null);
serializer.open();
serializer.serialize(root);
serializer.close();
}
@CheckForNull
@VisibleForTesting
@Restricted(NoExternalUse.class)
public Node toYaml(CNode config) throws ConfiguratorException {
if (config == null) return null;
switch (config.getType()) {
case MAPPING:
final Mapping mapping = config.asMapping();
final List<NodeTuple> tuples = new ArrayList<>();
final List<Map.Entry<String, CNode>> entries = new ArrayList<>(mapping.entrySet());
entries.sort(Comparator.comparing(Map.Entry::getKey));
for (Map.Entry<String, CNode> entry : entries) {
final Node valueNode = toYaml(entry.getValue());
if (valueNode == null) continue;
tuples.add(new NodeTuple(
new ScalarNode(Tag.STR, entry.getKey(), null, null, PLAIN),
valueNode));
}
if (tuples.isEmpty()) return null;
return new MappingNode(Tag.MAP, tuples, BLOCK);
case SEQUENCE:
final Sequence sequence = config.asSequence();
List<Node> nodes = new ArrayList<>();
for (CNode cNode : sequence) {
final Node valueNode = toYaml(cNode);
if (valueNode == null) continue;
nodes.add(valueNode);
}
if (nodes.isEmpty()) return null;
return new SequenceNode(Tag.SEQ, nodes, BLOCK);
case SCALAR:
default:
final Scalar scalar = config.asScalar();
final String value = scalar.getValue();
if (value == null || value.length() == 0) return null;
final DumperOptions.ScalarStyle style;
if (scalar.getFormat().equals(Format.MULTILINESTRING) && !scalar.isRaw()) {
style = LITERAL;
} else if (scalar.isRaw()) {
style = PLAIN;
} else {
style = DOUBLE_QUOTED;
}
return new ScalarNode(getTag(scalar.getFormat()), value, null, null, style);
}
}
private Tag getTag(Scalar.Format format) {
switch (format) {
case NUMBER:
return Tag.INT;
case FLOATING:
return Tag.FLOAT;
case BOOLEAN:
return Tag.BOOL;
case STRING:
case MULTILINESTRING:
default:
return Tag.STR;
}
}
public void configure(String ... configParameters) throws ConfiguratorException {
configure(Arrays.asList(configParameters));
}
public void configure(Collection<String> configParameters) throws ConfiguratorException {
List<YamlSource> configs = new ArrayList<>();
for (String p : configParameters) {
appendSources(configs, p);
}
sources = Collections.unmodifiableList(configParameters.stream().collect(toList()));
configureWith(configs);
lastTimeLoaded = System.currentTimeMillis();
}
public static boolean isSupportedURI(String configurationParameter) {
if(configurationParameter == null) {
return false;
}
final List<String> supportedProtocols = Arrays.asList("https","http","file");
URI uri;
try {
uri = new URI(configurationParameter);
} catch (URISyntaxException ex) {
return false;
}
if(uri.getScheme() == null) {
return false;
}
return supportedProtocols.contains(uri.getScheme());
}
@Restricted(NoExternalUse.class)
public void configureWith(YamlSource source) throws ConfiguratorException {
final List<YamlSource> sources = getStandardConfigSources();
sources.add(source);
configureWith(sources);
}
private void configureWith(List<YamlSource> sources) throws ConfiguratorException {
lastTimeLoaded = System.currentTimeMillis();
configureWith( YamlUtils.loadFrom(sources) );
closeSources(sources);
}
@Restricted(NoExternalUse.class)
public Map<Source, String> checkWith(YamlSource source) throws ConfiguratorException {
final List<YamlSource> sources = getStandardConfigSources();
sources.add(source);
return checkWith(sources);
}
private Map<Source, String> checkWith(List<YamlSource> sources) throws ConfiguratorException {
if (sources.isEmpty()) return Collections.emptyMap();
return checkWith( YamlUtils.loadFrom(sources) );
}
private void closeSources(List<YamlSource> sources) {
for (YamlSource source : sources) {
try {
source.close();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to close YAML Source", e);
}
}
}
/**
* Recursive search for all {@link #YAML_FILES_PATTERN} in provided base path
*
* @param path base path to start (can be file or directory)
* @return list of all paths matching pattern. Only base file itself if it is a file matching pattern
*/
@Restricted(NoExternalUse.class)
public List<Path> configs(String path) throws ConfiguratorException {
final Path root = Paths.get(path);
if (!Files.exists(root)) {
throw new ConfiguratorException("Invalid configuration: '"+path+"' isn't a valid path.");
}
if (Files.isRegularFile(root) && Files.isReadable(root)) {
return Collections.singletonList(root);
}
final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(YAML_FILES_PATTERN);
try (Stream<Path> stream = Files.find(Paths.get(path), Integer.MAX_VALUE,
(next, attrs) -> !attrs.isDirectory() && !isHidden(next) && matcher.matches(next))) {
return stream.sorted().collect(toList());
} catch (IOException e) {
throw new IllegalStateException("failed config scan for " + path, e);
}
}
private static boolean isHidden(Path path) {
return IntStream.range(0, path.getNameCount())
.mapToObj(path::getName)
.anyMatch(subPath -> subPath.toString().startsWith("."));
}
@FunctionalInterface
private interface ConfiguratorOperation {
Object apply(RootElementConfigurator configurator, CNode node) throws ConfiguratorException;
}
/**
* Configuration with help of {@link RootElementConfigurator}s.
* Corresponding configurator is searched by entry key, passing entry value as object with all required properties.
*
* @param entries key-value pairs, where key should match to root configurator and value have all required properties
* @throws ConfiguratorException configuration error
*/
private static void invokeWith(Mapping entries, ConfiguratorOperation function) throws ConfiguratorException {
// Run configurators by order, consuming entries until all have found a matching configurator.
// Configurators order is important so that io.jenkins.plugins.casc.plugins.PluginManagerConfigurator run
// before any other, and can install plugins required by other configuration to successfully parse yaml data
for (RootElementConfigurator configurator : RootElementConfigurator.all()) {
final Iterator<Map.Entry<String, CNode>> it = entries.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, CNode> entry = it.next();
if (! entry.getKey().equalsIgnoreCase(configurator.getName())) {
continue;
}
try {
function.apply(configurator, entry.getValue());
it.remove();
break;
} catch (ConfiguratorException e) {
throw new ConfiguratorException(
configurator,
format("error configuring '%s' with %s configurator", entry.getKey(), configurator.getClass()), e
);
}
}
}
if (!entries.isEmpty()) {
final Map.Entry<String, CNode> next = entries.entrySet().iterator().next();
throw new ConfiguratorException(format("No configurator for root element <%s>", next.getKey()));
}
}
private static void detectVaultPluginMissing() {
PluginManager pluginManager = Jenkins.getInstance().getPluginManager();
Set<String> envKeys = System.getenv().keySet();
if (envKeys.stream().anyMatch(s -> s.startsWith("CASC_VAULT_"))
&& pluginManager.getPlugin("hashicorp-vault-plugin") == null) {
LOGGER.log(Level.SEVERE,
"Vault secret resolver is not installed, consider installing hashicorp-vault-plugin v2.4.0 or higher\nor consider removing any 'CASC_VAULT_' variables");
}
}
private void configureWith(Mapping entries) throws ConfiguratorException {
// Initialize secret sources
SecretSource.all().forEach(SecretSource::init);
// Check input before actually applying changes,
// so we don't let master in a weird state after some ConfiguratorException has been thrown
final Mapping clone = entries.clone();
checkWith(clone);
final ObsoleteConfigurationMonitor monitor = ObsoleteConfigurationMonitor.get();
monitor.reset();
ConfigurationContext context = new ConfigurationContext(registry);
context.addListener(monitor::record);
try (ACLContext acl = ACL.as(ACL.SYSTEM)) {
invokeWith(entries, (configurator, config) -> configurator.configure(config, context));
}
}
public Map<Source, String> checkWith(Mapping entries) throws ConfiguratorException {
Map<Source, String> issues = new HashMap<>();
ConfigurationContext context = new ConfigurationContext(registry);
context.addListener( (node,message) -> issues.put(node.getSource(), message) );
invokeWith(entries, (configurator, config) -> configurator.check(config, context));
return issues;
}
public static ConfigurationAsCode get() {
return Jenkins.getInstance().getExtensionList(ConfigurationAsCode.class).get(0);
}
/**
* Used for documentation generation in index.jelly
*/
public Collection<?> getRootConfigurators() {
return new LinkedHashSet<>(RootElementConfigurator.all());
}
/**
* Used for documentation generation in index.jelly
*/
public Collection<?> getConfigurators() {
List<RootElementConfigurator> roots = RootElementConfigurator.all();
final ConfigurationContext context = new ConfigurationContext(registry);
Set<Object> elements = new LinkedHashSet<>(roots);
for (RootElementConfigurator root : roots) {
listElements(elements, root.describe(), context);
}
return elements;
}
/**
* Recursive configurators tree walk (DFS).
* Collects all configurators starting from root ones in {@link #getConfigurators()}
* @param elements linked set (to save order) of visited elements
* @param attributes siblings to find associated configurators and dive to next tree levels
* @param context
*/
private void listElements(Set<Object> elements, Set<Attribute<?,?>> attributes, ConfigurationContext context) {
attributes.stream()
.map(Attribute::getType)
.map(context::lookup)
.filter(Objects::nonNull)
.map(c -> c.getConfigurators(context))
.flatMap(Collection::stream)
.forEach(configurator -> {
if (elements.add(configurator)) {
listElements(elements, ((Configurator)configurator).describe(), context); // some unexpected type erasure force to cast here
}
});
}
// --- UI helper methods
/**
* Retrieve the html help tip associated to an attribute, used in documentation.jelly
* FIXME would prefer <st:include page="help-${a.name}.html" class="${c.target}" optional="true"/>
* @param attribute to get help for
* @return String that shows help. May be empty
* @throws IOException if the resource cannot be read
*/
@Restricted(NoExternalUse.class)
@NonNull
public String getHtmlHelp(Class type, String attribute) throws IOException {
final URL resource = Klass.java(type).getResource("help-" + attribute + ".html");
if (resource != null) {
return IOUtils.toString(resource.openStream());
}
return "";
}
/**
* Retrieve which plugin do provide this extension point, used in documentation.jelly
*
* @return String representation of the extension source, usually artifactId.
*/
@Restricted(NoExternalUse.class)
@CheckForNull
public String getExtensionSource(Configurator c) throws IOException {
final Class e = c.getImplementedAPI();
final String jar = Which.jarFile(e).getName();
if (jar.startsWith("jenkins-core-")) { // core jar has version in name
return "jenkins-core";
}
return jar.substring(0, jar.lastIndexOf('.'));
}
@Restricted(NoExternalUse.class)
public static String printThrowable(@NonNull Throwable t) {
String s = Functions.printThrowable(t)
.split("at io.jenkins.plugins.casc.ConfigurationAsCode.export")[0]
.replaceAll("\t", " ");
return s.substring(0, s.lastIndexOf(")") + 1);
}
}