Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support custom log lines processing via script #40

Merged
merged 6 commits into from
Mar 20, 2018
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
<properties>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<skipIntegrationTests>true</skipIntegrationTests>
<jenkins.version>2.7.3</jenkins.version>
<java.level>7</java.level>
</properties>

<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<version>1.599</version>
<version>2.9</version>
</parent>

<repositories>
Expand Down Expand Up @@ -88,7 +90,7 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.1.0</version>
<version>2.13.0</version>
<type>jar</type>
<scope>test</scope>
</dependency>
Expand All @@ -113,7 +115,6 @@
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>mask-passwords</artifactId>
<version>2.8</version>
<optional>true</optional>
</dependency>

<dependency>
Expand All @@ -127,6 +128,19 @@
<artifactId>structs</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>script-security</artifactId>
<version>1.37</version>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought you were going to use jenkinsci/script-security-plugin#169 here, so we can verify that the proposed API actually works for its supposed purpose? If so, you would need to deploy a snapshot of the upstream PR, then change this to a timestamped snapshot version, so CI can verify this PR.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jglick , I have verified the API works locally. Would you point me at how to deploy a timestamped snapshot?

Copy link

@jakub-bochenski jakub-bochenski Jan 12, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think @jglick meant to put a timestamped snapshot dependency here. If you point me to the artifact you need I think I can make the change.

EDIT: no apparently we also need to deploy it first. Still I think I could help with that but please point me to the exact thing you need.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically we need jenkinsci/script-security-plugin#169 built and deployed. Also we need 747a0bc reverted here so that the new API is used. Better let me first do little refactoring of script security pull request and then test it. I just have so much other work since new year. Hope to get back to this next week.

</dependency>

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,32 +32,46 @@
import hudson.model.BuildableItemWithBuildWrappers;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.CheckForNull;

import groovy.lang.Binding;

import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;

import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsBuildWrapper;
import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsBuildWrapper.VarPasswordPair;
import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsConfig;

/**
* Build wrapper that decorates the build's logger to insert a
* {@link LogstashNote} on each output line.
* Logstash note on each output line.
*
* @author K Jonathan Harker
*/
public class LogstashBuildWrapper extends BuildWrapper {

@CheckForNull
private SecureGroovyScript secureGroovyScript;

/**
* Create a new {@link LogstashBuildWrapper}.
*/
@DataBoundConstructor
public LogstashBuildWrapper() {}

@DataBoundSetter
public void setSecureGroovyScript(@CheckForNull SecureGroovyScript script) {
this.secureGroovyScript = script != null ? script.configuringWithNonKeyItem() : null;
}

/**
* {@inheritDoc}
*/
Expand Down Expand Up @@ -106,9 +120,19 @@ public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}

@CheckForNull
public SecureGroovyScript getSecureGroovyScript() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@CheckForNull would be useful

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look at this. Thanks.

return secureGroovyScript;
}

// Method to encapsulate calls for unit-testing
LogstashWriter getLogStashWriter(AbstractBuild<?, ?> build, OutputStream errorStream) {
return new LogstashWriter(build, errorStream, null);
LogstashScriptProcessor processor = null;
if (secureGroovyScript != null) {
processor = new LogstashScriptProcessor(secureGroovyScript, errorStream);
}

return new LogstashWriter(build, errorStream, null, processor);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
* POJO for storing global configurations shared between components.
*
Expand All @@ -65,6 +67,9 @@ public static Descriptor getLogstashDescriptor() {
public static final class Descriptor extends ToolDescriptor<LogstashInstallation> {
public IndexerType type;
public SyslogFormat syslogFormat;
@SuppressFBWarnings(
value="UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD",
justification="TODO: do we need this?")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you decide to delete it, make it transient first.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer if this findbug issues are fixed in another pull request as this one is large enough.
I will look at the date formatter issues while waiting for script security plugin though as they appear to be more critical.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And thank you for the quick turnaround!

public SyslogProtocol syslogProtocol;
public String host;
public Integer port = -1;
Expand All @@ -85,6 +90,9 @@ public boolean configure(StaplerRequest req, JSONObject formData) throws FormExc
}

@Override
@SuppressFBWarnings(
value="NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
justification="TODO: investigate")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't we just leave those cases unsuppressed? or is the build setup to fail in that case?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

build fails

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, I think we should disable this on maven level then -- just make it emit warnings for now

let me know if you need help with this

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

project automated CI will will show a failure. Is there a way to make it not fail but just warn?

Copy link

@jakub-bochenski jakub-bochenski Dec 22, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be set somewhere in maven and be overridable -- let me check

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we have the FB issues fixed in #43 and related PRs #44 #45 #46
maybe you can integrate those into your PR instead?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will look into that once I catch up with the holiday pile up of tasks.

public ToolInstallation newInstance(StaplerRequest req, JSONObject formData) throws FormException {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Req is marked as nullable in the interface, so apparently we should handle this gracefully.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just suppressed the warning, I don't think I touched anything about this. Good to go after all suppression later and have them fixed.

req.bindJSON(this, formData.getJSONObject("logstash"));
save();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsBuildWrapper.VarPasswordPair;
import com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsOutputStream;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
* Output stream that writes each line to the provided delegate output stream
* and also sends it to an indexer for logstash to consume.
Expand All @@ -61,6 +63,9 @@ public MaskPasswordsOutputStream maskPasswords(List<VarPasswordPair> passwords)
}

@Override
@SuppressFBWarnings(
value="DM_DEFAULT_ENCODING",
justification="TODO: not sure how to fix this")
protected void eol(byte[] b, int len) throws IOException {
delegate.write(b, 0, len);
this.flush();
Expand All @@ -86,6 +91,7 @@ public void flush() throws IOException {
*/
@Override
public void close() throws IOException {
logstash.close();
delegate.close();
super.close();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* The MIT License
*
* Copyright 2017 Red Hat inc, and individual contributors
*
* 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.plugins.logstash;

import net.sf.json.JSONObject;

/**
* Interface describing processors of persisted payload.
*
* @author Aleksandar Kostadinov
* @since 1.4.0
*/
public interface LogstashPayloadProcessor {
/**
* Modifies a JSON payload compatible with the Logstash schema.
*
* @param payload the JSON payload that has been constructed so far.
* @return The formatted JSON object, can be null to ignore this payload.
*/
JSONObject process(JSONObject payload) throws Exception;

/**
* Finalizes any operations, for example returns cashed lines at end of build.
*
* @return A formatted JSON object, can be null when it has nothing.
*/
JSONObject finish() throws Exception;
}
123 changes: 123 additions & 0 deletions src/main/java/jenkins/plugins/logstash/LogstashScriptProcessor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* The MIT License
*
* Copyright 2017 Red Hat inc. and individual contributors
*
* 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.plugins.logstash;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.LinkedHashMap;

import javax.annotation.Nonnull;

import groovy.lang.Binding;

import net.sf.json.JSONObject;

import jenkins.model.Jenkins;
import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
* This class is handling custom groovy script processing of JSON payload.
* Each call to process executes the script provided in job configuration.
* Script is executed under the same binding each time so that it has ability
* to persist data during build execution if desired by script author.
* When build is finished, script will receive null as the payload and can
* return any cached but non-sent data back for persisting.
* The return value of script is the payload to be persisted unless null.
*
* @author Aleksandar Kostadinov
* @since 1.4.0
*/
public class LogstashScriptProcessor implements LogstashPayloadProcessor{
@Nonnull
private final SecureGroovyScript script;

@Nonnull
private final OutputStream consoleOut;

/** Groovy binding for script execution */
@Nonnull
private final Binding binding;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems unsafe to keep this as a field. Initialize in process.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is it unsafe? The main idea is to allow executing the script always with the same binding. This would allow script to create properties for persisting data between executions. The way I understand your suggestion would not allow this. Or did I misunderstand?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, if we generate Binding in process(), that would mean creating a new object per each line of console output.


/** Classloader for script execution */
@Nonnull
private final ClassLoader classLoader;

public LogstashScriptProcessor(SecureGroovyScript script, OutputStream consoleOut) {
this.script = script;
this.consoleOut = consoleOut;

// TODO: should we put variables in the binding like manager, job, etc.?
binding = new Binding();
binding.setVariable("console", new BuildConsoleWrapper());

// not sure what the diff is compared to getClass().getClassLoader();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

uberClassLoader would be able to load typed defined in any enabled plugin. LogstashScriptProcessor.class.getClassLoader() would be able to load only those types accessible at compile time in this plugin.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sounds like uberClassLoader gives more flexibility to script writers

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it does, but then the scripts will be non portable -- you can have them working in one Jenkins instance but not another.
Security might be another concern, though the scripts need to be pre-approved anyway.

I'd suggest to do the more restrictive thing for now. It's easier to extend the possibilities later than restrict them

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can have them working in one Jenkins instance but not another

This is certainly a risk in any case.

Security might be another concern

Sandboxed scripts could only use whitelisted methods anyway.

final Jenkins jenkins = Jenkins.getInstance();
classLoader = jenkins.getPluginManager().uberClassLoader;
}

/**
* Helper method to allow logging to build console.
*/
@SuppressFBWarnings(
value="DM_DEFAULT_ENCODING",
justification="TODO: not sure how to fix this")
private void buildLogPrintln(Object o) throws IOException {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whitelisting a private method makes no sense. If you intend for scripts to call it (directly), make it public. Since it seems to be called only indirectly from BuildConsoleWrapper, it does not need to be annotated.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a leftover from my first attempts. Will fix!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm removing the extra whitelist now. Just wondering how can I make the script this method directly? I couldn't see this possible.

consoleOut.write(o.toString().getBytes());
consoleOut.write("\n".getBytes());
consoleOut.flush();
}

/*
* good examples in:
* https://github.com/jenkinsci/envinject-plugin/blob/master/src/main/java/org/jenkinsci/plugins/envinject/service/EnvInjectEnvVars.java
* https://github.com/jenkinsci/groovy-postbuild-plugin/pull/11/files
*/
@Override
public JSONObject process(JSONObject payload) throws Exception {
binding.setVariable("payload", payload);
script.evaluate(classLoader, binding);
return (JSONObject) binding.getVariable("payload");
}

@Override
public JSONObject finish() throws Exception {
buildLogPrintln("Tearing down Script Log Processor..");
return process(null);
}

/**
* Helper to allow access from sandboxed script to output messages to console.
*/
private class BuildConsoleWrapper {
@Whitelisted
public void println(Object o) throws IOException {
buildLogPrintln(o);
}
}
}
Loading