Loading bin/cc-node +24 −206 Changes for bin/cc-node: 24 added lines, 206 removed lines. Original line number Diff line number Diff line #!/usr/bin/env python import logging import threading import logging.handlers import sys import os import atexit import ConfigParser from math import exp from time import sleep from optparse import OptionParser from daemon import DaemonContext from sjrpc.core import RpcError from ccnode.ccnode import CCNode from ccnode import __version__ MAX_AUTH_TIMEOUT = 30 DEFAULT_CONFIG_FILE = '/etc/cc-node.conf' DEFAULT_PID_FILE = '/var/run/cc-node.pid' DEFAULT_CONFIGURATION = { 'address': '', 'login': '', 'password': '', 'port': '1984', 'verbosity': '0', 'detect_hypervisor': 'yes', #'ssl_cert': '', 'command_execution' : 'yes', 'force_xen' : 'no', } def authentication(node, suicide, login, password): ''' Node authentication thread ''' timeout = 1 while not suicide.is_set() and node.get_rpc(): logging.debug('Sending authentication request') if node.authentify(login, password): logging.error('Authentication suscessfull') return else: logging.error('Authentication failure') timeout += 0.1 if timeout >= MAX_AUTH_TIMEOUT: timeout = MAX_AUTH_TIMEOUT sleep(exp(timeout)) def setup_logging(options, instance_id=None): ''' ''' level = logging.ERROR verb = int(options['verbosity']) if verb: if verb == 1: level = logging.WARNING elif verb == 2: level = logging.INFO else: level = logging.DEBUG logger = logging.getLogger() logger.setLevel(level) if options['stdout']: handler = logging.StreamHandler() else: facility = logging.handlers.SysLogHandler.LOG_DAEMON handler = logging.handlers.SysLogHandler(address='/dev/log', facility=facility) fmt = 'cc-node: %(levelname)s ' if options['verbosity'] == 0: fmt += '%(message)s' else: if isinstance(instance_id, int): fmt += 'id=%i ' % instance_id if options['stdout']: fmt += ("\x1B[30;47m%(process)d\x1B[0m:" "\x1B[30;42m%(threadName)s\x1B[0m:" "\x1B[30;43m%(funcName)s\x1B[0m:" "\x1B[30;44m%(lineno)d\x1B[0m@" "\x1B[30;45m%(msecs)d" "\x1B[0m\t\t " "%(message)s") else: fmt += ("%(process)d:" "%(threadName)s:" "%(funcName)s:" "%(lineno)d@" "%(msecs)d " "%(message)s") handler.setFormatter(logging.Formatter(fmt)) logger.handlers = [] logger.addHandler(handler) def run_node(options): ''' ''' # instance death event suicide_event = threading.Event() try: # setup logging infrastructure setup_logging(options) # create client logging.debug('Initializing client') try: node = CCNode(options['address'], int(options['port']), options['detect_hypervisor'] == 'yes', options['command_execution'] == 'yes', force_xen=(options['force_xen'] == 'yes')) except Exception as err: logging.error('Client initialization failure: `%s`:`%s`', repr(err), err) raise err # reconfigure logging with instance ID setup_logging(options, instance_id=id(node)) # auth thread logging.debug('Starting authentication thread') auth_thread = threading.Thread(target=authentication, name='Auth', args=(node, suicide_event, options['login'], options['password'])) auth_thread.daemon = True auth_thread.start() # main loop logging.debug('Starting main loop') node.run() except Exception as err: logging.error('run_node: `%s` -> `%s`', repr(err), err) try: node.get_rpc().shutdown() except: pass finally: # ensure everything is killed properly suicide_event.set() # -*- coding: utf-8 -*- # # Cloud-Control Node # Copyright (C) 2011 SmartJog [http://www.smartjog.com] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Authors: # * 2011-06: Thibault VINCENT <thibault.vincent@smartjog.com> # from ccnode.launcher import Launcher if __name__ == '__main__': # configure argument parser op = OptionParser(version='%%prog %s' % __version__) op.add_option('-c', '--config', default=DEFAULT_CONFIG_FILE, help='configuration file (default: %default)') op.add_option('-d', '--daemonize', default=False, action='store_true', help='run as daemon and write pid file') op.add_option('-p', '--pidfile', default=DEFAULT_PID_FILE, help='pid file (default: %default)') op.add_option('-s', '--stdout', action='store_true', default=False, help='log on standard output instead of syslog') cliopts, args = op.parse_args() # read the config file config = ConfigParser.SafeConfigParser() config.read(cliopts.config) try: options = dict(config.items('node')) except ConfigParser.NoSectionError: sys.stderr.write('Configuration error: `node` section must exist ' 'in `%s`\n' % cliopts.config) sys.exit(1) # applying default config file options for opt, default in DEFAULT_CONFIGURATION.iteritems(): if opt not in options or not options[opt]: if default is None: sys.stderr.write('Configuration error: you must specify `%s` ' 'option in `%s` !\n' % (opt, cliopts.config)) sys.exit(1) else: options[opt] = default # Merge command options and .conf file options for opt in ('daemonize', 'pidfile', 'stdout'): if getattr(cliopts, opt) is not None: options[opt] = getattr(cliopts, opt) # Create option set for the daemonization process daemon_opts = {} daemonize = options['daemonize'] if isinstance(daemonize, str): daemonize = daemonize in ('yes', 'true') daemon_opts['detach_process'] = daemonize if not daemonize: daemon_opts['stderr'] = sys.stderr daemon_opts['stdout'] = sys.stderr if options['pidfile']: #daemon_opts['pidfile'] = lockfile.FileLock(options['pidfile']) pidfile = open(cliopts.pidfile, 'w') daemon_opts['files_preserve'] = [pidfile] with DaemonContext(**daemon_opts): # write pid in pidfile if pidfile is not None: pidfile.write('%s' % os.getpid()) pidfile.flush() # register pidfile cleaning @atexit.register def clean_pidfile(): pidfile.seek(0) pidfile.truncate() pidfile.flush() # run node while True: run_node(options) logging.critical('Critical error, restarting node !') sleep(2) Launcher().main() ccnode/__init__.py +46 −5 Changes for ccnode/__init__.py: 46 added lines, 5 removed lines. Original line number Diff line number Diff line #!/usr/bin/env python # -*- coding: utf-8 -*- # # Cloud-Control Node # Copyright (C) 2011 SmartJog [http://www.smartjog.com] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Authors: # * 2011-06: Thibault VINCENT <thibault.vincent@smartjog.com> # """ __product__ = 'Cloud-Control Node' __version__ = '0~dev' __canonical__ = 'cc-node' __develmode__ = False TODO : rewrite based on older doc """ def git_version(): global __version__ import os import sys from subprocess import Popen, PIPE, CalledProcessError cwd = os.getcwd() try: os.chdir(os.path.dirname(sys.argv[0])) p = Popen(["git", "log", "--pretty=format:%H" ], stdout=PIPE, stderr=open("/dev/null", "wb")) p.wait() if p.returncode == 0: githash = p.stdout.readline().strip() if len(githash) > 0: __version__ += "-git-%s" % githash except OSError: pass finally: os.chdir(cwd) __version__ = '17' if __version__.find("dev") != -1: __develmode__ = True git_version() ccnode/ccnode.py −102 File deleted. Show changes ccnode/common.py −359 File deleted. Show changes ccnode/config.py +193 File added.Preview size limit exceeded, changes collapsed. Show changes Loading
bin/cc-node +24 −206 Changes for bin/cc-node: 24 added lines, 206 removed lines. Original line number Diff line number Diff line #!/usr/bin/env python import logging import threading import logging.handlers import sys import os import atexit import ConfigParser from math import exp from time import sleep from optparse import OptionParser from daemon import DaemonContext from sjrpc.core import RpcError from ccnode.ccnode import CCNode from ccnode import __version__ MAX_AUTH_TIMEOUT = 30 DEFAULT_CONFIG_FILE = '/etc/cc-node.conf' DEFAULT_PID_FILE = '/var/run/cc-node.pid' DEFAULT_CONFIGURATION = { 'address': '', 'login': '', 'password': '', 'port': '1984', 'verbosity': '0', 'detect_hypervisor': 'yes', #'ssl_cert': '', 'command_execution' : 'yes', 'force_xen' : 'no', } def authentication(node, suicide, login, password): ''' Node authentication thread ''' timeout = 1 while not suicide.is_set() and node.get_rpc(): logging.debug('Sending authentication request') if node.authentify(login, password): logging.error('Authentication suscessfull') return else: logging.error('Authentication failure') timeout += 0.1 if timeout >= MAX_AUTH_TIMEOUT: timeout = MAX_AUTH_TIMEOUT sleep(exp(timeout)) def setup_logging(options, instance_id=None): ''' ''' level = logging.ERROR verb = int(options['verbosity']) if verb: if verb == 1: level = logging.WARNING elif verb == 2: level = logging.INFO else: level = logging.DEBUG logger = logging.getLogger() logger.setLevel(level) if options['stdout']: handler = logging.StreamHandler() else: facility = logging.handlers.SysLogHandler.LOG_DAEMON handler = logging.handlers.SysLogHandler(address='/dev/log', facility=facility) fmt = 'cc-node: %(levelname)s ' if options['verbosity'] == 0: fmt += '%(message)s' else: if isinstance(instance_id, int): fmt += 'id=%i ' % instance_id if options['stdout']: fmt += ("\x1B[30;47m%(process)d\x1B[0m:" "\x1B[30;42m%(threadName)s\x1B[0m:" "\x1B[30;43m%(funcName)s\x1B[0m:" "\x1B[30;44m%(lineno)d\x1B[0m@" "\x1B[30;45m%(msecs)d" "\x1B[0m\t\t " "%(message)s") else: fmt += ("%(process)d:" "%(threadName)s:" "%(funcName)s:" "%(lineno)d@" "%(msecs)d " "%(message)s") handler.setFormatter(logging.Formatter(fmt)) logger.handlers = [] logger.addHandler(handler) def run_node(options): ''' ''' # instance death event suicide_event = threading.Event() try: # setup logging infrastructure setup_logging(options) # create client logging.debug('Initializing client') try: node = CCNode(options['address'], int(options['port']), options['detect_hypervisor'] == 'yes', options['command_execution'] == 'yes', force_xen=(options['force_xen'] == 'yes')) except Exception as err: logging.error('Client initialization failure: `%s`:`%s`', repr(err), err) raise err # reconfigure logging with instance ID setup_logging(options, instance_id=id(node)) # auth thread logging.debug('Starting authentication thread') auth_thread = threading.Thread(target=authentication, name='Auth', args=(node, suicide_event, options['login'], options['password'])) auth_thread.daemon = True auth_thread.start() # main loop logging.debug('Starting main loop') node.run() except Exception as err: logging.error('run_node: `%s` -> `%s`', repr(err), err) try: node.get_rpc().shutdown() except: pass finally: # ensure everything is killed properly suicide_event.set() # -*- coding: utf-8 -*- # # Cloud-Control Node # Copyright (C) 2011 SmartJog [http://www.smartjog.com] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Authors: # * 2011-06: Thibault VINCENT <thibault.vincent@smartjog.com> # from ccnode.launcher import Launcher if __name__ == '__main__': # configure argument parser op = OptionParser(version='%%prog %s' % __version__) op.add_option('-c', '--config', default=DEFAULT_CONFIG_FILE, help='configuration file (default: %default)') op.add_option('-d', '--daemonize', default=False, action='store_true', help='run as daemon and write pid file') op.add_option('-p', '--pidfile', default=DEFAULT_PID_FILE, help='pid file (default: %default)') op.add_option('-s', '--stdout', action='store_true', default=False, help='log on standard output instead of syslog') cliopts, args = op.parse_args() # read the config file config = ConfigParser.SafeConfigParser() config.read(cliopts.config) try: options = dict(config.items('node')) except ConfigParser.NoSectionError: sys.stderr.write('Configuration error: `node` section must exist ' 'in `%s`\n' % cliopts.config) sys.exit(1) # applying default config file options for opt, default in DEFAULT_CONFIGURATION.iteritems(): if opt not in options or not options[opt]: if default is None: sys.stderr.write('Configuration error: you must specify `%s` ' 'option in `%s` !\n' % (opt, cliopts.config)) sys.exit(1) else: options[opt] = default # Merge command options and .conf file options for opt in ('daemonize', 'pidfile', 'stdout'): if getattr(cliopts, opt) is not None: options[opt] = getattr(cliopts, opt) # Create option set for the daemonization process daemon_opts = {} daemonize = options['daemonize'] if isinstance(daemonize, str): daemonize = daemonize in ('yes', 'true') daemon_opts['detach_process'] = daemonize if not daemonize: daemon_opts['stderr'] = sys.stderr daemon_opts['stdout'] = sys.stderr if options['pidfile']: #daemon_opts['pidfile'] = lockfile.FileLock(options['pidfile']) pidfile = open(cliopts.pidfile, 'w') daemon_opts['files_preserve'] = [pidfile] with DaemonContext(**daemon_opts): # write pid in pidfile if pidfile is not None: pidfile.write('%s' % os.getpid()) pidfile.flush() # register pidfile cleaning @atexit.register def clean_pidfile(): pidfile.seek(0) pidfile.truncate() pidfile.flush() # run node while True: run_node(options) logging.critical('Critical error, restarting node !') sleep(2) Launcher().main()
ccnode/__init__.py +46 −5 Changes for ccnode/__init__.py: 46 added lines, 5 removed lines. Original line number Diff line number Diff line #!/usr/bin/env python # -*- coding: utf-8 -*- # # Cloud-Control Node # Copyright (C) 2011 SmartJog [http://www.smartjog.com] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Authors: # * 2011-06: Thibault VINCENT <thibault.vincent@smartjog.com> # """ __product__ = 'Cloud-Control Node' __version__ = '0~dev' __canonical__ = 'cc-node' __develmode__ = False TODO : rewrite based on older doc """ def git_version(): global __version__ import os import sys from subprocess import Popen, PIPE, CalledProcessError cwd = os.getcwd() try: os.chdir(os.path.dirname(sys.argv[0])) p = Popen(["git", "log", "--pretty=format:%H" ], stdout=PIPE, stderr=open("/dev/null", "wb")) p.wait() if p.returncode == 0: githash = p.stdout.readline().strip() if len(githash) > 0: __version__ += "-git-%s" % githash except OSError: pass finally: os.chdir(cwd) __version__ = '17' if __version__.find("dev") != -1: __develmode__ = True git_version()