示例#1
0
    def run(self, q):
        # Block SIGTERM and SIGINT to allow graceful shutdown and cleanup after initialization
        signal.pthread_sigmask(signal.SIG_BLOCK,
                               [signal.SIGTERM, signal.SIGINT])

        with ExitStack() as stack:
            try:
                server = stack.enter_context(self._create_server())
                port = server.add_insecure_port("127.0.0.1:0")
                server.start()
            except Exception:
                q.put(None)
                raise

            # Send port to parent
            q.put(port)

            # Sleep until termination by signal
            signal.sigwait([signal.SIGTERM, signal.SIGINT])

            server.stop(0)

        # Save collected coverage data
        try:
            from pytest_cov.embed import cleanup
        except ImportError:
            pass
        else:
            cleanup()
示例#2
0
    def t_func():
        try:

            #Wait for shutdown signal if running in service mode
            print("Press Ctrl-C to quit...")
            if sys.platform == "win32":
                hwnd = _win32_create_message_hwnd()

                def _stop_loop():
                    _win32_post_hwnd_close(hwnd)

                try:
                    atexit.register(_stop_loop)
                    _win32_wait_message_hwnd(hwnd)
                finally:
                    try:
                        atexit.unregister(_stop_loop)
                    except Exception:
                        pass
            else:
                import signal
                signal.sigwait([signal.SIGTERM, signal.SIGINT])
        except Exception:
            traceback.print_exc()
        callback()
 def run(self):
     try:
         while True:
             signal.sigwait([signal.SIGINT])
             self.kernel.process.SendAsyncInterrupt()
     except Exception as e:
         self.kernel.log.error('Exception in SIGINTHandler: %s' % str(e))
示例#4
0
    def run(self):
        """
        按注册顺序启动所有worker,阻塞主进程。
        Hub在接收到 ``SIGTERM`` 或者 ``SIGINT`` 时会尝试安全退出。

        Start workers and block the main process.
        Hub tries to shutdown itself gracefully when receiving
        ``SIGTERM`` or ``SIGINT``.
        """
        with self._mu:
            self._assert_ready()
            assert len(self._workers) > 0, 'no worker registered'
        for worker in self._workers:
            worker.start()

        signal.sigwait((signal.SIGINT, signal.SIGTERM))
        self.close()
        for worker in self._workers:
            try:
                # close method does not exist until Python 3.7 and better
                if getattr(worker, 'close', False):
                    worker.close()
            except Exception as e:
                logging.error(
                    '[resource leak warning] failed to close process "%s": %s',
                    worker._name, e)
示例#5
0
def wait_exit():

    #Wait for shutdown signal if running in service mode
    print("Press Ctrl-C to quit...")
    if sys.platform == "win32":
        _win32_wait_exit()
    else:
        import signal
        signal.sigwait([signal.SIGTERM, signal.SIGINT])
示例#6
0
def receive_button(d):
    while True:
        print('waiting')
        # signal.signal(signal.SIGUSR1, receive_signal)
        signal.sigwait((signal.SIGUSR1, ))
        socketsend("fire", d.getLatitude(), d.getLongitude(),
                   d.getPersonalid())
        print('socketsend')
        print('Senyal d emergencia enviada')
示例#7
0
    def __del__(self):
        if not self.tb_process or self.tb_process.poll():
            return

        if self.wait_tb:
            print('Finished, press Ctrl+C to exit TensorBoard',
                  file=sys.stderr)
            sigwait([SIGINT])

        self.tb_process.terminate()
示例#8
0
def main():
    parser = argparse.ArgumentParser(
        description="Example Robot Raconteur iRobot Create service")
    parser.add_argument("--nodename",
                        type=str,
                        default="sense_hat.SenseHat",
                        help="The NodeName to use")
    parser.add_argument("--tcp-port",
                        type=int,
                        default=2354,
                        help="The listen TCP port")
    parser.add_argument("--wait-signal",
                        action='store_const',
                        const=True,
                        default=False)
    args = parser.parse_args()
    sense = SenseHat()
    imu_service = Sense_hat_IMU(sense)
    sensor_hat_service = Sense_hat(sense, imu_service)

    with RR.ServerNodeSetup(args.nodename, args.tcp_port) as node_setup:
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.uuid")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.identifier")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.geometry")

        RRN.RegisterServiceTypeFromFile("com.robotraconteur.color")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.datetime")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.sensordata")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.resource")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.device")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.datatype")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.param")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.units")

        RRN.RegisterServiceTypeFromFile("com.robotraconteur.sensor")
        RRN.RegisterServiceTypeFromFile("com.robotraconteur.imu")
        RRN.RegisterServiceTypeFromFile("experimental.sensehat")
        RRN.RegisterService("SensorHat", "experimental.sensehat.SenseHat",
                            sensor_hat_service)
        RRN.RegisterService("SensorHatIMU", "com.robotraconteur.imu.ImuSensor",
                            imu_service)
        sensor_hat_service.joystick_thread.start()

        if args.wait_signal:
            #Wait for shutdown signal if running in service mode
            print("Press Ctrl-C to quit...")
            import signal
            signal.sigwait([signal.SIGTERM, signal.SIGINT])
        else:
            #Wait for the user to shutdown the service
            if (sys.version_info > (3, 0)):
                input("Server started, press enter to quit...")
            else:
                raw_input("Server started, press enter to quit...")
示例#9
0
def main():

    #Accept the names of the webcams and the nodename from command line
            
    parser = argparse.ArgumentParser(description="Example Robot Raconteur webcam service")
    parser.add_argument("--camera-names",type=str,help="List of camera names separated with commas")
    parser.add_argument("--nodename",type=str,default="experimental.createwebcam2.WebcamHost",help="The NodeName to use")
    parser.add_argument("--tcp-port",type=int,default=2366,help="The listen TCP port")
    parser.add_argument("--wait-signal",action='store_const',const=True,default=False)
    args = parser.parse_args()

    #Initialize the webcam host root object
    camera_names=[(0,"Left"),(1,"Right")]
    if args.camera_names is not None:
        camera_names_split=list(filter(None,args.camera_names.split(',')))
        assert(len(camera_names_split) > 0)
        camera_names = [(i,camera_names_split[i]) for i in range(len(camera_names_split))]
        
        
    obj=WebcamHost_impl(camera_names)
    
    with RR.ServerNodeSetup(args.nodename,args.tcp_port) as node_setup:

        RRN.RegisterServiceTypeFromFile("robdef/experimental.createwebcam2")
        RRN.RegisterService("Webcam","experimental.createwebcam2.WebcamHost",obj)
    
        node_setup.tcp_transport.AddWebSocketAllowedOrigin("http://localhost")
        node_setup.tcp_transport.AddWebSocketAllowedOrigin("http://localhost:8000")
        node_setup.tcp_transport.AddWebSocketAllowedOrigin("https://johnwason.github.io")

        #password: cats111!
        authdata="cats be7af03a538bf30343a501cb1c8237a0 objectlock"
        p=RR.PasswordFileUserAuthenticator(authdata)
        policies={"requirevaliduser" : "true"}
        s=RR.ServiceSecurityPolicy(p,policies)
        
        c1=obj.get_Webcams(0)[0]
        c1.CaptureFrameToBuffer()
    
        if args.wait_signal:  
            #Wait for shutdown signal if running in service mode          
            print("Press Ctrl-C to quit...")
            import signal
            signal.sigwait([signal.SIGTERM,signal.SIGINT])
        else:
            #Wait for the user to shutdown the service
            if (sys.version_info > (3, 0)):
                input("Server started, press enter to quit...")
            else:
                raw_input("Server started, press enter to quit...")
    
        #Shutdown
        obj.Shutdown()    
示例#10
0
 def wait(self, timeout=None):
     success = False
     if timeout is None:
         signal.sigwait({
             self._signalnum,
         })
         success = True
     else:
         success = (signal.sigtimedwait({
             self._signalnum,
         }, timeout) is not None)
     self._occured = success
     return success
示例#11
0
def main():
    #Accept the names of the webcams and the nodename from command line
    parser = argparse.ArgumentParser(
        description="Gym Duckiebot Simulation Robot Raconteur Service")
    parser.add_argument("--nodename",
                        type=str,
                        default="experimental.gymDuckiebotSim.DuckiebotSim",
                        help="The NodeName to use")
    parser.add_argument(
        "--tcp-port", type=int, default=2356,
        help="The listen TCP port")  #random port, any unused port is fine
    parser.add_argument("--wait-signal",
                        action='store_const',
                        const=True,
                        default=False)
    args = parser.parse_args()

    #Initialize the objects in the service
    obj = gymDuckiebotSimRRService()

    with RR.ServerNodeSetup(args.nodename, args.tcp_port) as node_setup:

        RRN.RegisterServiceTypeFromFile(
            "experimental.gymDuckiebotSim")  # This is the .robdef file
        RRN.RegisterService("DuckiebotSim",
                            "experimental.gymDuckiebotSim.DuckiebotSim", obj)

        # These are for using the service on Web Browsers
        node_setup.tcp_transport.AddWebSocketAllowedOrigin("http://localhost")
        node_setup.tcp_transport.AddWebSocketAllowedOrigin(
            "http://localhost:8000")
        node_setup.tcp_transport.AddWebSocketAllowedOrigin(
            "https://johnwason.github.io")

        if args.wait_signal:
            #Wait for shutdown signal if running in service mode
            print("Press Ctrl-C to quit...")
            import signal
            signal.sigwait([signal.SIGTERM, signal.SIGINT])
        else:
            #Wait for the user to shutdown the service
            if (sys.version_info > (3, 0)):
                input("Server started, press enter to quit...")
            else:
                raw_input("Server started, press enter to quit...")

        #Shutdown
        obj.Shutdown()
示例#12
0
def __run(args: Namespace, camguard: Any) -> None:
    """Runs camguard as program or daemonized process.
    Shutdown is done by handling SystemExit exception.

    Args:
        args (Namespace): argument storage object, which is returned from parsing arguments
        camguard (Any): camguard instance to run

    """
    if args.daemonize:
        return __run_daemonized(args, camguard)

    camguard.start()
    LOGGER.info("Camguard running, press ctrl-c to quit")
    sigwait((SIGINT, ))
    __shutdown(camguard, SIGINT)
示例#13
0
    def run_forever(self, listen_port=None):
        with self._lock:
            self._transfer_status(tm_pb.MasterStatus.CREATED,
                                  tm_pb.MasterStatus.INITIALING)

        if listen_port:
            self._run_grpc_server(listen_port)

        while self._cluster_server is None:
            # waiting receive cluster_def from worker0
            with self._lock:
                if self._worker0_cluster_def:
                    fl_logging.info("received worker_0 cluster_def: %s",
                                    self._worker0_cluster_def)
                    self._cluster_server = ClusterServer(
                        tf.train.ClusterSpec(self._worker0_cluster_def),
                        "master")
                    break
            fl_logging.info("still waiting receive cluster_def from worker_0")
            time.sleep(2)

        self._run()

        sig = signal.sigwait([signal.SIGHUP, signal.SIGINT, signal.SIGTERM])
        fl_logging.info("Server shutdown by signal: %s",
                        signal.Signals(sig).name)
示例#14
0
文件: main.py 项目: erinix/middleware
    def main(self):
        setproctitle('logd')
        self.init_configstore()
        self.init_syslog_server()
        self.init_klog()
        self.init_rpc_server()
        self.init_flush()
        self.load_configuration()
        checkin()
        signal.signal(signal.SIGUSR1, signal.SIG_DFL)
        signal.signal(signal.SIGHUP, signal.SIG_DFL)

        while True:
            sig = signal.sigwait([signal.SIGTERM, signal.SIGUSR1, signal.SIGHUP])
            if sig == signal.SIGUSR1:
                with self.cv:
                    logging.info('Flushing logs on signal')
                    self.flush = True
                    self.cv.notify_all()

                continue

            if sig == signal.SIGHUP:
                logging.info('Reloading configuration on SIGHUP')
                self.load_configuration()
                continue

            if sig == signal.SIGTERM:
                logging.info('Got SIGTERM, exiting')
                with self.cv:
                    self.exiting = True
                    self.cv.notify_all()

                self.flush_thread.join()
                break
def run(program, *args):
    register_signals()
    if fcntl.ioctl(0, termios.TIOCNOTTY) == -1:
        logger.warn("Unable to detach from controlling tty")
    else:
        if os.getsid(0) == os.getpid():
            logger.info(
                "Detached from controlling tty, ignoring the first SIGHUP and SIGCONT we receive"
            )
            IGNORED_SIGMAP[signal.SIGHUP] = 1
            IGNORED_SIGMAP[signal.SIGCONT] = 1
        else:
            logger.info("Detached from controlling tty, but was not session leader.")

    child_pid = os.fork()
    if child_pid < 0:
        logger.error("Unable to fork. Exiting.")
        return 1
    elif child_pid == 0:
        if use_setsid:
            os.setsid()

        os.execvp(program, args)
        return 2
    else:
        logger.info(f"Child spawned with PID {child_pid}.")
        while True:
            signum = signal.sigwait(set(SIGMAP.keys()))
            handle_signal(signum)
示例#16
0
文件: main.py 项目: lukegb/middleware
    def main(self):
        setproctitle('logd')
        self.init_syslog_server()
        self.init_klog()
        self.init_rpc_server()
        self.init_flush()
        checkin()
        signal.signal(signal.SIGUSR1, signal.SIG_DFL)
        while True:
            sig = signal.sigwait([signal.SIGTERM, signal.SIGUSR1])
            if sig == signal.SIGUSR1:
                with self.cv:
                    logging.info('Flushing logs on signal')
                    self.flush = True
                    self.cv.notify_all()

                continue

            if sig == signal.SIGTERM:
                logging.info('Got SIGTERM, exiting')
                with self.cv:
                    self.exiting = True
                    self.cv.notify_all()

                self.flush_thread.join()
                break
示例#17
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("-v",
                        "--verbose",
                        action="count",
                        default=0,
                        help="Increase verbosity.")
    args = parser.parse_args()

    if args.verbose >= 3:
        level = logging.DEBUG
    elif args.verbose >= 2:
        level = logging.INFO
    elif args.verbose >= 1:
        level = logging.WARNING
    else:
        level = logging.ERROR
    logging.basicConfig(level=level,
                        format="[%(levelname)s] application: %(message)s")
    sysrepo.configure_logging(py_logging=True)

    try:
        with sysrepo.SysrepoConnection() as conn:
            with conn.start_session() as sess:
                logging.info("subscribing to module changes: sysrepo-example")
                sess.subscribe_module_change("sysrepo-example", None,
                                             module_change_cb)
                logging.info(
                    "subscribing to operational data requests: /sysrepo-example:state"
                )
                sess.subscribe_oper_data_request("sysrepo-example",
                                                 "/sysrepo-example:state",
                                                 oper_data_cb)
                logging.info(
                    "subscribing to rpc calls: /sysrepo-example:poweroff")
                sess.subscribe_rpc_call("/sysrepo-example:poweroff", poweroff)
                logging.info(
                    "subscribing to action calls: /sysrepo-example:conf/security/alarm/trigger"
                )
                sess.subscribe_rpc_call(
                    "/sysrepo-example:conf/security/alarm/trigger",
                    trigger_alarm)
                signal.sigwait({signal.SIGINT, signal.SIGTERM})
        return 0
    except sysrepo.SysrepoError as e:
        logging.error("%s", e)
        return 1
示例#18
0
    def __call__(self, args=None):
        parser = terminal.configure_parser(__doc__, log_params=False)
        parser.add_argument(
            '--status-queue',
            metavar='ADDR',
            default=const.STATUS_QUEUE,
            help="The address of the queue used to report status to monitors "
            "(default: %(default)s)")
        parser.add_argument(
            '--control-queue',
            metavar='ADDR',
            default=const.CONTROL_QUEUE,
            help="The address of the queue a monitor can use to control the "
            "master (default: %(default)s)")
        parser.add_argument(
            '-r',
            '--rotate',
            metavar='DEGREES',
            default=0,
            type=int,
            help="The rotation of the HAT in degrees; must be 0 (the default) "
            "90, 180, or 270")
        try:
            config = parser.parse_args(args)
        except:  # pylint: disable=bare-except
            return terminal.error_handler(*sys.exc_info())

        with SenseHAT() as hat:
            hat.rotation = config.rotate
            ctx = zmq.Context()
            try:
                stick = StickTask(config, hat)
                stick.start()
                screen = ScreenTask(config, hat)
                screen.start()
                signal.sigwait({signal.SIGINT, signal.SIGTERM})
            except KeyboardInterrupt:
                pass
            finally:
                screen.quit()
                screen.join()
                stick.quit()
                stick.join()
                ctx.destroy(linger=1000)
                ctx.term()
                hat.screen.fade_to(array(Color('black')))
示例#19
0
def receive_button(d):
    while True:
        # signal.signal(signal.SIGUSR1, receive_signal)
        signal.sigwait((signal.SIGUSR1, ))
        print('¡Button pushed!')
        if d.getType() == 3:  # Envia senyal d'alarma el detector de fums
            functionSocket(d.getBackendID(), d.getLongitude(), d.getLatitude(),
                           'fire')
            d.setStatus(1)
            print("Alarma d'incendi enviada!")
        elif d.getType() == 4:  # Envia senyal d'alarma el Pacient
            anomaly_on_sensors = d.getAnomaly()
            if anomaly_on_sensors == True:
                print("Emergencia enviada (sensors)!")
                functionSocket(d.getBackendID(), d.getLongitude(),
                               d.getLatitude(), 'pacientEmitAlarm')
            else:
                print("Emergencia enviada (general)!")
                functionSocket(d.getBackendID(), d.getLongitude(),
                               d.getLatitude(), 'pacientEmitGeneral')
示例#20
0
文件: cli.py 项目: akashi-org/akashi
def akashi_cli() -> None:
    # [XXX] argument_parse() must be called before configuring signals, or weird bugs occur
    parsed_option = argument_parse()

    if parsed_option.action == 'init':
        return do_init(parsed_option)

    if 'LD_LIBRARY_PATH' in os.environ.keys():
        os.environ['LD_LIBRARY_PATH'] += os.pathsep + LIBRARY_PATH
    else:
        os.environ['LD_LIBRARY_PATH'] = LIBRARY_PATH

    if 'LD_PRELOAD' in os.environ.keys():
        os.environ['LD_PRELOAD'] += os.pathsep + libpython_path()
    else:
        os.environ['LD_PRELOAD'] = libpython_path()

    if 'QT_LOGGING_RULES' not in os.environ.keys():
        os.environ['QT_LOGGING_RULES'] = '*=false;*.critical=true'

    os.environ['QT_XCB_GL_INTEGRATION'] = 'xcb_egl'

    if 'AK_ASSET_DIR' not in os.environ.keys():
        os.environ['AK_ASSET_DIR'] = ASSETS_DIR

    os.environ['AK_CORE_ARGS'] = " ".join(
        [path.abspath(parsed_option.conf_path)] + parsed_option.run_args)

    sigset: list[signal.Signals] = []
    sigset += [signal.SIGINT, signal.SIGHUP, signal.SIGQUIT, signal.SIGTERM]
    sigset += [signal.SIGPIPE, signal.SIGCHLD]

    signal.pthread_sigmask(signal.SIG_BLOCK, sigset)

    th_server = ServerThread(parsed_option)
    th_server.start()

    signal.sigwait(sigset)

    th_server.terminate()
    print('')
示例#21
0
def signal_handler_loop(child_pid, session_leader):
    """Wait for signals and handle them."""
    try:
        while True:
            signum = signal.sigwait(all_signals)
            handle_signal(signum, child_pid, session_leader)
    except SystemExit as sys_exit:
        log.debug("Init process terminates (exit=%d)", sys_exit.code)
        sys.exit(sys_exit.code)
    except:
        log.error("Unexpected exception thrown in signal handling")
        traceback.print_exc()
        sys.exit(1)  # make sure we never return but exit!
示例#22
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'manage "networks" (via network namespaces, veth pairs and bridges) for testing'
    )
    parser.add_argument('configuration',
                        help='YAML file containing networks and network nodes')

    args = parser.parse_args()
    with open(args.configuration) as conf_file:
        config = yaml.load(conf_file)

    net = TestNet(config)
    try:
        net.start()
    except Exception as ex:
        net.close()
        raise ex

    signal.sigwait([signal.SIGINT, signal.SIGTERM])
    print('cleaning up...')
    net.close()
示例#23
0
def transient(tor_iptables):
    SIGSET = frozenset({SIGINT, SIGTERM})

    try:
        old_rules = check_output(["iptables-save"])
    except CalledProcessError as err:
        print(f"  {Colors.ORANGE}[!] Could not save iptables rules{Colors.DEFAULT}")
        print(f"  {Colors.ORANGE}[!] Command failed: {err.cmd}{Colors.DEFAULT}")

    print(f"  [{Colors.PINK}+{Colors.DEFAULT}] iptables rules saved")
    flush(tor_iptables)
    load(tor_iptables)
    sigwait(SIGSET)
    p = Popen(["iptables-restore"], stdin=PIPE, stdout=DEVNULL, stderr=DEVNULL)
    r = p.communicate(old_rules)
    if p.returncode == 0:
        print(f"  [{Colors.PINK}+{Colors.DEFAULT}] iptables rules restored")
    else:
        print(
            f"  [{Colors.ORANGE}!{Colors.DEFAULT}] Could not restore iptables rules. Dumping to output!"
        )
        print(old_rules.decode())
        exit(1)
示例#24
0
        def inner():
            # Block signals we expect to receive
            signal.pthread_sigmask(signal.SIG_BLOCK,
                                   test_signals | {signal.SIGUSR1})
            # Save our pid so it is accessible to the test process, avoiding
            # any race conditions where the file may be empty.
            pid = os.getpid()
            fd, path = tempfile.mkstemp()
            os.write(fd, str(pid).encode("utf-8"))
            os.fsync(fd)
            os.close(fd)
            os.rename(path, runner_pid_file)

            for sig in test_signals:
                logger.debug("Waiting for %s", sig)
                signal.sigwait({sig})
                # Stop self to indicate success to test process.
                os.kill(pid, signal.SIGSTOP)

            logger.debug("Waiting for signal to exit")
            # This is required otherwise we may exit while the test is checking
            # for our status.
            signal.sigwait({resume_signal})
            logger.debug("All signals received")
示例#25
0
def main():
    blurb = "Local API for Yahoo Historic Data"
    print(blurb)
    #Build a datetime object with Current time
    dt = datetime.datetime.now()
    #Make the logging file
    loggingfile = "/tmp/stock_ticker_api_{timestamp}.log".format(
        timestamp=dt.now().isoformat())
    #Setup logging
    logging.basicConfig(
        format=
        '%(asctime)s\t%(name)-16s\t%(funcName)-16s\t[%(levelname)-8s] %(message)s',
        level=logging.DEBUG)
    #Let everyone know where we logged tp
    print("Logfile: {logfile}".format(logfile=loggingfile))
    logger = logging.getLogger('main')
    #Begin normal application
    logger.warning(blurb)
    # Parse the args
    parser = argparse.ArgumentParser(description=blurb)
    # Generate the parsed arguments
    args = parser.parse_args()
    logger.info("Args: %s", args)
    # Server
    ps = stockTickerServer.StockTickerServer(9456)
    ps.initialise()
    ps.start()
    #Clean up everything else...
    #Signal handler needed here to wait before exiting
    sigset = [signal.SIGINT, signal.SIGTERM]
    signal.sigwait(sigset)  #3.3 only
    signal.pause()
    #Finally shutdown the server
    ps.shutdown()
    logging.shutdown()
    print("Exiting...")
示例#26
0
def main():
    blurb = "AutoTrader"
    print(blurb)
    #Build a datetime object with Current time
    dt = datetime.datetime.now()
    #Make the logging file
    loggingfile = "/tmp/autoTrader_{timestamp}.log".format(
        timestamp=dt.now().isoformat())
    #Setup logging
    logging.basicConfig(
        format=
        '%(asctime)s\t%(name)-16s\t%(funcName)-16s\t[%(levelname)-8s] %(message)s',
        level=logging.DEBUG)
    #Let everyone know where we logged tp
    print("Logfile: {logfile}".format(logfile=loggingfile))
    logger = logging.getLogger('main')
    #Begin normal application
    logger.warning(blurb)
    # Parse the args
    parser = argparse.ArgumentParser(description=blurb)
    # Generate the parsed arguments
    args = parser.parse_args()
    logger.info("Args: %s", args)
    # Trader
    t = autoTrader.AutoTrader(OPTIONS_API_ADDR, OPTIONS_API_PORT)
    t.initialise()
    t.start()
    #Clean up everything else...
    #Signal handler needed here to wait before exiting
    sigset = [signal.SIGINT, signal.SIGTERM]
    signal.sigwait(sigset)  #3.3 only
    logger.error("Shutting down.....")
    #Finally shutdown the server
    t.shutdown()
    logging.shutdown()
    print("Exiting...")
示例#27
0
 def _run_reactor(self):
     """Run the twisted reactor."""
     threading.Thread(target=reactor.run,
                      daemon=True,
                      kwargs=dict(installSignalHandlers=0)).start()
     signal_map = {
         signal.SIGHUP: self._handle_reconfigure,
         signal.SIGINT: self._handle_shutdown,
         signal.SIGTERM: self._handle_shutdown,
         signal.SIGQUIT: self._handle_shutdown,
         signal.SIGUSR1: self._handle_debug,
     }
     while True:
         signal.pthread_sigmask(signal.SIG_BLOCK, signal_map.keys())
         signum = signal.sigwait(set(signal_map.keys()))
         logging.info("Got signal %s" % signum)
         if signum in signal_map:
             signal_map[signum](signum, None)
示例#28
0
def dispatch():
    '''Dispatch processing events at midnight every night'''
    while True:
        now           = time.time()
        next_midnight = math.ceil(now / SECONDS_IN_DAY) * SECONDS_IN_DAY 
        delay         = math.ceil(next_midnight - now)

        logging.info("Waiting %s seconds until %s" 
                % (delay, datetime.datetime.fromtimestamp(next_midnight)))
        signal.alarm(delay)
        signum = signal.sigwait([signal.SIGALRM, signal.SIGINT, signal.SIGTERM])

        if signum == signal.SIGALRM:
            logging.info("Starting work")
            run()
        else:
            logging.info("Exit requested")
            break
示例#29
0
def serve(block=True, port: int = random.randint(50000, 59000)):
    """

    :param block:
    :param port:
    :return:
    """
    logger.info("Search service, version={}".format(
        pkg_resources.get_distribution('tutorial-grpc-geodatas').version))

    # Register signal handler, only if blocking
    if block:
        for sig in SIGNALS:
            signal.signal(sig, _signal_handler)

    max_number_of_clients = 10
    # Creates Server with which RPCs can be serviced
    # https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor
    # https://stackoverflow.com/questions/51089746/grpc-python-thread-pool-vs-max-concurrent-rpcs
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),
                         maximum_concurrent_rpcs=max_number_of_clients)
    # Register Rpc Handlers with `SearchServicer` server
    search_pb2_grpc.add_SearchServicer_to_server(SearchServicer(), server)

    # Opens an insecure port for accepting RPCs.
    grpc_host_and_port = f'[::]:{port}'
    insecure_port = server.add_insecure_port(grpc_host_and_port)
    if insecure_port == 0:
        logger.error(f"Failed to start gRPC server on {insecure_port}")
        raise ConnectionError

    with consuled(insecure_port):
        logger.info(f"Starting server on port {insecure_port}...")
        server.start()
        logger.info("Ready and waiting for connections.")

        if not block:
            return server, insecure_port

        # Wait for a signal before exiting
        sig = signal.sigwait(SIGNALS)
        logger.info('Signal {} received, shutting down...'.format(sig))

        server.stop(5).wait()
示例#30
0
def fork():
    if os.name != 'posix':
        return -1

    pid = os.fork()
    if pid < 0:
        return -1

    if pid > 0:
        return pid

    # child
    os.setsid()

    received = signal.sigwait([signal.SIGUSR1])
    if received != signal.SIGUSR1:
        sys.exit(os.EX_OK)

    return 0
示例#31
0
async def main(connection):
    global exit_code
    app = await iterm2.async_get_app(connection)
    while True:
        print("Waiting for signal")
        sig = signal.sigwait(
            [signal.SIGHUP, signal.SIGINT, signal.SIGTERM, signal.SIGUSR1])
        if sig == signal.SIGUSR1:
            print("Creating new window")
            window = await iterm2.Window.async_create(connection)
            if window is not None:
                await window.async_activate()
                await app.async_activate(False)
            else:
                print("Unable to create window")
            continue

        print("Terminating on signal {}".format(sig))
        exit_code = sig
        break
示例#32
0
    def run(self):
        with no_daemon_context(self.working_dir, self.lock_file, self.signals):
            signal_map = {
                signal.SIGHUP: self._handle_reconfigure,
                signal.SIGINT: self._handle_shutdown,
                signal.SIGTERM: self._handle_shutdown,
                signal.SIGQUIT: self._handle_shutdown,
                signal.SIGUSR1: self._handle_debug,
            }
            signal.pthread_sigmask(signal.SIG_BLOCK, signal_map.keys())

            self._run_mcp()
            self._run_www_api()
            self._run_manhole()
            self._run_reactor()

            while True:
                signum = signal.sigwait(list(signal_map.keys()))
                if signum in signal_map:
                    logging.info(f"Got signal {str(signum)}")
                    signal_map[signum](signum, None)
示例#33
0
文件: trondaemon.py 项目: Yelp/Tron
    def run(self):
        with no_daemon_context(self.working_dir, self.lock_file, self.signals):
            signal_map = {
                signal.SIGHUP: self._handle_reconfigure,
                signal.SIGINT: self._handle_shutdown,
                signal.SIGTERM: self._handle_shutdown,
                signal.SIGQUIT: self._handle_shutdown,
                signal.SIGUSR1: self._handle_debug,
            }
            signal.pthread_sigmask(signal.SIG_BLOCK, signal_map.keys())

            self._run_mcp()
            self._run_www_api()
            self._run_manhole()
            self._run_reactor()

            while True:
                signum = signal.sigwait(list(signal_map.keys()))
                if signum in signal_map:
                    logging.info(f"Got signal {str(signum)}")
                    signal_map[signum](signum, None)
示例#34
0
文件: container.py 项目: FArian/tbf
def wait_for_child_and_forward_all_signals(child_pid, process_name):
    """Wait for a child to terminate and in the meantime forward all signals the current process
    receives to this child.
    @return a tuple of exit code and resource usage of the child as given by os.waitpid
    """
    assert _HAS_SIGWAIT
    block_all_signals()

    while True:
        logging.debug("Waiting for signals")
        signum = signal.sigwait(_ALL_SIGNALS)
        if signum == signal.SIGCHLD:
            pid, exitcode, ru_child = os.wait4(-1, os.WNOHANG)
            while pid != 0:
                if pid == child_pid:
                    return exitcode, ru_child
                else:
                    logging.debug("Received unexpected SIGCHLD for PID %s", pid)
                pid, exitcode, ru_child = os.wait4(-1, os.WNOHANG)

        else:
            _forward_signal(signum, child_pid, process_name)
示例#35
0
        config = self.config
        database = config["database"]["connection"]
        graphs = config["graphs"]
        sensors = gather_sensors(config)
        server_host = config["server"]["host"]
        server_port = int(config["server"]["port"])
        server_address = (server_host, server_port)

        db_connection = DatabaseConnection(database, sensors)
        server = Server(server_address, db_connection, graphs)
        self.server = server

        server.serve_forever()

        db_connection.close()
        server.server_close()


if __name__ == "__main__":
    config = None
    with open("telemetry.json", "r", encoding="utf-8") as config_file:
        config = json.load(config_file)

    server_thread = ServerThread(config)
    server_thread.start()

    signal.sigwait([signal.SIGABRT, signal.SIGINT, signal.SIGTERM])
    server_thread.server.shutdown()

    server_thread.join()
    def on_moved(self, event):
        self.handle_or_not(event)


if __name__ == "__main__":
    paths = {dirname(SAMPLE_FILE), dirname(BOTS_FILE), dirname(VALIDS_FILE)}
    patterns = [SAMPLE_FILE, BOTS_FILE, VALIDS_FILE]
    observer = Observer()

    if LOG_LEVEL == logging.DEBUG:
        from watchdog.events import LoggingEventHandler

        logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
        event_logger = LoggingEventHandler()
        for path in paths:
            observer.schedule(event_logger, path)
            logging.debug('Started watching {} for {}'.format(path, event_logger))

    event_handler = EventHandler(patterns)
    for path in paths:
        observer.schedule(event_handler, path)
        logging.debug('Started watching {} for {}'.format(path, event_handler))

    find_unknown(None)
    observer.start()

    rec_signal = sigwait((SIGINT, SIGTERM))  # FIXME
    logging.info("Received signal {}".format(rec_signal))

    observer.join()  # TODO funktion recherchieren
示例#37
0
        # relay commands from user
        prompt()
        for line in sys.stdin:
            cmd = line.strip()

            print('cmd: {:s}'.format(repr(cmd)))

            if cmd == 'exit':
                print('exiting')
                break
            elif cmd == 'run':
                print('running')
                driver._issue_cmd(cmd)
                driver._await_run()
                signum = signal.sigwait([signal.SIGINT])
                sigint_handler(signum, None)
            elif cmd == 'borken':
                driver._issue_cmd('help')
                output = driver._read_stdout(target=driver.exit_re, retries=100)
                print_with_spacer(output)
            elif cmd == 'borken2':
                driver._issue_cmd('md 0 4096')
                output = driver._read_stdout(target=driver.exit_re, retries=25)
                print_with_spacer(output)
            elif cmd == 'borclean':
                output = driver._read_stdout(target=re.compile(r'(?!x)x'), retries=100)
                print_with_spacer(output)
            else:
                print('issuing')
                driver._issue_cmd(cmd)