Search in sources :

Example 16 with Restricted

use of org.kohsuke.accmod.Restricted in project configuration-as-code-plugin by jenkinsci.

the class ConfigurationAsCode method doCheckNewSource.

@POST
@Restricted(NoExternalUse.class)
public FormValidation doCheckNewSource(@QueryParameter String newSource) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    String normalizedSource = Util.fixEmptyAndTrim(newSource);
    if (normalizedSource == null) {
        // empty, do nothing
        return FormValidation.ok();
    }
    List<String> candidateSources = new ArrayList<>();
    for (String candidateSource : inputToCandidateSources(normalizedSource)) {
        File file = new File(candidateSource);
        if (!file.exists() && !ConfigurationAsCode.isSupportedURI(candidateSource)) {
            return FormValidation.error("Configuration cannot be applied. File or URL cannot be parsed or do not exist.");
        }
        candidateSources.add(candidateSource);
    }
    try {
        List<YamlSource> candidates = getConfigFromSources(candidateSources);
        final Map<Source, String> issues = checkWith(candidates);
        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());
    }
}
Also used : ArrayList(java.util.ArrayList) JSONArray(net.sf.json.JSONArray) File(java.io.File) YamlSource(io.jenkins.plugins.casc.yaml.YamlSource) YamlSource(io.jenkins.plugins.casc.yaml.YamlSource) Source(io.jenkins.plugins.casc.model.Source) POST(org.kohsuke.stapler.verb.POST) RequirePOST(org.kohsuke.stapler.interceptor.RequirePOST) Restricted(org.kohsuke.accmod.Restricted)

Example 17 with Restricted

use of org.kohsuke.accmod.Restricted in project configuration-as-code-plugin by jenkinsci.

the class ConfigurationAsCode method getBundledCasCURIs.

@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.get().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;
}
Also used : PathMatcher(java.nio.file.PathMatcher) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) ServletContext(javax.servlet.ServletContext) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL) Restricted(org.kohsuke.accmod.Restricted)

Example 18 with Restricted

use of org.kohsuke.accmod.Restricted in project configuration-as-code-plugin by jenkinsci.

the class ConfigurationAsCode method doViewExport.

@RequirePOST
@Restricted(NoExternalUse.class)
public void doViewExport(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        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);
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) RequirePOST(org.kohsuke.stapler.interceptor.RequirePOST) Restricted(org.kohsuke.accmod.Restricted)

Example 19 with Restricted

use of org.kohsuke.accmod.Restricted in project configuration-as-code-plugin by jenkinsci.

the class ConfigurationAsCode method configs.

/**
 * 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), FileVisitOption.FOLLOW_LINKS)) {
        return stream.sorted().collect(toList());
    } catch (IOException e) {
        throw new IllegalStateException("failed config scan for " + path, e);
    }
}
Also used : Path(java.nio.file.Path) PathMatcher(java.nio.file.PathMatcher) IOException(java.io.IOException) Restricted(org.kohsuke.accmod.Restricted)

Example 20 with Restricted

use of org.kohsuke.accmod.Restricted in project configuration-as-code-plugin by jenkinsci.

the class ConfigurationAsCode method doCheck.

@RequirePOST
@Restricted(NoExternalUse.class)
public void doCheck(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().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());
}
Also used : Sequence(io.jenkins.plugins.casc.model.Sequence) Arrays(java.util.Arrays) StringUtils(org.apache.commons.lang.StringUtils) SequenceNode(org.yaml.snakeyaml.nodes.SequenceNode) URL(java.net.URL) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) Scanner(java.util.Scanner) CNode(io.jenkins.plugins.casc.model.CNode) Mapping(io.jenkins.plugins.casc.model.Mapping) Which(hudson.remoting.Which) Node(org.yaml.snakeyaml.nodes.Node) Initializer(hudson.init.Initializer) NonNull(edu.umd.cs.findbugs.annotations.NonNull) Map(java.util.Map) PathMatcher(java.nio.file.PathMatcher) Scalar(io.jenkins.plugins.casc.model.Scalar) URI(java.net.URI) GlobalConfiguration(jenkins.model.GlobalConfiguration) Path(java.nio.file.Path) Functions(hudson.Functions) Restricted(org.kohsuke.accmod.Restricted) Collection(java.util.Collection) Jenkins(jenkins.model.Jenkins) Set(java.util.Set) YamlSource(io.jenkins.plugins.casc.yaml.YamlSource) Logger(java.util.logging.Logger) StandardCharsets(java.nio.charset.StandardCharsets) String.format(java.lang.String.format) Objects(java.util.Objects) IOUtils(org.apache.commons.io.IOUtils) Serializer(org.yaml.snakeyaml.serializer.Serializer) YamlUtils(io.jenkins.plugins.casc.yaml.YamlUtils) List(java.util.List) POST(org.kohsuke.stapler.verb.POST) Stream(java.util.stream.Stream) Writer(java.io.Writer) SchemaGeneration.writeJSONSchema(io.jenkins.plugins.casc.SchemaGeneration.writeJSONSchema) InitMilestone(hudson.init.InitMilestone) Source(io.jenkins.plugins.casc.model.Source) JSONObject(net.sf.json.JSONObject) Permission(hudson.security.Permission) YAMLException(org.yaml.snakeyaml.error.YAMLException) IntStream(java.util.stream.IntStream) Format(io.jenkins.plugins.casc.model.Scalar.Format) ByteArrayOutputStream(java.io.ByteArrayOutputStream) QueryParameter(org.kohsuke.stapler.QueryParameter) StaplerRequest(org.kohsuke.stapler.StaplerRequest) HashMap(java.util.HashMap) PLAIN(org.yaml.snakeyaml.DumperOptions.ScalarStyle.PLAIN) TreeSet(java.util.TreeSet) MappingNode(org.yaml.snakeyaml.nodes.MappingNode) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) Inject(javax.inject.Inject) DumperOptions(org.yaml.snakeyaml.DumperOptions) ACLContext(hudson.security.ACLContext) ACL(hudson.security.ACL) RequirePOST(org.kohsuke.stapler.interceptor.RequirePOST) Extension(hudson.Extension) OutputStreamWriter(java.io.OutputStreamWriter) Resolver(org.yaml.snakeyaml.resolver.Resolver) DOUBLE_QUOTED(org.yaml.snakeyaml.DumperOptions.ScalarStyle.DOUBLE_QUOTED) LinkedHashSet(java.util.LinkedHashSet) Util(hudson.Util) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) Files(java.nio.file.Files) FormValidation(hudson.util.FormValidation) HttpServletResponse(javax.servlet.http.HttpServletResponse) ManagementLink(hudson.model.ManagementLink) NoExternalUse(org.kohsuke.accmod.restrictions.NoExternalUse) StaplerResponse(org.kohsuke.stapler.StaplerResponse) IOException(java.io.IOException) Tag(org.yaml.snakeyaml.nodes.Tag) File(java.io.File) NodeTuple(org.yaml.snakeyaml.nodes.NodeTuple) Klass(org.kohsuke.stapler.lang.Klass) Collectors.toList(java.util.stream.Collectors.toList) PluginManager(hudson.PluginManager) FileVisitOption(java.nio.file.FileVisitOption) Paths(java.nio.file.Paths) JSONArray(net.sf.json.JSONArray) Emitter(org.yaml.snakeyaml.emitter.Emitter) DefaultConfiguratorRegistry(io.jenkins.plugins.casc.impl.DefaultConfiguratorRegistry) ScalarNode(org.yaml.snakeyaml.nodes.ScalarNode) ServletContext(javax.servlet.ServletContext) CheckForNull(edu.umd.cs.findbugs.annotations.CheckForNull) LITERAL(org.yaml.snakeyaml.DumperOptions.ScalarStyle.LITERAL) Collections(java.util.Collections) BLOCK(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) FileSystems(java.nio.file.FileSystems) JSONObject(net.sf.json.JSONObject) JSONArray(net.sf.json.JSONArray) YamlSource(io.jenkins.plugins.casc.yaml.YamlSource) Source(io.jenkins.plugins.casc.model.Source) RequirePOST(org.kohsuke.stapler.interceptor.RequirePOST) Restricted(org.kohsuke.accmod.Restricted)

Aggregations

Restricted (org.kohsuke.accmod.Restricted)22 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 File (java.io.File)5 HashMap (java.util.HashMap)4 RequirePOST (org.kohsuke.stapler.interceptor.RequirePOST)4 YamlSource (io.jenkins.plugins.casc.yaml.YamlSource)3 Method (java.lang.reflect.Method)3 URL (java.net.URL)3 PathMatcher (java.nio.file.PathMatcher)3 Map (java.util.Map)3 Jenkins (jenkins.model.Jenkins)3 JSONArray (net.sf.json.JSONArray)3 JSONObject (net.sf.json.JSONObject)3 CheckForNull (edu.umd.cs.findbugs.annotations.CheckForNull)2 NonNull (edu.umd.cs.findbugs.annotations.NonNull)2 Describable (hudson.model.Describable)2 BuildStepDescriptor (hudson.tasks.BuildStepDescriptor)2 CNode (io.jenkins.plugins.casc.model.CNode)2 Source (io.jenkins.plugins.casc.model.Source)2