Skip to content

Commit

Permalink
Add some documentation
Browse files Browse the repository at this point in the history
Remove http support at request of pagerduty guys
Add a grab_oncall.py script to grab oncall for a specified time period.
Change README to rst to PyPi and github will both use it.
  • Loading branch information
gmjosack committed Dec 16, 2012
1 parent 55d6ab9 commit 96a9d4b
Show file tree
Hide file tree
Showing 7 changed files with 230 additions and 23 deletions.
1 change: 0 additions & 1 deletion .gitignore
Expand Up @@ -10,7 +10,6 @@ dist
build
eggs
parts
bin
var
sdist
develop-eggs
Expand Down
2 changes: 1 addition & 1 deletion MANIFEST.in
@@ -1,2 +1,2 @@
include LICENSE
include README.md
include README.rst
15 changes: 0 additions & 15 deletions README.md

This file was deleted.

90 changes: 90 additions & 0 deletions README.rst
@@ -0,0 +1,90 @@
=========
Pygerduty
=========

Python Library for PagerDuty's v1 REST API.

This library is currently evolving and backwards compatibility cannot always be guaranteed at this time.


Installation
============

You can install with ``pip install pygerduty``.

If you want to install from source, then ``python setup.py install``.


Requirements
============

Pygerduty is tested against >= Python 2.5

``simplejson`` is required on Python2.5


Documentation
=============

Pygerduty is a thin wrapper around PagerDuty's APIs. You will need to refer
to the the `PagerDuty Documentation <http://developer.pagerduty.com/>`_ for
all available parameters to pass and all available attributes on responses.

The main methods available to resources are list, show, create, update, and
delete. Not all resources have endpoints for all of the above methods. Again,
refer to the `PagerDuty Documentation <http://developer.pagerduty.com/>`_ to
see all available endpoints.

Top level resources will be accessible via the PagerDuty object and nested
resources available on containers returned from their parent resource.


Examples
========

Instantiating a client:

::

import pygerduty
pager = pygerduty.PagerClient("foobar", "SOMEAPIKEY123456")

Listing a resource:

::

for schedule in pager.schedules.list():
print schedule.id, schedule.name

# PX7F8S3 Primary
# PJ48C0S Tertiary
# PCJ94SK Secondary

Getting a resource by ID:

::

schedule = pager.schedules.show("PX7F8S3")

Creating a resource:

::

user = pager.users.list(query="gary")[0]
override = schedule.overrides.create(
start="2012-12-16", end="2012-12-17", user_id=user.id)

Delete a resource:

::

schedule.overrides.delete(override.id)


Updating a resource:

::

pagerduty.users.update(user.id, name="Gary Example")


134 changes: 134 additions & 0 deletions bin/grab_oncall.py
@@ -0,0 +1,134 @@
#!/usr/bin/env python

import datetime
import getpass
import optparse
import pygerduty
import re
import sys

TIME_STRING_RE = re.compile(
r'(?:(?P<days>\d+)d)?'
r'(?:(?P<hours>\d+)h)?'
r'(?:(?P<minutes>\d+)m)?'
r'(?:(?P<seconds>\d+)s)?'
)


def parse_time_string(time_string):
times = TIME_STRING_RE.match(time_string).groupdict()
for key, value in times.iteritems():
if value is None:
times[key] = 0
else:
times[key] = int(value)

return times


def get_times(time_string):
times = parse_time_string(time_string)

now = datetime.datetime.utcnow()
then = datetime.timedelta(**times)

return isoformat(now), isoformat(now + then)


def isoformat(dtime):
return "%sZ" % dtime.isoformat()


def format_overrides(overrides):
output = []
format_str = "%-10s%-28s%-28s%-20s"
output.append(format_str % ("ID:", "Start:", "End:", "User:"))
for override in overrides:
output.append(format_str % (
override.id, override.start, override.end, override.user.name))
return "\n".join(output)


def print_overrides(schedule):
now = datetime.datetime.utcnow()
since = isoformat(now)
until = isoformat(now + datetime.timedelta(hours=2))
overrides = schedule.overrides.list(
editable=True, overflow=True, since=since, until=until)
if not overrides:
print "No Editable Overrides."
sys.exit(1)
print format_overrides(overrides)


def main():
parser = optparse.OptionParser()

parser.add_option("--list", default=False, action="store_true",
help="List editable overrides.")
parser.add_option("--remove", default=None,
help="Remove <id> from list of overrides.")

parser.add_option("--user", default=getpass.getuser(),
help="User to create the override for.")
parser.add_option("--schedule", default=None,
help="Schedule to add the override to.")
parser.add_option("--api_key", default=None,
help="Schedule to add the override to.")
parser.add_option("--subdomain", default=None,
help="Schedule to add the override to.")

options, args = parser.parse_args()

time_string = None
if len(args) >= 1:
time_string = args[0]

required_options = [options.subdomain, options.api_key, options.schedule]
if not all(required_options):
parser.print_help()
sys.exit(1)

if not any([time_string, options.list, options.remove]):
print "Please provide either a time_string, --list, or --remove"
parser.print_help()
sys.exit(1)

if (time_string and
any([options.list, options.remove]) or
all([options.list, options.remove])):

print "Please provide a single time string argument",
print "OR action option (--list, --remove)."
parser.print_help()
sys.exit(1)

pager = pygerduty.PagerDuty(options.subdomain, options.api_key)

users = pager.users.list(query="%s" % options.user)
if len(users) != 1:
print "Expected 1 user. Found (%s)" % len(users)
sys.exit(1)
uid = users[0].id

schedules = pager.schedules.list(query=options.schedule)
if len(schedules) != 1:
print "Expected 1 schedule. Found (%s)" % len(schedules)
sys.exit(1)
schedule = schedules[0]

if time_string:
now, then = get_times(time_string)
schedule.overrides.create(start=now, end=then, user_id=uid)
print "Override created."
elif options.list:
print_overrides(schedule)
elif options.remove:
schedule.overrides.delete(options.remove)
print "Removed Override."
else:
parser.print_help()
sys.exit(1)

if __name__ == "__main__":
main()
8 changes: 3 additions & 5 deletions pygerduty.py
Expand Up @@ -9,7 +9,7 @@


__author__ = "Gary M. Josack <gary@dropbox.com>"
__version__ = "0.11"
__version__ = "0.12"


# TODO:
Expand Down Expand Up @@ -307,13 +307,11 @@ def __init__(self, *args, **kwargs):


class PagerDuty(object):
def __init__(self, subdomain, api_token, secure=True, timeout=10):
def __init__(self, subdomain, api_token, timeout=10):
self.subdomain = subdomain
self.api_token = api_token
self.secure = secure
self._proto = "https" if secure else "http"
self._host = "%s.pagerduty.com" % subdomain
self._api_base = "%s://%s/api/v1/" % (self._proto, self._host)
self._api_base = "https://%s/api/v1/" % self._host
self.timeout = timeout

# Collections
Expand Down
3 changes: 2 additions & 1 deletion setup.py
Expand Up @@ -4,8 +4,9 @@

kwargs = {
"name": "pygerduty",
"version": "0.11",
"version": "0.12",
"py_modules": ["pygerduty"],
"scripts": ["bin/grab_oncall.py"],
"description": "Python Client Library for PagerDuty's REST API",
"author": "Gary M. Josack",
"maintainer": "Gary M. Josack",
Expand Down

0 comments on commit 96a9d4b

Please sign in to comment.