|
| 1 | +""" |
| 2 | +sentry.tsdb.utils |
| 3 | +~~~~~~~~~~~~~~~~~ |
| 4 | +
|
| 5 | +:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. |
| 6 | +:license: BSD, see LICENSE for more details. |
| 7 | +""" |
| 8 | + |
| 9 | +from datetime import timedelta |
| 10 | + |
| 11 | +ONE_MINUTE = 60 |
| 12 | +ONE_HOUR = ONE_MINUTE * 60 |
| 13 | +ONE_DAY = ONE_HOUR * 24 |
| 14 | +ONE_WEEK = ONE_DAY * 7 |
| 15 | + |
| 16 | + |
| 17 | +class Granularity(object): |
| 18 | + SECONDS = 0 |
| 19 | + MINUTES = 1 |
| 20 | + HOURS = 2 |
| 21 | + DAYS = 3 |
| 22 | + WEEKS = 4 |
| 23 | + MONTHS = 5 |
| 24 | + YEARS = 6 |
| 25 | + ALL_TIME = 7 |
| 26 | + |
| 27 | + @classmethod |
| 28 | + def get_choices(cls): |
| 29 | + if hasattr(cls, '__choice_cache'): |
| 30 | + return cls.__choice_cache |
| 31 | + |
| 32 | + results = [] |
| 33 | + for name in dir(cls): |
| 34 | + if name.startswith('_'): |
| 35 | + continue |
| 36 | + if not name.upper() == name: |
| 37 | + continue |
| 38 | + results.append((getattr(cls, name), name.replace('_', ' ').title())) |
| 39 | + cls.__choice_cache = results |
| 40 | + return results |
| 41 | + |
| 42 | + @classmethod |
| 43 | + def normalize_to_epoch(cls, granularity, timestamp): |
| 44 | + timestamp = timestamp.replace(microsecond=0) |
| 45 | + if granularity == cls.ALL_TIME: |
| 46 | + return 0 |
| 47 | + if granularity == cls.SECONDS: |
| 48 | + return timestamp |
| 49 | + timestamp = timestamp.replace(seconds=0) |
| 50 | + if granularity == cls.MINUTES: |
| 51 | + return timestamp |
| 52 | + timestamp = timestamp.replace(minutes=0) |
| 53 | + if granularity == cls.HOURS: |
| 54 | + return timestamp |
| 55 | + timestamp = timestamp.replace(hours=0) |
| 56 | + if granularity == cls.WEEKS: |
| 57 | + timestamp -= timedelta(days=timestamp.weekday()) |
| 58 | + elif granularity in (cls.MONTHS, cls.YEARS): |
| 59 | + timestamp = timestamp.replace(day=1) |
| 60 | + elif granularity == cls.YEARS: |
| 61 | + timestamp = timestamp.replace(month=1) |
| 62 | + return int(timestamp.strftime('%s')) |
| 63 | + |
| 64 | + @classmethod |
| 65 | + def get_min_timestamp(cls, granularity, timestamp): |
| 66 | + if granularity in (cls.ALL_TIME, cls.YEARS): |
| 67 | + return None |
| 68 | + |
| 69 | + if granularity == cls.SECONDS: |
| 70 | + timestamp -= timedelta(minutes=1) |
| 71 | + elif granularity == cls.MINUTES: |
| 72 | + timestamp -= timedelta(hours=1) |
| 73 | + elif granularity == cls.HOURS: |
| 74 | + timestamp -= timedelta(days=1) |
| 75 | + elif granularity == cls.DAYS: |
| 76 | + # days are stored for a full month |
| 77 | + timestamp -= timedelta(months=1) |
| 78 | + elif granularity == cls.WEEKS: |
| 79 | + # weeks are stored for a full year |
| 80 | + timestamp -= timedelta(years=1) |
| 81 | + |
| 82 | + return cls.normalize_to_epoch(timestamp, granularity) |
0 commit comments