use python's logging system

This commit is contained in:
carmelo12341 committed 2018-04-07 22:45:58 -05:00
1 parent 2a9969cdbf
commit a4ecd38652
8 files changed
+58 -147

No files matched your search

+4 -11
View File
@@ -99,7 +99,7 @@ def main(ctx, verbose, debug, log, config) -> None:
if "logging" in conf:
logging.config.dictConfig(conf["logging"])
logger = logging.getLogger("KCommunity")
logger = logging.getLogger("kamina")
# There might not have been any configuration loaded, so let's at least set
# a baseline - these two values should at least be known.
@@ -131,9 +131,7 @@ def main(ctx, verbose, debug, log, config) -> None:
logger.addHandler(handle)
# Now, propogate the context for our sub-commands
ctx.obj = {}
ctx.obj["CONF"] = conf
ctx.obj["LOG"] = logger
ctx.obj = {"CONF": conf, "LOG": logger}
# Give value to our globals
kamina_instance = KaminaInstance(conf, logger)
@@ -142,9 +140,6 @@ def main(ctx, verbose, debug, log, config) -> None:
else:
cli_commands = importlib.import_module("core.ipfs.cli_commands").CliCommands(conf)
# Register instance
cli_commands.register_instance(kamina_instance)
# Add variable to global ctx object
ctx.obj["CLI_COMMANDS"] = cli_commands
ctx.obj["KAMINA_INSTANCE"] = kamina_instance
@@ -174,13 +169,10 @@ def init(ctx, install_ipfs) -> None:
except KeyboardInterrupt:
instance.running = False
print("Aborted!")
except RuntimeError as error:
except RuntimeError:
print("Failed!")
sys.stdout.write("\n%s" % error)
sys.stdout.flush()
else: # No exception ocurred
setup_thread.join()
sys.stdout.flush()
sys.exit(0)
@@ -192,5 +184,6 @@ def daemon(ctx) -> None:
cli_commands = ctx.obj["CLI_COMMANDS"]
cli_commands.daemon()
if __name__ == "__main__":
main()
+2 -4
View File
@@ -15,17 +15,15 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from flask import Flask
from backend.storage.storage import Storage
from utils.logger import Logger
class API:
app = Flask(__name__)
def __init__(self, settings: dict, logger: Logger):
def __init__(self, settings: dict):
# Routes
routes = [
{
@@ -63,7 +61,7 @@ class API:
for route in routes:
self.add_route(route)
self.storage = Storage(settings, logger)
self.storage = Storage(settings)
def add_route(self, route):
self.app.add_url_rule(route["r"], view_func=route["f"], methods=route["m"])
+3 -4
View File
@@ -16,14 +16,13 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import importlib
from utils.logger import Logger
import logging
class Storage:
def __init__(self, settings: dict, logger: Logger):
def __init__(self, settings: dict):
self.settings = settings
self.logger = logger
self.logger = logging.getLogger("kamina")
if not settings["enable_ipfs"]:
self.engine = importlib.import_module("backend.storage.non-ipfs.engine").Engine(settings)
else:
+1 -1
View File
@@ -32,7 +32,7 @@ directory = "${HOME}/.kamina/go-ipfs"
version = 1
disable_existing_loggers = false
[logging.loggers.KCommunity]
[logging.loggers.kamina]
level = "INFO"
handlers = ["console", "file"]
propagate = false
+23 -37
View File
@@ -19,30 +19,23 @@
advanced_commands.py - Class containing advanced command line commands
"""
import threading
import logging
import shlex
import subprocess
import logging
import sys
from multiprocessing import Process
from pathlib import PurePath
from utils.logger import Logger
from backend.api import API
class AdvancedCommands:
"""Manage advanced cli commands"""
def __init__(self, settings: dict, logger: Logger):
self.backend = API(settings, logger)
self.logger = logger
def __init__(self, settings: dict):
self.backend = API(settings)
self.logger = logging.getLogger("kamina")
self.settings = settings
self.verbose = settings.get("verbose")
self.__disable_flask_logger()
@staticmethod
def __disable_flask_logger():
flask_log = logging.getLogger("werkzeug")
flask_log.setLevel(logging.ERROR)
def __get_ipfs_bin_path(self):
local_ipfs_dir = self.settings["local_ipfs_install"]["directory"]
@@ -50,16 +43,15 @@ class AdvancedCommands:
ipfs_in_path = True
try:
subprocess.run([bin_path], stdout=subprocess.PIPE)
subprocess.run([bin_path], stdout=subprocess.DEVNULL)
except FileNotFoundError:
self.logger.print_verbose("IPFS is not in your path, trying to use local ipfs instead")
self.logger.info("IPFS is not in your path, trying to use local ipfs instead")
ipfs_in_path = False
if not ipfs_in_path:
try:
subprocess.run([str(PurePath(local_ipfs_dir, "ipfs"))], stdout=subprocess.DEVNULL)
except FileNotFoundError:
self.logger.print_verbose("IPFS not found in the local install directory")
raise FileNotFoundError
else:
bin_path = str(PurePath(local_ipfs_dir, "ipfs"))
@@ -67,51 +59,45 @@ class AdvancedCommands:
return bin_path
def start_community_daemon(self):
self.logger.print_info("Starting community daemon in http://localhost:1337/api")
self.logger.info("Starting community daemon in http://localhost:1337/api")
community_dir_path = shlex.quote(self.settings["general_information"]["node_directory"])
ipfs_binary = "ipfs"
try:
ipfs_binary = self.__get_ipfs_bin_path()
except FileNotFoundError:
self.logger.print_error("Unable to locate IPFS, aborting")
self.logger.exception("Unable to locate IPFS, aborting")
sys.exit(1)
ipfs_command = "IPFS_PATH=%s %s daemon" % (community_dir_path, ipfs_binary)
api_thread = Process(
target=self.backend.app.run,
kwargs={"port": 1337}
) # TODO: Fix logging with flask
ipfs_named_args = {
"shell": True,
"stdout": subprocess.PIPE
"shell": True
}
if not self.verbose:
ipfs_named_args["stdout"] = subprocess.DEVNULL
ipfs_thread = Process(
target=subprocess.run,
args=(ipfs_command,),
kwargs={
"shell": True,
"stdout": ipfs_named_args
}
kwargs=ipfs_named_args
)
api_thread = Process(
target=self.backend.app.run,
kwargs={"port": 1337}
) # TODO: Fix logging with flask
try:
self.logger.print_verbose("Starting flask api server")
self.logger.debug("Starting flask api server")
api_thread.start()
self.logger.print_verbose("Starting ipfs daemon")
self.logger.debug("Starting ipfs daemon")
ipfs_thread.start()
# self.logger.print_info("Done starting community daemon, api server listening on "
# "http://localhost:1337/api")
# self.backend.storage.engine.connect_ipfs()
except RuntimeError as error:
self.logger.print_verbose(str(error))
self.logger.print_error("There was an error starting the community daemon")
self.logger.exception(error)
self.logger.error("There was an error starting the community daemon")
except KeyboardInterrupt:
self.logger.print_error("Aborted!")
api_thread.terminate()
ipfs_thread.terminate()
self.logger.end_execution()
else:
api_thread.join()
ipfs_thread.join()
+23 -18
View File
@@ -25,20 +25,20 @@ import tempfile
import shutil
import shlex
import subprocess
import logging
import sys
from pathlib import PurePath
import requests
from tqdm import tqdm
from utils.logger import Logger
class BasicCommands:
"""Basic commands for managing the -community node."""
def __init__(self, settings: dict, logger: Logger):
def __init__(self, settings: dict):
self.settings = settings
self.verbose = settings.get("verbose")
self.logger = logger
self.logger = logging.getLogger("kamina")
def setup_community_node(self, install_ipfs: bool) -> None:
"""
@@ -48,7 +48,7 @@ class BasicCommands:
"""
community_dir_path = self.settings["general_information"]["node_directory"]
ipfs_init_command = ["IPFS_PATH=%s" % shlex.quote(community_dir_path), "ipfs", "init"]
self.logger.print_info("Setting up a new community node in %s" % community_dir_path)
self.logger.info("Setting up a new community node in %s" % community_dir_path)
# Try to create the folder in which kamina-community will reside
try:
@@ -63,22 +63,26 @@ class BasicCommands:
shell=True).returncode
else:
return_code = subprocess.run(" ".join(ipfs_init_command),
shell=True, stdout=subprocess.PIPE).returncode
shell=True, stdout=subprocess.DEVNULL).returncode
if return_code == 127: # Command not found
self.logger.print_error("It looks like ipfs is not in your PATH, "
"add flag --install-ipfs to install ipfs locally.")
self.logger.error("It looks like ipfs is not in your PATH, "
"add flag --install-ipfs to install ipfs locally.")
sys.exit(1)
elif return_code == 1: # ipfs node alredy exists
self.logger.print_error("Community node already "
"initialized in '%s'" % community_dir_path)
self.logger.error("Community node already "
"initialized in '%s'" % community_dir_path)
sys.exit(1)
else:
self.logger.print_verbose("Downloading ipfs for current platform")
self.logger.debug("Downloading ipfs for current platform")
# Only download if the folder go-ipfs doesnt exist already
install_dir = str(PurePath(self.settings["local_ipfs_install"]["directory"]))
if not os.path.exists(install_dir):
self.__install_ipfs(install_dir)
else:
self.logger.print_error("Directory '%s' already exists, "
"aborting download" % install_dir)
self.logger.error("Directory '%s' already exists, "
"aborting download" % install_dir)
sys.exit(1)
# Now initialize the ipfs node with the downloaded binary
ipfs_init_command[1] = shlex.quote(str(PurePath(
@@ -92,11 +96,12 @@ class BasicCommands:
return_code = subprocess.run(" ".join(ipfs_init_command),
shell=True, stdout=subprocess.DEVNULL).returncode
if return_code == 1: # ipfs node alredy exists
self.logger.print_error("Community node already "
"initialized in '%s'" % community_dir_path)
self.logger.error("Community node already "
"initialized in '%s'" % community_dir_path)
sys.exit(1)
# Print friendly message if everything went all right
self.logger.print_info("Finished setting up kamina-community node.")
self.logger.info("Finished setting up kamina-community node.")
def __install_ipfs(self, install_dir: str) -> None:
"""
@@ -141,7 +146,7 @@ class BasicCommands:
file.write(data)
# Extract it
self.logger.print_verbose("Extracting downloaded binary...")
self.logger.debug("Extracting downloaded binary...")
shutil.unpack_archive(temp_dl_file_location, temp_dl_dir.name)
self.logger.print_verbose("Copying files to '%s'..." % install_dir)
self.logger.debug("Copying files to '%s'..." % install_dir)
shutil.copytree(str(PurePath(temp_dl_dir.name, "go-ipfs")), install_dir)
+2 -12
View File
@@ -19,25 +19,15 @@
cli_commands.py: Class containing the command line commands - ipfs version
"""
from core.instance import KaminaInstance
from core.ipfs.basic_commands import BasicCommands
from core.ipfs.advanced_commands import AdvancedCommands
from utils.logger import Logger
class CliCommands:
"""Cli commands for managing the community node"""
def __init__(self, settings: dict):
self.settings = settings
self.verbose = settings["verbose"]
self.logger = None
self.basic_cmd = None
self.adv_cmd = None
def register_instance(self, instance: KaminaInstance):
self.logger = Logger(instance)
self.basic_cmd = BasicCommands(self.settings, self.logger)
self.adv_cmd = AdvancedCommands(self.settings, self.logger)
self.basic_cmd = BasicCommands(settings)
self.adv_cmd = AdvancedCommands(settings)
def init(self, install_ipfs: bool):
self.basic_cmd.setup_community_node(install_ipfs)
-60
View File
@@ -1,60 +0,0 @@
# Kamina - The />p/ social network
# Copyright (C) 2018, The Kamina Project
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
logger.py - Class that simplifies logging/output to console
"""
import sys
from colorama import Style, Fore
from core.instance import KaminaInstance
class Logger:
def __init__(self, instance: KaminaInstance):
self.instance = instance
def print_verbose(self, message: str) -> None:
if self.instance.verbose:
self.instance.logger.debug(message)
def print_error(self, message: str) -> None:
self.instance.logger.error(message)
self.end_execution()
def print_info(self, message: str) -> None:
self.instance.logger.info(message)
def end_execution(self):
self.instance.running = False
sys.exit(1)
@staticmethod
def __bright_msg(message: str) -> str:
"""Add bold escape character to message"""
return Style.BRIGHT + message + Style.RESET_ALL
def __error_msg(self) -> str:
return self.__bright_msg(Fore.RED + "[ERROR] ")
def __verbose_msg(self) -> str:
return self.__bright_msg(Fore.BLUE + "[VERBOSE] ")
def __info_msg(self) -> str:
return self.__bright_msg(Fore.WHITE + "[INFO] ")