deploy.py 2.35 KB
Newer Older
1 2
import os
import subprocess
3
import sys
labfis's avatar
labfis committed
4
import time
5 6

PROCESS_NAME = 'meteorologger'
7 8

BASE_DIR = os.path.abspath(os.path.dirname(__file__))
9
BASE_DIR = BASE_DIR[:BASE_DIR.rfind(os.path.sep)]
10 11 12
SUPERVISOR_CONFIG_FILENAME = '/etc/supervisor/conf.d/{}.conf'\
                             .format(PROCESS_NAME)

Nelso Jost's avatar
Nelso Jost committed
13
PID_FILENAME = 'logger/logs/pid_{}'.format(PROCESS_NAME)
14

15 16 17
TEMPLATE_SUPERVISOR_CONF =\
"""\
[program:{PROCESS_NAME}]
18
command={BASE_DIR}/.venv/bin/python {BASE_DIR}/logger/run.py --background
19 20 21 22 23 24 25 26
directory={BASE_DIR}
user=root
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile={BASE_DIR}/logger/logs/stdout.log
logfile={BASE_DIR}/logger/logs/supervisor-{PROCESS_NAME}.log
""".format(**globals())
27

28
def deploy_supervisor():
29

30 31 32 33 34 35
    if os.system("supervisorctl status"):
        print("\nThe supervisor tool is required for logger deployment.\n"
              "Please install it before proceding. On Debian:\n\n"
              "   $ sudo apt-get install supervisor\n")
        return

36 37 38
    print('\nRegistering supervisor config at \n    {}\n'
          .format(SUPERVISOR_CONFIG_FILENAME) + '='*60 + '\n'
          + TEMPLATE_SUPERVISOR_CONF + '='*60)
39

40 41
    with open(SUPERVISOR_CONFIG_FILENAME, 'w') as f:
        f.write(TEMPLATE_SUPERVISOR_CONF + '\n')
42 43 44

    print('\nRestarting supervisor..')
    proc = subprocess.Popen('supervisorctl update', shell=True)
45
    proc.wait()
46

labfis's avatar
labfis committed
47 48 49 50 51 52
    print('')
    time.sleep(2)

    proc = subprocess.Popen('supervisorctl status meteorologger', shell=True)
    proc.wait()

53 54
    proc = subprocess.Popen('supervisorctl pid {}'.format(PROCESS_NAME),
                            shell=True, stdout=subprocess.PIPE)
55
    proc.wait()
56
    pid = proc.stdout.read().decode('ascii').strip()
57

58 59
    try:
        pid = int(pid)
60

61
        with open(PID_FILENAME, 'w') as f:
62
            f.write(str(pid) + '\n')
63
    except:
labfis's avatar
labfis committed
64 65
        print("\nUnable to save PID={} at '{}'".format(pid, PID_FILENAME))

66

67 68 69 70 71 72 73 74 75 76 77 78

def undeploy_supervisor():
    print('\nRemoving supervisor config file at\n   {}'
          .format(SUPERVISOR_CONFIG_FILENAME))
    os.system('rm -f {}'.format(SUPERVISOR_CONFIG_FILENAME))
    os.system('rm -f {}'.format(PID_FILENAME))

    print('\nRestarting supervisor..')
    proc = subprocess.Popen('supervisorctl update', shell=True)
    proc.wait()


79
if __name__ == '__main__':
80 81 82 83
    if '-u' in sys.argv:
        undeploy_supervisor()
    else:
        deploy_supervisor()