aboutsummaryrefslogtreecommitdiffstats
path: root/moon_engine/moon_engine/__main__.py
blob: 16f1d3228f0bbac0b7a441fd340f718511e6315a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# Software Name: MOON

# Version: 5.4

# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors
# SPDX-License-Identifier: Apache-2.0

# This software is distributed under the 'Apache License 2.0',
# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt'
# or see the "LICENSE" file for more details.


import logging
import subprocess  # nosec
import os
import sys
import hug.interface
from moon_engine.api import configuration


LOGGER = logging.getLogger("moon.engine")


@hug.cli("start_server")
@hug.local()
def start_server(conf_file):
    """ Start the server of the engine """

    try:
        guni_conf_file = get_info(conf_file, "moon").strip('"\n')
        port = get_info(conf_file, "bind").split(":")[1].strip('"\n')
        log_dir = get_info(conf_file, "pid_file_dir").strip('"\n')
    except ValueError:
        return

    configuration.init_logging(guni_conf_file)
    LOGGER.setLevel(logging.ERROR)

    pid_filename = log_dir + port + ".pid"
    _command = ["gunicorn", "moon_engine.server:__hug_wsgi__", "-D", "-p", pid_filename, "-c", conf_file]
    subprocess.Popen(_command, stdout=subprocess.PIPE, close_fds=True)  # nosec


@hug.cli("stop_server")
@hug.local()
def stop_server(conf_file):
    """ Stop the server of the engine """

    try:
        guni_conf_file = get_info(conf_file, "moon").strip('"\n')
        port = get_info(conf_file, "bind").split(":")[1].strip('"\n')
        log_dir = get_info(conf_file, "pid_file_dir").strip('"\n')
    except ValueError:
        return

    configuration.init_logging(guni_conf_file)
    LOGGER.setLevel(logging.ERROR)

    pid_filename = log_dir + port + ".pid"

    try:
        pid_file = open(pid_filename, 'r')
    except FileNotFoundError:
        LOGGER.error(f"File {pid_filename} not found. Server on port {port} not running?")
        return

    try:
        pid = int(pid_file.read())
    except ValueError:
        LOGGER.error(f"The pid found in {pid_filename} is not valid")
        return

    os.kill(pid, 15)


def get_info(conf, key):
    with open(conf) as config:
        lines = config.readlines()
        for line in lines:
            if line.startswith(key):
                return line.split("=")[1].strip()
        LOGGER.error(f"Key \"{key}\" missing from Gunicorn configuration file")
        raise ValueError


def run():
    if len(sys.argv) > 1:

        command = sys.argv[1]
        sys.argv.pop(1)
        # if command == "conf":
        #     configuration.get_configuration.interface.cli()
        # elif command == "db":
        #     configuration.init_database.interface.cli()
        if command == "start":
            start_server.interface.cli()
        elif command == "stop":
            stop_server.interface.cli()
        else:
            LOGGER.critical("Unknown command {}".format(command))

    else:
        # TODO: update the command management by using argparse
        print("""Possible commands are:
        # - conf
        # - db
        - start
        - stop
        """)


if __name__ == "__main__":
    run()