Skip to content

Instantly share code, notes, and snippets.

@opsgenie-github
Created September 7, 2015 11:30
Show Gist options
  • Save opsgenie-github/8ac5f0779622045ca865 to your computer and use it in GitHub Desktop.
Save opsgenie-github/8ac5f0779622045ca865 to your computer and use it in GitHub Desktop.
import com.ifountain.opsgenie.client.http.OpsGenieHttpClient
import com.ifountain.opsgenie.client.util.ClientConfiguration
import com.ifountain.opsgenie.client.util.JsonUtils
import org.apache.http.HttpHeaders
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.impl.auth.BasicScheme
LOG_PREFIX = "[${action}]:";
logger.warn("${LOG_PREFIX} Will execute action for alertId ${alert.alertId}");
CONF_PREFIX = "jira.";
HTTP_CLIENT = createHttpClient();
JIRA_ISSUE_KEY_PREFIX = 'jiraIssueKey:'
jiraIssuePath = "${_conf("basepath")}/issue"
try {
if (action == "Create") {
createJiraIssue()
} else if (action == "AddNote") {
addCommentToJiraIssue()
} else if (action == "Acknowledge") {
startJiraIssueProgress()
} else if (action == "Close" || action == "Delete") {
closeJiraIssue()
}
}
finally {
HTTP_CLIENT.close()
}
def postToJira(Map postParams, String path, int expectedCode){
def url = "${_conf("protocol")}://${_conf("host")}:${_conf("port")}${path}"
logger.debug("${LOG_PREFIX} Posting to Jira. Url ${url} params:${postParams}")
def postMethod = ((OpsGenieHttpClient) HTTP_CLIENT).preparePostMethod(url,JsonUtils.toJson(postParams),[:],[:])
postMethod.addHeader(HttpHeaders.CONTENT_TYPE,"application/json")
def creds = new UsernamePasswordCredentials(_conf("username",true), _conf("password", true))
postMethod.addHeader(BasicScheme.authenticate(creds,"US-ASCII",false))
def response = ((OpsGenieHttpClient) HTTP_CLIENT).executeHttpMethod(postMethod)
if(response.statusCode == expectedCode){
logger.info("${LOG_PREFIX} Successfully executed at Jira.");
if(response.getContent() != null){
logger.debug("${LOG_PREFIX} Jira response: ${response.getContentAsString()}")
}else{
logger.debug("${LOG_PREFIX} No content found on Jira response.")
}
}else{
if(response.getContent() != null) {
logger.warn("${LOG_PREFIX} Could not execute at Jira. Response:${response.getContentAsString()}")
}else{
logger.warn("${LOG_PREFIX} Could not execute at Jira. No content found on response")
}
}
return response
}
def createJiraIssue() {
def jiraProjectKey = determineJiraProjectKey()
logger.info("${LOG_PREFIX} creating issue to project: ${jiraProjectKey}")
def reqParams = [
fields: [
project: [key: jiraProjectKey],
summary: alert.message,
description: "Issue created for OpsGenie Alert " + alert.alertId + " via " + alert.source,
issuetype: [name: 'Bug'] // Make sure your JIRA project configuration(s) supports this Issue Type.
]
]
def expectedCode = 201
def response = postToJira(reqParams, "${jiraIssuePath}", 201)
if (response.statusCode == expectedCode){
logger.info("${LOG_PREFIX} adding issue key as tag to alert")
def content = JsonUtils.parse(response.getContentAsString())
def resp = opsgenie.addTags([id: alert.alertId, tags: ["${JIRA_ISSUE_KEY_PREFIX}${content.key}"]])
if (resp.success) {
logger.warn("Successfully added tags to alert");
} else {
logger.warn("Could not add tags to alert");
}
}
}
def determineJiraProjectKey(){
List<String> tags = alert.tags
def projectKeysFromConfig = determineAlertTagToProjectKeyMappings()
def jiraProjectKey
projectKeysFromConfig.each {
if (tags.contains(it.key)){
logger.debug("${LOG_PREFIX} determined jira project key from alert tags. Project Key: ${it.value}")
jiraProjectKey = it.value
}
}
if(jiraProjectKey == null){
def defaultKey = _conf("default.project.key")
logger.debug("${LOG_PREFIX} could not determine jira project key from alert tags, will use default key from configuration: ${defaultKey}")
return defaultKey
}
return jiraProjectKey
}
def determineAlertTagToProjectKeyMappings(){
def projectKeysMappingsFromConfig = conf.findAll{ it.key.contains("${CONF_PREFIX}project")}
def projectKeyMappingsWithoutPrefix = [:]
projectKeysMappingsFromConfig.each {
def matcher = it.key =~ "${CONF_PREFIX}project.(.+)"
projectKeyMappingsWithoutPrefix[matcher[0][1]] = it.value
}
logger.debug("${LOG_PREFIX} alert tag to project key mappings: ${projectKeyMappingsWithoutPrefix}")
return projectKeyMappingsWithoutPrefix
}
def addCommentToJiraIssue() {
logger.info("${LOG_PREFIX} adding comment to issue")
def params = [body: alert.note]
postToJiraWithExistingIssue(params, "/comment", 201)
}
def startJiraIssueProgress() {
transitionJiraIssue("4", "starting issue progress")
}
def closeJiraIssue() {
transitionJiraIssue("2", "closing issue")
}
def transitionJiraIssue(String transIdStr, String logMessage){
logger.info("${LOG_PREFIX} ${logMessage}")
def params = [transition: [id: transIdStr]]
postToJiraWithExistingIssue(params, "/transitions", 204)
}
def postToJiraWithExistingIssue(Map postParams,String reqPathSuffix, int expectedResponseCode){
def jiraIssueKey = extractJiraIssueKeyFromAlertTag()
if(jiraIssueKey == null){
logger.warn("${LOG_PREFIX} Cannot determine associated JIRA issue. Alert data lacks JIRA issue key tag.")
}else{
def url = "${jiraIssuePath}/${jiraIssueKey}${reqPathSuffix}"
postToJira(postParams, url, expectedResponseCode)
}
}
def extractJiraIssueKeyFromAlertTag(){
def tags = alert.tags
for(String tag: tags){
if(tag.startsWith(JIRA_ISSUE_KEY_PREFIX)){
return tag.substring(JIRA_ISSUE_KEY_PREFIX.size())
}
}
return null
}
def _conf(confKey, boolean isMandatory = true) {
def confVal = conf[CONF_PREFIX + confKey]
logger.debug("confVal ${CONF_PREFIX + confKey} from file is ${confVal}");
if (isMandatory && confVal == null) {
def errorMessage = "${LOG_PREFIX} Skipping action, Mandatory Conf item ${CONF_PREFIX + confKey} is missing. Check your marid conf file.";
logger.warn(errorMessage);
throw new Exception(errorMessage);
}
return confVal
}
def createHttpClient() {
def timeout = _conf("request.timeout", false);
if (timeout == null) {
timeout = 30000;
} else {
timeout = timeout.toInteger();
}
ClientConfiguration clientConfiguration = new ClientConfiguration().setSocketTimeout(timeout)
return new OpsGenieHttpClient(clientConfiguration)
}
######################################## JIRA CONFIGURATION #######################################
jira.username=username
jira.password=password
jira.basepath=/rest/api/latest
jira.protocol=https
jira.host=your_account.atlassian.net
jira.port=443
jira.request.timeout=10000
## Set your alert tag to project key mappings here.
## These values are used to determine a JIRA project
## at which an issue will be created for the new alert.
## The following mappings (and the default key) are provided as examples.
jira.project.paymentService=PAYM
jira.project.authenticationService=AUTH
## If alert tags does not match any of the configurations above,
## the following configuration will be used for the default project key.
jira.default.project.key=DEF
######################################## JIRA INTEGRATION - ALERT ACTION CONFIGURATION ######################
actions.Create.script=jiraActionExecutor.groovy
actions.AddNote.script=jiraActionExecutor.groovy
actions.Acknowledge.script=jiraActionExecutor.groovy
actions.Close.script=jiraActionExecutor.groovy
actions.Delete.script=jiraActionExecutor.groovy
@radupopa2010
Copy link

Hello,

I'm trying to use Marid to create issues into Jira from OpsGenie and I'm getting the error from below.
Is there a newer version of those scripts where it's fixed?

marid_1_f6e91abc84ef | 18/12/14 14:15:03.731 WARN: [Create]: Will execute action for alertId 3a09c725-a24c-487c-80c7-c6f402807697-1544796903081
marid_1_f6e91abc84ef | 18/12/14 14:15:04.568 WARN: Exception occurred while executing script [jiraActionExecutor.groovy]. Reason: com.fasterxml.jackson.databind.JsonMappingException: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String (through reference chain: com.opsgenie.oas.sdk.model.AddTagsToAlertPayload["tags"]->java.util.ArrayList[0])
marid_1_f6e91abc84ef | javax.ws.rs.ProcessingException: com.fasterxml.jackson.databind.JsonMappingException: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String (through reference chain: com.opsgenie.oas.sdk.model.AddTagsToAlertPayload["tags"]->java.util.ArrayList[0])
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:287)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:684)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:681)
marid_1_f6e91abc84ef | at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
marid_1_f6e91abc84ef | at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
marid_1_f6e91abc84ef | at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
marid_1_f6e91abc84ef | at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:681)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:437)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:343)
marid_1_f6e91abc84ef | at com.opsgenie.oas.sdk.ApiClient.invokeAPI(ApiClient.java:680)
marid_1_f6e91abc84ef | at com.opsgenie.oas.sdk.api.AlertApi.addTags(AlertApi.java:353)
marid_1_f6e91abc84ef | at com.ifountain.opsgenie.client.script.util.ScriptProxy.addTags(ScriptProxy.java:141)
marid_1_f6e91abc84ef | at com.ifountain.opsgenie.client.script.util.ScriptProxy$addTags.call(Unknown Source)
marid_1_f6e91abc84ef | at jiraActionExecutor.createJiraIssue(jiraActionExecutor.groovy:76)
marid_1_f6e91abc84ef | at jiraActionExecutor$createJiraIssue.callCurrent(Unknown Source)
marid_1_f6e91abc84ef | at jiraActionExecutor.run(jiraActionExecutor.groovy:18)
marid_1_f6e91abc84ef | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
marid_1_f6e91abc84ef | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
marid_1_f6e91abc84ef | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
marid_1_f6e91abc84ef | at java.lang.reflect.Method.invoke(Method.java:498)
marid_1_f6e91abc84ef | at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
marid_1_f6e91abc84ef | at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
marid_1_f6e91abc84ef | at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1054)
marid_1_f6e91abc84ef | at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1110)
marid_1_f6e91abc84ef | at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:884)
marid_1_f6e91abc84ef | at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:704)
marid_1_f6e91abc84ef | at groovy.lang.GroovyObjectSupport.invokeMethod(GroovyObjectSupport.java:44)
marid_1_f6e91abc84ef | at groovy.lang.Script.invokeMethod(Script.java:78)
marid_1_f6e91abc84ef | at com.ifountain.opsgenie.client.script.GroovyCompiledScriptEngine.doRun(GroovyCompiledScriptEngine.java:21)
marid_1_f6e91abc84ef | at com.ifountain.opsgenie.client.script.AbstractCompiledScriptEngine.runScript(AbstractCompiledScriptEngine.java:30)
marid_1_f6e91abc84ef | at com.ifountain.opsgenie.client.script.ScriptManager.runScript(ScriptManager.java:62)
marid_1_f6e91abc84ef | at com.ifountain.opsgenie.client.marid.alert.AlertActionUtils.executeActionScript(AlertActionUtils.java:43)
marid_1_f6e91abc84ef | at com.ifountain.opsgenie.client.marid.alert.PubnubAlertActionListener.processMessage(PubnubAlertActionListener.java:163)
marid_1_f6e91abc84ef | at com.ifountain.opsgenie.client.marid.alert.PubnubAlertActionListener$2$1$1.run(PubnubAlertActionListener.java:99)
marid_1_f6e91abc84ef | at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
marid_1_f6e91abc84ef | at java.util.concurrent.FutureTask.run(FutureTask.java:266)
marid_1_f6e91abc84ef | at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
marid_1_f6e91abc84ef | at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
marid_1_f6e91abc84ef | at java.lang.Thread.run(Thread.java:745)
marid_1_f6e91abc84ef | Caused by: com.fasterxml.jackson.databind.JsonMappingException: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String (through reference chain: com.opsgenie.oas.sdk.model.AddTagsToAlertPayload["tags"]->java.util.ArrayList[0])
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:388)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:360)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:369)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ser.impl.IndexedStringListSerializer.serializeContents(IndexedStringListSerializer.java:125)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ser.impl.IndexedStringListSerializer.serialize(IndexedStringListSerializer.java:79)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ser.impl.IndexedStringListSerializer.serialize(IndexedStringListSerializer.java:21)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1419)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:940)
marid_1_f6e91abc84ef | at com.fasterxml.jackson.jaxrs.base.ProviderBase.writeTo(ProviderBase.java:618)
marid_1_f6e91abc84ef | at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
marid_1_f6e91abc84ef | at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
marid_1_f6e91abc84ef | at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
marid_1_f6e91abc84ef | at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.ClientRequest.doWriteEntity(ClientRequest.java:517)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:499)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:393)
marid_1_f6e91abc84ef | at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285)
marid_1_f6e91abc84ef | ... 40 more
marid_1_f6e91abc84ef | Caused by: java.lang.ClassCastException: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String
marid_1_f6e91abc84ef | at com.fasterxml.jackson.databind.ser.impl.IndexedStringListSerializer.serializeContents(IndexedStringListSerializer.java:117)
marid_1_f6e91abc84ef | ... 57 more
marid_1_f6e91abc84ef | 18/12/14 14:15:04.573 WARN: [PubnubAlertActionListener]: Could not process message {"alert":"{"alertId":"3a09c725-a24c-487c-80c7-c6f402807697-1544796903081","message":"marcelo","tags":[],"tinyId":"2627","source":"","entity":"","alias":"3a09c725-a24c-487c-80c7-c6f402807697-1544796903081","createdAt":1544796903081,"updatedAt":1544796903332000000,"username":"","userId":"b2c4dc89-6916-4b90-8a2e-bb94a2a5406e","userFullName":"Marcelo Veglienzone","description":"","team":"SRE_DSM","recipients":[],"oldTeams":[],"teams":["1a736563-8600-4f83-9d83-1bf1f5307035"],"teamsForVisibility":["1a736563-8600-4f83-9d83-1bf1f5307035"],"actions":[],"extraProperties":{},"insertedAt":1544796903162000000,"tag":[],"details":{},"priority":"P3"}","action":"Create","source":"{"name":"","type":"web"}"}Reason: Exception occurred while executing script [jiraActionExecutor.groovy]. Reason: com.fasterxml.jackson.databind.JsonMappingException: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String (through reference chain: com.opsgenie.oas.sdk.model.AddTagsToAlertPayload["tags"]->java.util.ArrayList[0])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment