コード例 #1
0
ファイル: server.py プロジェクト: mpdehaan/virt-factory
def main(argv):
    """
    Start things up.
    """

    websvc = XmlRpcInterface()

    for arg in sys.argv:
        if arg == "import" or arg == "--import":
            prov_obj = provisioning.Provisioning()
            prov_obj.init(None, {})
            return
        elif arg == "sync" or arg == "--sync":
            prov_obj = provisioning.Provisioning()
            prov_obj.sync(None, {}) # just for testing
            return
    if "qpid" in sys.argv or "--qpid" in sys.argv:
        if "daemon" in sys.argv or "--daemon" in sys.argv:
            utils.daemonize("/var/run/vf_server_qpid.pid")
        else:
            print "serving...\n"
        serve_qpid("/etc/virt-factory/qpid.conf")
    else:
        if "daemon" in sys.argv or "--daemon" in sys.argv:
            utils.daemonize("/var/run/vf_server.pid")
        else:
            print "serving...\n"
            # daemonize only if --daemonize, because I forget to type "debug" -- MPD
        serve(websvc)
コード例 #2
0
def run():
    (opts, args) = get_options()
    if opts.version:
        print "escrotum %s" % VERSION
        exit()

    if opts.countdown and not opts.delay:
        print "Countdown parameter requires delay"
        exit()

    filename = None
    if len(args) > 0:
        filename = args[0]

    if opts.clipboard:
        daemonize()

    Escrotum(filename=filename,
             selection=opts.select,
             xid=opts.xid,
             delay=opts.delay,
             countdown=opts.countdown,
             use_clipboard=opts.clipboard,
             command=opts.command)

    try:
        gtk.main()
    except KeyboardInterrupt:
        print "Canceled by the user"
        exit(EXIT_CANCEL)
コード例 #3
0
ファイル: server.py プロジェクト: mpdehaan/virt-factory
def main(argv):
    """
    Start things up.
    """
   
    # create watch file
    wf = open("/var/lib/virt-factory-nodes/watch","w+")
    wf.write("")
    wf.close()
 
    websvc = XmlRpcInterface()
    host = socket.gethostname()
     
    if "--daemon" in sys.argv:
        utils.daemonize("/var/run/vf_node_server.pid")

    pid = os.fork()
    if pid == 0:
        serve_qpid("/etc/virt-factory-nodes/qpid.conf")
    else:
        try:
            serve_status()
        except KeyboardInterrupt:
            print "caught interrupt"
            os.kill(pid, signal.SIGINT)
            os.waitpid(pid,0)
コード例 #4
0
    def run(self, daemon=True):
        """ Run as a background process, rotating proxies """

        # Touch heartbeat file
        open(self.hbf, 'w').write('')
        # Fork
        if daemon:
            print 'Daemonizing...'
            daemonize('rotator.pid', logfile='rotator.log', drop=True)
        else:
            # Write PID anyway
            open('rotator.pid', 'w').write(str(os.getpid()))

        print 'Proxy rotate daemon started.'
        count = 1

        while True:
            # Wait on event object till woken up
            self.alarm.wait(self.config.frequency)
            status = self.alive()
            if not status:
                print 'Daemon signalled to exit. Quitting ...'
                break

            print 'Rotating proxy node, round #%d ...' % count
            if self.test_mode:
                self.test()
            else:
                self.rotate()
            count += 1

        sys.exit(0)
コード例 #5
0
ファイル: main.py プロジェクト: crew/metrics-backend
def main(argv):
    FLAGS(argv)
    if not FLAGS.logfile and not FLAGS.daemonize:
        # No log file and not daemonized.
        log.startLogging(sys.stderr)
    elif not FLAGS.logfile and FLAGS.daemonize:
        # Daemonized, but no log file.
        fd, name = tempfile.mkstemp(prefix='flamongo', suffix='.log')
        os.close(fd)
        sys.stderr.write('Logging to %s\n' % name)
        log.startLogging(open(name, 'a'))
    else:
        f = open(FLAGS.logfile, 'a')
        log.startLogging(f)
    # FIXME
    mongoengine.connect('flamongo')
    # TODO define connection options.
    site = server.Site(TopLevel(lambda: Connection()))
    reactor.listenTCP(FLAGS.port, site)
    try:
        from twisted.internet import ssl
        ssl_context = ssl.DefaultOpenSSLContextFactory(FLAGS.privatekey,
            FLAGS.certificate)
        reactor.listenSSL(FLAGS.secureport, site, ssl_context)
    except ImportError:
        # removes the partial import.
        ssl = None
        log.err('SSL not enabled. Needs PyOpenSSL.')
    except Exception as ex:
        log.err(str(ex))
    if FLAGS.daemonize:
        utils.daemonize()
    reactor.run()
コード例 #6
0
ファイル: main.py プロジェクト: Phaeilo/escrotum
def run():
    args = get_options()

    if args.version:
        print ("escrotum %s" % __version__)
        exit()

    if args.countdown and not args.delay:
        print "Countdown parameter requires delay"
        exit()

    if args.clipboard:
        daemonize()

    Escrotum(
        filename=args.FILENAME,
        selection=args.select,
        xid=args.xid,
        delay=args.delay,
        selection_delay=args.selection_delay,
        countdown=args.countdown,
        use_clipboard=args.clipboard,
        command=args.command,
    )

    try:
        gtk.main()
    except KeyboardInterrupt:
        print "Canceled by the user"
        exit(EXIT_CANCEL)
コード例 #7
0
def main():

    utils.daemonize('monitor.pid', logfile='monitor.log')
    
    while True:
        parse_config()
        time.sleep(300)
コード例 #8
0
ファイル: taskatron.py プロジェクト: mpdehaan/virt-factory
def main(argv):
    """
    Start things up.
    """
    config_obj = config_data.Config()
    config = config_obj.get()
    databases = config['databases']
    url = databases['primary']
    # connect
    db.Database(url)

    textdomain(I18N_DOMAIN)
    taskatron = Taskatron()
    if len(sys.argv) > 2 and sys.argv[1].lower() == "--test":
        print taskatron.node_comm(sys.argv[2],"test_add",1,2)
    elif len(sys.argv) > 1 and sys.argv[1].lower() == "--daemon":
        taskatron.clean_up_tasks()
        utils.daemonize("/var/run/vf_taskatron.pid")
        taskatron.run_forever()
    elif len(sys.argv) > 1 and sys.argv[1].lower() == "--infinity":
        taskatron.clean_up_tasks()
        taskatron.run_forever()
    elif len(sys.argv) == 1:
        print _("Running single task in debug mode, since --daemon wasn't specified...")
        taskatron.clean_up_tasks()
        taskatron.dotick(socket.gethostname(), True)
    else:
        useage = _("""Usage:
vf_taskatron --test server.fqdn
vf_taskatron --daemon
vf_tasktron  (no args) (just runs through one pass)
""")
        print useage
コード例 #9
0
ファイル: main.py プロジェクト: 404d/escrotum
def run():
    (opts, args) = get_options()
    if opts.version:
        print "escrotum %s" % VERSION
        exit()

    if opts.countdown and not opts.delay:
        print "Countdown parameter requires delay"
        exit()

    filename = None
    if len(args) > 0:
        filename = args[0]

    if opts.clipboard:
        daemonize()

    Escrotum(filename=filename, selection=opts.select, xid=opts.xid,
             delay=opts.delay, countdown=opts.countdown,
             use_clipboard=opts.clipboard, exec_command=opts.exec_command)

    try:
        gtk.main()
    except KeyboardInterrupt:
        print "Canceled by the user"
        exit(EXIT_CANCEL)
コード例 #10
0
ファイル: main.py プロジェクト: mehulsbhatt/conference
def main(config):
    configureLogging(config)
    log = logging.getLogger('main')
    log.info('Starting conf_tracker version %s.', pkg_resources.require('conf_tracker')[0].version)
    if config.getboolean('daemon', 'daemon'):
        pidfile = config.get('daemon', 'pidfile')
        daemonize(pidfile)
        
    
    pw = config.get('host', 'password')
    h = config.get('host', 'host')
    p = config.get('host', 'port')
    
    #Setting up the DB connection
    log.info('Connecting to DB on: %s ' % (config.get('database', 'url')))

    if ("sqlite" in config.get('database', 'url')):
        engine = create_engine( config.get('database', 'url'), poolclass=NullPool )
        log.warning('You are using SQLite and we will use NullPool as pooling engine.')
    else:
        engine = create_engine( config.get('database', 'url'), pool_recycle=3600 )


    #meta.Session = sessionmaker( autoflush=False, autocommit=False, bind=engine)
    meta.Session.configure(bind=engine)
    
    con = connect(h, p, pw)
    conferences = {}
    while True:
        while not con.connected():
            log.warning("On main loop retrying...")
            con = connect(h, p, pw)
            
        e = con.recvEventTimed(5000)

        if e is None:
            continue

        conf_uuid = getUnquotedHeader(e, 'Conference-Unique-ID')
        action = getUnquotedHeader(e, 'Action')
        conf_size = getUnquotedHeader(e, 'Conference-Size')
        
        if action == 'stop-recording':
            try:
                TrackerConference.stop_recording(e, config)
                continue
            except Exception, e:
                log.exception('An error has occurred while executing stop-recording!')
                continue
        
        if conf_uuid not in conferences.keys():
            try:
                conf = TrackerConference(e, config)
                conferences[conf_uuid] = conf
            except Exception, e:
                log.exception('An error occured creating a new conference object! Continuing...')
                continue
コード例 #11
0
ファイル: main.py プロジェクト: mehulsbhatt/conference
def main(config):
            
    configureLogging(config)
    log = logging.getLogger('main')
    
    if config.getboolean('daemon', 'daemon'):
        pidfile = config.get('daemon', 'pidfile')
        daemonize(pidfile)
        
    
    pw = config.get('host', 'password')
    h = config.get('host', 'host')
    p = config.get('host', 'port')
    
    #Setting up the DB connection
    log.info('Connecting to DB on: %s ' % (config.get('database', 'url')))

    if ("sqlite" in config.get('database', 'url')):
        engine = create_engine( config.get('database', 'url'), poolclass=NullPool )
        log.warning('You are using SQLite and we will use NullPool as pooling engine.')
    else:
        engine = create_engine( config.get('database', 'url'), pool_recycle=3600 )


    Session = sessionmaker( autoflush=False, autocommit=False, bind=engine)
    
    log.info('Connecting to: %s:%s ' % (h, p))
    con = ESLconnection(h, p, pw)
    con.events('plain', 'CUSTOM conference::maintenance')
    conferences = {}
    while con.connected():
        e = con.recvEvent()

        if e is None:
            continue
            

        conf_uuid = getUnquotedHeader(e, 'Conference-Unique-ID')
        action = getUnquotedHeader(e, 'Action')
        conf_size = getUnquotedHeader(e, 'Conference-Size')
        
        if action == 'stop-recording':
            try:
                TrackerConference.stop_recording(e, config, Session())
                continue
            except Exception, e:
                log.critical('An error has occurred while executing stop-recording!\n%s' % traceback.format_exc())
                continue
        
        if conf_uuid not in conferences.keys():
            try:
                conf = TrackerConference(e, config, Session())
                conferences[conf_uuid] = conf
            except Exception, e:
                log.warning('An error occured creating a new conference object! Continuing... \n%s' % e)
                continue
コード例 #12
0
ファイル: certmaster.py プロジェクト: alikins/certmaster
def main(argv):
    
    cm = CertMaster('/etc/certmaster/certmaster.conf')

    if "daemon" in argv or "--daemon" in argv:
        utils.daemonize("/var/run/certmaster.pid")
    else:
        print "serving...\n"


    # just let exceptions bubble up for now
    serve(cm)
コード例 #13
0
ファイル: mayue.py プロジェクト: biubiu/grma
    def run(self):
        print __logo__

        print '[OK] Running grma {version}'.format(version=__version__)

        print '-' * 10 + ' CONFIG ' + '-' * 10

        cf = dict()
        for arg in vars(self.app.args):
            cf[arg] = getattr(self.app.args, arg)

        for k, v in cf.items():
            msg = '{key}\t{value}'.format(key=k, value=v)
            print msg

        print '-' * 28

        if self.app.args.daemon:
            utils.daemonize()

        self.pid = os.getpid()

        self.app.server.bind(
            self.app.args.host, self.app.args.port,
            self.app.args.private, self.app.args.certificate
            )

        print '[OK] Master running pid: {pid}'.format(pid=self.pid)
        utils.setproctitle('grma master pid={pid}'.format(pid=self.pid))

        for i in range(self.app.args.num):
            self.spawn_worker()

        if self.app.args.pid:
            self.pidfile = Pidfile(self.app.args.pid)
            self.pidfile.create(self.pid)

        self.init_signals()

        while True:
            try:
                sleep(1)
                if self.try_to_stop:
                    break
            except:
                self.clean()
                break
        # gRPC master server should close first
        self.kill_worker(self.pid, signal.SIGKILL)
コード例 #14
0
ファイル: certmaster.py プロジェクト: jude/certmaster
def main(argv):

    sys.excepthook = excepthook
    cm = CertMaster('/etc/certmaster/certmaster.conf')

    if "--version" in sys.argv or "-v" in sys.argv:
        print >> sys.stderr, file("/etc/certmaster/version").read().strip()
        sys.exit(0)

    if "daemon" in argv or "--daemon" in argv:
        utils.daemonize("/var/run/certmaster.pid")
    else:
        print "serving...\n"

    # just let exceptions bubble up for now
    serve(cm)
コード例 #15
0
ファイル: certmaster.py プロジェクト: scibian/certmaster
def main(argv):

    sys.excepthook = excepthook
    cm = CertMaster('/etc/certmaster/certmaster.conf')

    if "--version" in sys.argv or "-v" in sys.argv:
        print >> sys.stderr, file("/etc/certmaster/version").read().strip()
        sys.exit(0)

    if "daemon" in argv or "--daemon" in argv:
        utils.daemonize("/var/run/certmaster.pid")
    else:
        print "serving...\n"

    # just let exceptions bubble up for now
    serve(cm)
コード例 #16
0
ファイル: service.py プロジェクト: TeraprocSoftware/jaguar
def start(config, daemon):
    """Start Jaguar service.

    Examples:

    $ jaguar service start

    $ jaguar service --daemon start
    """
    # Make sure java is available
    if not environ.get(JAGUAR_HOME):
        raise click.UsageError('JAGUAR_HOME envrionment variable is not set.')
    dir_must_exist(environ.get(JAGUAR_HOME))
    execute_envsh(config.conf)
    if environ["JAVA_HOME"] is not None and environ["JAVA_HOME"]:
        prg = join(environ["JAVA_HOME"], "bin", "java")
    else:
        prg = which("java")

    if prg is None:
        quit("Cannot locate java.")
    # Jaguar conf
    properties = join(config.conf, JAGUAR_PROPERTIES)
    args = JAGUAR_CONF_ARGS.format(properties).split()
    # Jaguar log
    logback = join(config.conf, JAGUAR_LOGBACK)
    args.extend(JAGUAR_LOG_ARGS.format(logback).split())
    # Jaguar port
    args.extend(JAGUAR_PORT_ARGS.format(config.server['port']).split())
    # Jaguar classpath
    classpath = join(environ.get(JAGUAR_HOME), 'lib', '*')
    jvm_opts_list = DEFAULT_JVM_OPTS.split()
    # Shall we daemonize?
    if daemon:
        daemonize()
        environ['LOG_APPENDER'] = 'FILE'
    else:
        environ['LOG_APPENDER'] = 'STDOUT'

    commandline = [prg]
    commandline.extend(jvm_opts_list)
    commandline.append("-classpath")
    commandline.append(classpath)
    commandline.append(JAGUAR_CLASSNAME)
    commandline.extend(args)

    return run(commandline)
コード例 #17
0
    def screenshot(self):
        """
        Capture the screenshot based on the window size or the selected window
        """

        x, y = (self.x, self.y)
        window = self.root
        width, height = self.width, self.height

        # get screenshot of the selected window
        if self.click_selection:
            xid = get_selected_window()
            if not xid:
                print "Can't get the xid of the selected window"
                exit(EXIT_XID_ERROR)
            selected_window = gtk.gdk.window_foreign_new(xid)
            width, height = selected_window.get_size()
            x, y = selected_window.get_origin()

        pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, width, height)
        # mask the pixbuf if we have more than one screen
        root_width, root_height = window.get_size()
        pb2 = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8,
                             root_width, root_height)
        pb2 = pb2.get_from_drawable(window, window.get_colormap(),
                                    x, y, x, y,
                                    width, height)
        pb2 = self.mask_pixbuf(pb2, root_width, root_height)
        pb2.copy_area(x, y, width, height, pb, 0, 0)

        if not pb:
            print "Invalid Pixbuf"
            exit(EXIT_INVALID_PIXBUF)
        if self.use_clipboard:
            self.save_clipboard(pb)
        else:
            self.save_file(pb, width, height)
        if self.command:
            self.call_exec(width, height)

        # daemonize here so we don't mess with the CWD on subprocess
        if self.use_clipboard:
            daemonize()
        else:
            # exit here instead of inside save_file
            exit()
コード例 #18
0
ファイル: main.py プロジェクト: Roger/escrotum
    def screenshot(self):
        """
        Capture the screenshot based on the window size or the selected window
        """

        x, y = (self.x, self.y)
        window = self.root
        width, height = self.width, self.height

        # get screenshot of the selected window
        if self.click_selection:
            xid = get_selected_window()
            if not xid:
                print "Can't get the xid of the selected window"
                exit(EXIT_XID_ERROR)
            selected_window = gtk.gdk.window_foreign_new(xid)
            width, height = selected_window.get_size()
            x, y = selected_window.get_origin()

        pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, width, height)
        # mask the pixbuf if we have more than one screen
        root_width, root_height = window.get_size()
        pb2 = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8,
                             root_width, root_height)
        pb2 = pb2.get_from_drawable(window, window.get_colormap(),
                                    x, y, x, y,
                                    width, height)
        pb2 = self.mask_pixbuf(pb2, root_width, root_height)
        pb2.copy_area(x, y, width, height, pb, 0, 0)

        if not pb:
            print "Invalid Pixbuf"
            exit(EXIT_INVALID_PIXBUF)
        if self.use_clipboard:
            self.save_clipboard(pb)
        else:
            self.save_file(pb, width, height)
        if self.command:
            self.call_exec(width, height)

        # daemonize here so we don't mess with the CWD on subprocess
        if self.use_clipboard:
            daemonize()
        else:
            # exit here instead of inside save_file
            exit()
コード例 #19
0
ファイル: airplayer.py プロジェクト: songww/Airplayer
    def run(self):
        """
        Run the application.
        Perform some bootstrapping, fork/daemonize if necessary.
        """
        self._parse_opts()
        self._setup_path()

        if self._opts.daemon:
            utils.daemonize()

            pid = os.getpid()
            self._pidfile = Pidfile(self._opts.pidfile)
            self._pidfile.create(pid)

        self._init_signals()
        self._configure_logging()
        self.log.info('Starting Airplayer')

        self._register_bonjour()
        self._register_media_backend()

        self._media_backend.notify_started()
        self._start_protocol_handler()
コード例 #20
0
ファイル: zabbix-server.py プロジェクト: RayGuolq/zabbix

def main():
    # Check the lockfile to make sure there is only one instance running
    lockfile_fd = open(config.LOCK_FILE, "a+")
    try:
        fcntl.flock(lockfile_fd.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError, e:
        logger.error("lock file (%s) failed, (%d) %s" % \
                     (config.LOCK_FILE, e.errno, e.strerror))
        os._exit(1)

    options, metadataXMLFile = parse_command_line()
    if options.daemonize:
        logger.info("Run the server in daemon mode")
        daemonize("/", config.PID_FILE)
    else:
        logger.info("Run the server in interactive mode")

    try:
        server = Server()
        server.start()
    except Exception:
        logger.error("Start server failure")
        os._exit(2)
    server.loop()

    return 0


if __name__ == "__main__":
コード例 #21
0
                             config["task_exchange"], config["icinga_path"])

logger = get_logger(config["verbose"])
configure_logging(logger, config["logging"])


def signal_handler(signum, frame):
    logging.warn("SIGNAL " + str(signum) + " received! Frame: " + str(frame))
    logging.debug("Stop ResultWriter thread")
    result_writer.stop()
    logging.debug("Wait for ResultWriter thread to join")
    result_writer.join()
    logging.debug("ResultWriter thread joined")
    if config["daemonize"]:
        os.remove("/var/run/monitunnel.pid")
    sys.exit(0)


if "__main__" == __name__:
    if config["daemonize"]:
        daemonize()
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGALRM, signal_handler)
    signal.signal(signal.SIGHUP, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    logging.debug("Start Icinga ResultWriter Thread")
    result_writer.start()
    run = True
    while run:
        time.sleep(1)
コード例 #22
0
    form_data['ac_id'] = '1'

    headers = {}
    headers[
        'User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3440.75 Safari/537.36'

    if args.local_only:
        form_data['username'] += '@tsinghua'
    if args.action == 'login' and (args.username == None
                                   or args.password == None):
        sys.exit('Error: specify username and password')
    if args.action == 'logout' and args.username == None:
        sys.exit('Error: specify username')

    if args.daemon != 0:
        daemonize(stdout='/tmp/portal_log.log', stderr='/tmp/portal_err.log')
        while True:
            attempt = 0
            while attempt < args.max_retries:
                log('Attemp %d: %s' % (attempt + 1, args.action))
                if args.action == 'check_status':
                    status = check_online(headers)
                    if status['online'] != 'Error':
                        disp_online_info(status)
                        break
                elif args.action == 'login':
                    status = check_online(headers)
                    if args.force or status['online'] == 'Not online':
                        login_status = do_login(headers, form_data)
                        if login_status == 1:
                            log('login succeeded')
コード例 #23
0
ファイル: __init__.py プロジェクト: nixon/Tinman
def main(*args):
    # Setup optparse
    usage = "usage: %prog -c <configfile> [options]"
    version_string = "%%prog %s" % __version__
    description = "Tornado application runner"

    # Create our parser and setup our command line options
    parser = OptionParser(usage=usage,
                          version=version_string,
                          description=description)

    parser.add_option("-c", "--config",
                      action="store",
                      dest="config",
                      help="Specify the configuration file for use")
    parser.add_option("-f", "--foreground",
                      action="store_true",
                      dest="foreground",
                      default=False,
                      help="Run interactively in console")
    parser.add_option("-r", "--route-decorator",
                      action="store_true",
                      dest="route_decorator",
                      default=False,
                      help="Utilize the route decorator instead of the Routes\
                            section of the config")

    # Parse our options and arguments
    options, args = parser.parse_args()

    # No configuration file?
    if options.config is None:
        stderr.write('\nERROR: Missing configuration file\n\n')
        parser.print_help()
        exit(1)

    # Load in the YAML config file
    config = utils.load_configuration_file(options.config)

    # Required

    if 'Application' not in config:
        raise AttributeError("Missing Application section in configuration")

    if 'HTTPServer' not in config:
        raise AttributeError("Missing HTTPServer section in configuration")

    if 'Logging' not in config:
        raise AttributeError("Missing Logging section in configuration")

    if not options.route_decorator and 'Routes' not in config:
        raise AttributeError("Missing Routes section in configuration")

    if not options.route_decorator and \
       not isinstance(config['Routes'], list):
        raise AttributeError("Error in Routes section in configuration")

    if 'base_path' in config:
        import sys
        sys.path.insert(0, config['base_path'])

    # Setup our logging
    utils.setup_logging(config['Logging'], options.foreground)

    # Setup our signal handlers
    utils.setup_signals()

    # Daemonize if we need to
    if not options.foreground:
        utils.daemonize(pidfile=config.get("pidfile", None),
                        user=config.get("user", None),
                        group=config.get("group", None))
    else:
        config['Application']['debug'] = True

    # Loop through and kick off our processes
    children = []
    for port in config['HTTPServer']['ports']:
        debug("Starting process for port %i" % port)
        # Kick off the child process
        child = Process(target=start,
                        name="tinman-%i" % port,
                        args=(config['Routes'],
                              config['Application'],
                              config['HTTPServer'],
                              port))
        children.append(child)
        child.start()
    debug("All children spawned")

    # Have a main event loop for dealing with stats
    utils.running = True
    while utils.running:
        try:
            sleep(1)
        except KeyboardInterrupt:
            info("CTRL-C pressed, shutting down.")
            break

    # Tell all the children to shutdown
    for child in children:
        debug("Sending terminate signal to %s", child.name)
        child.terminate()

    # Loop while the children are shutting down
    debug("Waiting for children to shutdown")
    while True in [child.is_alive() for child in children]:
        sleep(0.5)

    # Remove our pidfile
    if 'pidfile' in config:
        if exists(config['pidfile']):
            try:
                unlink(config['pidfile'])
            except OSError as e:
                error("Could not remove pidfile: %s", e)

    # Log that we're shutdown cleanly
    info("tinman has shutdown")
コード例 #24
0
ファイル: xaif_server.py プロジェクト: aMiss-aWry/ADserver
for o, a in opts:
    if o in ("-h", "--help"):
        print "help"
    if o=="--verbose":
        verbose = 1
    if o=="--timeout":
        timeout = int(a)
    if o=="--server_port":
        server_port = int(a)
    if o=="--scheduler_port":
        scheduler_port = int(a)
    if o=="--basedir":
        basedir = a
    if o=="--stdout":
        stdout = a
    if o=="--stderr":
        stderr = a
    if o=="--server_type":
        server_type = a
    if o=="--scheduler_host":
        scheduler_host = a
        
daemonize(stdin,stdout,stderr)
signal.signal(signal.SIGTERM, my_signal_handler)
signal.signal(signal.SIGQUIT, my_signal_handler)
signal.signal(signal.SIGINT, my_signal_handler)
signal.signal(signal.SIGALRM, my_alarm_signal_handler)
os.chdir(basedir)    # change to work directory
mainloop()

コード例 #25
0
ファイル: parser.py プロジェクト: slient2010/ManageGame
 def daemonize_if_required(self):
     if self.options.daemon:
         daemonize(self.config["swall"]["user"])
コード例 #26
0
ファイル: mayue.py プロジェクト: GuoJing/grma
    def run(self):
        host = self.app.args.host
        port = self.app.args.port

        print __logo__

        print '[OK] Running grma {version}'.format(version=__version__)

        print '-' * 10 + ' CONFIG ' + '-' * 10

        cf = dict()
        for arg in vars(self.app.args):
            cf[arg] = getattr(self.app.args, arg)

        for k, v in cf.items():
            msg = '{key}\t{value}'.format(key=k, value=v)
            print msg

        print '-' * 28

        if self.app.args.daemon:
            utils.daemonize()

        self.pid = os.getpid()

        binded = self.app.server.bind(
            host, port,
            self.app.args.private, self.app.args.certificate
            )

        if not binded:
            logging.info('[FAILED] Master cannot bind {host}:{port}, '
                         'or maybe bind function return None?'.format(
                             host=host, port=port))
            sys.exit(1)

        logging.info('[OK] Master running pid: {pid}'.format(pid=self.pid))
        utils.setproctitle('grma master pid={pid}'.format(pid=self.pid))

        self.init_signals()

        if self.app.args.pid:
            try:
                self.pidfile = Pidfile(self.app.args.pid)
                self.pidfile.create(self.pid)
            except:
                self.clean()
                sys.exit(1)

        self.manage_workers()
        while True:
            try:
                if self.try_to_stop:
                    break

                sig = self.signal_list.pop(0) if self.signal_list else None

                if sig is None:
                    self.sleep()
                    self.manage_workers()
                    continue

                self.process_signal(sig)
                self.wakeup()
            except KeyboardInterrupt:
                self.clean()
                break
            except Exception as e:
                self.logger.exception(e)
                self.clean()
                break
        # gRPC master server should close first
        self.kill_worker(self.pid, signal.SIGKILL)
コード例 #27
0
ファイル: mayue.py プロジェクト: gitter-badger/grma
    def run(self):
        host = self.app.args.host
        port = self.app.args.port

        print __logo__

        print '[OK] Running grma {version}'.format(version=__version__)

        print '-' * 10 + ' CONFIG ' + '-' * 10

        cf = dict()
        for arg in vars(self.app.args):
            cf[arg] = getattr(self.app.args, arg)

        for k, v in cf.items():
            msg = '{key}\t{value}'.format(key=k, value=v)
            print msg

        print '-' * 28

        if self.app.args.daemon:
            utils.daemonize()

        self.pid = os.getpid()

        binded = self.app.server.bind(
            host, port,
            self.app.args.private, self.app.args.certificate
            )

        if not binded:
            logging.info('[FAILED] Master cannot bind {host}:{port}, '
                         'or maybe bind function return None?'.format(
                             host=host, port=port))
            sys.exit(1)

        logging.info('[OK] Master running pid: {pid}'.format(pid=self.pid))
        utils.setproctitle('grma master pid={pid}'.format(pid=self.pid))

        self.init_signals()

        if self.app.args.pid:
            try:
                self.pidfile = Pidfile(self.app.args.pid)
                self.pidfile.create(self.pid)
            except:
                self.clean()
                sys.exit(1)

        self.manage_workers()
        while True:
            try:
                if self.try_to_stop:
                    break

                sig = self.signal_list.pop(0) if self.signal_list else None

                if sig is None:
                    self.manage_workers()
                    continue

                self.process_signal(sig)
            except KeyboardInterrupt:
                self.clean()
                break
            except Exception as e:
                self.logger.exception(e)
                self.clean()
                break
        # gRPC master server should close first
        self.kill_worker(self.pid, signal.SIGKILL)
コード例 #28
0
    -d          Debug mode
    -u user     Drop privileges to run as user
    -h          Display this help message
""" % os.path.basename(sys.argv[0])
  sys.exit(1)

for opt,val in opts:
  if opt == '-d':
    debug = True
  elif opt == '-u':
    user = val

if debug:
  logify()
else:
  daemonize()
  logify('log/agent.log')
  pf = open('pid/agent.pid','w')
  pf.write( str(os.getpid()) )
  pf.close()
  try: dropprivs(user)
  except: pass
print 'carbon-agent started (pid=%d)' % os.getpid()

def handleDeath(signum,frame):
  print 'Received SIGTERM, killing children'
  try:
    os.kill( persisterProcess.pid, SIGTERM )
    print 'Sent SIGTERM to carbon-persister'
    os.wait()
    print 'wait() complete, exitting'
コード例 #29
0
for o, a in opts:
    if o in ("-h", "--help"):
        print "help"
    if o=="--verbose":
        verbose = 1
    if o=="--timeout":
        timeout = int(a)
    if o=="--server_port":
        server_port = int(a)
    if o=="--scheduler_port":
        scheduler_port = int(a)
    if o=="--basedir":
        basedir = a
    if o=="--stdout":
        stdout = a
    if o=="--stderr":
        stderr = a
    if o=="--server_type":
        server_type = a
    if o=="--scheduler_host":
        scheduler_host = a
        
daemonize(stdin,stdout,stderr)
signal.signal(signal.SIGTERM, my_signal_handler)
signal.signal(signal.SIGQUIT, my_signal_handler)
signal.signal(signal.SIGINT, my_signal_handler)
signal.signal(signal.SIGALRM, my_alarm_signal_handler)
os.chdir(basedir)    # change to work directory
mainloop()

コード例 #30
0
  if cmd == "start":
    print("Start Mapper system components")

  elif cmd == "connect":
    print("Connect Mapper system components")

  elif cmd == "stop":
    print("Terminate Mapper system components")

  elif cmd == "activate":
    print("Activate Mapper system components")

  elif cmd == "deactivate":
    print("Deactivate Mapper system components")

  else:
    print("No such command: ", cmd)
  
  print("<hr>")
  print('[<a href="/">Back to the top page.</a>]')
  print("</body>")
  print("</html>")

  sys.stdout.flush()

  utils.daemonize()

  if cmd:
    arg=['/usr/local/openrtm/path_plan.sh', cmd, disp]
    p = subprocess.Popen(arg)
コード例 #31
0
    # read config file
    CFGFILE = os.path.abspath(CFGFILE)
    if not os.path.isfile(CFGFILE):
        print "error: config file %s does not exist" % (CFGFILE)
        sys.exit(1)
    CFG = utils.read_config(CFGFILE)

    # check if working directory exists
    WORKDIR = os.path.abspath(CFG['workdir'])
    if not os.path.isdir(WORKDIR):
        print "error: working directory %s does not exist" % (WORKDIR)
        sys.exit(1)

    try:
        if RUNASDAEMON:
            utils.daemonize(WORKDIR)
    except SystemExit:
        sys.exit(0)

    # try to open server on unprivileged port
    try:
        # allow re-ue port after CTRL-C
        SocketServer.TCPServer.allow_reuse_address = True
        httpd = SocketServer.ThreadingTCPServer(('', PORT), CustomHandler)
    except:
        time.sleep(2)
        print "failed to open port %d" % PORT
        print sys.exc_info()
        sys.exit(1)

    print "serving at port", PORT
コード例 #32
0
        scp_client = scp.SCPClient(ssh_client.get_transport())
        s = StringIO(ip)
        scp_client.putfo(s, '%s/%s.ddnsip' % (remote_dir, domain))
        scp_client.close()
        s.close()
    except scp.SCPException as e:
        print(e.args)


if __name__ == '__main__':
    conf = {}
    with open('client.conf', 'r') as fp:
        conf = json.load(fp)

    if conf['daemon'].lower() == 'true':
        daemonize(stdout='/tmp/ddns_client.log',
                  stderr='/tmp/ddns_client_err.log')

    domain = conf['domain']
    ddns_host = conf['ddns_host']
    ssh_user = conf['ssh_user']
    ssh_port = conf['ssh_port']
    ssh_password = conf['ssh_password']
    id_rsa = conf['id_rsa']
    remote_dir = conf['remote_dir']
    interval = conf['interval']

    last_ip = None

    while True:
        new_ip = get_ip()
        while last_ip == new_ip:
コード例 #33
0
ファイル: server.py プロジェクト: zrdthu/DDNS-Python
            return True
        else:
            return False


def update_dnsmasq():
    for pid in psutil.pids():
        if psutil.pid_exists(pid) and psutil.Process(
                pid).username() == 'dnsmasq':
            os.kill(pid, signal.SIGHUP)
            print('%s: dnsmasq updated' % timestamp2str(time.time()))


if __name__ == '__main__':
    conf = {}
    with open('server.conf', 'r') as fp:
        conf = json.load(fp)

    if conf['daemon'].lower() == 'true':
        daemonize(stdout='/var/log/ddns_server.log',
                  stderr='/var/log/ddns_server_err.log')

    path = conf['path']
    interval = conf['interval']

    domain_maintainance = Domain_Maintainance(path)
    while True:
        if domain_maintainance.update():
            update_dnsmasq()
        time.sleep(interval)
コード例 #34
0
import sys
import subprocess
import utils

if __name__ == '__main__':
  print("Content-type: text/html")
  print("")
  print("<html>")
  print("<head>")
  print("<title>RTM Naming Service</title>")
  print('<META http-equiv="Refresh" content="3;URL=/">')
  print("</head>")
  print("<body>")


  try:
    res=subprocess.check_output(['pgrep', 'omniNames'])
    if res:
      print("omniNames already running")
    print("</body>")
    print("</html>")
  except:
    print("Start omniNames")
    print("</body>")
    print("</html>")
    sys.stdout.flush()

    utils.daemonize()
    utils.start_omniNames()

コード例 #35
0
            sys.exit(0)
        if o == "-v":
            VERBOSE += 1
        elif o == "-D":
            RUNASDAEMON = True

    # read config file
    CFGFILE = os.path.abspath(CFGFILE)
    if not os.path.isfile(CFGFILE):
        print "error: config file %s does not exist" % (CFGFILE)
        sys.exit(1)
    CFG = utils.read_config(CFGFILE)

    try:
        if RUNASDAEMON:
            utils.daemonize(CFG['workdir'])
    except SystemExit:
        sys.exit(0)

    sport = serial.Serial(CFG['serialport'], CFG['baudrate'])
    sport.close()
    sport.open()
    print "sensorlogger v%s\n reading config %s\n started at %s" % (
        VERSION, CFGFILE, time.asctime())
    sys.stdout.flush()
    while 1:
        try:
            x = sport.readline().strip()
            # eliminate 0 bytes ... bug in buffer handling sensorapp.c
            x = x.replace("\0", "")
            x = x.strip("\r")