From 1140452aaef30297723db405727727f551a8d411 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Henrik=20tom=20W=C3=B6rden?= <henrik@trineo.org>
Date: Mon, 23 Mar 2020 14:18:06 +0100
Subject: [PATCH] log tool

---
 log.py | 171 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 171 insertions(+)
 create mode 100755 log.py

diff --git a/log.py b/log.py
new file mode 100755
index 0000000..d347c9d
--- /dev/null
+++ b/log.py
@@ -0,0 +1,171 @@
+#!/usr/bin/env python3
+
+# ** header v3.0
+# This file is a part of the CaosDB Project.
+#
+# Copyright (C) 2019 Daniel Hornung, IndiScale GmbH
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+#
+# ** end header
+
+"""Remote module for SQL logging
+"""
+
+import argparse
+import subprocess
+import sys
+
+SQL_BASE = ["mysql", "--batch",
+            "--user=caosdb", "--password=random1234",
+            "--host=sqldb", "--port=3306"]
+
+test_yaml = """
+action: log
+log_action: storeoff
+"""
+
+
+def exec(args):
+    "Executing the logging action action."
+    action = args["log_action"]
+
+    result = None
+
+    if action.startswith("store"):
+        result = {"tsv_content": _store_log()}
+
+    if action.endswith("on"):
+        _logging(True)
+    elif action.endswith("off"):
+        _logging(False)
+
+    return result
+
+
+def _store_log():
+    """Retrieves the log table and returns it as a TSV string.
+
+    Returns
+    -------
+    out : str
+      The string representing the logging information, as TSV.
+    """
+    # print("store")
+    sql_command = 'select event_time, argument from mysql.general_log where command_type="Query";'
+    result = subprocess.run(SQL_BASE, input=sql_command, encoding="utf8",
+                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+                            # capture_output=True)  ## Only works since 3.7
+    if result.returncode > 0:
+        print("Error during SQL command, while retrieving SQL logs:", file=sys.stderr)
+        print(result.stderr, file=sys.stderr)
+
+    return result.stdout
+
+
+def _logging(turn_on):
+    """Turn SQL logging off/on.
+
+This function tells the SQL database to turn logging off or on (depending on the
+arguments).  It returns nothing.
+
+Parameters
+----------
+turn_on : bool
+  Whether to turn logging on or off.
+    """
+    on_off = "ON" if turn_on else "OFF"
+    sql_command = """
+SET GLOBAL log_output = 'TABLE';
+SET GLOBAL general_log = '{on_off}';
+""".format(on_off=on_off)
+    result = subprocess.run(SQL_BASE, input=sql_command, encoding="utf8",
+                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+                            # capture_output=True)  ## Only works since 3.7
+    if result.returncode > 0:
+        print("Error during SQL command, while setting SQL logging to '{on_off}':".format(
+            on_off=on_off), file=sys.stderr)
+        print(result.stderr, file=sys.stderr)
+        print(result.stdout)
+
+    # Return nothing if no error.
+
+
+def start_logging(args):
+    _logging(True)
+
+
+def stop_logging(args):
+    _logging(False)
+
+
+def store(args):
+    print(_store_log())
+
+
+def store_off(args):
+    print(_store_log())
+    _logging(False)
+
+
+def example_error(args):
+    print(_store_log(False))
+
+
+def parse_args():
+    """Parse the command line arguments."""
+    parser = argparse.ArgumentParser(
+        description=__doc__+"""
+To view additional information about subcommands, execute:
+    linkahead <subcmd> -h""",
+        prog="linkahead",
+        formatter_class=argparse.RawDescriptionHelpFormatter
+    )
+    subparsers = parser.add_subparsers(
+        help='The action to take.', dest="action", required=True)
+
+    # mysql logging
+    start_parser = subparsers.add_parser(
+        'on',
+        help='Turns SQL logging on and off, stores logs.')
+    start_parser.set_defaults(func=start_logging)
+
+    stop_parser = subparsers.add_parser(
+        'off',
+        help='Turns SQL logging on and off, stores logs.')
+    stop_parser.set_defaults(func=stop_logging)
+
+    stop_parser = subparsers.add_parser(
+        'store',
+        help='Turns SQL logging on and off, stores logs.')
+    stop_parser.set_defaults(func=store)
+
+    stop_off_parser = subparsers.add_parser(
+        'storeoff',
+        help='Turns SQL logging on and off, stores logs.')
+    stop_off_parser.set_defaults(func=store_off)
+
+    example_parser = subparsers.add_parser(
+        'example_error',
+        help='Turns SQL logging on and off, stores logs.')
+    example_parser.set_defaults(func=example_error)
+
+    return parser.parse_args()
+
+
+if __name__ == "__main__":
+    """The main function."""
+    args = parse_args()
+    print(args)
+    args.func(args)
-- 
GitLab