import requests import json from config import Config import logging class SentryProjectRule: def __init__(self, rule: dict, base_url: str, logger: logging.Logger): self.name = rule['name'] self.actionMatch = rule['actionMatch'] self.conditions = rule['conditions'] self.actions = rule['actions'] self.base_url = base_url self.logger = logger if 'id' in rule: self.id = int(rule['id']) if 'environment' in rule: self.environment = rule['environment'] if 'dateCreated' in rule: self.dateCreated = rule['dateCreated'] if 'frequency' in rule: self.frequency = int(rule['frequency']) def create_rule(self): self.logger.debug(f'POST {self.base_url}/rules/') try: r = requests.post( f'{self.base_url}/rules/', data=self.to_json(), headers={**Config.auth_header, **Config.content_type_header} ) r.raise_for_status() except requests.exceptions.HTTPError as e: self.logger.error(e.response.text) raise SystemExit(e) def update_rule(self): self.logger.debug(f'PUT {self.base_url}/rules/{self.id}/') try: r = requests.put( f'{self.base_url}/rules/{self.id}/', data=self.to_json(), headers={**Config.auth_header, **Config.content_type_header} ) r.raise_for_status() except requests.exceptions.HTTPError as e: self.logger.error(e.response.text) raise SystemExit(e) def delete_rule(self): self.logger.debug(f'DELETE {self.base_url}/rules/{self.id}/') try: r = requests.delete( f'{self.base_url}/rules/{self.id}/', headers=Config.auth_header ) r.raise_for_status() except requests.exceptions.HTTPError as e: self.logger.error(e.response.text) raise SystemExit(e) def to_dict(self): return { 'environment': self.environment, 'actionMatch': self.actionMatch, 'frequency': self.frequency, 'name': self.name, 'conditions': [vars(SentryProjectRuleCondition(c)) for c in self.conditions], 'actions': [vars(SentryProjectRuleAction(a)) for a in self.actions], } def to_json(self): return json.dumps(self.to_dict()) class SentryProjectRuleAction: def __init__(self, action: dict): self.id = action['id'] self.name = action['name'] if 'tags' in action: self.tags = action['tags'] if 'workspace' in action: self.workspace = action['workspace'] if 'channel' in action: self.channel = action['channel'] if 'channel_id' in action: self.channel_id = action['channel_id'] class SentryProjectRuleCondition: def __init__(self, condition: dict): self.id = condition['id'] self.name = condition['name'] if 'interval' in condition: self.interval = condition['interval'] if 'value' in condition: self.value = condition['value'] if 'match' in condition: self.match = condition['match'] if 'attribute' in condition: self.attribute = condition['attribute']