Skip to content

Commit

Permalink
Events v2 (#4)
Browse files Browse the repository at this point in the history
Completed implementation for EventsAPI V2
  • Loading branch information
adilbaig authored Sep 14, 2018
1 parent 788fb52 commit 177e016
Show file tree
Hide file tree
Showing 6 changed files with 218 additions and 133 deletions.
98 changes: 61 additions & 37 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,55 +1,59 @@
PHP PagerDuty Events API
=========
PHP implementation of the [PagerDuty Events API](https://v2.developer.pagerduty.com/v2/docs/events-api)
PHP implementation of the [PagerDuty Events API V2](https://v2.developer.pagerduty.com/docs/events-api-v2)

**Important**: v2 is a complete rewrite of the library. It is not backwards compatible with v1.

For all new projects i suggest using v2. It is more flexible and easier to use than v1, and overcomes some of its predecessor's design limitations.
UPGRADE NOTICE
---
The [Events API V2](https://v2.developer.pagerduty.com/docs/events-api-v2) is **not backwards compatible** with the [Events API V1](https://v2.developer.pagerduty.com/docs/events-api). Hence, this API has changed. If you are upgrading from a [2.* release](https://github.com/adilbaig/pagerduty/releases), make sure you pay attention to the contructor of the `TriggerEvent`

[![Latest Stable Version](https://poser.pugx.org/adilbaig/pagerduty/v/stable.svg)](https://packagist.org/packages/adilbaig/pagerduty) [![Total Downloads](https://poser.pugx.org/adilbaig/pagerduty/downloads.svg)](https://packagist.org/packages/adilbaig/pagerduty)

Features :
----
Features
---

- Compatible with [PD Events API V2](https://v2.developer.pagerduty.com/v2/docs/#the-events-api).
- Trigger, acknowledge and resolve incidents.
- Support for [Event contexts](https://v2.developer.pagerduty.com/v2/docs/trigger-events#contexts).
- Works with [Events API V1](https://v2.developer.pagerduty.com/v2/docs/#the-events-api).
- Supports [Event contexts](https://v2.developer.pagerduty.com/v2/docs/trigger-events#contexts). Attach links and images to your incident reports.
- Unit Tests


Installation :
----
Installation
---
Add this line to your project's `composer.json`
````
{
...
"require": {
"adilbaig/pagerduty": "2.*"
"adilbaig/pagerduty": "3.*"
}
...
}
````

The packagist URL is https://packagist.org/packages/adilbaig/pagerduty

Usage:
----
Usage
---

Trigger an event

````php
use \PagerDuty\TriggerEvent;
use \PagerDuty\PagerDutyException;

$serviceKey = "1d334a4819fc4b67a795b1c54f9a"; //Replace this with the integration key of your service.
$routingKey = "1d334a4819fc4b67a795b1c54f9a"; //Replace this with the integration key of your service.

// In this example, we're triggering a "Service is down" message.
// In this example, we're triggering a "Service is down" message from a web server.
try {
$responseCode = (new TriggerEvent($serviceKey, "Service is down"))->send();
$event = new TriggerEvent($routingKey, "Service is down", "web-server-01", TriggerEvent::ERROR, true);
$responseCode = $event->send();
if($responseCode == 200)
echo "Success";
elseif($responseCode == 403)
elseif($responseCode == 429)
echo "Rate Limited"; //You're being throttled. Slow down.
else // An error occured. Try again later
echo "Some error has occured. Try again later";
} catch(PagerDutyException $exception) { //This doesn't happen unless you've broken their guidelines. The API tries to minimize user mistakes
var_dump($exception->getErrors());
}
Expand All @@ -60,53 +64,73 @@ Automatically send only one PagerDuty incident for repeated errors

````php

//After this example, you will see just one incident on PD

(new TriggerEvent($serviceKey, "Service is down", true))->send();
(new TriggerEvent($serviceKey, "Service is down", true))->send();
(new TriggerEvent($serviceKey, "Service is down", true))->send();
//You will only see one incident on PD
(TriggerEvent($routingKey, "Service is down", "web-server-01", TriggerEvent::ERROR, true))->send();
(TriggerEvent($routingKey, "Service is down", "web-server-01", TriggerEvent::ERROR, true))->send();
(TriggerEvent($routingKey, "Service is down", "web-server-01", TriggerEvent::ERROR, true))->send();

````

Create a detailed 'trigger' event, add optional data. Dump the event and inspect
response from PD
Create a detailed 'trigger' event, add optional data. Dump the event and inspect response from PD

````php
use \PagerDuty\TriggerEvent;
use \PagerDuty\Context\LinkContext;
use \PagerDuty\Context\ImageContext;

//Taken from the `trigger` example @ https://v2.developer.pagerduty.com/v2/docs/trigger-events
//Taken from the `trigger` example @ https://v2.developer.pagerduty.com/docs/send-an-event-events-api-v2
//Send a detailed event, and store the `dedup_key` generated on the server

$event = new TriggerEvent($serviceKey, "FAILURE for production/HTTP on machine srv01.acme.com");
$event = new TriggerEvent(
$routingKey,
"Example alert on host1.example.com",
"monitoringtool:cloudvendor:central-region-dc-01:852559987:cluster/api-stats-prod-003",
TriggerEvent::INFO
);
$event
->setClient("Sample Monitoring Service")
->setClientURL("https://monitoring.service.com")
->setDetails(["ping time" => "1500ms", "load avg" => 0.75])
->addContext(new LinkContext("http://acme.pagerduty.com"))
->addContext(new LinkContext("http://acme.pagerduty.com", "View the incident on PagerDuty"))
->addContext(new ImageContext("https://chart.googleapis.com/chart?chs=600x400&chd=t:6,2,9,5,2,5,7,4,8,2,1&cht=lc&chds=a&chxt=y&chm=D,0033FF,0,0,5,1"));
->setPayloadTimestamp("2015-07-17T08:42:58.315+0000")
->setPayloadComponent("postgres")
->setPayloadGroup("prod-datapipe")
->setPayloadClass("deploy")
->setPayloadCustomDetails(["ping_time" => "1500ms", "load_avg" => 0.75])
->addContext(new LinkContext("https://example.com/", "Link text"))
->addContext(new ImageContext("https://www.pagerduty.com/wp-content/uploads/2016/05/pagerduty-logo-green.png", "https://example.com/", "Example text"))
;

// Pass in the '$response' variable by reference if you want to inspect PD's response. This is optional, and you probably don't need this in production.
$response = null;
$responseCode = $event->send($response);
var_dump($response);
// In this case, we will save the `dedup_key` generated by the PD server
var_dump($response['dedup_key']);
````

Acknowledge an event
----

````php
(new AcknowledgeEvent($serviceKey, "incident key"))->send();
(new AcknowledgeEvent($routingKey, "dedup key"))->send();
````

Resolve an event

----
````php
(new ResolveEvent($serviceKey, "incident key"))->send();
(new ResolveEvent($routingKey, "dedup key"))->send();
````

UnitTests
---

````bash
> ./vendor/bin/phpunit test/
..... 5 / 5 (100%)

Time: 37 ms, Memory: 4.00MB

OK (5 tests, 6 assertions)
````

Questions
----
---

**Q.** How do i get the service key from PagerDuty?

Expand All @@ -115,7 +139,7 @@ Questions
Read more here : https://v2.developer.pagerduty.com/v2/docs/events-api#getting-started

Requirements
----
---
This library needs the [curl pecl extension](https://php.net/curl).

In Ubuntu 16.04, install it like so :
Expand Down
6 changes: 3 additions & 3 deletions src/PagerDuty/AcknowledgeEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
class AcknowledgeEvent extends Event
{

public function __construct($serviceKey, $incidentKey)
public function __construct($routingKey, $dedupKey)
{
parent::__construct($serviceKey, 'acknowledge');
parent::__construct($routingKey, 'acknowledge');

$this->setIncidentKey($incidentKey);
$this->setDeDupKey($dedupKey);
}
}
56 changes: 28 additions & 28 deletions src/PagerDuty/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

/**
* An abstract Event
*
*
* @author adil
*/
abstract class Event implements \ArrayAccess, \JsonSerializable
Expand All @@ -14,40 +14,40 @@ abstract class Event implements \ArrayAccess, \JsonSerializable

/**
* ctor
*
* @param string $serviceKey
* @param string $type - One of trigger, acknowledge or resolve
*
* @param string $routingKey
* @param string $type - One of 'trigger', 'acknowledge' or 'resolve'
*/
protected function __construct($serviceKey, $type)
protected function __construct($routingKey, $type)
{
$this->dict['service_key'] = (string) $serviceKey;
$this->dict['event_type'] = (string) $type;
$this->dict['routing_key'] = (string) $routingKey;
$this->dict['event_action'] = (string) $type;
}

/**
* A unique incident key to identify an outage.
* Multiple events with the same $incidentKey will be grouped into one open incident. From the PD docs :
*
* `Submitting subsequent events for the same incident_key will result in those events being applied to an open incident
* matching that incident_key. Once the incident is resolved, any further events with the same incident_key will
* create a new incident (for trigger events) or be dropped (for acknowledge and resolve events).`
*
* @link https://v2.developer.pagerduty.com/docs/events-api#incident-de-duplication-and-incident_key
*
* @param string $incidentKey
*
* A unique key to identify an outage.
* Multiple events with the same $key will be grouped into one open incident. From the PD docs :
*
* `Submitting subsequent events for the same `dedup_key` will result in those events being applied to an open alert
* matching that `dedup_key`. Once the alert is resolved, any further events with the same `dedup_key` will create a
* new alert (for `trigger` events) or be dropped (for `acknowledge` and `resolve` events).`
*
* @link https://v2.developer.pagerduty.com/docs/events-api-v2#alert-de-duplication
*
* @param string $key
*
* @return self
*/
public function setIncidentKey($incidentKey)
public function setDeDupKey($key)
{
$this->dict['incident_key'] = (string) $incidentKey;
$this->dict['dedup_key'] = substr((string) $key, 0, 255);
return $this;
}

/**
* Get the array
* Get the request json as an array
* Useful for debugging or logging.
*
*
* @return array
*/
public function toArray()
Expand All @@ -57,27 +57,27 @@ public function toArray()

/**
* Send the event to PagerDuty
*
*
* @param array $result (Opt)(Pass by reference) - If this parameter is given the result of the CURL call will be filled here. The response is an associative array.
*
*
* @throws PagerDutyException - If status code == 400
*
*
* @return int - HTTP response code
* 200 - Event Processed
* 202 - Event Processed
* 400 - Invalid Event. Throws a PagerDutyException
* 403 - Rate Limited. Slow down and try again later.
*/
public function send(&$result = null)
{
$jsonStr = json_encode($this);

$curl = curl_init("https://events.pagerduty.com/generic/2010-04-15/create_event.json");
$curl = curl_init("https://events.pagerduty.com/v2/enqueue");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonStr)
'Content-Length: ' . strlen($jsonStr),
));

$result = json_decode(curl_exec($curl), true);
Expand Down
6 changes: 3 additions & 3 deletions src/PagerDuty/ResolveEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
class ResolveEvent extends Event
{

public function __construct($serviceKey, $incidentKey)
public function __construct($routingKey, $dedupKey)
{
parent::__construct($serviceKey, 'resolve');
parent::__construct($routingKey, 'resolve');

$this->setIncidentKey($incidentKey);
$this->setDeDupKey($dedupKey);
}
}
Loading

0 comments on commit 177e016

Please sign in to comment.