make_sample_checks.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from random import randrange
  2. from django.utils import timezone
  3. from freezegun import freeze_time
  4. from model_bakery import baker
  5. from model_bakery.random_gen import gen_json, gen_slug
  6. from glitchtip.base_commands import MakeSampleCommand
  7. from glitchtip.uptime.models import Monitor, MonitorCheck
  8. from organizations_ext.models import Organization
  9. from projects.models import Project
  10. baker.generators.add("organizations.fields.SlugField", gen_slug)
  11. baker.generators.add("django.db.models.JSONField", gen_json)
  12. class Command(MakeSampleCommand):
  13. help = "Create a number of monitors each with checks for dev and demonstration purposes."
  14. def add_arguments(self, parser):
  15. self.add_org_project_arguments(parser)
  16. parser.add_argument("--monitor-quantity", type=int, default=10)
  17. parser.add_argument("--checks-quantity-per", type=int, default=100)
  18. parser.add_argument("--first-check-down", type=bool, default=False)
  19. def handle(self, *args, **options):
  20. super().handle(*args, **options)
  21. monitor_quantity = options["monitor_quantity"]
  22. checks_quantity_per = options["checks_quantity_per"]
  23. first_check_down = options["first_check_down"]
  24. monitors = [
  25. Monitor(
  26. project=self.project,
  27. name=f"Test Monitor #{i}",
  28. organization=self.organization,
  29. url="https://example.com",
  30. interval="60",
  31. monitor_type="Ping",
  32. expected_status="200",
  33. )
  34. for i in range(monitor_quantity)
  35. ]
  36. Monitor.objects.bulk_create(monitors)
  37. # Create checks sequentially based on time
  38. # Creates a better representation of data on disk
  39. checks = []
  40. start_time = timezone.now() - timezone.timedelta(minutes=checks_quantity_per)
  41. for time_i in range(checks_quantity_per):
  42. for monitor in monitors:
  43. is_first = time_i == 0
  44. is_up = True
  45. if first_check_down and is_first:
  46. is_up = False
  47. checks.append(
  48. MonitorCheck(
  49. monitor=monitor,
  50. is_up=is_up,
  51. is_change=is_first,
  52. start_check=start_time + timezone.timedelta(minutes=time_i),
  53. response_time=timezone.timedelta(
  54. milliseconds=randrange(1, 5000)
  55. ),
  56. )
  57. )
  58. if len(checks) > 10000:
  59. MonitorCheck.objects.bulk_create(checks)
  60. self.progress_tick()
  61. checks = []
  62. if checks:
  63. MonitorCheck.objects.bulk_create(checks)
  64. self.success_message('Successfully created "%s" monitors' % monitor_quantity)