import jinja2 import os import subprocess import sys PROCESS_NAME = 'meteorologger' BASE_DIR = os.path.abspath(os.path.dirname(__file__)) BASE_DIR = BASE_DIR[:BASE_DIR.rfind(os.path.sep)] SUPERVISOR_CONFIG_FILENAME = '/etc/supervisor/conf.d/{}.conf'\ .format(PROCESS_NAME) PID_FILENAME = 'logs/pid_{}'.format(PROCESS_NAME) def deploy_supervisor(): with open('app/supervisor.conf') as f_temp: template = jinja2.Template(f_temp.read()) config_file_str = template.render(base_dir=BASE_DIR, process_name=PROCESS_NAME) print('\nRegistering supervisor config at \n {}' .format(SUPERVISOR_CONFIG_FILENAME)) print('='*60) print(config_file_str) print('='*60) with open(SUPERVISOR_CONFIG_FILENAME, 'w') as f: f.write(config_file_str + '\n') print('\nRestarting supervisor..') proc = subprocess.Popen('supervisorctl update', shell=True) proc.wait() proc = subprocess.Popen('supervisorctl pid {}'.format(PROCESS_NAME), shell=True, stdout=subprocess.PIPE) proc.wait() pid = proc.stdout.read().decode('ascii').strip() try: pid = int(pid) with open(PID_FILENAME, 'w') as f: f.write(str(pid) + '\n') print("\nPID: {} (saved at '{}')".format(pid, PID_FILENAME)) print('\n[{} process is running]'.format(PROCESS_NAME)) print('\nYou can manage it with supervisorctl tool.') except: print("\nSomething went wrong and the daemon process was NOT created.") 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() if __name__ == '__main__': if '-u' in sys.argv: undeploy_supervisor() else: deploy_supervisor()