send_metrics.py 8.7 KB

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