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

add logstash DAO #29

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
8 changes: 7 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

<artifactId>logstash</artifactId>
<packaging>hpi</packaging>
<version>1.2.1-SNAPSHOT</version>
<version>1.3.0-SNAPSHOT</version>
<name>Logstash</name>
<description>A Logstash agent to send Jenkins logs to a Logstash indexer.</description>
<url>http://wiki.jenkins-ci.org/display/JENKINS/Logstash+Plugin</url>
Expand Down Expand Up @@ -108,6 +108,12 @@
<artifactId>junit</artifactId>
<version>1.10</version>
</dependency>

<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>structs</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public DescriptorImpl getDescriptor() {

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

/**
Expand Down
30 changes: 24 additions & 6 deletions src/main/java/jenkins/plugins/logstash/LogstashNotifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,33 @@

import hudson.Extension;
import hudson.Launcher;
import hudson.FilePath;
import hudson.model.BuildListener;
import hudson.model.TaskListener;
import hudson.model.AbstractBuild;
import hudson.model.Run;
import hudson.model.AbstractProject;
import hudson.model.Result;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;

import jenkins.tasks.SimpleBuildStep;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.IOException;

import org.kohsuke.stapler.DataBoundConstructor;
import org.jenkinsci.Symbol;

/**
* Post-build action to push build log to Logstash.
*
* @author Rusty Gerard
* @since 1.0.0
*/
public class LogstashNotifier extends Notifier {
public class LogstashNotifier extends Notifier implements SimpleBuildStep {

public int maxLines;
public boolean failBuild;
Expand All @@ -58,16 +65,27 @@ public LogstashNotifier(int maxLines, boolean failBuild) {

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) {
return perform(build, listener);
}

@Override
public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher,
TaskListener listener) throws InterruptedException, IOException {
if (!perform(run, listener)) {
run.setResult(Result.FAILURE);
}
}

private boolean perform(Run<?, ?> run, TaskListener listener) {
PrintStream errorPrintStream = listener.getLogger();
LogstashWriter logstash = getLogStashWriter(build, errorPrintStream);
LogstashWriter logstash = getLogStashWriter(run, errorPrintStream, listener);
logstash.writeBuildLog(maxLines);

return !(failBuild && logstash.isConnectionBroken());
}

// Method to encapsulate calls for unit-testing
LogstashWriter getLogStashWriter(AbstractBuild<?, ?> build, OutputStream errorStream) {
return new LogstashWriter(build, errorStream);
LogstashWriter getLogStashWriter(Run<?, ?> run, OutputStream errorStream, TaskListener listener) {
return new LogstashWriter(run, errorStream, listener);
}

public BuildStepMonitor getRequiredMonitorService() {
Expand All @@ -80,7 +98,7 @@ public Descriptor getDescriptor() {
return (Descriptor) super.getDescriptor();
}

@Extension
@Extension @Symbol("logstashSend")
public static class Descriptor extends BuildStepDescriptor<Publisher> {

@Override
Expand Down
17 changes: 12 additions & 5 deletions src/main/java/jenkins/plugins/logstash/LogstashWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@


import hudson.model.AbstractBuild;
import hudson.model.TaskListener;
import hudson.model.Run;
import jenkins.model.Jenkins;
import jenkins.plugins.logstash.persistence.BuildData;
import jenkins.plugins.logstash.persistence.IndexerDaoFactory;
Expand All @@ -52,15 +54,17 @@
public class LogstashWriter {

final OutputStream errorStream;
final AbstractBuild<?, ?> build;
final Run<?, ?> build;
final TaskListener listener;
final BuildData buildData;
final String jenkinsUrl;
final LogstashIndexerDao dao;
private boolean connectionBroken;

public LogstashWriter(AbstractBuild<?, ?> build, OutputStream error) {
public LogstashWriter(Run<?, ?> run, OutputStream error, TaskListener listener) {
this.errorStream = error != null ? error : System.err;
this.build = build;
this.build = run;
this.listener = listener;
this.dao = this.getDaoOrNull();
if (this.dao == null) {
this.jenkinsUrl = "";
Expand All @@ -69,7 +73,6 @@ public LogstashWriter(AbstractBuild<?, ?> build, OutputStream error) {
this.jenkinsUrl = getJenkinsUrl();
this.buildData = getBuildData();
}

}

/**
Expand Down Expand Up @@ -131,7 +134,11 @@ LogstashIndexerDao getDao() throws InstantiationException {
}

BuildData getBuildData() {
return new BuildData(build, new Date());
if (build instanceof AbstractBuild) {
return new BuildData((AbstractBuild) build, new Date());
} else {
return new BuildData(build, new Date(), listener);
}
}

String getJenkinsUrl() {
Expand Down
63 changes: 48 additions & 15 deletions src/main/java/jenkins/plugins/logstash/persistence/BuildData.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
import hudson.model.Environment;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.TaskListener;
import hudson.model.Run;
import hudson.model.Node;
import hudson.model.Executor;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.tasks.test.TestResult;

Expand All @@ -42,6 +45,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.IOException;

import net.sf.json.JSONObject;

Expand Down Expand Up @@ -112,19 +116,9 @@ public TestData(Action action) {

BuildData() {}

// Freestyle project build
public BuildData(AbstractBuild<?, ?> build, Date currentTime) {
result = build.getResult() == null ? null : build.getResult().toString();
id = build.getId();
projectName = build.getProject().getName();
displayName = build.getDisplayName();
fullDisplayName = build.getFullDisplayName();
description = build.getDescription();
url = build.getUrl();

Action testResultAction = build.getAction(AbstractTestResultAction.class);
if (testResultAction != null) {
testResults = new TestData(testResultAction);
}
initData(build, currentTime);

Node node = build.getBuiltOn();
if (node == null) {
Expand All @@ -135,10 +129,7 @@ public BuildData(AbstractBuild<?, ?> build, Date currentTime) {
buildLabel = StringUtils.isBlank(node.getLabelString()) ? "master" : node.getLabelString();
}

buildNum = build.getNumber();
// build.getDuration() is always 0 in Notifiers
buildDuration = currentTime.getTime() - build.getStartTimeInMillis();
timestamp = DATE_FORMATTER.format(build.getTimestamp().getTime());
rootProjectName = build.getRootBuild().getProject().getName();
rootProjectDisplayName = build.getRootBuild().getDisplayName();
rootBuildNum = build.getRootBuild().getNumber();
Expand Down Expand Up @@ -166,6 +157,48 @@ public BuildData(AbstractBuild<?, ?> build, Date currentTime) {
}
}

// Pipeline project build
public BuildData(Run<?, ?> build, Date currentTime, TaskListener listener) {
initData(build, currentTime);

Executor executor = build.getExecutor();
if (executor == null) {
buildHost = "master";
} else {
buildHost = StringUtils.isBlank(executor.getDisplayName()) ? "master" : executor.getDisplayName();
}

rootProjectName = projectName;
rootProjectDisplayName = displayName;
rootBuildNum = buildNum;

try {
// TODO: sensitive variables are not filtered, c.f. https://stackoverflow.com/questions/30916085
buildVariables = build.getEnvironment(listener);
} catch (Exception e) {
buildVariables = new HashMap<String, String>();
}
}

private void initData(Run<?, ?> build, Date currentTime) {
result = build.getResult() == null ? null : build.getResult().toString();
id = build.getId();
projectName = build.getParent().getName();
displayName = build.getDisplayName();
fullDisplayName = build.getFullDisplayName();
description = build.getDescription();
url = build.getUrl();
buildNum = build.getNumber();

Action testResultAction = build.getAction(AbstractTestResultAction.class);
if (testResultAction != null) {
testResults = new TestData(testResultAction);
}

buildDuration = currentTime.getTime() - build.getStartTimeInMillis();
timestamp = DATE_FORMATTER.format(build.getTimestamp().getTime());
}

@Override
public String toString() {
Gson gson = new GsonBuilder().create();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public final class IndexerDaoFactory {
indexerMap.put(IndexerType.RABBIT_MQ, RabbitMqDao.class);
indexerMap.put(IndexerType.ELASTICSEARCH, ElasticSearchDao.class);
indexerMap.put(IndexerType.SYSLOG, SyslogDao.class);
indexerMap.put(IndexerType.LOGSTASH, LogstashDao.class);

INDEXER_MAP = Collections.unmodifiableMap(indexerMap);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package jenkins.plugins.logstash.persistence;

import com.cloudbees.syslog.Facility;
import com.cloudbees.syslog.MessageFormat;
import com.cloudbees.syslog.Severity;
import com.cloudbees.syslog.sender.UdpSyslogMessageSender;

Choose a reason for hiding this comment

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

These imports from com.cloudbees are not used

import org.apache.http.impl.client.HttpClientBuilder;

import java.io.*;
import java.net.Socket;


public class LogstashDao extends AbstractLogstashIndexerDao {

final String logstashHost;
final int logstashPort;
Socket logstashClientSocket;

Choose a reason for hiding this comment

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

Why is this not private? And why an instance variable?


public LogstashDao(String logstashHostString, int logstashPortInt, String indexKey, String username, String password) {
this(null, logstashHostString, logstashPortInt, indexKey, username, password);
}

public LogstashDao(HttpClientBuilder factory, String logstashHostString, int logstashPortInt, String indexKey, String username, String password) {
super(logstashHostString, logstashPortInt, indexKey, username, password);
this.logstashHost = logstashHostString;
this.logstashPort = logstashPortInt;
}

@Override
public void push(String data) throws IOException {

try
{
logstashClientSocket = new Socket(logstashHost, logstashPort);
DataOutputStream outToServer = new DataOutputStream(logstashClientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(logstashClientSocket.getInputStream()));

Choose a reason for hiding this comment

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

Why opening a reader when you never read data?

outToServer.writeBytes(data);
Copy link

@mwinter69 mwinter69 Jan 2, 2018

Choose a reason for hiding this comment

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

The javadoc for this method says:

Each character in the string is written out, in sequence, by discarding its high eight bits.

Is this really a good idea? What if we have unicode characters (very likely to happen)?

logstashClientSocket.setSoTimeout(10000);
logstashClientSocket.close();

Choose a reason for hiding this comment

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

resources should be closed in finally block, or even better used in try-with-resource block

Choose a reason for hiding this comment

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

Is it a good idea to close the Socket before closing the outputstream?
Closing the outputtstream also closes the socket.

outToServer.close();
inFromServer.close();
}
catch (Exception exc)

Choose a reason for hiding this comment

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

can you please change this to a multi-catch with specific Exception?

{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exc.printStackTrace(pw);
throw new IOException(sw.toString());

Choose a reason for hiding this comment

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

why not chain the exception?

}

}

@Override
public IndexerType getIndexerType() { return IndexerType.LOGSTASH; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ static enum IndexerType {
REDIS,
RABBIT_MQ,
ELASTICSEARCH,
SYSLOG
SYSLOG,
LOGSTASH
}

String getDescription();
Expand Down
Loading