parse_events.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # This Source Code Form is subject to the terms of the Mozilla Public
  2. # License, v. 2.0. If a copy of the MPL was not distributed with this
  3. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. import re
  5. import yaml
  6. import itertools
  7. import datetime
  8. import string
  9. from shared_telemetry_utils import add_expiration_postfix
  10. MAX_CATEGORY_NAME_LENGTH = 30
  11. MAX_METHOD_NAME_LENGTH = 20
  12. MAX_OBJECT_NAME_LENGTH = 20
  13. MAX_EXTRA_KEYS_COUNT = 10
  14. MAX_EXTRA_KEY_NAME_LENGTH = 15
  15. IDENTIFIER_PATTERN = r'^[a-zA-Z][a-zA-Z0-9_.]+[a-zA-Z0-9]$'
  16. DATE_PATTERN = r'^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
  17. def nice_type_name(t):
  18. if isinstance(t, basestring):
  19. return "string"
  20. return t.__name__
  21. def convert_to_cpp_identifier(s, sep):
  22. return string.capwords(s, sep).replace(sep, "")
  23. class OneOf:
  24. """This is a placeholder type for the TypeChecker below.
  25. It signals that the checked value should match one of the following arguments
  26. passed to the TypeChecker constructor.
  27. """
  28. pass
  29. class TypeChecker:
  30. """This implements a convenience type TypeChecker to make the validation code more readable."""
  31. def __init__(self, kind, *args):
  32. """This takes 1-3 arguments, specifying the value type to check for.
  33. It supports:
  34. - atomic values, e.g.: TypeChecker(int)
  35. - list values, e.g.: TypeChecker(list, basestring)
  36. - dict values, e.g.: TypeChecker(dict, basestring, int)
  37. - atomic values that can have different types, e.g.: TypeChecker(OneOf, int, date)"""
  38. self._kind = kind
  39. self._args = args
  40. def check(self, key, value):
  41. # Check fields that can be one of two different types.
  42. if self._kind is OneOf:
  43. if not isinstance(value, self._args[0]) and not isinstance(value, self._args[1]):
  44. raise ValueError, "failed type check for %s - expected %s or %s, got %s" %\
  45. (key,
  46. nice_type_name(self._args[0]),
  47. nice_type_name(self._args[1]),
  48. nice_type_name(type(value)))
  49. return
  50. # Check basic type of value.
  51. if not isinstance(value, self._kind):
  52. raise ValueError, "failed type check for %s - expected %s, got %s" %\
  53. (key,
  54. nice_type_name(self._kind),
  55. nice_type_name(type(value)))
  56. # Check types of values in lists.
  57. if self._kind is list:
  58. if len(value) < 1:
  59. raise ValueError, "failed check for %s - list should not be empty" % key
  60. for x in value:
  61. if not isinstance(x, self._args[0]):
  62. raise ValueError, "failed type check for %s - expected list value type %s, got %s" %\
  63. (key,
  64. nice_type_name(self._args[0]),
  65. nice_type_name(type(x)))
  66. # Check types of keys and values in dictionaries.
  67. elif self._kind is dict:
  68. if len(value.keys()) < 1:
  69. raise ValueError, "failed check for %s - dict should not be empty" % key
  70. for x in value.iterkeys():
  71. if not isinstance(x, self._args[0]):
  72. raise ValueError, "failed dict type check for %s - expected key type %s, got %s" %\
  73. (key,
  74. nice_type_name(self._args[0]),
  75. nice_type_name(type(x)))
  76. for k,v in value.iteritems():
  77. if not isinstance(x, self._args[1]):
  78. raise ValueError, "failed dict type check for %s - expected value type %s for key %s, got %s" %\
  79. (key,
  80. nice_type_name(self._args[1]),
  81. k,
  82. nice_type_name(type(x)))
  83. def type_check_event_fields(category, definition):
  84. """Perform a type/schema check on the event definition."""
  85. REQUIRED_FIELDS = {
  86. 'methods': TypeChecker(list, basestring),
  87. 'objects': TypeChecker(list, basestring),
  88. 'bug_numbers': TypeChecker(list, int),
  89. 'notification_emails': TypeChecker(list, basestring),
  90. 'description': TypeChecker(basestring),
  91. }
  92. OPTIONAL_FIELDS = {
  93. 'release_channel_collection': TypeChecker(basestring),
  94. 'expiry_date': TypeChecker(OneOf, basestring, datetime.date),
  95. 'expiry_version': TypeChecker(basestring),
  96. 'extra_keys': TypeChecker(dict, basestring, basestring),
  97. }
  98. ALL_FIELDS = REQUIRED_FIELDS.copy()
  99. ALL_FIELDS.update(OPTIONAL_FIELDS)
  100. # Check that all the required fields are available.
  101. missing_fields = [f for f in REQUIRED_FIELDS.keys() if f not in definition]
  102. if len(missing_fields) > 0:
  103. raise KeyError(category + ' - missing required fields: ' + ', '.join(missing_fields))
  104. # Is there any unknown field?
  105. unknown_fields = [f for f in definition.keys() if f not in ALL_FIELDS]
  106. if len(unknown_fields) > 0:
  107. raise KeyError(category + ' - unknown fields: ' + ', '.join(unknown_fields))
  108. # Type-check fields.
  109. for k,v in definition.iteritems():
  110. ALL_FIELDS[k].check(k, v)
  111. def string_check(category, field_name, value, min_length, max_length, regex=None):
  112. # Length check.
  113. if len(value) > max_length:
  114. raise ValueError("Value '%s' for %s in %s exceeds maximum length of %d" %\
  115. (value, field_name, category, max_length))
  116. # Regex check.
  117. if regex and not re.match(regex, value):
  118. raise ValueError, 'String value for %s in %s is not matching pattern "%s": %s' % \
  119. (field_name, category, regex, value)
  120. class EventData:
  121. """A class representing one event."""
  122. def __init__(self, category, definition):
  123. type_check_event_fields(category, definition)
  124. string_check(category, 'methods', definition.get('methods')[0], 1, MAX_METHOD_NAME_LENGTH, regex=IDENTIFIER_PATTERN)
  125. string_check(category, 'objects', definition.get('objects')[0], 1, MAX_OBJECT_NAME_LENGTH, regex=IDENTIFIER_PATTERN)
  126. # Check release_channel_collection
  127. rcc_key = 'release_channel_collection'
  128. rcc = definition.get(rcc_key, 'opt-in')
  129. allowed_rcc = ["opt-in", "opt-out"]
  130. if not rcc in allowed_rcc:
  131. raise ValueError, "Value for %s in %s should be one of: %s" %\
  132. (rcc_key, category, ", ".join(allowed_rcc))
  133. # Check extra_keys.
  134. extra_keys = definition.get('extra_keys', {})
  135. if len(extra_keys.keys()) > MAX_EXTRA_KEYS_COUNT:
  136. raise ValueError, "Number of extra_keys in %s exceeds limit %d" %\
  137. (category, MAX_EXTRA_KEYS_COUNT)
  138. for key in extra_keys.iterkeys():
  139. string_check(category, 'extra_keys', key, 1, MAX_EXTRA_KEY_NAME_LENGTH, regex=IDENTIFIER_PATTERN)
  140. # Check expiry.
  141. if not 'expiry_version' in definition and not 'expiry_date' in definition:
  142. raise KeyError, "Event in %s is missing an expiration - either expiry_version or expiry_date is required" %\
  143. (category)
  144. expiry_date = definition.get('expiry_date')
  145. if expiry_date and isinstance(expiry_date, basestring) and expiry_date != 'never':
  146. if not re.match(DATE_PATTERN, expiry_date):
  147. raise ValueError, "Event in %s has invalid expiry_date, it should be either 'never' or match this format: %s" %\
  148. (category, DATE_PATTERN)
  149. # Parse into date.
  150. definition['expiry_date'] = datetime.datetime.strptime(expiry_date, '%Y-%m-%d')
  151. # Finish setup.
  152. self._category = category
  153. self._definition = definition
  154. definition['expiry_version'] = add_expiration_postfix(definition.get('expiry_version', 'never'))
  155. @property
  156. def category(self):
  157. return self._category
  158. @property
  159. def category_cpp(self):
  160. # Transform e.g. category.example into CategoryExample.
  161. return convert_to_cpp_identifier(self._category, ".")
  162. @property
  163. def methods(self):
  164. return self._definition.get('methods')
  165. @property
  166. def objects(self):
  167. return self._definition.get('objects')
  168. @property
  169. def expiry_version(self):
  170. return self._definition.get('expiry_version')
  171. @property
  172. def expiry_day(self):
  173. date = self._definition.get('expiry_date')
  174. if not date:
  175. return 0
  176. if isinstance(date, basestring) and date == 'never':
  177. return 0
  178. # Convert date to days since UNIX epoch.
  179. epoch = datetime.date(1970, 1, 1)
  180. days = (date - epoch).total_seconds() / (24 * 60 * 60)
  181. return round(days)
  182. @property
  183. def cpp_guard(self):
  184. return self._definition.get('cpp_guard')
  185. @property
  186. def enum_labels(self):
  187. def enum(method_name, object_name):
  188. m = convert_to_cpp_identifier(method_name, "_")
  189. o = convert_to_cpp_identifier(object_name, "_")
  190. return m + '_' + o
  191. combinations = itertools.product(self.methods, self.objects)
  192. return [enum(t[0], t[1]) for t in combinations]
  193. @property
  194. def dataset(self):
  195. """Get the nsITelemetry constant equivalent for release_channel_collection.
  196. """
  197. rcc = self._definition.get('release_channel_collection', 'opt-in')
  198. if rcc == 'opt-out':
  199. return 'nsITelemetry::DATASET_RELEASE_CHANNEL_OPTOUT'
  200. else:
  201. return 'nsITelemetry::DATASET_RELEASE_CHANNEL_OPTIN'
  202. @property
  203. def extra_keys(self):
  204. return self._definition.get('extra_keys', {}).keys()
  205. def load_events(filename):
  206. """Parses a YAML file containing the event definitions.
  207. :param filename: the YAML file containing the event definitions.
  208. :raises Exception: if the event file cannot be opened or parsed.
  209. """
  210. # Parse the event definitions from the YAML file.
  211. events = None
  212. try:
  213. with open(filename, 'r') as f:
  214. events = yaml.safe_load(f)
  215. except IOError, e:
  216. raise Exception('Error opening ' + filename + ': ' + e.message)
  217. except ValueError, e:
  218. raise Exception('Error parsing events in ' + filename + ': ' + e.message)
  219. event_list = []
  220. # Events are defined in a fixed two-level hierarchy within the definition file.
  221. # The first level contains the category (group name), while the second level contains the
  222. # event definitions (e.g. "category.name: [<event definition>, ...], ...").
  223. for category_name,category in events.iteritems():
  224. string_check('', 'category', category_name, 1, MAX_CATEGORY_NAME_LENGTH, regex=IDENTIFIER_PATTERN)
  225. # Make sure that the category has at least one entry in it.
  226. if not category or len(category) == 0:
  227. raise ValueError(category_name + ' must contain at least one entry')
  228. for entry in category:
  229. event_list.append(EventData(category_name, entry))
  230. return event_list