Skip to content
cc-node 2.63 KiB
Newer Older
Benziane Chakib's avatar
Benziane Chakib committed
#!/usr/bin/env python
# This file is part of CloudControl.
#
# CloudControl is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CloudControl 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with CloudControl.  If not, see <http://www.gnu.org/licenses/>.


import os
import sys
import atexit
from optparse import OptionParser
from os.path import isfile, abspath

from daemon import DaemonContext

from cloudcontrol.node import __version__
Anael Beutot's avatar
Anael Beutot committed
from cloudcontrol.node.node import NodeLoop
from cloudcontrol.node.config import NodeConfigParser, configure_logging


DEFAULT_CONFIG_FILE = '/etc/cc-node.conf'


# command line arguments...
oparser = OptionParser(version='%%prog %s' % __version__)
oparser.add_option('-d', '--daemonize', default=False, action='store_true',
                  help=u'run as daemon and write pid file')
oparser.add_option('-c', '--config', metavar='FILE',
                  default=DEFAULT_CONFIG_FILE,
                  help=u'configuration file ABSOLUTE path (default: %default)')
oparser.add_option('-p', '--pidfile', metavar='FILE',
                  help=u'pid file path for daemon mode')
options, args = oparser.parse_args()
Anael Beutot's avatar
Anael Beutot committed

# check argument configuration
if options.daemonize and not options.pidfile:
    sys.exit(u'Please supply a pid file...')

options.config = abspath(options.config)
if not isfile(options.config):
    sys.exit(u'Please supply a valid path to configuration file...')
configure_logging(1, 'console')
config = NodeConfigParser(options.config)


# take care of pid file if daemon
if options.daemonize:
    pidfile = open(options.pidfile, 'w')
    files_preserve = [pidfile]
else:
    files_preserve = None

if config.debug:
    stderr = sys.stderr
    stdout = sys.stdout
else:
    stderr = None
    stdout = None

with DaemonContext(detach_process=options.daemonize,
                   files_preserve=files_preserve,
                   stderr=stderr,
                   stdout=stdout):

    # take care of pidfile
    if options.daemonize:
        pidfile.write('%s' % os.getpid())
        pidfile.flush()

        @atexit.register
        def clean_pidfile():
            pidfile.seek(0)
            pidfile.truncate()
            pidfile.flush()

Anael Beutot's avatar
Anael Beutot committed
    NodeLoop(options.config).start()