def conv_start(update, context): """Start conversion""" LOGGER.info('"@%s" start remove account conversation', update.message.from_user.username) update.message.reply_text( 'Starting removal conversation, use /cancel to stop.') return conv_ask_player(update, context)
def put(self, route_id): LOGGER.info('UPDATE Route') args = self.parser.parse_args() stops = [] checkpoints = [] if args['stops']: stops = [RouteStopM(p['lat'], p['lng']) for p in args['stops']] if args['checkpoints']: checkpoints = [ RouteCheckpointM(p['lat'], p['lng']) for p in args['checkpoints'] ] route = self.get_or_abort(route_id) if args['name']: route.name = args['name'] if args['status']: route.status = args['status'] if args['path_color']: route.path_color = args['path_color'] if args['path']: route.path = json.dumps(args['path']) if stops: route.stops = stops if checkpoints: route.checkpoints = checkpoints db.session.commit() return route, 200
def create_alert(self, content): LOGGER.info("Creating alert") tags = [] for s in content['data']['series']: try: tags.extend([{ 'key': k, 'value': v } for k, v in s['tags'].items()]) except KeyError: continue al = Alert( alertid=content['id'], duration=content['duration'] // (10**9), message=content['message'], level=content['level'], previouslevel=content['previousLevel'], alerttime=self.datestr_to_timestamp(datestr=content['time']), tags=tags) for key in app.config['STATE_DURATION']: if al.id.find(key) != -1: if al.duration < app.config['STATE_DURATION'][key]: al.state_duration = True if app.config['AWS_API_ENABLED']: suppress, modified_tags = self.check_instance_tags(tags) if suppress: return None if modified_tags: al.tags = modified_tags return al
def post(self): LOGGER.info('CREATE Route') args = self.parser.parse_args() stops = [] checkpoints = [] if args['stops']: stops = [RouteStopM(**p) for p in args['stops']] if args['checkpoints']: checkpoints = [RouteCheckpointM(**p) for p in args['checkpoints']] for p in stops + checkpoints: db.session.add(p) route = RouteM(args['name'], args['status']) if args['path_color']: route.path_color = args['path_color'] if args['path']: route.path = json.dumps(args['path']) if stops: route.stops = stops if checkpoints: route.checkpoints = checkpoints db.session.add(route) db.session.commit() # path = json.loads(args['path']) return route, 201
def delete(self, route_id): LOGGER.info('DELETE route') route = self.get_or_abort(route_id) db.session.delete(route) db.session.commit() return '', 204
def delete(self, vehicle_id): LOGGER.info('DELETE vehicle') vehicle = self.get_or_abort(vehicle_id) db.session.delete(vehicle) db.session.commit() return '', 204
def put(self): # update existing offer args = self.req_parser.parse_args() offer_id = args['offer_id'] candidate_response = args['candidate_response'] accepted_accommodation_award = args['accepted_accommodation_award'] accepted_travel_award = args['accepted_travel_award'] rejected_reason = args['rejected_reason'] offer = db.session.query(Offer).filter(Offer.id == offer_id).first() LOGGER.info('Updating offer {} with values: candidate response: {}, Accepted accommodation: {}, ' 'Accepted travel: {}, Rejected Reason: {}'.format(offer_id, candidate_response, accepted_accommodation_award, accepted_travel_award, rejected_reason)) if not offer: return errors.OFFER_NOT_FOUND try: user_id = verify_token(request.headers.get('Authorization'))['id'] if offer and offer.user_id != user_id: return errors.FORBIDDEN offer.responded_at = datetime.now() offer.candidate_response = candidate_response offer.accepted_accommodation_award = accepted_accommodation_award offer.accepted_travel_award = accepted_travel_award offer.rejected_reason = rejected_reason db.session.commit() except Exception as e: LOGGER.error("Failed to update offer with id {} due to {}".format(args['offer_id'], e)) return errors.ADD_OFFER_FAILED return offer_update_info(offer), 201
def run(self): LOGGER.info("Searching for flapping alerts") logged_alerts = self.db.get_log_count_interval() flapping_alerts = self.db.get_flapping_alerts() flaphash = [x[0] for x in flapping_alerts] logged_hash = [] for a in logged_alerts: logged_hash.append(a[0]) if a[3] > self.limit and a[0] not in flaphash: # Set flapping self.db.set_flapping(a[0], a[1], a[2], a[3]) self.notify(a[1], a[2], a[3]) elif a[3] > self.limit and a[0] in flaphash: # Send reminder every hour if alert is still flapping self.db.update_flapping(a[0], a[4]) flaptime = [x[2] for x in flapping_alerts if x[0] == a[0]] if 0 < (time.time() % 3600 - flaptime[0] % 3600) <= 60: self.notify(a[1], a[2], a[3], reminder=True) elif a[3] <= self.limit and a[0] in flaphash: # Too low count to be marked as flapping # Check that time now is bigger than # modified + quarantine interval quarantine = [x[3] + x[4] for x in flapping_alerts if x[0] == a[0]] if time.time() > quarantine[0]: self.db.unset_flapping(a[0], a[1]) # If alert is no longer in the log it is not flapping, unset for a in [(x[0], x[1]) for x in flapping_alerts if x[0] not in logged_hash]: self.db.unset_flapping(a[0], a[1])
def send_lotery_message(state_id, department_type, language, amount): """Send lotery message""" LOGGER.info('"%s": Send lotery message for "%s" department', state_id, department_type) yesterday_professors = database.get_yesterday_professors( state_id, department_type) professor_count = len(yesterday_professors) random_index = random.randint(0, professor_count) - 1 winning_professor = yesterday_professors[random_index] winner = winning_professor.player winner_name = re.sub(r'\[.*]\s', '', winner.name) amount_of_points = database.get_amount_of_points(state_id, department_type, winner.id) LOGGER.info('"%s": candidates "%s", winner "%s" with "%s" points', state_id, professor_count, winner_name, amount_of_points) tg_message = '. '.join([ "The daily department lotery is won by: {:}".format(winner_name), "With {:} points you won $ {:,.0f}".format( amount_of_points, amount_of_points * amount).replace(',', '.'), "Send @bergjnl a message to receive your price.", ]) print(tg_message) TELEGRAM_BOT.sendMessage(chat_id='@vn_lottery', text=tg_message) rr_message = '. '.join([ "De department loterij is gewonnen door: {:}".format(winner_name), "Met {:} punten heb je $ {:,.0f} gewonnen".format( amount_of_points, amount_of_points * amount).replace(',', '.'), "Stuur me een bericht om de prijs te ontvangen.", ]) print(rr_message) api.send_message(language, rr_message)
def __init__(self, server, username, password, project_key, assignee): LOGGER.info("Initiating jira incident") self._server = server self._username = username self._password = password self._project_key = project_key self._assignee = assignee
def _create(self, alert): desc = alert.message if alert.grafana_url: jira_link = "[Go to Grafana|{}]".format(alert.grafana_url) desc = alert.message + " - " + jira_link issue_dict = { 'project': { 'key': self._project_key }, 'summary': alert.id, 'description': desc, # 'assignee': {'name': self._assignee}, 'components': [{ 'name': self._assignee }], 'issuetype': { 'name': 'Incident' }, 'security': { 'name': 'Internal Issue' } } jira = self._connect() if jira: try: LOGGER.info("Creating JIRA ticket") issue = jira.create_issue(fields=issue_dict) if issue: return issue.key except JIRAError as err: LOGGER.error("Failed creating JIRA ticket") LOGGER.error(err) return None
def save_work_permits(state_id, work_permits): """Save residents to database""" session = SESSION() player_ids = [] new_work_permits = 0 for player_dict in work_permits: player = session.query(Player).get(player_dict['id']) if player is None: player = save_player(session, player_dict) player_ids.append(player.id) last_work_permit = player.state_work_permits \ .filter(StateWorkPermit.state_id == state_id) \ .filter(StateWorkPermit.until_date_time == None) \ .first() if not last_work_permit: new_work_permits += 1 state_work_permit = StateWorkPermit() state_work_permit.player_id = player.id state_work_permit.state_id = state_id state_work_permit.from_date_time = player_dict['from'] session.add(state_work_permit) session.commit() LOGGER.info('state %6s: "%s" new work permits', state_id, new_work_permits) current_work_permits = session.query(StateWorkPermit) \ .filter(StateWorkPermit.state_id == state_id) \ .filter(StateWorkPermit.until_date_time == None).all() for current_work_permit in current_work_permits: if current_work_permit.player_id not in player_ids: current_work_permit.until_date_time = datetime.now().replace( second=0, minute=0) session.commit() session.close()
def on_disconnect(): """ Invoked when user disconnects and closes the room user was in. :return: None """ close_room(current_user.id) LOGGER.info('%s disconnected', str(current_user))
def __init__(self, url, channel, username): LOGGER.info("Initiating slack") self._url = url self._channel = channel self._username = username self._colors = {"OK": "good", "INFO": "#439FE0", "WARNING": "warning", "CRITICAL": "danger"}
def __init__(self): super(SlackAlertSummary, self).__init__() LOGGER.info("Initiating SlackAlertSummary") self.alertctrl = AlertController() self.db = DBController() self.url = "http://" + \ app.config['SERVER_FQDN'] + "/kap/log?environment="
def save_residents(region_id, residents): """Save residents to database""" session = SESSION() player_ids = [] new_residents = 0 for player_dict in residents: player = session.query(Player).get(player_dict['id']) if player is None: player = save_player(session, player_dict) player_ids.append(player.id) last_residency = player.residencies \ .filter(PlayerResidency.region_id == region_id) \ .filter(PlayerResidency.until_date_time == None) \ .first() if not last_residency: new_residents += 1 player_location = PlayerResidency() player_location.player_id = player.id player_location.region_id = region_id player_location.from_date_time = datetime.now().replace(second=0, minute=0) session.add(player_location) LOGGER.info('regio %6s: "%s" new residents', region_id, new_residents) session.commit() current_residents = session.query(PlayerResidency) \ .filter(PlayerResidency.region_id == region_id) \ .filter(PlayerResidency.until_date_time == None).all() for current_resident in current_residents: if current_resident.player_id not in player_ids: current_resident.until_date_time = datetime.now().replace(second=0, minute=0) session.commit() session.close()
def set_flapping(self, alhash, alid, environment, interval): LOGGER.info("Setting flapping on %s", alid) now = int(time.time()) quarantine = int(interval * 1.2) query = "INSERT INTO flapping_alerts (hash, id, environment, " + \ "time, quarantine, modified) VALUES (?, ?, ?, ?, ?, ?)" values = (alhash, alid, environment, now, quarantine, now) self.execute_query(query, values)
def state_duration(self, al): LOGGER.info("Checking state duration") query = "SELECT state_duration FROM active_alerts " + \ "where hash = '{}'".format(al.alhash) res = self.select(query) if res: return bool(res[0]) return False
def get_rr_players(telegram_account): """Get Rival Region players associated with Telegram player""" LOGGER.info('"%s" get RR accounts', telegram_account.id,) session = SESSION() players = _get_rr_players(session, telegram_account.id) LOGGER.info('"%s" found %s RR accounts', telegram_account.id, len(players)) session.close() return players
def excluded_tick(al, excluded_ticks): # This only works if {{ .TaskName }} is the last element of the al.id LOGGER.info("Check for excluded tick script") tn = al.id.split()[-1] if tn in excluded_ticks: LOGGER.info("Tick %s is excluded", tn) return True return False
def __init__(self): super(FlapDetective, self).__init__() LOGGER.info("Initiating flap detective") self.alertctrl = AlertController() self.db = DBController() self.limit = app.config['FLAPPING_LIMIT'] self.slack_enabled = app.config['SLACK_ENABLED'] self.excluded_tags = app.config['SLACK_EXCLUDED_TAGS']
def _send_report(kaos_report): LOGGER.info("Sending KAOS report") try: requests.post(app.config['KAOS_URL'], verify=app.config['KAOS_CERT'], json=kaos_report, timeout=5) except requests.exceptions.RequestException: LOGGER.exception("Failed posting to KAOS")
def post(self, invitedGuest=False): args = self.req_parser.parse_args() email = args['email'] firstname = args['firstname'] lastname = args['lastname'] user_title = args['user_title'] policy_agreed = args['policy_agreed'] user_primaryLanguage = args['language'] if (invitedGuest): password = self.randomPassword() else: password = args['password'] if (password is None): return MISSING_PASSWORD if not policy_agreed: return POLICY_NOT_AGREED LOGGER.info("Registering email: {}".format(email)) user = AppUser(email=email, firstname=firstname, lastname=lastname, user_title=user_title, password=password, organisation_id=g.organisation.id) user.user_primaryLanguage = user_primaryLanguage db.session.add(user) try: db.session.commit() except IntegrityError: LOGGER.error("email: {} already in use".format(email)) return EMAIL_IN_USE if (not invitedGuest): email_user( 'verify-email', template_parameters=dict(system=g.organisation.system_name, organisation=g.organisation.name, host=misc.get_baobab_host(), token=user.verify_token), user=user, subject_parameters=dict(system=g.organisation.system_name)) LOGGER.debug("Sent verification email to {}".format(user.email)) else: user.verified_email = True try: db.session.commit() except IntegrityError: LOGGER.error("Unable to verify email: {}".format(email)) return VERIFY_EMAIL_INVITED_GUEST return user_info(user, []), 201
def delete(self, route_id, stop_id): LOGGER.info('DELETE stop') route = self.get_route_or_abort(route_id) stop = self.get_or_abort(stop_id) db.session.delete(stop) db.session.commit() return '', 204
def on_connect(): """ Invoked when client tries to establish connection. If this client is authenticated user, he is added to room with the name of his id. :return: None """ if current_user.is_authenticated: LOGGER.info('%s connected', str(current_user)) join_room(current_user.id)
def test_send_email(self): try: LOGGER.info("Testing mailer") send_mail(recipient='*****@*****.**', subject='TestSMTPEmail', body_text='Hello world from Amazon SES') return True except Exception: return False
def deactive_maintenance(self, start, stop, key, value): LOGGER.info("Deactivate maintenance on %s %s", key, value) query = ("DELETE FROM active_maintenance where " "start = {start} and stop = {stop} and key = '{key}' " "and value = '{value}'".format(start=start, stop=stop, key=key, value=value)) self.execute_query(query)
def delete(self, route_id, checkpoint_id): LOGGER.info('DELETE checkpoint') route = self.get_route_or_abort(route_id) checkpoint = self.get_or_abort(checkpoint_id) db.session.delete(checkpoint) db.session.commit() return '', 204
def conv_player_confirm(update, context): """Sending announcement""" player = context.user_data['player'] LOGGER.info('"@%s" remove verified account %s', update.message.from_user.username, player.name) update.message.reply_text('Removing verified account.', parse_mode=ParseMode.MARKDOWN) database.remove_verified_player(update.message.from_user.id, player.id) context.user_data.clear() return ConversationHandler.END
def cmd_start(update, context): """Start command""" LOGGER.info('"@%s" start bot', update.message.from_user.username) update.message.reply_text( 'Hello {}, use /add to add an account, use /help for a list of commands.' .format(update.message.from_user.first_name)) telegram_account = database.get_telegram_account( update.message.from_user.id) if not telegram_account: database.add_telegram_account(update)