Beispiel #1
0
    def __init__(self, subdomain='', api='', service_key=''):
        """Set up required vars."""
        self._subdomain = os.environ.get('PD_SUBDOMAIN', subdomain)
        self._api = os.environ.get('PD_API_TOKEN', api)
        self._service_key = os.environ.get('PD_SERVICE_KEY', service_key)

        self.pagerduty = pygerduty.PagerDuty(self._subdomain, self._api)
Beispiel #2
0
def alert_pagerduty(alert, metric):
    """
    Called by :func:`~trigger_alert` and sends an alert via PagerDuty
    """
    import pygerduty
    pager = pygerduty.PagerDuty(settings.PAGERDUTY_OPTS['subdomain'], settings.PAGERDUTY_OPTS['auth_token'])
    pager.trigger_incident(settings.PAGERDUTY_OPTS['key'], "Anomalous metric: %s (value: %s)" % (metric[1], metric[0]))
Beispiel #3
0
def actionPDTrigger(redata, jdata, logger):
    ''' Perform EC2 Actions '''
    try:
        pager = pygerduty.PagerDuty(
            redata['data']['subdomain'],
            redata['data']['api_key'])
        try:
            service_key=redata['data']['service_key']
            description=redata['data']['incident_description']
            details=redata['data']['details']
            incident_key=redata['data']['incident_key']

            # Should I test if incident_key is empty string or null?

            new_incident_key=pager.trigger_incident(service_key, description, incident_key, details)

            # What do I do with new_incident_key?

            return True
        except:
            return False
    except:
        line = "pagerduty-notification: Could not connect to PagerDuty for monitor %s" % jdata['cid']
        logger.info(line)
        return False
Beispiel #4
0
def alert_pagerduty(alert, metric):
    import pygerduty
    pager = pygerduty.PagerDuty(settings.PAGERDUTY_OPTS['subdomain'],
                                settings.PAGERDUTY_OPTS['auth_token'])
    pager.trigger_incident(
        settings.PAGERDUTY_OPTS['key'],
        "Anomalous metric: %s (value: %s)" % (metric[1], metric[0]))
 def set_service_maintenance(self,
                             message,
                             service_name=None,
                             interval=None):
     if not interval:
         interval = 1
     pager = pygerduty.PagerDuty(settings.PAGERDUTY_SUBDOMAIN,
                                 settings.PAGERDUTY_API_KEY)
     for service in pager.services.list(limit=50):
         if service.name == service_name:
             user = self._associate_pd_user(
                 self.get_hipchat_user(
                     message.sender['hipchat_id'])['email'], pager)
             if user is None:
                 self.reply(message,
                            "I couldn't find your user :(",
                            color="yellow")
                 return
             now = datetime.datetime.utcnow()
             start_time = now.strftime("%Y-%m-%dT%H:%MZ")
             end_time = (now + datetime.timedelta(hours=int(interval))
                         ).strftime("%Y-%m-%dT%H:%MZ")
             try:
                 pager.maintenance_windows.create(service_ids=[service.id],
                                                  requester_id=user.id,
                                                  start_time=start_time,
                                                  end_time=end_time)
                 self.reply(message, "Ok.")
             except pygerduty.BadRequest as e:
                 self.reply(message,
                            "Failed: %s" % e.message,
                            color="yellow")
def alert_pagerduty(datapoint, metric_name, expiration_time, metric_trigger, algorithm):
    if settings.PAGERDUTY_ENABLED:
        import pygerduty
        pager = pygerduty.PagerDuty(settings.BOUNDARY_PAGERDUTY_OPTS['subdomain'], settings.BOUNDARY_PAGERDUTY_OPTS['auth_token'])
        pager.trigger_incident(settings.BOUNDARY_PAGERDUTY_OPTS['key'], 'Anomalous metric: %s (value: %s) - %s' % (metric_name, datapoint, algorithm))
    else:
        return False
Beispiel #7
0
    def notify_users(self, group, event, fail_silently=False):
        if not self.is_configured(group.project):
            return

        api_key = self.get_option('api_key', group.project)
        domain_name = self.get_option('domain_name', group.project)
        service_key = self.get_option('service_key', group.project)
        description = event.message[:1024]
        details = {
            'event_id': event.event_id,
            'project': group.project.name,
            'release': event.get_tag('sentry:release'),
            'platform': event.platform,
            'culprit': event.culprit,
            'message': event.message,
            'datetime': event.datetime.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
            'time_spent': event.time_spent,
            'tags': dict(event.get_tags()),
            'url': group.get_absolute_url(),
        }

        client = pygerduty.PagerDuty(domain_name, api_key)
        client.trigger_incident(service_key,
                                description,
                                incident_key=group.id,
                                details=details,
                                client='sentry',
                                client_url=group.get_absolute_url())
Beispiel #8
0
def test_get_user():
    httpretty.register_uri(
        httpretty.GET,
        "https://contosso.pagerduty.com/api/v1/users/PIJ90N7",
        body=textwrap.dedent("""\
            {
              "user": {
                "avatar_url": "https://secure.gravatar.com/avatar/6e1b6fc29a03fc3c13756bd594e314f7.png?d=mm&r=PG",
                "color": "dark-slate-grey",
                "email": "*****@*****.**",
                "id": "PIJ90N7",
                "invitation_sent": true,
                "job_title": "Developer",
                "marketing_opt_out": true,
                "name": "Bart Simpson",
                "role": "admin",
                "time_zone": "Eastern Time (US & Canada)",
                "user_url": "/users/PIJ90N7"
              }
            }
            """),
        status=200)

    p = pygerduty.PagerDuty("contosso", "password")
    user = p.users.show("PIJ90N7")

    assert user.id == "PIJ90N7"
    assert user.name == "Bart Simpson"
    assert user.role == "admin"
Beispiel #9
0
def test_to_json_v1():
    p = pygerduty.PagerDuty("contosso", "password")
    collection = pygerduty.Collection(p)

    container1 = pygerduty.Container(collection, name='first')
    container2 = pygerduty.Container(collection, container=container1)

    assert {'container': {'name': 'first'}} == container2.to_json()
Beispiel #10
0
def test_unknown_subdomain():
    httpretty.register_uri(
        httpretty.GET, "https://contosso.pagerduty.com/api/v1/users/ABCDEFG",
        body='{"error":{"message":"Account Not Found","code":2007}}', status=404)

    p = pygerduty.PagerDuty("contosso", "password")

    with pytest.raises(pygerduty.NotFound):
        p.users.show("ABCDEFG")
Beispiel #11
0
    def post_process(self, group, event, is_new, is_sample, **kwargs):
        if not self.is_configured(group.project):
            return

        api_key = self.get_option('api_key', group.project)
        domain_name = self.get_option('domain_name', group.project)
        service_key = self.get_option('service_key', group.project)

        client = pygerduty.PagerDuty(domain_name, api_key)
        client.trigger_incident(service_key, event.message)
Beispiel #12
0
def alert_pagerduty(alert, metric, second_order_resolution_seconds):
    """
    Called by :func:`~trigger_alert` and sends an alert via PagerDuty
    """
    if settings.PAGERDUTY_ENABLED:
        import pygerduty
        pager = pygerduty.PagerDuty(settings.PAGERDUTY_OPTS['subdomain'], settings.PAGERDUTY_OPTS['auth_token'])
        pager.trigger_incident(settings.PAGERDUTY_OPTS['key'], "Mirage alert - %s - %s" % (metric[0], metric[1]))
    else:
        return False
Beispiel #13
0
def alert_pagerduty(alert, metric, context):
    """
    Called by :func:`~trigger_alert` and sends an alert via PagerDuty
    """
    if settings.PAGERDUTY_ENABLED:
        import pygerduty
        pager = pygerduty.PagerDuty(settings.PAGERDUTY_OPTS['subdomain'], settings.PAGERDUTY_OPTS['auth_token'])
        pager.trigger_incident(settings.PAGERDUTY_OPTS['key'], '%s alert - %s - %s' % (context, str(metric[0]), metric[1]))
    else:
        return
Beispiel #14
0
def send_to_pagerduty(token,
                      service_key,
                      description,
                      details=None,
                      client=None,
                      client_url=None):
    pager = pygerduty.PagerDuty("skypicker", api_token=token)
    pager.trigger_incident(service_key,
                           description,
                           details=details,
                           client=client,
                           client_url=client_url)
Beispiel #15
0
def _get_pager(profile):
    '''
    Return the pagerduty connection
    '''
    creds = __salt__['config.option'](profile)

    pager = pygerduty.PagerDuty(
        creds.get('pagerduty.subdomain'),
        creds.get('pagerduty.api_key'),
    )

    return pager
Beispiel #16
0
def test_get_user_v1():
    body = open('tests/fixtures/user_v1.json').read()
    httpretty.register_uri(
        httpretty.GET,
        "https://contosso.pagerduty.com/api/v1/users/PIJ90N7",
        body=body,
        status=200)

    p = pygerduty.PagerDuty("contosso", "password")
    user = p.users.show("PIJ90N7")

    assert user.id == "PIJ90N7"
    assert user.name == "Bart Simpson"
    assert user.role == "admin"
Beispiel #17
0
 def __new__(cls, settings):
     '''
     Cache base class
     Args:
         settings (object): pagerduty settings
     Returns:
         Pager (object): trigger incidents on pagerduty api
     '''
     if cls.pager is None:
         cls.settings = settings
         # api_token is not actually used for what we are doing, we don't
         # need to auth only send to the service_key below
         cls.pager = pygerduty.PagerDuty(cls.settings.PAGERDUTY_SUBDOMAIN, api_token='junk')
     return super(Pager, cls).__new__(cls)
Beispiel #18
0
def get_on_call_dev():
    """ Returns the username (gareth, ross, trevor) of the current on-call dev """
    pager = pygerduty.PagerDuty('tinker', os.environ['PAGERDUTY_API_KEY'])

    escalation_policies = pager.escalation_policies.on_call()
    default_policy = [p for p in escalation_policies if p.name == 'Default'][0]

    on_call_users = default_policy.on_call
    on_call = [u for u in on_call_users if u.level == 1][0]

    name = on_call.user.name
    first_name = name.split()[0]
    username = first_name.lower()

    return username
Beispiel #19
0
def test_loads_without_datetime():
    httpretty.register_uri(
        httpretty.GET, "https://acme.pagerduty.com/api/v1/incidents/PIJ90N7",
        body=INCIDENT_RESPONSE, status=200
    )

    pd = pygerduty.PagerDuty("acme", "password", parse_datetime=False)
    incident = pd.incidents.show("PIJ90N7")

    assert incident.last_status_change_on == "2012-12-22T00:35:22Z"
    assert incident.created_on == "2012-12-22T00:35:21Z"

    assert incident.assigned_to[0].at == "2012-12-22T00:35:21Z"

    assert incident.pending_actions[0].at == "2014-01-01T08:00:00Z"
    assert incident.pending_actions[1].at == "2014-01-01T10:00:00Z"
    assert incident.pending_actions[2].at == "2014-01-01T11:00:00Z"
Beispiel #20
0
def test_loads_with_datetime():
    httpretty.register_uri(
        httpretty.GET, "https://acme.pagerduty.com/api/v1/incidents/PIJ90N7",
        body=INCIDENT_RESPONSE, status=200
    )

    pd = pygerduty.PagerDuty("acme", "password", parse_datetime=True)
    incident = pd.incidents.show("PIJ90N7")

    assert incident.last_status_change_on == datetime.datetime(2012, 12, 22, 0, 35, 22)
    assert incident.created_on == datetime.datetime(2012, 12, 22, 0, 35, 21)

    assert incident.assigned_to[0].at == datetime.datetime(2012, 12, 22, 0, 35, 21)

    assert incident.pending_actions[0].at == datetime.datetime(2014, 1, 1, 8, 0)
    assert incident.pending_actions[1].at == datetime.datetime(2014, 1, 1, 10, 0)
    assert incident.pending_actions[2].at == datetime.datetime(2014, 1, 1, 11, 0)
Beispiel #21
0
 def __init__(self,
              subdomain,
              organization_token,
              default_svc_key,
              alert_footer=''):
     """
     :type subdomain: str
     :type organization_token: str
     :type default_svc_key: str
     :type alert_footer: str
     """
     self._log = logging.getLogger('pagerduty')
     self._pager = pygerduty.PagerDuty(subdomain,
                                       api_token=organization_token)
     self._org_token = organization_token
     self._default_svc_key = default_svc_key  # Zoom Service api key
     self._alert_footer = alert_footer
Beispiel #22
0
def pd_create_event(certification, resource_type):

    if not os.environ.get('PD_KEY') or not os.environ.get('PD_SERVICE_KEY'):
        raise Exception("Set PD_KEY and PD_SERVICE_KEY")

    # Send pager duty alert
    pd_key = os.environ.get('PD_KEY')
    pd_service_key = os.environ.get('PD_SERVICE_KEY')

    if resource_type == 'elb':

        description = "ELB %s's SSL cert expires soon." % certification['dns_name']
        incident_key = "ELB-%s/SSL_EXPIRY" % certification['dns_name']
        details = "ELB %s's' with cert %s, expires in %s days" % \
                    (certification['dns_name'], certification['arn'], certification['days_til_expiry'])

    if resource_type == 'cloudfront':

        description = "Distribution %s's SSL cert expires soon." % certification['dns_name']
        incident_key = "CDN-%s/SSL_EXPIRY" % certification['dns_name']
        details = "Distribution %s expires in %s days" % \
                    (certification['dns_name'], certification['days_til_expiry'])

    if resource_type == 'domain':
        description = "Domain %s's SSL cert expires soon." % certification['dns_name']
        incident_key = "DOMAIN-%s/SSL_EXPIRY" % certification['dns_name']
        details = "Distribution %s expires in %s days" % \
                    (certification['dns_name'], certification['days_til_expiry'])


    try:

        pager = pygerduty.PagerDuty("behance", pd_key)
        pager.create_event(
            pd_service_key,
            description,
            'trigger',
            details,
            incident_key
        )

    except Exception as e:
        print e
        raise
Beispiel #23
0
    def send_alert(self, service, users, duty_officers):
        """Implement your send_alert functionality here."""

        if not self._service_alertable(service):
            return

        subdomain = os.environ.get('PAGERDUTY_SUBDOMAIN')
        api_token = os.environ.get('PAGERDUTY_API_TOKEN')

        client = pygerduty.PagerDuty(subdomain, api_token)

        description = 'Service: %s is %s' % (service.name,
                                             service.overall_status)

        failed_checks = [check.name for check in service.all_failing_checks()]
        if len(failed_checks) > 0:
            description += ' failed checks [%s]' % ','.join(failed_checks)

        incident_key = '%s/%d' % (service.name.lower().replace(
            ' ', '-'), service.pk)

        users = service.users_to_notify.all()

        service_keys = []
        for userdata in PagerdutyAlertUserData.objects.filter(
                user__user__in=users):
            if userdata.service_key:
                service_keys.append(str(userdata.service_key))

        for service_key in service_keys:
            try:
                if service.overall_status not in self.alert_status_list:
                    client.resolve_incident(service_key, incident_key)
                else:
                    client.trigger_incident(service_key,
                                            description,
                                            incident_key=incident_key)
            except Exception, exp:
                logger.exception('Error invoking pagerduty: %s' % str(exp))
                raise
Beispiel #24
0
def test_list_user_contact_methods_v1():
    user_body = open('tests/fixtures/user_v1.json').read()
    contact_body = open('tests/fixtures/contacts_v1.json').read()
    httpretty.register_uri(
        httpretty.GET,
        "https://contosso.pagerduty.com/api/v1/users/PIJ90N7",
        body=user_body,
        status=200),
    httpretty.register_uri(
        httpretty.GET,
        "https://contosso.pagerduty.com/api/v1/users/PIJ90N7/contact_methods",
        body=contact_body,
        status=200)

    p = pygerduty.PagerDuty("contosso", "password")
    user = p.users.show("PIJ90N7")
    contact_methods = [c for c in user.contact_methods.list()]

    assert len(contact_methods) == 3
    assert len([c for c in contact_methods if c.type == "email"]) == 1
    assert len([c for c in contact_methods if c.type == "phone"]) == 1
    assert len([c for c in contact_methods if c.type == "SMS"]) == 1
Beispiel #25
0
    def send_alert(self, service, users, duty_officers):
        """Implement your send_alert functionality here."""

        if not self._service_alertable(service):
            return

        subdomain = os.environ.get('PAGERDUTY_SUBDOMAIN')
        api_token = os.environ.get('PAGERDUTY_API_TOKEN')

        client = pygerduty.PagerDuty(subdomain, api_token)

        description = 'Service: %s is %s' % (service.name,
                                             service.overall_status)

        incident_key = '%s/%d' % (service.name.lower().replace(' ', '-'),
                                  service.pk)

        users = service.users_to_notify.all()

        service_keys = []
        for user in users:
            for plugin in user.profile.user_data():
                service_key = getattr(plugin, 'service_key', None)

                if service_key:
                    service_keys.append(str(service_key))

        for service_key in service_keys:
            try:
                if service.overall_status == service.PASSING_STATUS:
                    client.resolve_incident(service_key,
                                            incident_key)
                else:
                    client.trigger_incident(service_key,
                                            description,
                                            incident_key=incident_key)
            except Exception, exp:
                logger.exception('Error invoking pagerduty: %s' % str(exp))
                raise
Beispiel #26
0
def send_pagerduty(current_skyline_app, message, log=True):
    """
    Send a pagerduty event.

    :param current_skyline_app: the app calling the function
    :param message: the message
    :type current_skyline_app: str
    :type message: str
    :return: page_sent
    :rtype: boolean

    """

    function_str = 'functions.pagerduty.send_pagerduty'
    if log:
        current_skyline_app_logger = current_skyline_app + 'Log'
        current_logger = logging.getLogger(current_skyline_app_logger)
    else:
        current_logger = None

    page_sent = False
    pager = None
    try:
        pager = pygerduty.PagerDuty(settings.PAGERDUTY_OPTS['subdomain'],
                                    settings.PAGERDUTY_OPTS['auth_token'])
    except Exception as e:
        current_logger.error('error :: %s :: failed to Initialize pager - %s' %
                             (function_str, e))
        pager = None
    if pager:
        try:
            page_sent = pager.trigger_incident(settings.PAGERDUTY_OPTS['key'],
                                               '%s - %s' % (message))
        except Exception as e:
            current_logger.error(
                'error :: %s :: failed to Initialize pager - %s' %
                (function_str, e))
    return page_sent
Beispiel #27
0
    def send_messages(self, messages):
        sent_messages = 0

        try:
            pager = pygerduty.PagerDuty(self.subdomain, self.token)
        except Exception as e:
            if not self.fail_silently:
                raise
            logger.error(
                smart_text(
                    _("Exception connecting to PagerDuty: {}").format(e)))
        for m in messages:
            try:
                pager.trigger_incident(m.recipients()[0],
                                       description=m.subject,
                                       details=m.body,
                                       client=m.from_email)
                sent_messages += 1
            except Exception as e:
                logger.error(
                    smart_text(_("Exception sending messages: {}").format(e)))
                if not self.fail_silently:
                    raise
        return sent_messages
Beispiel #28
0
 def configure(self, configuration):
     super(PagerDuty, self).configure(configuration)
     if configuration and ('SUBDOMAIN' in configuration and 'API_KEY' in configuration):
         self.pager = pygerduty.PagerDuty(self.config['SUBDOMAIN'], self.config['API_KEY'])
Beispiel #29
0
def test_to_json_list_convertion_v1():
    p = pygerduty.PagerDuty("contosso", "password")
    collection = pygerduty.Collection(p)

    container = pygerduty.Container(collection, handlers=['first', 'second'])
    assert {'handlers': ['first', 'second']} == container.to_json()
Beispiel #30
0
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)