How to configure Jenkins to report major errors to the administrator? - jenkins

e.g. I have the following errors in jenkins.err.log. How can I make Jenkins email this type of errors to me?
caused by: com.microsoft.tfs.core.ws.runtime.exceptions.UnauthorizedException: Authorization failure connecting to 'http://vstsprodapp:8080/Services/v1.0/Registration.asmx' (authenticating as domain\user)

This isn't a feature that's built into Jenkins.
You could use whatever system you use for monitoring your servers, and check the logs on the Jenkins server for error messages.
There is also an idea suggested on the Jenkins wiki, which allows you to use a Groovy hook script to add a further Java logging handler to Jenkins. But again, even if you do this, you would still have to implement a custom solution to send notifications based on the log's contents.
From https://wiki.jenkins-ci.org/display/JENKINS/Logging:
Put the following Groovy script into a file called $JENKINS_HOME/init.groovy.d/extra_logging.groovy:
import java.util.logging.ConsoleHandler
import java.util.logging.LogManager
def logger = LogManager.getLogManager().getLogger("hudson.WebAppMain")
logger.addHandler (new ConsoleHandler())
This will just copy all log records generated by Jenkins and any plugins to the console.

Related

How can I install a plugin using jenkinsfile?

Problem Statement
I am using Jenkins for CI/CD automation. I installed the GitHub Pull Request Builder through Jenkin's Plugin Manager.
However I cannot figure out how to do this with a Jenkins Pipeline
Attempts/Documentation
I have skimmed through this exhaustive list of pipeline steps and declarative documentation but cannot find any documentation on how to accomplish this?
Installing Plugin via Jenkinsfile
Firstly, I would question why exactly you want to do this. This is a fairly odd requirement that I have not seen in my 10 years of Jenkins & Hudson experience. With that said, anything that can be done in the Jenkins web interface, and a billion other things that cannot, can be done in either a Pipeline or in the Script Console because these two constructs have access to the entire SDK.
node {
// 'ghprb' is this plugins short name value
GITHUB_PULL_REQUEST_BUILDER = 'ghprb'
for (plugin in [GITHUB_PULL_REQUEST_BUILDER]) {
e = Hudson.instance.updateCenter.getPlugin(plugin).deploy().get().getError()
if (e != null)
println e.message
}
}
Security
Anything you see on the Jenkins GUI can be done in the script console or a pipeline via the Jenkins SDK. Jenkins has implemented a Sandbox to prevent nefarious actors from executing malicious scripts. Your requirement must use the Jenkins/Hudson SDK and therefore you have two options:
Disable the Sandbox for this pipeline
Authorize the scripts and/or methods being used
If you try and run the aforementioned script without solving these security constraints the following exception will be thrown:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method jenkins.model.Jenkins getUpdateCenter
Sandbox
To disable the Sandbox simply uncheck the "Use Groovy Sandbox" checkbox. This is the easiest solution.
Script Approval
If your administrator does not authorize you to outright disable the Sandbox for that job then you can approve the method signatures used in your script or approve the script itself.
The following message signatures would need to be approved for this script
staticMethod hudson.model.Hudson getInstance
method jenkins.model.Jenkins getUpdateCenter
method hudson.model.UpdateSite$Plugin deploy
method java.util.concurrent.Future get
method hudson.model.UpdateCenter$UpdateCenterJob getError
Additional Information
Most likely the plugin will not be available until a restart has occurred. You can automate a restart a variety of ways. You can hit the following endpoints
http://<jenkins.server>/restart
http://<jenkins.server>/safeRestart
You could invoke the jenkins-cli.jar tool. If you're feeling exceptionally risky you could even do something like Jenkins.instance.restart()
Note: don't use the SDK to restart unless you really know what you're doing

How to send email/trigger parameterized remote job based on error category from Build Failure Analyzer Jenkins plugin?

I want to categorize different types of errors appearing in the console output of Jenkins using the Build Failure Analyzer plugin. If there aren't any errors caught by that plugin, then I want to trigger another job using Parameterized Remote trigger plugin. Else, I want to send an email to the concerned team describing all the attributes in the failure cause of that plugin (e.g. Name in that Failure Cause and the corresponding error text which got printed in the failure logs).
Build Failure Analyzer window
For example, if the console output of different failure logs show the following errors:
You don't have the required permissions to copy this file.
java.lang.NullPointerException
at Login.processLogin(Login.java:68)
I want to categorize these errors based on the analyzer plugin and if caught by that plugin, I want to send an email:
e.g. Build #48 at {My_Jenkins_Job_Url} failed due to Permission denied (Failure cause Name). You don't have the required permissions to copy this file (console log text).
If not caught and successful, then I should be able to trigger parameterized remote Jenkins job.
I am just a beginner with regards to Jenkins. It would be better if anyone explains and assists me with complete details. Thanks!
Well you can do it something like this, you can parse Jenkins console output which will look for this error message, you have to add the condition in your jenkinsfile
if (manager.logContains('.*You don't have the required permissions to copy this file.*') || (manager.logContains('.*java.lang.NullPointerException at Login.processLogin(Login.java:68).*'))) {
emailext body: 'Build failure', subject: 'Build failure', to: 'test#ab.org'
}

Extending the Jenkins Groovy DSL

How can I add/edit new code to my Jenkins instance that would be accesible in a DSL script? Context follows
I've inherited a Jenkins instance. Part of this inheritance includes spending the night in a haunted house writing some new automation in groovy via the Jobs DSL plugin. Since I'm fearful of ruining our jenkins instance, my first step is setting up a local development instance.
I'm having trouble running one of our existing DSL Scripts on my local development instance -- my builds on the local server fail with the following in the Jenkins error console.
Processing DSL script jobs.groovy
ERROR: startup failed:
jobs.groovy: 1: unable to resolve class thecompanysname.jenkins.extensions
The script in question starts off like this.
import thecompanysname.jenkins.extensions
use(extensions) {
def org = 'project-name'
def project = 'test-jenkins-repo'
def _email = 'foo#example.com'
So, as near I can tell, it seems like a predecesor has written some custom Groovy code that they're importing
import thecompanysname.jenkins.extensions
What's not clear to me is
Where this code lives
How I can find it in our real Jenkins instance
How I can add to to my local instance
Specific answers are welcome, as our here's how you can learn to fish answers.
While there may be other ways to accomplish this, after a bit of poking around I discovered
The Jenkins instance I've installed has an older version of the Jobs DSL plugin installed.
This version of the Jobs DSL plugin allowed you to set an additional classpath in your Process DSL Builds job section that pointed to additional jar files.
These jar files can give you access to additional classes in your groovy scripts (i.e. thecompanysname.jenkins.extensions)
Unfortunately, more recent versions of the Jobs DSL plugin have removed this option, and it's not clear if it's possible to add it back. That, however, is another question.
Configure Global Security -> uncheck "Enable script security for Job DSL
scripts".
works for me

How to configure jenkins slack plugin?

I tried to configure jenkins slack plugin to send a notification to slack channel. But it doesn't work. I followed below instruction:
1. Get a Slack account: https://slack.com/
2. Configure the Jenkins integration: https://my.slack.com/services/new/jenkins-ci
3. Install this plugin on your Jenkins server.
4. Configure it in your Jenkins job (and optionally as global configuration) and add it as a Post-build action.
After I install jenkins on slack app there is a instruction about how to configure jenkins. But the configuration fields mentioned on the instruction is a little different than my jenkins configuration.
Below is the configuration screenshot from the instruction:
the configuration for my jenkins server looks like below:
how can I fill in the Base URL in my configuration? I have tried to fill in my jenkins url but it doesn't work. The test connection failed.
I get below error in jenkins system log:
Slack post may have failed. Response: <html><head><meta http-equiv='refresh' content='1;url=/login?from=%2FOPRc9G4zB2JX289VOnTvfeey'/><script>window.location.replace('/login?from=%2FOPRc9G4zB2JX289VOnTvfeey');</script></head><body style='background-color:white; color:white;'>
Authentication required
<!--
You are authenticated as: anonymous
Groups that you are in:
Permission you need to have (but didn't): hudson.model.Hudson.Read
... which is implied by: hudson.security.Permission.GenericRead
... which is implied by: hudson.model.Hudson.Administer
-->
I have tried to leave base url empty but still doesn't work
After a lot of testing, I figured out the problem. The issue relates to the configuration panel for slack. When I change the slack configuration and hit the test button, it doesn't take the current configuration, instead, it takes the previously saved configuration. I have to save the configuration first then test the connection.
Base URL doesn't need to be filled. Try from Specific Project. Only supply Team SubDomain in Global setting.
You have to provide these info separately for every project:
Team Domain/Sub-Domain
Integration Token(Taken from the Browse Apps > Jenkins CI)
Channel Name
For each Project that you would like receive notifications for, choose Configure from the project's menu in Jenkins.
You'll also need to add Slack Notifications to the Post-build Actions for this project.
Provide the Channel name, Team Subdomain and Integration Token there.
Test the connection.
you can directly run a POST build shell script per project basis or per slack channel
#!/bin/bash
curl -X POST --data-urlencode 'payload={"text": "'"$SLACK_MSG"'"}' $SLACK_WEB_HOOK_URL
where $SLACK_WEB_HOOK_URL and $SLACK_MSG can be exported as env variables or hardcode it for each project
Hay,
you have to add you integration Token to your Jenkins(I would recommend to add a Credential ID but its not necessary), that should sole your Problem. Keep in mind that your Jenkins just can send Messages to channels, the Account which generated the token has access to.
As said previously, you dont have to add a Team-Domain and your Subdomain has to be the following part of your Slack link:
www.EXAMPLE.slack.com
Hopefully i was able to help

Read Jenkins log in shell

I have a requirement that I need to parse the Jenkins job after the completion to grep out the error log and send it in email to the team. Could someone of you suggest what plugin/option is available in Jenkins?
If you want to parse out the console output after the build steps, try using Groovy Postbuild Plugin.
You can use the manager.logContains function or the manager.build.logFile variable to get the console output.

Resources