samples.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from collections import namedtuple
  2. class Timestamp(object):
  3. """A nanosecond-resolution timestamp."""
  4. def __init__(self, sec, nsec):
  5. if nsec < 0 or nsec >= 1e9:
  6. raise ValueError("Invalid value for nanoseconds in Timestamp: {0}".format(nsec))
  7. if sec < 0:
  8. nsec = -nsec
  9. self.sec = int(sec)
  10. self.nsec = int(nsec)
  11. def __str__(self):
  12. return "{0}.{1:09d}".format(self.sec, self.nsec)
  13. def __repr__(self):
  14. return "Timestamp({0}, {1})".format(self.sec, self.nsec)
  15. def __float__(self):
  16. return float(self.sec) + float(self.nsec) / 1e9
  17. def __eq__(self, other):
  18. return type(self) == type(other) and self.sec == other.sec and self.nsec == other.nsec
  19. def __ne__(self, other):
  20. return not self == other
  21. def __gt__(self, other):
  22. return self.sec > other.sec or self.nsec > other.nsec
  23. # Timestamp and exemplar are optional.
  24. # Value can be an int or a float.
  25. # Timestamp can be a float containing a unixtime in seconds,
  26. # a Timestamp object, or None.
  27. # Exemplar can be an Exemplar object, or None.
  28. Sample = namedtuple('Sample', ['name', 'labels', 'value', 'timestamp', 'exemplar'])
  29. Sample.__new__.__defaults__ = (None, None)
  30. Exemplar = namedtuple('Exemplar', ['labels', 'value', 'timestamp'])
  31. Exemplar.__new__.__defaults__ = (None,)