make_sample_checks.py 2.7 KB

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