Skip to content

Commit

Permalink
Merge pull request #344 from ThomasWaldmann/stale-domains
Browse files Browse the repository at this point in the history
implement django-admin domains --stale-check
  • Loading branch information
ThomasWaldmann committed Apr 25, 2018
2 parents 930d3f6 + 4e41cfb commit b5ed335
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions nsupdate/management/commands/domains.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from django.db import transaction
from django.utils.translation import ugettext_lazy as _

from nsupdate.main.models import Domain
from nsupdate.main.models import Domain, Host
from nsupdate.main.dnstools import FQDN, query_ns, NameServerNotAvailable
from nsupdate.utils.mail import translate_for_user, send_mail_to_user

Expand Down Expand Up @@ -40,6 +40,11 @@
""")


LOG_MSG_IS_AVAILABLE = _('Domain %%(domain)s is available.')
LOG_MSG_HAS_HOSTS = _('Domain %%(domain)s is not available, but has %(hosts)d hosts.')
LOG_MSG_DELETE = _('Domain %%(domain)s is not available and has no hosts -> deleted domain.')


def check_dns(domain):
"""
checks if the nameserver is reachable and answers queries for the domain.
Expand All @@ -62,6 +67,28 @@ def check_dns(domain):
return queries_ok


def check_staleness(d):
"""
checks the staleness of Domain d (is not available and has no hosts) and if it is stale, delete it.
Return log msg (can be None).
:param d: Domain instance
:return: log_msg
"""
if d.available:
log_msg = LOG_MSG_IS_AVAILABLE
else:
host_count = Host.objects.filter(domain=d).count()
if host_count > 0:
log_msg = LOG_MSG_HAS_HOSTS % dict(hosts=host_count)
else:
# is not available and has no hosts
d.delete()
log_msg = LOG_MSG_DELETE
return log_msg


class Command(BaseCommand):
help = 'deal with domains'

Expand All @@ -76,14 +103,20 @@ def add_arguments(self, parser):
dest='notify_user',
default=False,
help='notify the user by email when domain gets flagged as unavailable')
parser.add_argument('--stale-check',
action='store_true',
dest='stale_check',
default=False,
help='check whether domain is available or has hosts, delete if not')

def handle(self, *args, **options):
check = options['check']
stale_check = options['stale_check']
notify_user = options['notify_user']
with transaction.atomic():
for d in Domain.objects.all():
domain = d.name
if check and d.available:
domain = d.name
comment = d.comment
creator = d.created_by
available = check_dns(domain)
Expand All @@ -102,3 +135,8 @@ def handle(self, *args, **options):
msg = "setting unavailable flag for domain %s (created by %s)\n" % (domain, creator,)
self.stdout.write(msg)
d.save()
if stale_check:
log_msg = check_staleness(d)
if log_msg:
log_msg = log_msg % dict(domain=domain)
self.stdout.write(log_msg)

0 comments on commit b5ed335

Please sign in to comment.