healthchecks/hc/api/management/commands/prunepingsslow.py
Pēteris Caune 1e3285423f Ping objects get "n" field, their serial numbers, used in "log page". "fillnpings" management command initially populates this field (it touches every ping so it takes time to complete).
Check.n_pings now stores the total number of pings the check has ever received. Running "prunepings" command doesn't affect this field. +a new "prunepingsslow" command which works in smaller chunks so is appropriate for initial pruning of a huge api_ping table.
2016-01-03 18:11:12 +02:00

36 lines
1.2 KiB
Python

from django.db.models import F
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from hc.accounts.models import Profile
from hc.api.models import Check, Ping
class Command(BaseCommand):
help = """Prune pings based on limits in user profiles.
This command prunes each check individually. So it does the work
in small chunks instead of a few big SQL queries like the `prunepings`
command. It is appropriate for initial pruning of the potentially
huge api_ping table.
"""
def handle(self, *args, **options):
# Create any missing user profiles
for user in User.objects.filter(profile=None):
Profile.objects.for_user(user)
checks = Check.objects.annotate(
limit=F("user__profile__ping_log_limit"))
for check in checks:
q = Ping.objects.filter(owner_id=check.id)
q = q.filter(n__lt=check.n_pings - check.limit)
q = q.filter(n__gt=0)
n_pruned, _ = q.delete()
self.stdout.write("Pruned %d pings for check %s (%s)" %
(n_pruned, check.id, check.name))
return "Done!"