Skip to content

Commit 83fb6b3

Browse files
b4ldrjenkins-bot
authored and
jenkins-bot
committed
getstats: Delete old versions of this report before running
This CR updates the job so that it first deletes all previous versions of this report before running. The code is based on the PR that added the JOBRESULT_RETENTION config item[1] [1]netbox-community/netbox#8957 Bug: T311048 Change-Id: I8895a851592036fe34d1b24e42953510cbc754e6
1 parent 591f80d commit 83fb6b3

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

customscripts/getstats.py

+40
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,59 @@
11
"""Produce Prometheus-formatted statistics about devices."""
2+
import sys
23

34
from collections import Counter
5+
from datetime import timedelta
6+
from pathlib import Path
47
from io import StringIO
58

9+
from django.contrib.contenttypes.models import ContentType
10+
from django.utils import timezone
11+
612
from dcim.models import Device
713

14+
from extras import models
15+
from extras.choices import JobResultStatusChoices
816
from extras.scripts import Script
917

1018

19+
def get_module(module):
20+
"""Get the module of this file handling the use case if its called as a script
21+
22+
Arguments
23+
module: the value of __module__
24+
25+
Returns:
26+
A string representing the module
27+
"""
28+
if module != '__main__':
29+
return module
30+
return Path(sys.modules[module].__file__).stem
31+
32+
1133
class GetDeviceStats(Script):
34+
"""Get device statistics"""
35+
1236
class Meta:
37+
"""Metadata"""
1338
name = "Get Device Statistics"
1439
description = "Dump a set of statistics about various devices for Prometheus."
1540

1641
def run(self, data, commit):
42+
"""The run method"""
43+
# Delete old versions of this report
44+
obj_type = ContentType.objects.get_for_model(models.Script)
45+
name = ".".join((get_module(self.__module__), self.__class__.__name__))
46+
# Keep any reports from the last 5 minutes to make this less racy
47+
cutoff = timezone.now() - timedelta(minutes=5)
48+
jobs = models.JobResult.objects.filter(
49+
obj_type=obj_type,
50+
name=name,
51+
status__in=JobResultStatusChoices.TERMINAL_STATE_CHOICES,
52+
created__lt=cutoff,
53+
)
54+
# Make sure we call delete on each job to trigger any customized delete methods
55+
for job in jobs:
56+
job.delete()
1757
counts = Counter()
1858
output = StringIO()
1959
for device in Device.objects.all().values_list(

0 commit comments

Comments
 (0)