def service_iter_print(api_key): api_session = APISession(api_key) # all_services = list(api_session.iter_all("services")) count = 1 for service in api_session.iter_all("services"): print(count, service) count += 1
def get_escalation_policies(pd_session: APISession) -> List[Dict[str, Any]]: all_escalation_policies: List[Dict[str, Any]] = [] params = {"include[]": ["services", "teams", "targets"]} for escalation_policy in pd_session.iter_all("escalation_policies", params=params): all_escalation_policies.append(escalation_policy) return all_escalation_policies
def get_team_members( pd_session: APISession, teams: List[Dict[str, Any]], ) -> List[Dict[str, str]]: relations: List[Dict[str, str]] = [] for team in teams: team_id = team["id"] for member in pd_session.iter_all(f"teams/{team_id}/members"): relations.append( { "team": team_id, "user": member["user"]["id"], "role": member["role"] }, ) return relations
def service_iter_all(api_key): api_session = APISession(api_key) all_services = list(api_session.iter_all("services")) return all_services
print("Processed %d/%d incidents" % (num - 1, total)) Path(alerts_db).write_text(json.dumps(db)) return print_status for incident in pd.iter_all('incidents', total=True, item_hook=status_reporter(db), params={ 'since': since, 'until': datetime.utcnow(), 'time_zone': 'UTC', 'sort_by': 'created_at:ASC', 'team_ids[]': [team_id], 'statuses[]': ['resolved'], 'include[]': [ 'users', 'assignees', 'services', 'acknowledgers', 'assignments', 'acknowledgements' ] }): if 'name' not in incident['service'].keys(): continue if not incident['service']['name'].endswith('-hive-cluster'): continue incident['log_entries'] = [ entry for entry in pd.rget('/incidents/%s/log_entries' % incident["id"], params={
def get_services(pd_session: APISession) -> List[Dict[str, Any]]: all_services: List[Dict[str, Any]] = [] for service in pd_session.iter_all("services"): all_services.append(service) return all_services
def ep_iter_all(api_key): api_session = APISession(api_key) all_ep = list(api_session.iter_all("escalation_policies")) return all_ep
def get_vendors(pd_session: APISession) -> List[Dict[str, Any]]: all_vendors: List[Dict[str, Any]] = [] for vendor in pd_session.iter_all("vendors"): all_vendors.append(vendor) return all_vendors
def get_users(pd_session: APISession) -> List[Dict[str, Any]]: all_users: List[Dict[str, Any]] = [] for user in pd_session.iter_all("users"): all_users.append(user) return all_users
def main(): """ Do all the things """ logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') secrets = { 'pagerduty': {'key': os.environ.get('PAGERDUTY_API_KEY')}, 'slack': {'url': os.environ.get('SLACK_API_URL')} } config = { 'responders': [ { 'escalation_policy_ids': [ os.environ.get('PAGERDUTY_ESCALATION_POLICY_ID') ], 'schedule_ids': [ os.environ.get('PAGERDUTY_SCHEDULE_ID') ] } ] } # instantiate a pdpyras object api = APISession( secrets.get('pagerduty').get('key'), # PagerDuty API token from secrets 'PagerDuty' # Name for logging (optional) ## or, with default_from: #'PagerDuty', # Name for logging (optional) #'*****@*****.**' # default_from for request header - must be a valid PagerDuty user ) for responder in config.get('responders'): # Generally speaking, at the first esclation level where these schedule(s) are mentioned, # there should be only one active on-call, regardless of time of day. # The expectation is that a level with split day/night or follow-the-sun responsibility will not overlap. logging.debug('Retrieving oncalls from PagerDuty API') # Poll for a single oncall, based on a schedule id and escalation policy id # The use of both Schedule and Escalation Policy limits scope oncalls = api.iter_all( 'oncalls', # method { #"include[]": "users", # including users doesn't give us the contact details "schedule_ids[]": responder.get('schedule_ids'), "escalation_policy_ids[]": responder.get('escalation_policy_ids') } #params ) oncalls_list = api.get( 'oncalls', # method params={ #"include[]": "users", # including users doesn't give us the contact details "schedule_ids[]": responder.get('schedule_ids'), "escalation_policy_ids[]": responder.get('escalation_policy_ids') } #params ) logging.debug(oncalls_list.text) if oncalls: for oncall in oncalls: # If we have a Live Call Routing number configured, just display it here if responder.get('lcr'): ## directly print the result # schedule - Live Call Routing: +xx xxxxxx,,x User Name until yyyy-mm-ddThh:mm:ssZ msg = u'`{}` - Live Call Routing: `{}` {} until {}'.format( oncall.get('schedule').get('summary'), responder.get('lcr'), oncall.get('user').get('summary'), oncall.get('end') ) # We don't have an LCR configured, so find the user's phone number(s) else: response = api.request( 'get', # requests type '/users/{}'.format(oncall.get('user').get('id')), # get single user params={"include[]": "contact_methods"} # include contact _details_ ) # prepare an empty phone list to populate - there could be more than one phone = {} if response.ok: user = response.json()['user'] # loop through all of the contact methods, looking for phone numbers for contact_method in user.get('contact_methods'): logging.debug(u'Contact Method: %s %s', contact_method.get('type'), contact_method.get('label')) # add phone numbers in the constructed format to the `phone` list if 'phone' in contact_method['type']: phone[contact_method.get('label')] = u'`{}: +{} {}`'.format( contact_method.get('label'), contact_method.get('country_code'), contact_method.get('address')) # if no `contact_methods` of type `phone` if not phone: phone['EMPTY'] = 'NO PHONE ENTRIES FOUND' ## print the result # schedule - user name - Work: +xx xxxxxx, Mobile: +xx xxxxxx until yyyy-mm-ddThh:mm:ssZ msg = u'{}: *{}* - {} until {}'.format( oncall.get('schedule').get('summary'), oncall.get('user').get('summary'), ', '.join(phone.values()), oncall.get('end') ) print(msg) print_slack(message_text=msg, slack_url=secrets.get('slack').get('url')) # In the event that multiple results are returned, the first result is provided break else: logging.critical('No oncalls returned')
def get_teams(pd_session: APISession) -> List[Dict[str, Any]]: all_teams: List[Dict[str, Any]] = [] for teams in pd_session.iter_all("teams"): all_teams.append(teams) return all_teams
def get_schedules(pd_session: APISession) -> List[Dict[str, Any]]: all_schedules: List[Dict[str, Any]] = [] params = {"include[]": ["schedule_layers"]} for schedule in pd_session.iter_all("schedules", params=params): all_schedules.append(schedule) return all_schedules