]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
suricatactl: Fix PyLint issues
authorShivani Bhardwaj <shivanib134@gmail.com>
Sat, 16 Feb 2019 18:49:22 +0000 (00:19 +0530)
committerVictor Julien <victor@inliniac.net>
Sun, 24 Feb 2019 19:00:55 +0000 (20:00 +0100)
Pylint is a tool to make sure we do not regress the support for Python
3. The following conventions, warnings, errors, refactors have been
fixed.

W0301: Unnecessary semicolon (unnecessary-semicolon)
C0303: Trailing whitespace (trailing-whitespace)
W1401: Anomalous backslash in string
C0103: Variable name doesn't conform to snake_case naming style
R1705: Unnecessary "elif" after "return"
W1201: Specify string format arguments as logging function parameters
W0611: Unused import
R1710: Either all return statements in a function should return an expression, or none of them should
W0612: Unused variable
C0103: Method name doesn't conform to snake_case naming style
R0201: Method could be a function

python/suricata/ctl/filestore.py
python/suricata/ctl/loghandler.py
python/suricata/ctl/main.py
python/suricata/ctl/test_filestore.py

index c0f101b36eb45690a0515e8b86bea9aacc8a15a6..76ca5cb8b33ad12052b3e6340db280c9c51f8c2f 100644 (file)
@@ -21,23 +21,23 @@ import os
 import os.path
 import time
 import re
-import glob
 import logging
 
 logger = logging.getLogger("filestore")
 
+
 class InvalidAgeFormatError(Exception):
     pass
 
+
 def register_args(parser):
     parsers = parser.add_subparsers()
-
     prune_parser = parsers.add_parser("prune")
     prune_parser.add_argument("-d", "--directory", help="filestore directory")
     prune_parser.add_argument("--age", help="prune files older than age")
     prune_parser.add_argument(
         "-n", "--dry-run", action="store_true", default=False,
-        help="only print what would happen");
+        help="only print what would happen")
     prune_parser.add_argument(
         "-v", "--verbose", action="store_true",
         default=False, help="increase verbosity")
@@ -46,30 +46,32 @@ def register_args(parser):
         help="be quiet, log warnings and errors only")
     prune_parser.set_defaults(func=prune)
 
+
 def is_fileinfo(path):
     return path.endswith(".json")
 
+
 def parse_age(age):
-    m = re.match("(\d+)\s*(\w+)", age)
-    if not m:
+    matched_age = re.match(r"(\d+)\s*(\w+)", age)
+    if not matched_age:
         raise InvalidAgeFormatError(age)
-    val = int(m.group(1))
-    unit = m.group(2)
-
+    val = int(matched_age.group(1))
+    unit = matched_age.group(2)
     if unit == "s":
         return val
-    elif unit == "m":
+    if unit == "m":
         return val * 60
-    elif unit == "h":
+    if unit == "h":
         return val * 60 * 60
-    elif unit == "d":
+    if unit == "d":
         return val * 60 * 60 * 24
-    else:
-        raise InvalidAgeFormatError("bad unit: %s" % (unit))
+    raise InvalidAgeFormatError("bad unit: %s" % (unit))
+
 
 def get_filesize(path):
     return os.stat(path).st_size
 
+
 def remove_file(path, dry_run):
     size = 0
     size += get_filesize(path)
@@ -77,6 +79,7 @@ def remove_file(path, dry_run):
         os.unlink(path)
     return size
 
+
 def prune(args):
 
     if args.verbose:
@@ -89,7 +92,7 @@ def prune(args):
             "error: the filestore directory must be provided with --directory",
             file=sys.stderr)
         return 1
-    
+
     if not args.age:
         print("error: no age provided, nothing to do", file=sys.stderr)
         return 1
@@ -100,7 +103,6 @@ def prune(args):
     count = 0
 
     for dirpath, dirnames, filenames in os.walk(args.directory, topdown=True):
-
         # Do not go into the tmp directory.
         if "tmp" in dirnames:
             dirnames.remove("tmp")
@@ -110,8 +112,9 @@ def prune(args):
             mtime = os.path.getmtime(path)
             this_age = now - mtime
             if this_age > age:
-                logger.debug("Deleting %s; age=%ds" % (path, this_age))
+                logger.debug("Deleting %s; age=%ds", path, this_age)
                 size += remove_file(path, args.dry_run)
                 count += 1
 
-    logger.info("Removed %d files; %d bytes." % (count, size))
+    logger.info("Removed %d files; %d bytes.", count, size)
+    return 0
index f417eca8a7fde392afd4e5f768ccfddcfa431ba6..553b896fd1deeb31ef7d402a8529b60a802b497e 100644 (file)
@@ -40,15 +40,16 @@ class SuriColourLogHandler(logging.StreamHandler):
     """An alternative stream log handler that logs with Suricata inspired
     log colours."""
 
-    def formatTime(self, record):
-        lt = time.localtime(record.created)
-        t = "%d/%d/%d -- %02d:%02d:%02d" % (lt.tm_mday,
-                                            lt.tm_mon,
-                                            lt.tm_year,
-                                            lt.tm_hour,
-                                            lt.tm_min,
-                                            lt.tm_sec)
-        return "%s" % (t)
+    @staticmethod
+    def format_time(record):
+        local_time = time.localtime(record.created)
+        formatted_time = "%d/%d/%d -- %02d:%02d:%02d" % (local_time.tm_mday,
+                                                         local_time.tm_mon,
+                                                         local_time.tm_year,
+                                                         local_time.tm_hour,
+                                                         local_time.tm_min,
+                                                         local_time.tm_sec)
+        return "%s" % (formatted_time)
 
     def emit(self, record):
 
@@ -64,7 +65,7 @@ class SuriColourLogHandler(logging.StreamHandler):
 
         self.stream.write("%s%s%s - <%s%s%s> -- %s%s%s\n" % (
             GREEN,
-            self.formatTime(record),
+            self.format_time(record),
             RESET,
             level_prefix,
             record.levelname.title(),
@@ -73,7 +74,8 @@ class SuriColourLogHandler(logging.StreamHandler):
             self.mask_secrets(record.getMessage()),
             RESET))
 
-    def mask_secrets(self, msg):
+    @staticmethod
+    def mask_secrets(msg):
         for secret in secrets:
             msg = msg.replace(secret, "<%s>" % secrets[secret])
         return msg
index 1d09b900e5b5576361097df98aecbbff21c5ea3a..a8125f96c133b59df5791bf03b3595ffefeab679 100644 (file)
@@ -19,8 +19,7 @@ import os
 import argparse
 import logging
 
-from suricata.ctl import filestore
-from suricata.ctl import loghandler
+from suricata.ctl import filestore, loghandler
 
 def init_logger():
     """ Initialize logging, use colour if on a tty. """
@@ -34,17 +33,12 @@ def init_logger():
             format="%(asctime)s - <%(levelname)s> - %(message)s")
 
 def main():
-
     init_logger()
-
     parser = argparse.ArgumentParser(description="Suricata Control Tool")
-
     subparsers = parser.add_subparsers(
         title="subcommands",
         description="Commands")
-
     filestore.register_args(subparsers.add_parser("filestore"))
-
     args = parser.parse_args()
     try:
         func = args.func
index 0cb0dd08a956ea561e9ee89d0629b4fefcad5adc..3bac1c6feb0fc527fcd860a4a695ca040bc4e949 100644 (file)
@@ -12,7 +12,7 @@ class PruneTestCase(unittest.TestCase):
         self.assertEqual(filestore.parse_age("1h"), 3600)
         self.assertEqual(filestore.parse_age("1d"), 86400)
 
-        with self.assertRaises(filestore.InvalidAgeFormatError) as err:
+        with self.assertRaises(filestore.InvalidAgeFormatError):
             filestore.parse_age("1")
-        with self.assertRaises(filestore.InvalidAgeFormatError) as err:
+        with self.assertRaises(filestore.InvalidAgeFormatError):
             filestore.parse_age("1y")