GithubHelp home page GithubHelp logo

dikhan / pagerduty-client Goto Github PK

View Code? Open in Web Editor NEW
23.0 5.0 26.0 274 KB

Simple PagerDuty client with full integration with PagerDuty Events APIs v2

Home Page: https://dikhan.github.io/pagerduty-client/

License: MIT License

Java 97.01% Shell 2.99%
pagerduty-events pagerduty-apis pagerduty-client pagerduty java pagerduty-utils

pagerduty-client's Introduction

PagerDuty Events Client for Java Build Status

PagerDuty Events Client aims to provide a full-fledged Java client which is easy to use and integrates seamlessly with PagerDuty Events API v2. Note that the library does not integrate with PagerDuty REST Api - it is only meant for PagerDuty Events API v2. Please refer to the following link to see the differences between PagerDuty REST API and Events API:

What is the difference between PagerDuty APIs? PagerDuty APIs: Events API and REST API Using the Events API V2 to send events to PagerDuty

License | version | Build Status

Getting started

PagerDutyEventsClient is really easy to create. The static method exposed with no parameters will create a new client which internally will default the API calls to PagerDuty Events API (events.pagerduty.com). Please note that as per PagerDUty Events documentation there is no need to use an ApiAccessKey to make calls to the events API - the service token is sufficient to trigger/acknowledge/resolve incidents.

An example on how to create the clients is as follows:

PagerDutyEventsClient pagerDutyEventsClient = PagerDutyEventsClient.create();

The library supports the creation of Alert and Change type events. For your reference, below are examples on how to create each incident type as well as how to use PagerDutyEventsClient to perform the according operation.

Alert events

Alert type events are used to notify a problem in a machine monitored system using the trigger event. Follow up events can be sent to acknowledge or resolve an existing alert.

Examples of these alerts may include high error rate, CPU usage exceeded limit, deployment failed, etc.

Trigger:

This will send a new 'trigger' incident to PagerDuty's Alert Events Endpoint containing the details specified in the IncidentBuilder. A helper IncidentBuilder is provided for the sake of simplicity to ease with the creation of trigger incidents. The trigger event requires two mandatory parameters:

  • routingKey: The GUID of one of your "Generic API" services. This is the "Integration Key" listed on a Generic API's service detail page.
  • payload: The payload class contains mandatory fields that are required to trigger an event. See below to see how to construct payload field.

More details can be provided to the incident as previously mentioned by calling the available methods offered by the IncidentBuilder.

Payload:

The PagerDuty Events API v2 requires that every incident to contain a payload structure, though payload is only supported for trigger incident. The Payload can be created similar to other trigger using a builder. Below contains a list of mandatory fields to build a payload instance.

  • summary: A brief text summary of the event, used to generate the summaries/titles of any associated alerts.
  • source: The unique location of the affected system, preferably a hostname or FQDN.
  • severity: The perceived severity of the status the event is describing with respect to the affected system. This can be Severity.CRTICAL, Severity.ERROR, Severity.WARNING, or Severity.INFO.

More details can be provided to the payload by calling the available methods offered by the Payload builder.

Payload payload = Payload.Builder.newBuilder()
        .setSummary("Summary of this incident")
        .setSource("testing host")
        .setSeverity(Severity.INFO)
        .setTimestamp(OffsetDateTime.now())
        .build();

TriggerIncident incident = TriggerIncident.TriggerIncidentBuilder
        .newBuilder("ROUTING_KEY", payload)
        .setDedupKey("DEDUP_KEY")
        .build();
pagerDutyEventsClient.trigger(incident);

Acknowledge:

This will send a new acknowledge incident to PagerDuty based upon the 'routingKey' and 'dedupKey' provided. Please note that PagerDuty does not support payload added to the acknowledge event, so by default, filler context will be used to popular the payload instance.

AcknowledgeIncident ack = AcknowledgeIncident.AcknowledgeIncidentBuilder
        .newBuilder("ROUTING_KEY", "DEDUP_KEY")
        .build();
pagerDutyEventsClient.acknowledge(ack);

Resolve:

This will send a new resolve incident to PagerDuty based upon the 'service_key' and 'dedup_key' provided. Payload is also not supported by resolve incident.

ResolveIncident resolve = ResolveIncident.ResolveIncidentBuilder
        .newBuilder("ROUTING_KEY", "DEDUP_KEY")
        .build();
pagerDutyEventsClient.resolve(resolve);

Change events

Change type events are used to notify a change in a system that does not represent a problem.

Examples may include a pull request merged, secret successfully rotated, configuration update applied, etc.

Track:

This will send a change event to PagerDuty's Change Events Endpoint and associate it with the corresponding service based on the "ROUTING_KEY" provided and including the information specified in the change event payload.

ChangeEventPayload changeEventPayload = ChangeEventPayload.Builder.
        newBuilder()
        .setSummary("Pull request merged")
        .setTimestamp(OffsetDateTime.now())
        .setCustomDetails(new JSONObject("{\"build_state\":\"passed\",\"build_number\":\"2\",\"run_time\":\"1236s\"}"))
        .build();

ChangeEvent changeEvent = ChangeEvent.ChangeEventBuilder
        .newBuilder("ROUTING_KEY", changeEventPayload)
        .build();
pagerDutyEventsClient.trackChange(changeEvent);

Integration:

PagerDuty Events Api v2 client

PagerDuty Events Client can be easily integrated in other projects by adding the following snippet to the pom:

<dependency>
  <groupId>com.github.dikhan</groupId>
  <artifactId>pagerduty-client</artifactId>
  <version>3.0.0</version>
</dependency>

The library uses SL4J facade for logging purposes. Thus, making it fully flexible for integration with other projects whereby a specific logging implementation is already being used (e,g: log4j, logback, etc).

Snapshots of dev versions can be found at oss.sonatype.org

PagerDuty Events Api v1 client

This library has evolved from supporting PagerDuty Events v1 api to support PagerDuty Events v2 in the most recent release. If you are interested in integrating with PagerDuty Events v1 you can still do so by using the last release version that supported v1:

<dependency>
  <groupId>com.github.dikhan</groupId>
  <artifactId>pagerduty-client</artifactId>
  <version>2.0.4</version>
</dependency>

Please refer to the following tag for more information about the release: pagerduty-client-2.0.4

For more information about the differentes between the different PagerDuty Events Apis refer to the following link: PagerDuty APIs: Events API and REST API

Contributing

  • Fork it!
  • Create your feature branch: git checkout -b my-new-feature
  • Commit your changes: git commit -am 'Add some feature'
  • Push to the branch: git push origin my-new-feature
  • Submit a pull request :D

Authors

Daniel I. Khan Ramiro - Cisco Systems

See also the list of contributors who participated in this project.

Acknowledgements:

pagerduty-client's People

Contributors

adamvaughan avatar bot-devuxteam avatar dependabot[bot] avatar dikhan avatar fabiim avatar kentwang929 avatar luis-filipe-almeida-santos avatar shawnduxy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

pagerduty-client's Issues

Annotation error thrown in Scala 2.12

FYI -

[error] While parsing annotations in /com/github/dikhan/pagerduty-client/3.0.2/pagerduty-client-3.0.2.jar(com/github/dikhan/pagerduty/client/events/domain/Incident.class), could not find NON_NULL in enum object Include.
[error] This is likely due to an implementation restriction: an annotation argument cannot refer to a member of the annotated class (SI-7014).

SI-7014 is - https://issues.scala-lang.org/browse/SI-7014

Possible this is caused by various collisions of class versions and needing to shade one or the other. But, this is the default behavior I am getting without doing finicky configurations.

Proxy Support

Hello,

I'm not sure if it's the right place where to fill the issue but let's go..

I setup the Jenkins PagerDuty plugin where Jenkins is running behind a proxy.

Jenkins is started with the following JVM args:

java -Dhttp.proxyHost=xxx -Dhttp.proxyPort=8080 -Dhttps.proxyHost=xxxx -Dhttps.proxyPort=xxx

But when the job trigger the pagerduty plugin, which use the current library, I have the following exception:

events.pagerduty.com/54.245.165.68] failed: Connection refused (Connection refused)
	at com.github.dikhan.HttpApiServiceImpl.notifyEvent(HttpApiServiceImpl.java:52)
	at com.github.dikhan.PagerDutyEventsClient.trigger(PagerDutyEventsClient.java:78)
	at org.jenkinsci.plugins.pagerduty.util.PagerDutyUtils.triggerPagerDuty(PagerDutyUtils.java:106)
	at org.jenkinsci.plugins.pagerduty.PagerDutyTrigger.perform(PagerDutyTrigger.java:217)
	at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
	at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:744)
	at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:690)
	at hudson.model.Build$BuildExecution.post2(Build.java:186)
	at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:635)
	at hudson.model.Run.execute(Run.java:1752)
	at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
	at hudson.model.ResourceController.execute(ResourceController.java:97)
	at hudson.model.Executor.run(Executor.java:429)

So I'm wondering if it's the expected behavior, and if there a way to setup a proxy on this lib

Cheers

FakePagerDutyEventsClient - Status returned doesn't match PagerDuty API

From what i can tell PagerDuty Events API V2 will always return success if everything was ok.

When using FakePagerDutyEventsClient in a test i instead received success-trigger.

return EventResult.successEvent("success-" + incident.getEventAction().getEventType(), "Event processed", incident.getDedupKey());

Can this be changed to match PagerDuty API?

Regards,
Andreas

Fix potential security vulnerabilities com.fasterxml.jackson.core:jackson-databind

Update jackson-databind artifact version to 2.8.11.1 as suggested by GitHub after finding potential security vulnerabilities:

Remediation
Upgrade com.fasterxml.jackson.core:jackson-databind to version 2.8.11.1 or later. For example:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>[2.8.11.1,)</version>
</dependency>

Details:

CVE-2017-17485 (high severity)
Vulnerable versions: < 2.8.11
Patched version: 2.8.11
FasterXML jackson-databind through 2.8.10 and 2.9.x through 2.9.3 allows unauthenticated remote code execution because of an incomplete fix for the CVE-2017-7525 deserialization flaw. This is exploitable by sending maliciously crafted JSON input to the readValue method of the ObjectMapper, bypassing a blacklist that is ineffective if the Spring libraries are available in the classpath.

CVE-2017-15095 (high severity)
Vulnerable versions: < 2.8.11
Patched version: 2.8.11
A deserialization flaw was discovered in the jackson-databind in versions before 2.8.10 and 2.9.1, which could allow an unauthenticated user to perform code execution by sending the maliciously crafted input to the readValue method of the ObjectMapper. This issue extends the previous flaw CVE-2017-7525 by blacklisting more classes that could be used maliciously.

CVE-2018-7489 (high severity)
Vulnerable versions: < 2.8.11.1
Patched version: 2.8.11.1
FasterXML jackson-databind before 2.8.11.1 and 2.9.x before 2.9.5 allows unauthenticated remote code execution because of an incomplete fix for the CVE-2017-7525 deserialization flaw. This is exploitable by sending maliciously crafted JSON input to the readValue method of the ObjectMapper, bypassing a blacklist that is ineffective if the c3p0 libraries are available in the classpath.

CVE-2017-7525 (high severity)
Vulnerable versions: >= 2.8.0, < 2.8.9
Patched version: 2.8.9
A deserialization flaw was discovered in the jackson-databind, versions before 2.6.7.1, 2.7.9.1 and 2.8.9, which could allow an unauthenticated user to perform code execution by sending the maliciously crafted input to the readValue method of the ObjectMapper.

Handle the cases where the asynchronous Events API return 201/202 responses

Talked to PagerDuty support earlier today and got the following response:

The reason you will sometimes get something other than a 200 response code is because the Events API is asynchronous. It sends back a response immediately, so if it is still processing or it hasn’t been completed yet, it may send back a 201 or a 202 response.

Currently HttpApiServiceImpl only looks for 200 so it needs some minor changes

A JSONArray text must start with '[' at 1 [character 2 line 1]

We are using the client to submit a trigger using the following code:

 
            Payload payload = Payload.Builder.newBuilder()
                    .setSummary(createSummary(operation))
                    .setSource(operation.getAttribute().getId())
                    .setComponent(IdManager.getAncestorId(IdManager.Service.NODE_NODE, operation.getAttribute().getId()))
                    .setGroup(IdManager.getAncestorId(IdManager.Service.NODE_ECU, operation.getAttribute().getId()))
                    .setSeverity(convertHealthToSeverity(operation.getAttribute().getHealth()))
                    .setTimestamp(OffsetDateTime.ofInstant(Instant.ofEpochSecond(operation.getTimestamp()), ZoneOffset.UTC))
                    .setCustomDetails(Json.writeValueToString(operation.getAttribute()))
                    .build();

            TriggerIncident incident = TriggerIncident.TriggerIncidentBuilder
                    .newBuilder(routingKey, payload)
                    .setDedupKey(operation.getAttribute().getId())
                    .setClient(client)
                    .build();
                    
           this.client.trigger(incident);    

The serialized incident as a json looks like this:

{
    "client":"--removed_for_security--",
    "dedup_key":"cu3fbbe4-ne30773e-nnd17182-na11f804",
    "event_action":"trigger",
    "payload":{
       "component":"cu3fbbe4-ne30773e-nnd17182",
       "custom_details":"{\"ecuId\":\"cu3fbbe4-ne30773e\",\"health\":500,\"id\":\"cu3fbbe4-ne30773e-nnd17182-na11f804\",\"nodeId\":\"cu3fbbe4-ne30773e-nnd17182\",\"projectId\":\"cu3fbbe4-np932c1d\",\"read\":{\"type\":\"STRING\"},\"reference\":\"s1_server_disconnected_on_system_initialisation_alarm!\",\"value\":\"Critical\"}",
       "group":"cu3fbbe4-ne30773e",
       "severity":"critical",
       "source":"cu3fbbe4-ne30773e-nnd17182-na11f804",
       "summary":"The value of 's1_server_disconnected_on_system_initialisation_alarm' changed to Critical",
       "timestamp":"2022-07-29T13:45:32Z"
    },
    "routing_key":"--removed_for_security--"
 }

However, we are unexpectedly getting the following error:

com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException: com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]

Screenshot 2022-07-29 at 16 06 36

Any ideas?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.