load-mocks 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. #!/usr/bin/env python
  2. import time
  3. from sentry.runner import configure
  4. configure()
  5. import itertools
  6. import random
  7. from datetime import datetime, timedelta
  8. from hashlib import sha1
  9. from random import randint
  10. from uuid import uuid4
  11. from django.conf import settings
  12. from django.db import IntegrityError, transaction
  13. from django.db.models import F
  14. from django.utils import timezone
  15. from pytz import utc
  16. from sentry import buffer, roles, tsdb
  17. from sentry.event_manager import HashDiscarded
  18. from sentry.incidents.logic import create_alert_rule, create_alert_rule_trigger, create_incident
  19. from sentry.incidents.models import AlertRuleThresholdType, IncidentType
  20. from sentry.models import (
  21. TOMBSTONE_FIELDS_FROM_GROUP,
  22. Activity,
  23. Broadcast,
  24. CheckInStatus,
  25. Commit,
  26. CommitAuthor,
  27. CommitFileChange,
  28. Deploy,
  29. Environment,
  30. EventAttachment,
  31. File,
  32. Group,
  33. GroupRelease,
  34. GroupTombstone,
  35. Monitor,
  36. MonitorCheckIn,
  37. MonitorStatus,
  38. MonitorType,
  39. Organization,
  40. OrganizationAccessRequest,
  41. OrganizationMember,
  42. Project,
  43. Release,
  44. ReleaseCommit,
  45. ReleaseEnvironment,
  46. ReleaseFile,
  47. ReleaseProjectEnvironment,
  48. Repository,
  49. Team,
  50. User,
  51. UserReport,
  52. )
  53. from sentry.signals import mocks_loaded
  54. from sentry.similarity import features
  55. from sentry.utils import loremipsum
  56. from sentry.utils.hashlib import md5_text
  57. from sentry.utils.samples import create_sample_event as _create_sample_event
  58. from sentry.utils.samples import create_trace, generate_user, random_normal
  59. PLATFORMS = itertools.cycle(["ruby", "php", "python", "java", "javascript"])
  60. LEVELS = itertools.cycle(["error", "error", "error", "fatal", "warning"])
  61. ENVIRONMENTS = itertools.cycle(["production", "production", "staging", "alpha", "beta", ""])
  62. MONITOR_NAMES = itertools.cycle(settings.CELERYBEAT_SCHEDULE.keys())
  63. MONITOR_SCHEDULES = itertools.cycle(["* * * * *", "0 * * * *", "0 0 * * *"])
  64. LONG_MESSAGE = """Code: 0.
  65. DB::Exception: String is too long for DateTime: 2018-10-26T19:14:18+00:00. Stack trace:
  66. 0. clickhouse-server(StackTrace::StackTrace()+0x16) [0x99e9626]
  67. 1. clickhouse-server(DB::Exception::Exception(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)+0x22) [0x3087172]
  68. 2. clickhouse-server(DB::FunctionComparison<DB::EqualsOp, DB::NameEquals>::executeDateOrDateTimeOrEnumOrUUIDWithConstString(DB::Block&, unsigned long, DB::IColumn const*, DB::IColumn const*, std::shared_ptr<DB::IDataType const> const&, std::shared_ptr<DB::IDataType const> const&, bool, unsigned long)+0x13c8) [0x3b233d8]
  69. 3. clickhouse-server(DB::FunctionComparison<DB::EqualsOp, DB::NameEquals>::executeImpl(DB::Block&, std::vector<unsigned long, std::allocator<unsigned long> > const&, unsigned long, unsigned long)+0x576) [0x3bafc86]
  70. 4. clickhouse-server(DB::PreparedFunctionImpl::defaultImplementationForNulls(DB::Block&, std::vector<unsigned long, std::allocator<unsigned long> > const&, unsigned long, unsigned long)+0x174) [0x7953cd4]
  71. 5. clickhouse-server(DB::PreparedFunctionImpl::executeWithoutLowCardinalityColumns(DB::Block&, std::vector<unsigned long, std::allocator<unsigned long> > const&, unsigned long, unsigned long)+0x54) [0x7953b04]
  72. 6. clickhouse-server(DB::PreparedFunctionImpl::execute(DB::Block&, std::vector<unsigned long, std::allocator<unsigned long> > const&, unsigned long, unsigned long)+0x3e2) [0x7954222]
  73. 7. clickhouse-server(DB::ExpressionAction::execute(DB::Block&, std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, unsigned long, std::hash<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::equal_to<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, unsigned long> > >&) const+0x69b) [0x7b021fb]
  74. 8. clickhouse-server(DB::ExpressionActions::execute(DB::Block&) const+0xe6) [0x7b03676]
  75. 9. clickhouse-server(DB::FilterBlockInputStream::FilterBlockInputStream(std::shared_ptr<DB::IBlockInputStream> const&, std::shared_ptr<DB::ExpressionActions> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)+0x711) [0x79b7e31]
  76. 10. clickhouse-server() [0x75e9443]
  77. 11. clickhouse-server(DB::InterpreterSelectQuery::executeImpl(DB::InterpreterSelectQuery::Pipeline&, std::shared_ptr<DB::IBlockInputStream> const&, bool)+0x118f) [0x75f212f]
  78. 12. clickhouse-server(DB::InterpreterSelectQuery::InterpreterSelectQuery(std::shared_ptr<DB::IAST> const&, DB::Context const&, std::shared_ptr<DB::IBlockInputStream> const&, std::shared_ptr<DB::IStorage> const&, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, DB::QueryProcessingStage::Enum, unsigned long, bool)+0x5e6) [0x75f2d46]
  79. 13. clickhouse-server(DB::InterpreterSelectQuery::InterpreterSelectQuery(std::shared_ptr<DB::IAST> const&, DB::Context const&, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, DB::QueryProcessingStage::Enum, unsigned long, bool)+0x56) [0x75f3aa6]
  80. 14. clickhouse-server(DB::InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery(std::shared_ptr<DB::IAST> const&, DB::Context const&, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, DB::QueryProcessingStage::Enum, unsigned long, bool)+0x7e7) [0x75ffab7]
  81. 15. clickhouse-server(DB::InterpreterFactory::get(std::shared_ptr<DB::IAST>&, DB::Context&, DB::QueryProcessingStage::Enum)+0x3a8) [0x75dc138]
  82. 16. clickhouse-server() [0x768fad9]
  83. 17. clickhouse-server(DB::executeQuery(std::__cxx11::basic..."""
  84. def make_sentence(words=None):
  85. if words is None:
  86. words = int(random.weibullvariate(8, 3))
  87. return " ".join(random.choice(loremipsum.words) for _ in range(words))
  88. def create_sample_event(*args, **kwargs):
  89. try:
  90. event = _create_sample_event(*args, **kwargs)
  91. except HashDiscarded as e:
  92. print(f"> Skipping Event: {e.message}") # NOQA
  93. else:
  94. if event is not None:
  95. features.record([event])
  96. return event
  97. def generate_commits(user):
  98. commits = []
  99. for i in range(random.randint(1, 20)):
  100. if i == 1:
  101. filename = "raven/base.py"
  102. else:
  103. filename = random.choice(loremipsum.words) + ".js"
  104. if random.randint(0, 5) == 1:
  105. author = (user.name, user.email)
  106. else:
  107. author = (
  108. f"{random.choice(loremipsum.words)} {random.choice(loremipsum.words)}",
  109. f"{random.choice(loremipsum.words)}@example.com",
  110. )
  111. commits.append(
  112. {
  113. "key": sha1(uuid4().bytes).hexdigest(),
  114. "message": f"feat: Do something to {filename}\n{make_sentence()}",
  115. "author": author,
  116. "files": [(filename, "M")],
  117. }
  118. )
  119. return commits
  120. def generate_tombstones(project, user):
  121. # attempt to create a high enough previous_group_id
  122. # that it won't conflict with any group ids
  123. prev_group_id = 100000
  124. try:
  125. prev_group_id = (
  126. max(
  127. GroupTombstone.objects.order_by("-previous_group_id")[0].previous_group_id,
  128. prev_group_id,
  129. )
  130. + 1
  131. )
  132. except IndexError:
  133. pass
  134. for group in Group.objects.filter(project=project)[:5]:
  135. GroupTombstone.objects.create(
  136. previous_group_id=prev_group_id,
  137. actor_id=user.id,
  138. **{name: getattr(group, name) for name in TOMBSTONE_FIELDS_FROM_GROUP},
  139. )
  140. prev_group_id += 1
  141. def create_system_time_series():
  142. now = datetime.utcnow().replace(tzinfo=utc)
  143. for _ in range(60):
  144. count = randint(1, 10)
  145. tsdb.incr_multi(
  146. (
  147. (tsdb.models.internal, "client-api.all-versions.responses.2xx"),
  148. (tsdb.models.internal, "client-api.all-versions.requests"),
  149. ),
  150. now,
  151. int(count * 0.9),
  152. )
  153. tsdb.incr_multi(
  154. ((tsdb.models.internal, "client-api.all-versions.responses.4xx"),),
  155. now,
  156. int(count * 0.05),
  157. )
  158. tsdb.incr_multi(
  159. ((tsdb.models.internal, "client-api.all-versions.responses.5xx"),),
  160. now,
  161. int(count * 0.1),
  162. )
  163. now = now - timedelta(seconds=1)
  164. for _ in range(24 * 30):
  165. count = randint(100, 1000)
  166. tsdb.incr_multi(
  167. (
  168. (tsdb.models.internal, "client-api.all-versions.responses.2xx"),
  169. (tsdb.models.internal, "client-api.all-versions.requests"),
  170. ),
  171. now,
  172. int(count * 4.9),
  173. )
  174. tsdb.incr_multi(
  175. ((tsdb.models.internal, "client-api.all-versions.responses.4xx"),),
  176. now,
  177. int(count * 0.05),
  178. )
  179. tsdb.incr_multi(
  180. ((tsdb.models.internal, "client-api.all-versions.responses.5xx"),),
  181. now,
  182. int(count * 0.1),
  183. )
  184. now = now - timedelta(hours=1)
  185. def create_sample_time_series(event, release=None):
  186. if event is None:
  187. return
  188. group = event.group
  189. project = group.project
  190. key = project.key_set.all()[0]
  191. now = datetime.utcnow().replace(tzinfo=utc)
  192. environment = Environment.get_or_create(
  193. project=project, name=Environment.get_name_or_default(event.get_tag("environment"))
  194. )
  195. if release:
  196. ReleaseEnvironment.get_or_create(
  197. project=project, release=release, environment=environment, datetime=now
  198. )
  199. grouprelease = GroupRelease.get_or_create(
  200. group=group, release=release, environment=environment, datetime=now
  201. )
  202. for _ in range(60):
  203. count = randint(1, 10)
  204. tsdb.incr_multi(
  205. ((tsdb.models.project, project.id), (tsdb.models.group, group.id)),
  206. now,
  207. count,
  208. environment_id=environment.id,
  209. )
  210. tsdb.incr_multi(
  211. (
  212. (tsdb.models.organization_total_received, project.organization_id),
  213. (tsdb.models.project_total_received, project.id),
  214. (tsdb.models.key_total_received, key.id),
  215. ),
  216. now,
  217. int(count * 1.1),
  218. )
  219. tsdb.incr(
  220. tsdb.models.project_total_forwarded,
  221. project.id,
  222. now,
  223. int(count * 1.1),
  224. )
  225. tsdb.incr_multi(
  226. (
  227. (tsdb.models.organization_total_rejected, project.organization_id),
  228. (tsdb.models.project_total_rejected, project.id),
  229. (tsdb.models.key_total_rejected, key.id),
  230. ),
  231. now,
  232. int(count * 0.1),
  233. )
  234. frequencies = [
  235. (tsdb.models.frequent_issues_by_project, {project.id: {group.id: count}}),
  236. (tsdb.models.frequent_environments_by_group, {group.id: {environment.id: count}}),
  237. ]
  238. if release:
  239. frequencies.append(
  240. (tsdb.models.frequent_releases_by_group, {group.id: {grouprelease.id: count}})
  241. )
  242. tsdb.record_frequency_multi(frequencies, now)
  243. now = now - timedelta(seconds=1)
  244. for _ in range(24 * 30):
  245. count = randint(100, 1000)
  246. tsdb.incr_multi(
  247. ((tsdb.models.project, group.project.id), (tsdb.models.group, group.id)),
  248. now,
  249. count,
  250. environment_id=environment.id,
  251. )
  252. tsdb.incr_multi(
  253. (
  254. (tsdb.models.organization_total_received, project.organization_id),
  255. (tsdb.models.project_total_received, project.id),
  256. (tsdb.models.key_total_received, key.id),
  257. ),
  258. now,
  259. int(count * 1.1),
  260. )
  261. tsdb.incr_multi(
  262. (
  263. (tsdb.models.organization_total_rejected, project.organization_id),
  264. (tsdb.models.project_total_rejected, project.id),
  265. (tsdb.models.key_total_rejected, key.id),
  266. ),
  267. now,
  268. int(count * 0.1),
  269. )
  270. frequencies = [
  271. (tsdb.models.frequent_issues_by_project, {project.id: {group.id: count}}),
  272. (tsdb.models.frequent_environments_by_group, {group.id: {environment.id: count}}),
  273. ]
  274. if release:
  275. frequencies.append(
  276. (tsdb.models.frequent_releases_by_group, {group.id: {grouprelease.id: count}})
  277. )
  278. tsdb.record_frequency_multi(frequencies, now)
  279. now = now - timedelta(hours=1)
  280. def main(num_events=1, extra_events=False, load_trends=False, slow=False):
  281. try:
  282. user = User.objects.filter(is_superuser=True)[0]
  283. except IndexError:
  284. raise Exception("No superuser exists (run `make bootstrap`)")
  285. dummy_user, _ = User.objects.get_or_create(
  286. username="dummy@example.com", defaults={"email": "dummy@example.com"}
  287. )
  288. dummy_user.set_password("dummy")
  289. dummy_user.save()
  290. mocks = (
  291. ("Massive Dynamic", ("Ludic Science",)),
  292. ("Captain Planet", ("Earth", "Fire", "Wind", "Water", "Heart")),
  293. )
  294. project_map = {}
  295. Broadcast.objects.create(
  296. title="Learn about Source Maps",
  297. message="Source maps are JSON files that contain information on how to map your transpiled source code back to their original source.",
  298. link="https://docs.sentry.io/platforms/javascript/#source-maps",
  299. )
  300. if settings.SENTRY_SINGLE_ORGANIZATION:
  301. org = Organization.get_default()
  302. print(f"Mocking org {org.name}") # NOQA
  303. else:
  304. print("Mocking org {}".format("Default")) # NOQA
  305. org, _ = Organization.objects.get_or_create(slug="default")
  306. OrganizationMember.objects.get_or_create(
  307. user=user, organization=org, role=roles.get_top_dog().id
  308. )
  309. dummy_member, _ = OrganizationMember.objects.get_or_create(
  310. user=dummy_user, organization=org, defaults={"role": roles.get_default().id}
  311. )
  312. # Allow for 0 events, if you only want transactions
  313. event1 = event2 = event3 = event4 = event5 = None
  314. for team_name, project_names in mocks:
  315. print(f"> Mocking team {team_name}") # NOQA
  316. team, _ = Team.objects.get_or_create(name=team_name, defaults={"organization": org})
  317. for project_name in project_names:
  318. print(f" > Mocking project {project_name}") # NOQA
  319. project, _ = Project.objects.get_or_create(
  320. name=project_name,
  321. defaults={
  322. "organization": org,
  323. "first_event": timezone.now(),
  324. "flags": Project.flags.has_releases,
  325. },
  326. )
  327. project_map[project_name] = project
  328. project.add_team(team)
  329. if not project.first_event:
  330. project.update(first_event=project.date_added)
  331. if not project.flags.has_releases:
  332. project.update(flags=F("flags").bitor(Project.flags.has_releases))
  333. monitor, created = Monitor.objects.get_or_create(
  334. name=next(MONITOR_NAMES),
  335. project_id=project.id,
  336. organization_id=org.id,
  337. type=MonitorType.CRON_JOB,
  338. defaults={
  339. "config": {"schedule": next(MONITOR_SCHEDULES)},
  340. "next_checkin": timezone.now() + timedelta(minutes=60),
  341. "last_checkin": timezone.now(),
  342. },
  343. )
  344. if not created:
  345. if not (monitor.config or {}).get("schedule"):
  346. monitor.config = {"schedule": next(MONITOR_SCHEDULES)}
  347. monitor.update(
  348. config=monitor.config,
  349. status=MonitorStatus.OK if randint(0, 10) < 7 else MonitorStatus.ERROR,
  350. last_checkin=timezone.now(),
  351. next_checkin=monitor.get_next_scheduled_checkin(timezone.now()),
  352. )
  353. MonitorCheckIn.objects.create(
  354. project_id=monitor.project_id,
  355. monitor=monitor,
  356. status=CheckInStatus.OK
  357. if monitor.status == MonitorStatus.OK
  358. else CheckInStatus.ERROR,
  359. )
  360. with transaction.atomic():
  361. has_release = Release.objects.filter(
  362. version=sha1(uuid4().bytes).hexdigest(),
  363. organization_id=project.organization_id,
  364. projects=project,
  365. ).exists()
  366. if not has_release:
  367. release = Release.objects.filter(
  368. version=sha1(uuid4().bytes).hexdigest(),
  369. organization_id=project.organization_id,
  370. ).first()
  371. if not release:
  372. release = Release.objects.create(
  373. version=sha1(uuid4().bytes).hexdigest(),
  374. organization_id=project.organization_id,
  375. )
  376. release.add_project(project)
  377. generate_tombstones(project, user)
  378. raw_commits = generate_commits(user)
  379. try:
  380. with transaction.atomic():
  381. repo, _ = Repository.objects.get_or_create(
  382. organization_id=org.id,
  383. provider="integrations:github",
  384. external_id="example/example",
  385. defaults={
  386. "name": "Example Repo",
  387. "url": "https://github.com/example/example",
  388. },
  389. )
  390. except IntegrityError:
  391. # for users with legacy github plugin
  392. # upgrade to the new integration
  393. repo = Repository.objects.get(
  394. organization_id=org.id,
  395. provider="github",
  396. external_id="example/example",
  397. name="Example Repo",
  398. )
  399. repo.provider = "integrations:github"
  400. repo.save()
  401. authors = set()
  402. for commit_index, raw_commit in enumerate(raw_commits):
  403. author = CommitAuthor.objects.get_or_create(
  404. organization_id=org.id,
  405. email=raw_commit["author"][1],
  406. defaults={"name": raw_commit["author"][0]},
  407. )[0]
  408. commit = Commit.objects.get_or_create(
  409. organization_id=org.id,
  410. repository_id=repo.id,
  411. key=raw_commit["key"],
  412. defaults={"author": author, "message": raw_commit["message"]},
  413. )[0]
  414. authors.add(author)
  415. for file in raw_commit["files"]:
  416. ReleaseFile.objects.get_or_create(
  417. organization_id=project.organization_id,
  418. release_id=release.id,
  419. name=file[0],
  420. file=File.objects.get_or_create(
  421. name=file[0], type="release.file", checksum="abcde" * 8, size=13043
  422. )[0],
  423. defaults={"organization_id": project.organization_id},
  424. )
  425. CommitFileChange.objects.get_or_create(
  426. organization_id=org.id, commit=commit, filename=file[0], type=file[1]
  427. )
  428. ReleaseCommit.objects.get_or_create(
  429. organization_id=org.id, release=release, commit=commit, order=commit_index
  430. )
  431. # create an unreleased commit
  432. Commit.objects.get_or_create(
  433. organization_id=org.id,
  434. repository_id=repo.id,
  435. key=sha1(uuid4().bytes).hexdigest(),
  436. defaults={
  437. "author": CommitAuthor.objects.get_or_create(
  438. organization_id=org.id, email=user.email, defaults={"name": user.name}
  439. )[0],
  440. "message": "feat: Do something to {}\n{}".format(
  441. random.choice(loremipsum.words) + ".js", make_sentence()
  442. ),
  443. },
  444. )[0]
  445. Activity.objects.create(
  446. type=Activity.RELEASE,
  447. project=project,
  448. ident=release.version,
  449. user=user,
  450. data={"version": release.version},
  451. )
  452. environment = Environment.get_or_create(project=project, name=next(ENVIRONMENTS))
  453. deploy = Deploy.objects.create(
  454. organization_id=project.organization_id,
  455. release=release,
  456. environment_id=environment.id,
  457. )
  458. release.update(
  459. commit_count=len(raw_commits),
  460. last_commit_id=commit.id,
  461. total_deploys=Deploy.objects.filter(release=release).count(),
  462. last_deploy_id=deploy.id,
  463. authors=[str(a.id) for a in authors],
  464. )
  465. ReleaseProjectEnvironment.objects.create_or_update(
  466. project=project,
  467. environment=environment,
  468. release=release,
  469. defaults={"last_deploy_id": deploy.id},
  470. )
  471. Activity.objects.create(
  472. type=Activity.DEPLOY,
  473. project=project,
  474. ident=release.version,
  475. data={
  476. "version": release.version,
  477. "deploy_id": deploy.id,
  478. "environment": environment.name,
  479. },
  480. datetime=deploy.date_finished,
  481. )
  482. # Add a bunch of additional dummy events to support pagination
  483. if extra_events:
  484. for _ in range(45):
  485. platform = next(PLATFORMS)
  486. create_sample_event(
  487. project=project,
  488. platform=platform,
  489. release=release.version,
  490. level=next(LEVELS),
  491. environment=next(ENVIRONMENTS),
  492. message="This is a mostly useless example %s exception" % platform,
  493. checksum=md5_text(platform + str(_)).hexdigest(),
  494. user=generate_user(),
  495. )
  496. for _ in range(num_events):
  497. event1 = create_sample_event(
  498. project=project,
  499. platform="python",
  500. release=release.version,
  501. environment=next(ENVIRONMENTS),
  502. user=generate_user(),
  503. )
  504. EventAttachment.objects.create(
  505. project_id=project.id,
  506. event_id=event1.event_id,
  507. name="example-logfile.txt",
  508. file_id=File.objects.get_or_create(
  509. name="example-logfile.txt",
  510. type="text/plain",
  511. checksum="abcde" * 8,
  512. size=13043,
  513. )[0].id,
  514. )
  515. event2 = create_sample_event(
  516. project=project,
  517. platform="javascript",
  518. release=release.version,
  519. environment=next(ENVIRONMENTS),
  520. sdk={"name": "raven-js", "version": "2.1.0"},
  521. user=generate_user(),
  522. )
  523. event3 = create_sample_event(project, "java")
  524. event4 = create_sample_event(
  525. project=project,
  526. platform="ruby",
  527. release=release.version,
  528. environment=next(ENVIRONMENTS),
  529. user=generate_user(),
  530. )
  531. event5 = create_sample_event(
  532. project=project,
  533. platform="cocoa",
  534. release=release.version,
  535. environment=next(ENVIRONMENTS),
  536. user=generate_user(),
  537. )
  538. create_sample_event(
  539. project=project,
  540. platform="php",
  541. release=release.version,
  542. environment=next(ENVIRONMENTS),
  543. message=LONG_MESSAGE,
  544. user=generate_user(),
  545. )
  546. create_sample_event(
  547. project=project,
  548. platform="cocoa",
  549. sample_name="react-native",
  550. release=release.version,
  551. environment=next(ENVIRONMENTS),
  552. user=generate_user(),
  553. )
  554. create_sample_event(
  555. project=project,
  556. platform="pii",
  557. release=release.version,
  558. environment=next(ENVIRONMENTS),
  559. user=generate_user(),
  560. )
  561. if event5:
  562. Commit.objects.get_or_create(
  563. organization_id=org.id,
  564. repository_id=repo.id,
  565. key=sha1(uuid4().bytes).hexdigest(),
  566. defaults={
  567. "author": CommitAuthor.objects.get_or_create(
  568. organization_id=org.id, email=user.email, defaults={"name": user.name}
  569. )[0],
  570. "message": f"Ooops!\nFixes {event5.group.qualified_short_id}",
  571. },
  572. )[0]
  573. create_sample_event(project=project, environment=next(ENVIRONMENTS), platform="csp")
  574. if event3:
  575. UserReport.objects.create(
  576. project_id=project.id,
  577. event_id=event3.event_id,
  578. group_id=event3.group.id,
  579. name="Jane Bloggs",
  580. email="jane@example.com",
  581. comments=make_sentence(),
  582. )
  583. # Metric alerts
  584. alert_rule = create_alert_rule(
  585. org,
  586. [project],
  587. "My Alert Rule",
  588. "level:error",
  589. "count()",
  590. 10,
  591. AlertRuleThresholdType.ABOVE,
  592. 1,
  593. )
  594. create_alert_rule_trigger(alert_rule, "critical", 10)
  595. create_incident(
  596. org,
  597. type_=IncidentType.DETECTED,
  598. title="My Incident",
  599. date_started=datetime.utcnow().replace(tzinfo=utc),
  600. alert_rule=alert_rule,
  601. projects=[project],
  602. )
  603. print(f" > Loading time series data") # NOQA
  604. if event1:
  605. create_sample_time_series(event1, release=release)
  606. if event2:
  607. create_sample_time_series(event2, release=release)
  608. if event3:
  609. create_sample_time_series(event3)
  610. if event4:
  611. create_sample_time_series(event4, release=release)
  612. if event5:
  613. create_sample_time_series(event5, release=release)
  614. if hasattr(buffer, "process_pending"):
  615. print(" > Processing pending buffers") # NOQA
  616. buffer.process_pending()
  617. mocks_loaded.send(project=project, sender=__name__)
  618. OrganizationAccessRequest.objects.create_or_update(member=dummy_member, team=team)
  619. create_mock_transactions(project_map, load_trends, slow)
  620. Activity.objects.create(
  621. type=Activity.RELEASE,
  622. project=project,
  623. ident="4f38b65c62c4565aa94bba391ff8946922a8eed4",
  624. user=user,
  625. data={"version": "4f38b65c62c4565aa94bba391ff8946922a8eed4"},
  626. )
  627. create_system_time_series()
  628. def create_mock_transactions(project_map, load_trends=False, slow=False):
  629. backend_project = project_map["Earth"]
  630. frontend_project = project_map["Fire"]
  631. service_projects = [
  632. project_map["Wind"],
  633. project_map["Water"],
  634. project_map["Heart"],
  635. ]
  636. for project in project_map.values():
  637. if not project.flags.has_transactions:
  638. project.update(flags=F("flags").bitor(Project.flags.has_transactions))
  639. timestamp = timezone.now()
  640. print(f" > Loading a trace") # NOQA
  641. create_trace(
  642. slow,
  643. timestamp - timedelta(milliseconds=random_normal(4000, 250, 1000)),
  644. timestamp,
  645. generate_user(),
  646. uuid4().hex,
  647. None,
  648. {
  649. "project": frontend_project,
  650. "transaction": "/plants/:plantId/",
  651. "frontend": True,
  652. "errors": 1,
  653. "children": [
  654. {
  655. "project": backend_project,
  656. "transaction": "/api/plants/",
  657. "children": [
  658. {
  659. "project": service_projects[0],
  660. "transaction": "/products/all/",
  661. "children": [],
  662. },
  663. {
  664. "project": service_projects[1],
  665. "transaction": "/analytics/",
  666. "children": [],
  667. },
  668. {
  669. "project": service_projects[2],
  670. "transaction": "tasks.create_invoice",
  671. "children": [
  672. {
  673. "project": service_projects[2],
  674. "transaction": "tasks.process_invoice",
  675. "children": [
  676. {
  677. "project": service_projects[2],
  678. "transaction": "tasks.process_invoice",
  679. "children": [
  680. {
  681. "project": service_projects[2],
  682. "transaction": "tasks.process_invoice",
  683. "children": [
  684. {
  685. "project": service_projects[2],
  686. "transaction": "tasks.process_invoice",
  687. "children": [],
  688. },
  689. ],
  690. },
  691. ],
  692. },
  693. ],
  694. },
  695. ],
  696. },
  697. ],
  698. },
  699. ],
  700. },
  701. )
  702. if load_trends:
  703. print(f" > Loading trends data") # NOQA
  704. for day in range(14):
  705. for hour in range(24):
  706. timestamp = timezone.now() - timedelta(days=day, hours=hour)
  707. transaction_user = generate_user()
  708. trace_id = uuid4().hex
  709. frontend_span_id = uuid4().hex[:16]
  710. frontend_root_span_id = uuid4().hex[:16]
  711. frontend_duration = random_normal(2000 - 50 * day, 250, 1000)
  712. create_sample_event(
  713. project=frontend_project,
  714. platform="javascript-transaction",
  715. transaction="/trends/:frontend/",
  716. event_id=uuid4().hex,
  717. user=transaction_user,
  718. timestamp=timestamp,
  719. # start_timestamp decreases based on day so that there's a trend
  720. start_timestamp=timestamp - timedelta(milliseconds=frontend_duration),
  721. measurements={
  722. "fp": {"value": random_normal(1250 - 50 * day, 200, 500)},
  723. "fcp": {"value": random_normal(1250 - 50 * day, 200, 500)},
  724. "lcp": {"value": random_normal(2800 - 50 * day, 400, 2000)},
  725. "fid": {"value": random_normal(5 - 0.125 * day, 2, 1)},
  726. },
  727. # Root
  728. parent_span_id=None,
  729. span_id=frontend_root_span_id,
  730. trace=trace_id,
  731. spans=[
  732. {
  733. "same_process_as_parent": True,
  734. "op": "http",
  735. "description": "GET /api/plants/?all_plants=1",
  736. "data": {
  737. "duration": random_normal(
  738. 1 - 0.05 * day, 0.25, 0.01, frontend_duration / 1000
  739. ),
  740. "offset": 0.02,
  741. },
  742. "span_id": frontend_span_id,
  743. "trace_id": trace_id,
  744. }
  745. ],
  746. )
  747. # try to give clickhouse some breathing room
  748. if slow:
  749. time.sleep(0.05)
  750. backend_duration = random_normal(1500 + 50 * day, 250, 500)
  751. create_sample_event(
  752. project=backend_project,
  753. platform="transaction",
  754. transaction="/trends/backend/",
  755. event_id=uuid4().hex,
  756. user=transaction_user,
  757. timestamp=timestamp,
  758. start_timestamp=timestamp - timedelta(milliseconds=backend_duration),
  759. # match the trace from the javascript transaction
  760. trace=trace_id,
  761. parent_span_id=frontend_root_span_id,
  762. spans=[],
  763. )
  764. # try to give clickhouse some breathing room
  765. if slow:
  766. time.sleep(0.05)
  767. if __name__ == "__main__":
  768. settings.CELERY_ALWAYS_EAGER = True
  769. from optparse import OptionParser
  770. parser = OptionParser()
  771. parser.add_option("--events", default=1, type=int, help="number of events to generate")
  772. parser.add_option(
  773. "--extra-events",
  774. default=False,
  775. action="store_true",
  776. help="add multiple events for each error group",
  777. )
  778. parser.add_option(
  779. "--load-trends",
  780. default=False,
  781. action="store_true",
  782. help="load multiple transactions for each id to show trends",
  783. )
  784. parser.add_option(
  785. "--slow",
  786. default=False,
  787. action="store_true",
  788. help="sleep between each transaction to let clickhouse rest",
  789. )
  790. (options, args) = parser.parse_args()
  791. try:
  792. main(
  793. num_events=options.events,
  794. extra_events=options.extra_events,
  795. load_trends=options.load_trends,
  796. slow=options.slow,
  797. )
  798. except Exception:
  799. # Avoid reporting any issues recursively back into Sentry
  800. import sys
  801. import traceback
  802. traceback.print_exc()
  803. sys.exit(1)