configd.py 6.35 KB
Newer Older
1
#!/usr/local/bin/python2.7
2
# -*- coding: utf-8 -*-
3

Ad Schellevis's avatar
Ad Schellevis committed
4
"""
5
    Copyright (c) 2014-2016 Ad Schellevis
Ad Schellevis's avatar
Ad Schellevis committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

    --------------------------------------------------------------------------------------
30

31
    package : configd
Ad Schellevis's avatar
Ad Schellevis committed
32 33
    function: delivers a process coordinator to handle frontend functions
"""
34

Ad Schellevis's avatar
Ad Schellevis committed
35 36 37 38
__author__ = 'Ad Schellevis'

import os
import sys
39
import logging
40 41
import signal
import time
42
import subprocess
Ad Schellevis's avatar
Ad Schellevis committed
43
import modules.processhandler
44
import modules.csconfigparser
Ad Schellevis's avatar
Ad Schellevis committed
45
from modules.daemonize import Daemonize
46
import cProfile, pstats
Ad Schellevis's avatar
Ad Schellevis committed
47 48 49 50 51 52 53 54 55 56 57

# find program path
if len(__file__.split('/')[:-1]) >0 :
    program_path = '/'.join(__file__.split('/')[:-1])
else:
    program_path = os.getcwd()

# set working directory to program_path
sys.path.append(program_path)
os.chdir(program_path)

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
def get_config():
    """ open configuration
    """
    cnf = modules.csconfigparser.CSConfigParser()
    cnf.read('conf/configd.conf')
    return cnf

def validate_config(cnf):
    """ validate configuration, exit on missing item
    """
    for config_item in  ['socket_filename','pid_filename']:
        if cnf.has_section('main') == False or cnf.has_option('main',config_item) == False:
            print('configuration item main/%s not found in %s/conf/configd.conf'%(config_item,program_path))
            sys.exit(0)

def main(cnf, simulate=False, single_threaded=False):
    """ configd startup
    """
    # setup configd environment to use for all configured actions
    if not cnf.has_section('environment'):
        config_environment = os.environ.copy()
    else:
        config_environment={}
        for envKey in cnf.items('environment'):
            config_environment[envKey[0]] = envKey[1]

    # run process coordinator ( on console or as daemon )
    # if command-line arguments contain "emulate",  start in emulation mode
    if simulate:
        proc_handler = modules.processhandler.Handler(socket_filename=cnf.get('main','socket_filename'),
                                                      config_path='%s/conf'%program_path,
                                                      config_environment=config_environment,
                                                      simulation_mode=True)
    else:
        proc_handler = modules.processhandler.Handler(socket_filename=cnf.get('main','socket_filename'),
                                                      config_path='%s/conf'%program_path,
                                                      config_environment=config_environment)
    proc_handler.single_threaded = single_threaded
    proc_handler.run()

def run_watch():
    """ start configd process and restart if it dies unexpected
    """
101 102 103 104 105 106 107 108
    current_child_pid = None
    def signal_handler(sig, frame):
        print current_child_pid
        if current_child_pid is not None:
            os.kill(current_child_pid, sig)
        sys.exit(1)

    signal.signal(signal.SIGTERM, signal_handler)
109 110
    while True:
        process = subprocess.Popen(['/usr/local/opnsense/service/configd.py', 'console'])
111 112
        # save created pid for signal_handler() to use
        current_child_pid = process.pid
113
        process.wait()
114 115
        # wait a small period of time before trying to restart a new process
        time.sleep(0.5)
116 117 118

this_config = get_config()
validate_config(this_config)
Ad Schellevis's avatar
Ad Schellevis committed
119 120
if len(sys.argv) > 1 and 'console' in sys.argv[1:]:
    print('run %s in console mode'%sys.argv[0])
121 122 123 124 125 126 127
    if 'profile' in sys.argv[1:]:
        # profile configd
        # for graphical output use gprof2dot:
        #   gprof2dot -f pstats /tmp/configd.profile  -o /tmp/callingGraph.dot
        # (https://code.google.com/p/jrfonseca/wiki/Gprof2Dot)
        print ("...<ctrl><c> to stop profiling")
        profile = cProfile.Profile()
128
        profile.enable(subcalls=True)
129
        try:
130 131 132 133 134
            if len(sys.argv) > 1 and 'simulate' in sys.argv[1:]:
                print('simulate calls.')
                main(cnf=this_config, simulate=True, single_threaded=True)
            else:
                main(cnf=this_config, single_threaded=True)
135 136 137 138 139 140 141
        except KeyboardInterrupt:
            pass
        except:
            raise
        profile.disable()
        profile.dump_stats('/tmp/configd.profile')
    else:
142
        main(cnf=this_config)
Ad Schellevis's avatar
Ad Schellevis committed
143
else:
144
    # run as daemon, wrap the actual work process to enable automatic restart on sudden death
145 146 147 148 149 150 151 152 153 154 155 156
    syslog_socket = "/var/run/log"
    if os.path.exists(syslog_socket):
        # bind log handle to syslog to catch messages from Daemonize()
        # (if syslog facility is active)
        loghandle = logging.getLogger("configd.py")
        loghandle.setLevel(logging.INFO)
        handler = logging.handlers.SysLogHandler(address=syslog_socket,
                                                 facility=logging.handlers.SysLogHandler.LOG_DAEMON)
        handler.setFormatter(logging.Formatter("%(name)s %(message)s"))
        loghandle.addHandler(handler)
    else:
        loghandle = None
Ad Schellevis's avatar
Ad Schellevis committed
157
    # daemonize process
158
    daemon = Daemonize(app=__file__.split('/')[-1].split('.py')[0],
159 160
                       pid=this_config.get('main','pid_filename'),
                       action=run_watch,
161 162
                       logger=loghandle
                       )
Ad Schellevis's avatar
Ad Schellevis committed
163 164
    daemon.start()
sys.exit(0)