]> gitweb.michael.orlitzky.com - djbdns-logparse.git/blobdiff - bin/djbdns-logparse.py
bin/djbdns-logparse.py: move regex handling down a level.
[djbdns-logparse.git] / bin / djbdns-logparse.py
index 067d9b17749cbc87b9b786dcb11f4054cb68ba79..33fc69d391277a699132ca9b82bd4afba2aefb36 100755 (executable)
@@ -70,11 +70,15 @@ query_type = {
 
 # tinydns can drop a query for one of three reasons; this dictionary
 # maps the symbol that gets logged in each case to a human-readable
-# reason.
+# reason. We include the "+" case here, indicating that the query was
+# NOT dropped, to avoid a special case later on when we're formatting
+# the human-readable output.
 query_drop_reason = {
+    "+": None,
     "-": "no authority",
     "I": "invalid query",
     "C": "invalid class",
+    "/": "couldn't parse"
 }
 
 
@@ -124,7 +128,11 @@ def decode_type(words, i):
     qt = words[i]
     words[i] = query_type.get(int(qt), qt)
 
-def handle_dnscache_log(line, match):
+def handle_dnscache_log(line) -> bool:
+    match = dnscache_log_re.match(line)
+    if not match:
+        return False
+
     (timestamp, event, data) = match.groups()
 
     words = data.split()
@@ -194,31 +202,37 @@ def handle_dnscache_log(line, match):
         decode_client(words, 0)
 
     print(timestamp, event, " ".join(words))
+    return True
 
 
-def handle_tinydns_log(line : str, match: re.Match):
+def handle_tinydns_log(line : str) -> bool:
     """
-    Handle a line that matched the ``tinydns_log_re`` regex.
+    Handle a single log line if it matches the ``tinydns_log_re`` regex.
 
     Parameters
     ----------
 
     line : string
-        The tinydns log line that matched ``tinydns_log_re``.
+        The log line that might match ``tinydns_log_re``.
+
+    Returns
+    -------
 
-    match : re.Match
-        The match object that was returned when ``line`` was
-        tested against ``tinydns_log_re``.
+    ``True`` if the log line was handled (that is, if it was really a
+    tinydns log line), and ``False`` otherwise.
 
     Examples
     --------
 
         >>> line = "2022-09-14 21:04:40.206516500 7f000001:9d61:be69 - 0001 www.example.com"
-        >>> match = tinydns_log_re.match(line)
-        >>> handle_tinydns_log(line, match)
+        >>> _ = handle_tinydns_log(line)
         2022-09-14 21:04:40.206516500 dropped query (no authority) from 127.0.0.1:40289 (id 48745): a www.example.com
 
     """
+    match = tinydns_log_re.match(line)
+    if not match:
+        return False
+
     (timestamp, ip, port, id, code, type, name) = match.groups()
     ip = convert_ip(ip)
     port = int(port, 16)
@@ -232,19 +246,23 @@ def handle_tinydns_log(line : str, match: re.Match):
 
     print(timestamp, end=' ')
 
+    reason = query_drop_reason[code]
     if code == "+":
-        print ("sent response to %s:%s (id %s): %s %s"
-               % (ip, port, id, type, name))
-    elif code in ("-", "I", "C"):
-        reason = query_drop_reason[code]
-        print ("dropped query (%s) from %s:%s (id %s): %s %s"
-               % (reason, ip, port, id, type, name))
-    elif code == "/":
-        print ("dropped query (couldn't parse) from %s:%s"
-               % (ip, port))
+        line_tpl = "sent response to {ip}:{port} (id {id}): {type} {name}"
     else:
-        print ("%s from %s:%s (id %s): %s %s"
-               % (code, ip, port, id, type, name))
+        line_tpl = "dropped query ({reason}) from {ip}:{port}"
+        if code != "/":
+            # If the query can actually be parsed, the log line is a
+            # bit more informative than it would have been otherwise.
+            line_tpl += " (id {id}): {type} {name}"
+
+    print(line_tpl.format(reason=reason,
+                          ip=ip,
+                          port=port,
+                          id=id,
+                          type=type,
+                          name=name))
+    return True
 
 
 def parse_logfile(file : typing.TextIO):
@@ -281,19 +299,17 @@ def parse_logfile(file : typing.TextIO):
         tai.stdin.write(line)
         line = tai.stdout.readline()
 
-        match = tinydns_log_re.match(line)
-        if match:
-            handle_tinydns_log(line, match)
-            continue
-
-        match = dnscache_log_re.match(line)
-        if match:
-            handle_dnscache_log(line, match)
-            continue
-
-        print(line)
+        if not handle_tinydns_log(line):
+            if not handle_dnscache_log(line):
+                print(line, end='')
 
 def main():
+    r"""
+    The entry point to the program.
+
+    This function is responsible only for parsing any command-line
+    arguments, and then calling :func`parse_logfile` on them.
+    """
     # Create an argument parser using the file's docsctring as its
     # description.
     from argparse import ArgumentParser, FileType