def _adapter_connect(self): """Connect to the remote socket, adding the socket to the IOLoop if connected :rtype: bool """ LOGGER.debug('init io and signal watchers if any') # reuse existing signal watchers, can only be declared for 1 ioloop global global_sigint_watcher, global_sigterm_watcher error = super(LibuvConnection, self)._adapter_connect() if not error: if self._on_signal_callback and not global_sigterm_watcher: global_sigint_watcher = pyuv.Signal(self.ioloop) if self._on_signal_callback and not global_sigint_watcher: global_sigterm_watcher = pyuv.Signal(self.ioloop) if not self._io_watcher: self._io_watcher = pyuv.Poll(self.ioloop, self.socket.fileno()) self._io_watcher.fd = self.socket.fileno() self. async = pyuv.Async(self.ioloop, self._noop_callable()) self. async .send() if self._on_signal_callback: global_sigterm_watcher.start(signal.SIGTERM, self._handle_sigterm) global_sigint_watcher.start(signal.SIGINT, self._handle_sigint) self._io_watcher.start(self._PIKA_TO_LIBUV_ARRAY[self.event_state], self._handle_events) return error
def switch(self, timeout=None, interrupt=False): """Switch to the hub. This method may be called from the root fiber to start or switch to the Hub, or from a non-root fiber yield and wait for a switch back. The optional *timeout* argument specifies the maximum time to wait. If the timeout expires then a switch back is automatically performed. If called from the root fiber, then this method returns when there are no more callbacks (see :meth:`run_callback`) and no more events in the event loop. """ if self.current() is self: raise RuntimeError('Cannot switch() to the Hub from the Hub') if timeout is not None: timer = pyuv.Timer(self.loop) timer.start(self.switch_back(), timeout, 0) if interrupt: sigh = pyuv.Signal(self.loop) sigh.start(self.switch_back(), signal.SIGINT) ret = super(Hub, self).switch() if timeout is not None: timer.close() if interrupt: sigh.close() return ret
def install_sigchld(self): if sys.platform == 'win32': raise NotImplementedError if self._loop.default and self._sigchld_handle is None: self._sigchld_handle = pyuv.Signal(self._loop) self._sigchld_handle.start(self._handle_SIGCHLD, signal.SIGCHLD) self._sigchld_handle.unref()
def __init__(self, loop, ip_iface, iface_index, alpacaport, discoport=32227, mcgroup="ff12::00a1:9aca"): self.server = pyuv.UDP(loop) self.__alpacaport = alpacaport self.__sockv6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) self.__sockv6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if os.name != "nt": self.__sockv6.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEPORT, 1 ) #needed on Linux and OSX to share port with net core. Remove on windows. self.server.open(self.__sockv6.fileno()) self.server.bind((ip_iface, discoport)) addrinfo = socket.getaddrinfo(mcgroup, None)[0] group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0]) # Join group mreq = group_bin + struct.pack('@I', iface_index) if os.name == "nt": self.__sockv6.setsockopt( 41, socket.IPV6_JOIN_GROUP, mreq ) #some versions of python on Windows do not have this option else: self.__sockv6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) self.server.start_recv(self.__on_read) self.signal_h = pyuv.Signal(loop) self.signal_h.start(self.__signal_cb, signal.SIGINT)
def __init__(self): if self.parent is not None: raise RuntimeError('Hub must be created in the root fiber') super(Hub, self).__init__(target=self.run) self.name = 'Hub' self.context = '' self._loop = pyuv.Loop() self._loop.excepthook = self._uncaught_exception self._data = {} self._noswitch_depth = 0 self._callbacks = collections.deque() # Thread IDs may be recycled when a thread exits. But as long as the # hub is alive, it won't be recycled so in that case we can use just # the ID as a check whether we are in the same thread or not. self._thread = compat.get_thread_ident() self._async = pyuv.Async(self._loop, lambda h: self._loop.stop()) self._sigint = pyuv.Signal(self._loop) self._sigint.start(self._on_sigint, signal.SIGINT) # Mark our own handles as "system handles". This allows the test suite # to check that no active handles except these escape from tests. self._async._system_handle = True self._sigint._system_handle = True self._log = logging.get_logger() self._log.debug('new Hub for {.name}', threading.current_thread()) self._closing = False self._error = None
class SignalTest(unittest2.TestCase): __disabled__ = ['win32'] def setUp(self): self.async_cb_called = 0 self.signal_cb_called = 0 self. async = None self.signal_h = None self.loop = pyuv.Loop.default_loop() signal.signal(signal.SIGUSR1, self.signal_cb) def signal_cb(self, sig, frame): self.signal_cb_called += 1 self. async = pyuv.Async(self.loop) self. async .send(self.async_cb) def async_cb(self, async): self.async_cb_called += 1 async .close() self.signal_h.close() def test_signal1(self): self.async_cb_called = 0 def async_cb(async, data): self.async_cb_called += 1 async .close() self.signal_h = pyuv.Signal(self.loop) self.signal_h.start() thread = threading.Thread(target=self.loop.run) thread.start() os.kill(os.getpid(), signal.SIGUSR1) thread.join() self.assertEqual(self.async_cb_called, 1)
def __init__(self,multicast_addr,localip): # get local socket name sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect(("8.8.8.8",80)) self.__m_localip = sock.getsockname()[0] print("local ip ",self.__m_localip) # init recv_socket self.loop = pyuv.Loop.default_loop() self.__m_multicast_addr = multicast_addr self.__m_recv_socket = pyuv.UDP(self.loop) self.__m_recv_socket.bind((g_listenip,g_multicast_port),pyuv.UV_UDP_REUSEADDR) self.__m_recv_socket.set_membership(multicast_addr,pyuv.UV_JOIN_GROUP) self.__m_recv_socket.set_broadcast(True) self.__m_recv_socket.start_recv(self.handlerRecv) # recieve handler # init send_socket self.__m_send_socket = pyuv.UDP(self.loop) self.__m_send_socket.bind((g_listenip,g_multicast_port),pyuv.UV_UDP_REUSEADDR) # self.__m_send_socket.set_membership(multicast_addr,pyuv.UV_JOIN_GROUP) # self.__m_localEndpoint = "" self.__m_localrpcEndpoint = "" self.__m_jsnCbMap = {} self.__m_msgCbMap = {} self.__m_serviceCallMap = {} self.__m_topicMap = {} # std::unordered_map<std::string, std::unordered_set<std::string>> self.__m_serviceMap = {} # std::unordered_map<std::string, std::unordered_set<std::string>> self.__m_signal_h = pyuv.Signal(self.loop) self.__m_signal_h.start(self.signal_handler, signal.SIGINT)
def connect(self, host, port): self._handle = pyuv.TCP(self._loop) self._handle.connect((host, int(port)), self._on_connected) self._handle.start_read(self._on_read) self._sigint_handler = pyuv.Signal(self._loop) self._sigint_handler.start(self._on_signal, signal.SIGINT) return
def start(self): self.server = pyuv.TCP(pyuv.Loop.default_loop()) self.server.bind(('0.0.0.0', 6379)) # Notice the tuple parameter self.server.listen(self.handle_pending_client) # Make sure to listen for SIGINT to happen so ^C works. self.sigint = pyuv.Signal(pyuv.Loop.default_loop()) self.sigint.start(self.handle_end_signal, signal.SIGINT)
def _initialize(self): def signal_cb(signal_handle, signal_num): self._loop.stop() # sig = pyuv.Signal(self._loop) sig.start(signal_cb, signal.SIGINT) # return sig
def __init__(self, endpoint): loop = pyuv.Loop.default_loop() self.acceptor = Acceptor(self, endpoint) self.signalHandle = pyuv.Signal(loop) self.signalHandle.start(self.onSignal, signal.SIGINT) self.connections = [] self.endpoint = endpoint
def resize_unix(): def resize_terminal(signal_handle, signal_num): w, h = self._system_stdin.get_winsize() self.handler.write_channel(RESIZE_CHANNEL, json.dumps({"Height": h, "Width": w})) self._resize_signal = pyuv.Signal(self._loop) self._resize_signal.start(resize_terminal, signal.SIGWINCH) # Run first time to set the proper terminal size resize_terminal(None, None)
def _setup_signals(self, signals): self._signal_handles = [] def handler(h, signum): self._on_signal(signum) for signum in signals: handle = pyuv.Signal(self._loop) handle.start(handler, signum) self._signal_handles.append(handle)
def _resize_terminal(self): def resize_terminal(signal_handle, signal_num): w, h = self._system_stdin.get_winsize() self.client.api.exec_resize(self.exec_id, height=h, width=w) self._resize_signal = pyuv.Signal(self._loop) self._resize_signal.start(resize_terminal, signal.SIGWINCH) # Run first time to set the proper terminal size resize_terminal(None, None)
def start(self): self.sock.listen(socket.SOMAXCONN) self.poll_watcher.start(pyuv.UV_READABLE, self.io_cb) for sig in STOPSIGNALS: handle = pyuv.Signal(self.loop) handle.start(self.signal_cb, sig) self.signal_watchers.add(handle) logging.debug("{0}: started on {0.address}".format(self)) self.loop.run() logging.debug("{0}: stopped".format(self))
def __init__(self, filename): self.filename = filename self.loop = pyuv.Loop.default_loop() self.end_of_file = os.stat(filename).st_size self.filehandle = open(filename, "r") self.signal_h = pyuv.Signal(self.loop) self.signal_h.start(self.signal_cb, signal.SIGINT) self.event_handle = pyuv.fs.FSEvent(self.loop) self.event_handle.start(filename, 0, self.read_handle)
def test_signal1(self): self.async_cb_called = 0 self.signal_cb_called = 0 self. async = pyuv.Async(self.loop, self.async_cb) self.signal_h = pyuv.Signal(self.loop) self.signal_h.start(self.signal_cb, signal.SIGUSR1) thread = threading.Thread(target=self.loop.run) thread.start() os.kill(os.getpid(), signal.SIGUSR1) thread.join() self.assertEqual(self.async_cb_called, 1) self.assertEqual(self.signal_cb_called, 1)
def run(application, address=None, fd=None): # The one and only event loop loop = pyuv.Loop.default_loop() # The one and only WSGI server server = WSGIServer(loop, application, address, fd) # Signal handlers for quitting sigint_h = pyuv.Signal(loop) sigint_h.start(lambda *x: server.stop(), signal.SIGINT) sigint_h.unref() sigterm_h = pyuv.Signal(loop) sigterm_h.start(lambda *x: server.stop(), signal.SIGTERM) sigterm_h.unref() # Here we go! server.start() loop.run() # Free all resources _close_loop(loop)
def run(self, stdin, callbacks): # The PosixEventLoop basically sets up a callback for sigwinch to # monitor terminal resizes, and a callback for when stdin is ready. # libuv can do the stdin with the TTY handler, so we'll give that a # whirl self.sigw = pyuv.Signal(self.realloop) self.sigw.start(self.sigwinch, signal.SIGWINCH) self.tty = pyuv.TTY(self.realloop, sys.stdin.fileno(), True) self.tty.start_read(self.ttyread) self._callbacks = callbacks self.inputstream = prompt_toolkit.terminal.vt100_input.InputStream(callbacks.feed_key) return self.realloop.run()
def add_signal_handler(self, sig, callback, *args): self._validate_signal(sig) signal_h = pyuv.Signal(self._loop) handler = events.make_handle(callback, args) signal_h.handler = handler try: signal_h.start(self._signal_cb, sig) except Exception as e: signal_h.close() raise RuntimeError(str(e)) else: self._signal_handlers[sig] = signal_h return handler
def __init__(self, config, callback): """ :param config: {"CarbonHost": "127.0.0.1", "CarbonPort": 2014} :param callback: Callback for each datapoint recieved """ self.buf = None self.host = config['host'] self.port = config['port'] self.callback = callback self.clients = [] self.loop = pyuv.Loop.default_loop() self.server = pyuv.TCP(self.loop) self.signal_handler = pyuv.Signal(self.loop)
def main(path): loop = pyuv.Loop.default_loop() try: fsevents = pyuv.fs.FSEvent(loop) fsevents.start(path, 0, fsevent_callback) fsevents.ref = False except pyuv.error.FSEventError as e: print('error: %s' % e) sys.exit(2) signal_h = pyuv.Signal(loop) signal_h.start(sig_cb, signal.SIGINT) print('Watching path %s' % os.path.abspath(path)) loop.run()
def __init__(self, loop, ip_iface, iface_index, discoport=32227, mcgroup="ff12::00a1:9aca"): self.server = pyuv.UDP(loop) self.server.bind((ip_iface, 0)) self.server.start_recv(self.__on_read) self.signal_h = pyuv.Signal(loop) self.signal_h.start(self.__signal_cb, signal.SIGINT) self.server.try_send((mcgroup, discoport), "alpacadiscovery1".encode())
def add_signal_handler(self, sig, callback, *args, **kwargs): self._validate_signal(sig) signal_h = pyuv.Signal(self._loop) handler = SignalHandler(signal_h, callback, *args, **kwargs) signal_h.handler = handler signal_h.signum = sig try: signal_h.start(self._signal_cb, sig) signal_h.unref() except Exception as e: signal_h.close() raise RuntimeError(str(e)) else: self._signals.setdefault(sig, set()).add(signal_h) return handler
def __init__(self): self._loop = pyuv.Loop() """ Is Event Loop running? If not, and _active_count > 0 (i.e. some processes need loop to handle!) Just create a thread execute `loop.run()` """ self.proc_pool = MCProcessPool() self.callback = MCProcessCallback() self.info_monitor = MCInstanceInfoMonitor(self._loop) self._init_proc_pool() self._signal_handle = pyuv.Signal(self._loop) pass
def node_setup(port, handler, call_interface=None, loop=None): """Starts up just the chorus communication handler.""" if not loop: loop = pyuv.Loop() if not call_interface: call_interface = CallInterface(loop) node = Node(loop, port, call_interface, handler) signal_stop = pyuv.Signal(loop) signal_stop.start( partial(_unwind_loop, [call_interface, node], signal_stop), signal.SIGINT, ) return loop
def __init__(self): self._loop = pyuv.Loop() self._count = 0 self._signal_stop = pyuv.Signal(self._loop) self._signal_stop.start( self._unwind_loop, signal.SIGINT, ) self._timer = pyuv.Timer(self._loop) self._timer.start( self._print_count, timeout=0, repeat=1, )
def __init__(self, clock=time.time, ptr=None, default=True): """ :param clock: :type clock: :param default: default loop :type default: boolean :param ptr: a pointer a an (optional) libuv loop :type ptr: a "uv_loop_t*" """ self.clock = clock self.greenlet = greenlet.greenlet(self.run) self.stopping = False self.running = False self.timers = set() self.pollers = {} self.callbacks = set() self.debug_exceptions = True self.debug_blocking = False self.debug_blocking_resolution = 1 self.interrupted = False if ptr: self.uv_loop = ptr else: if _default_loop_destroyed: default = False self.uv_sighandlers = set() self.uv_loop = pyuv.Loop.default_loop() if default: #self.uv_signal_checker = pyuv.SignalChecker(self.uv_loop) for signum in self.SYSTEM_EXCEPTIONS_SIGNUMS: handler = pyuv.Signal(self.uv_loop) handler.start(self.signal_received, int(signum)) self.uv_sighandlers.add(handler) #else: # self.uv_signal_checker = None if not self.uv_loop: raise SystemError("default_loop() failed")
def __init__(self, alpacaport, discport, loop): self.server = pyuv.UDP(loop) self.__alpacaport = alpacaport self.__sockv6 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.__sockv6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if os.name != "nt": self.__sockv6.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEPORT, 1 ) #needed on Linux and OSX to share port with net core. Remove on windows. self.server.open(self.__sockv6.fileno()) self.server.bind(('0.0.0.0', discport)) self.server.start_recv(self.__on_read) self.signal_h = pyuv.Signal(loop) self.signal_h.start(self.__signal_cb, signal.SIGINT)
def run(self): """Run the loop.""" loop = pyuv.Loop.default_loop() # Attach a handler for each subdirectory underneath for subdirectory in [ os.path.realpath(x[0]) for x in os.walk(self.directory) ]: event_handle = pyuv.fs.FSEvent(loop) event_handle.start(subdirectory, 0, self.read_handle) self.event_handles.append(event_handle) # Attach a handler for CTRL-C self.signal_h = pyuv.Signal(loop) self.signal_h.start(lambda handle, signum: self.close_handles(), signal.SIGINT) loop.run()