def test_27_monitoring_stats(self): # Simple test to write data to the monitoring stats table key1 = "user_count" key2 = "successful_auth" utcnow = datetime.utcnow() MonitoringStats(utcnow - timedelta(seconds=1), key1, 15).save() MonitoringStats(utcnow, key1, 21).save() MonitoringStats(utcnow, key2, 123).save() self.assertEqual(MonitoringStats.query.filter_by(stats_key=key1).count(), 2) self.assertEqual(MonitoringStats.query.filter_by(stats_key=key2).count(), 1) # Delete all entries MonitoringStats.query.delete() self.assertEqual(MonitoringStats.query.filter_by(stats_key=key1).count(), 0) self.assertEqual(MonitoringStats.query.filter_by(stats_key=key2).count(), 0)
def add_value(self, stats_key, stats_value, timestamp, reset_values=False): utc_timestamp = convert_timestamp_to_utc(timestamp) try: ms = MonitoringStats(utc_timestamp, stats_key, stats_value) self.session.add(ms) self.session.commit() if reset_values: # Successfully saved the new stats entry, so remove old entries self.session.query(MonitoringStats).filter( and_(MonitoringStats.stats_key == stats_key, MonitoringStats.timestamp < utc_timestamp)).delete() self.session.commit() except Exception as exx: # pragma: no cover log.error(u"exception {0!r}".format(exx)) log.error(u"DATA: {0!s} -> {0!s}".format(stats_key, stats_value)) log.debug(u"{0!s}".format(traceback.format_exc())) self.session.rollback() finally: self.session.close()
def write_stats(stats_key, stats_value, timestamp=None, reset_values=False): """ Write a new statistics value to the database :param stats_key: The key, that identifies the measurment point :type stats_key: basestring :param stats_value: The value to be measured :type stats_value: int :param timestamp: The time, when the value was measured :type timestamp: timezone-aware datetime object :param reset_values: Whether old entries should be deleted :return: id of the database entry """ timestamp = timestamp or datetime.datetime.now(tzlocal()) # Convert timestamp to UTC for database utc_timestamp = convert_timestamp_to_utc(timestamp) MonitoringStats(utc_timestamp, stats_key, stats_value) if reset_values: # Successfully saved the new stats entry, so remove old entries MonitoringStats.query.filter( and_(MonitoringStats.stats_key == stats_key, MonitoringStats.timestamp < utc_timestamp)).delete()