send_metrics.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # pylint: skip-file
  2. # flake8: noqa
  3. import base64
  4. import datetime
  5. import functools
  6. import itertools
  7. import json
  8. import pprint
  9. import random
  10. import string
  11. import struct
  12. import click
  13. from arroyo.backends.kafka import KafkaPayload, KafkaProducer
  14. from arroyo.types import Topic
  15. from sentry.sentry_metrics.use_case_id_registry import UseCaseID
  16. def make_counter_payload(use_case, org_id, rand_str):
  17. return {
  18. "name": f"c:{use_case}/{use_case}@none",
  19. "tags": {
  20. "environment": "production",
  21. "session.status": "init",
  22. f"metric_e2e_{use_case}_counter_k_{rand_str}": f"metric_e2e_{use_case}_counter_v_{rand_str}",
  23. },
  24. "timestamp": int(datetime.datetime.now(tz=datetime.UTC).timestamp()),
  25. "type": "c",
  26. "value": 1,
  27. "org_id": org_id,
  28. "retention_days": 90,
  29. "project_id": 3,
  30. }
  31. def make_dist_payload(use_case, org_id, rand_str, value_len, b64_encode):
  32. nums = [random.random() for _ in range(value_len)]
  33. return {
  34. "name": f"d:{use_case}/duration@second",
  35. "tags": {
  36. "environment": "production",
  37. "session.status": "healthy",
  38. f"metric_e2e_{use_case}_dist_k_{rand_str}": f"metric_e2e_{use_case}_dist_v_{rand_str}",
  39. },
  40. "timestamp": int(datetime.datetime.now(tz=datetime.UTC).timestamp()),
  41. "type": "d",
  42. "value": (
  43. {
  44. "format": "base64",
  45. "data": base64.b64encode(struct.pack(f"<{len(nums)}d", *nums))
  46. .replace(b"=", b"")
  47. .decode("ascii"),
  48. }
  49. if b64_encode
  50. else {
  51. "format": "array",
  52. "data": nums,
  53. }
  54. ),
  55. "org_id": org_id,
  56. "retention_days": 90,
  57. "project_id": 3,
  58. }
  59. def make_set_payload(use_case, org_id, rand_str, value_len, b64_encode):
  60. INT_WIDTH = 4
  61. nums = [random.randint(0, 2048) for _ in range(value_len)]
  62. return {
  63. "name": f"s:{use_case}/error@none",
  64. "tags": {
  65. "environment": "production",
  66. "session.status": "errored",
  67. f"metric_e2e_{use_case}_set_k_{rand_str}": f"metric_e2e_{use_case}_set_v_{rand_str}",
  68. },
  69. "timestamp": int(datetime.datetime.now(tz=datetime.UTC).timestamp()),
  70. "type": "s",
  71. "value": (
  72. {
  73. "format": "base64",
  74. "data": base64.b64encode(
  75. b"".join([num.to_bytes(INT_WIDTH, byteorder="little") for num in nums])
  76. )
  77. .replace(b"=", b"")
  78. .decode("ascii"),
  79. }
  80. if b64_encode
  81. else {
  82. "format": "array",
  83. "data": nums,
  84. }
  85. ),
  86. "org_id": org_id,
  87. "retention_days": 90,
  88. "project_id": 3,
  89. }
  90. def make_gauge_payload(use_case, org_id, rand_str):
  91. return {
  92. "name": f"s:{use_case}/error@none",
  93. "tags": {
  94. "environment": "production",
  95. "session.status": "errored",
  96. f"metric_e2e_{use_case}_set_k_{rand_str}": f"metric_e2e_{use_case}_set_v_{rand_str}",
  97. },
  98. "timestamp": int(datetime.datetime.now(tz=datetime.UTC).timestamp()),
  99. "type": "g",
  100. "value": {
  101. "min": 1,
  102. "max": 1,
  103. "sum": 1,
  104. "count": 1,
  105. "last": 1,
  106. },
  107. "org_id": org_id,
  108. "retention_days": 90,
  109. "project_id": 3,
  110. }
  111. make_psql = (
  112. lambda rand_str, is_generic: f"""
  113. SELECT string,
  114. organization_id,
  115. {"use_case_id," if is_generic else ""}
  116. date_added,
  117. last_seen
  118. FROM {"sentry_perfstringindexer" if is_generic else "sentry_stringindexer"}
  119. WHERE string ~ 'metric_e2e_.*{rand_str}';
  120. """
  121. )
  122. make_csql = lambda rand_str, is_generic: "UNION ALL".join(
  123. [
  124. f"""
  125. SELECT use_case_id,
  126. org_id,
  127. project_id,
  128. metric_id,
  129. timestamp,
  130. tags.key,
  131. tags.raw_value
  132. FROM {table_name}
  133. WHERE arrayExists(v -> match(v, 'metric_e2e_.*{rand_str}'), tags.raw_value)
  134. """
  135. for table_name in (
  136. [
  137. "generic_metric_counters_raw_local",
  138. "generic_metric_distributions_raw_local",
  139. "generic_metric_sets_raw_local",
  140. "generic_metric_gauges_raw_local",
  141. ]
  142. if is_generic
  143. else [
  144. "metrics_counters_v2_local",
  145. "metrics_distributions_v2_local",
  146. "metrics_sets_v2_local",
  147. ]
  148. )
  149. ]
  150. )
  151. def produce_msgs(messages, is_generic, host, dryrun, quiet):
  152. conf = {"bootstrap.servers": host}
  153. producer = KafkaProducer(conf)
  154. for i, message in enumerate(messages):
  155. print(f"{i + 1} / {len(messages)}")
  156. if not quiet:
  157. pprint.pprint(message)
  158. if not dryrun:
  159. producer.produce(
  160. Topic(name=("ingest-performance-metrics" if is_generic else "ingest-metrics")),
  161. KafkaPayload(key=None, value=json.dumps(message).encode("utf-8"), headers=[]),
  162. )
  163. print("Done")
  164. print()
  165. producer.close()
  166. @click.command()
  167. @click.option(
  168. "--metric-types", default="cdsg", show_default=True, help="The types of metrics to send"
  169. )
  170. @click.option(
  171. "--use-cases",
  172. multiple=True,
  173. default=[
  174. use_case_id.value for use_case_id in UseCaseID if use_case_id is not UseCaseID.SESSIONS
  175. ],
  176. show_default=True,
  177. help="The use case IDs.",
  178. )
  179. @click.option("--rand-str", default=None, help="The random string prefix for each key value pairs.")
  180. @click.option(
  181. "--host", default="127.0.0.1:9092", show_default=True, help="The host and port for kafka."
  182. )
  183. @click.option(
  184. "--dryrun",
  185. "-d",
  186. is_flag=True,
  187. default=False,
  188. show_default=True,
  189. help="Generate the messages without sending them.",
  190. )
  191. @click.option(
  192. "--quiet",
  193. "-q",
  194. is_flag=True,
  195. default=False,
  196. show_default=True,
  197. help="Disable printing the messages.",
  198. )
  199. @click.option(
  200. "--start-org-id",
  201. default=1,
  202. show_default=True,
  203. help="Specify which org id(s) to start from.",
  204. )
  205. @click.option(
  206. "--end-org-id",
  207. default=1,
  208. show_default=True,
  209. help="Specify which org id(s) to end with.",
  210. )
  211. @click.option(
  212. "--num-bad-msg",
  213. default=0,
  214. show_default=True,
  215. help="Number of additional badly formatted metric messages to send.",
  216. )
  217. @click.option(
  218. "--value-len",
  219. default=8,
  220. show_default=True,
  221. help="Number of elements for metrics (sets and distributions).",
  222. )
  223. @click.option(
  224. "--b64-encode",
  225. default=True,
  226. show_default=True,
  227. help="Encode sets and distribution metrics values in base64",
  228. )
  229. def main(
  230. metric_types,
  231. use_cases,
  232. rand_str,
  233. host,
  234. dryrun,
  235. quiet,
  236. start_org_id,
  237. end_org_id,
  238. num_bad_msg,
  239. value_len,
  240. b64_encode,
  241. ):
  242. if UseCaseID.SESSIONS.value in use_cases and len(use_cases) > 1:
  243. click.secho(
  244. "ERROR: UseCaseID.SESSIONS is in use_cases and there are more than 1 use cases",
  245. blink=True,
  246. bold=True,
  247. )
  248. exit(1)
  249. is_generic = UseCaseID.SESSIONS.value not in use_cases
  250. metric_types = "".join(set(metric_types))
  251. rand_str = rand_str or "".join(random.choices(string.ascii_uppercase + string.digits, k=8))
  252. payload_generators = {
  253. "c": functools.partial(make_counter_payload, rand_str=rand_str),
  254. "d": functools.partial(
  255. make_dist_payload, rand_str=rand_str, value_len=value_len, b64_encode=b64_encode
  256. ),
  257. "s": functools.partial(
  258. make_set_payload, rand_str=rand_str, value_len=value_len, b64_encode=b64_encode
  259. ),
  260. "g": functools.partial(make_gauge_payload, rand_str=rand_str),
  261. }
  262. messages = list(
  263. itertools.chain.from_iterable(
  264. (
  265. payload_generators[metric_type](use_case=use_case, org_id=org_id)
  266. for metric_type in metric_types
  267. )
  268. for use_case in use_cases
  269. for org_id in range(start_org_id, end_org_id + 1)
  270. )
  271. )
  272. messages.extend([{"BAD_VALUE": rand_str, "idx": i} for i in range(num_bad_msg)])
  273. random.shuffle(messages)
  274. produce_msgs(messages, is_generic, host, dryrun, quiet)
  275. strs_per_use_case = 3
  276. print(
  277. f"Use the following SQL to verify postgres, "
  278. f"there should be {strs_per_use_case} strings for each use cases, "
  279. f"{strs_per_use_case * len(use_cases) * (end_org_id - start_org_id + 1)} in total."
  280. )
  281. print(make_psql(rand_str, is_generic))
  282. if is_generic:
  283. print(
  284. f"Use the following SQL to verify clickhouse, "
  285. f"there should be {len(metric_types)} metrics for each use cases, "
  286. f"{len(metric_types) * len(use_cases) * (end_org_id - start_org_id + 1)} in total."
  287. )
  288. print(make_csql(rand_str, is_generic))
  289. if __name__ == "__main__":
  290. main()