Exemple #1
0
def list_users():
  users = get_all_users()

  user: User
  for i, user in enumerate(users):
    clrc.info("{0}: {1}".format(i, user.username))

  clrc.info("Total {0} users".format(len(users)))
Exemple #2
0
def _run_flask_app(debug=False):
    if LOG_PATH:
        logger.add(LOG_PATH, colorize=True, rotation="100mb")
        logger.opt(exception=True)

        clrc.config.add_printer(clrc.LoguruPrinter(logger))

        clrc.info("Starting flask process..")

    app.run(host=HOST, port=PORT, debug=debug)
Exemple #3
0
def delete_user():
  username: str = click.prompt("Please provide username to delete user")

  if not username.strip():
    clrc.info("No username provided")
    return

  user = find_user(username)

  if not user:
    clrc.info("User not found")
    return

  click.confirm("Are you sure you want to delete user {0}?".format(username), abort=True)
  #TODO: write user deletion

  clrc.success("User deleted!")
Exemple #4
0
def stop_flask_server():
    if not Path(PID_PATH).exists():
        clrc.info(
            "It seems daemon process is not running. PID file does not exist")
        return

    pid = int(Path(PID_PATH).read_text())

    if pid not in psutil.pids():
        clrc.info("It seems daemon process is not running.")

        Path(PID_PATH).unlink()
    else:
        p = psutil.Process(pid)
        p.terminate()

        Path(PID_PATH).unlink()

        clrc.success("Daemon process stopped")
Exemple #5
0
def add_log(user: str):
  if user:
    user = find_user(user)
    if not user:
      clrc.info("User with provided username not found. Aborting")
      return

  filepath: str = click.prompt("Please enter absolute path for log file")

  if not filepath.strip():
    clrc.info("No path provided")
    return

  if LOG_PATH == filepath:
    clrc.info("Sorry, you cannot add log file of showme daemon to the logs. It creates eternal recursion, will eat up your space and speed up your fans :D")
    return

  try:
    with open(filepath, "r") as file:
      file.read(1)

    name: str = click.prompt("Please enter name for your log")

    if not name.strip():
      clrc.info("No name provided")
      return

    if not user:
      click.confirm("You are going to add log file for all users, without specifying --user=USERNAME option. It will be accessible by all users. Proceed?", abort=True)
      add_log_file(name, filepath)
      clrc.success("Log file added for everyone")
    else:
      add_log_file(name, filepath, user)
      clrc.success("Log file added for user {0}".format(user.username))


  except:
    clrc.warn("There seems to be the problem with opening file with the provided path. Here is more debug info for you to possibly discover source of the problem:")
    clrc.error(traceback.format_exc())
Exemple #6
0
def create_user_cmd():
  username: str = click.prompt("Please enter username")

  if not username.strip():
    clrc.info("No username provided")
    return

  existing = find_user(username)

  if existing:
    clrc.info("User already exists")
    return

  password: str = click.prompt("Please enter password", hide_input=True)

  if not password.strip():
    clrc.info("No password provided")
    return

  create_user(username, password)

  clrc.success("User {0} created! User can now login with provided credentials".format(username))
Exemple #7
0
def start_flask_server(daemonize=True, debug=True):
    if Path(PID_PATH).exists():
        pid = int(Path(PID_PATH).read_text())

        if pid in psutil.pids():
            clrc.info(
                "It seems daemon is already running. Use restart command to restart it"
            )
            return
        else:
            clrc.warn(
                "It seems daemon was not stopped correctly the last time. PID file exists, and PID inside it do not match any running process. Please remove PID file manually: {0}"
                .format(PID_PATH))
            clrc.info("After removing PID file daemon should start as usual")
            return

    if daemonize:
        if debug:
            clrc.info("Information:")
            clrc.info("Database is at: {0}".format(DATABASE_PATH))
            clrc.info("Daemon process PID file is at: {0}".format(PID_PATH))
            if LOG_PATH:
                clrc.info(
                    "You specified LOG_PATH. It's at: {0}".format(LOG_PATH))
        if (_can_create_pid_file() and _can_create_logs()):
            clrc.info("Starting daemon...")
            clrc.info(
                "Daemon started successfully. You can access your server at http://{0}:{1}"
                .format(HOST, PORT))
            clrc.info(
                "If you are not able to access the web server and sure this is not a problem with firewall/closed port etc, please check logs here: {0}"
                .format(LOG_PATH))
            logger = logging.getLogger()
            logger.setLevel(logging.DEBUG)
            fh = logging.FileHandler(LOG_PATH)
            logger.addHandler(fh)

            # Fix to work with pyinstaller onefile
            fds_to_myself = []
            if getattr(sys, 'frozen', False):
                fds_to_myself = [
                    of.fd for of in psutil.Process(os.getpid()).open_files()
                    if of.path == sys.executable
                ]

            with daemon.DaemonContext(
                    pidfile=pidlockfile.PIDLockFile(PID_PATH),
                    stdout=fh.stream,
                    stderr=fh.stream,
                    files_preserve=[fh.stream] + fds_to_myself):
                _run_flask_app()

            clrc.success(
                "Daemon started! You can access server at {0}:{1}".format(
                    HOST, PORT))
    else:
        _run_flask_app(debug=True)
Exemple #8
0
def init(reinstall: bool):
  if Path(CONFIG_PATH).exists() and not reinstall:
    clrc.info("It seems config file already exists. You either already initialized program, or created config file manually. If you want to reinstall program, use --reinstall flag")
    return

  if Path(CONFIG_PATH).exists() and reinstall:
    click.confirm("You are going to reinstall program configuration. This will stop daemon (if it is working) and wipe database with rows for users and logs (your actual log files won't be affected). Are you sure?", abort=True)

    clrc.info("Stopping daemon...")
    stop_flask_server()

    if Path(CONFIG_PATH).exists():
      Path(CONFIG_PATH).unlink()
      clrc.info("Config file removed...")
    if Path(DATABASE_PATH).exists():
      Path(DATABASE_PATH).unlink()
      clrc.info("Database removed...")

    clrc.success("Done! Now, to initializing program...")

    clrc.info("Initializing...")

  cfg = """SECRET_KEY={0}
HOST=0.0.0.0
PORT=4020
""".format(hashlib.md5(
    (secrets.token_urlsafe(64) + str(datetime.datetime.now())).encode("utf-8")
  ).hexdigest())

  Path(CONFIG_PATH).write_text(cfg)

  clrc.success("Config file created and filled with some default parameters. More information about config parameters you can see at the documentation")

  clrc.info("You can now use `user create` command to create first user, `log create` command to add log and `daemon start` command to start web server")
  clrc.info("Would you like to know more? Use `help` command")
Exemple #9
0
def help():
  clrc.info("Welcome to ShowMe program, which will output your log files to the browser!")
  clrc.info("To view list of available commands just type `showme` press enter and see the list.")
Exemple #10
0
from pathlib import Path
from dotenv import load_dotenv
import clrc

HOME_DIR = str(Path.home())

CONFIG_PATH = os.path.join(HOME_DIR, ".showme")

config_exists = Path(CONFIG_PATH).exists()

if config_exists:
    load_dotenv(CONFIG_PATH)

if not config_exists:
    clrc.info(
        "Config file does not exist. Please enter `init` command to initialize config at path: {0}"
        .format(CONFIG_PATH))


def get_env(name: str, default: str, cast_to=None):
    try:
        if not config_exists:
            return default

        value = os.getenv(name, default)

        if cast_to:
            value = cast_to(value)

        return value
    except: