Function to run in a separate gevent greenlet to read progress
    events from a unix-domain socket.
974913
def _do_watch_progress(filename, sock, handler):
    """"""
    connection, client_address = sock.accept()
    data = b''
    try:
        while True:
            more_data = connection.recv(16)
            if not more_data:
                break
            data += more_data
            lines = data.split(b'\n')
            for line in lines[:-1]:
                line = line.decode()
                parts = line.split('=')
                key = parts[0] if len(parts) > 0 else None
                value = parts[1] if len(parts) > 1 else None
                handler(key, value)
            data = lines[-1]
    finally:
        connection.close()
754476
def execute_process_async(func, *args, **kwargs):
  
  global _GIPC_EXECUTOR
  if _GIPC_EXECUTOR is None:
    _GIPC_EXECUTOR = GIPCExecutor(
      num_procs=settings.node.gipc_pool_size,
      num_greenlets=settings.node.greenlet_pool_size)
  return _GIPC_EXECUTOR.submit(func, *args, **kwargs)
498054
def run(self):  # Thread for receiving data from pilight
        """"""
        logging.debug('Pilight receiver thread started')
        if not self.callback:
            raise RuntimeError('No callback function set, cancel readout thread')

        def handle_messages(messages):
            """Call callback on each receive message."""
            for message in messages:  # Loop over received  messages
                if message:  # Can be empty due to splitlines
                    message_dict = json.loads(message.decode())
                    if self.recv_codes_only:
                        # Filter: Only use receiver messages
                        if 'receiver' in message_dict['origin']:
                            if self.veto_repeats:
                                if message_dict.get('repeats', 1) == 1:
                                    self.callback(message_dict)
                            else:
                                self.callback(message_dict)
                    else:
                        self.callback(message_dict)

        while not self._stop_thread.isSet():
            try:  # Read socket in a non blocking call and interpret data
                # Sometimes more than one JSON object is in the stream thus
                # split at \n
                with self._lock:
                    messages = self.receive_socket.recv(1024).splitlines()
                handle_messages(messages)
            except (socket.timeout, ValueError):  # No data
                pass
        logging.debug('Pilight receiver thread stopped')
1248241
def worker(sock, authenticated):
    
    signal.signal(SIGHUP, SIG_DFL)
    signal.signal(SIGCHLD, SIG_DFL)
    signal.signal(SIGTERM, SIG_DFL)
    # restore the handler for SIGINT,
    # it's useful for debugging (show the stacktrace before exit)
    signal.signal(SIGINT, signal.default_int_handler)

    # Read the socket using fdopen instead of socket.makefile() because the latter
    # seems to be very slow; note that we need to dup() the file descriptor because
    # otherwise writes also cause a seek that makes us miss data on the read side.
    infile = os.fdopen(os.dup(sock.fileno()), "rb", 65536)
    outfile = os.fdopen(os.dup(sock.fileno()), "wb", 65536)

    if not authenticated:
        client_secret = UTF8Deserializer().loads(infile)
        if os.environ["PYTHON_WORKER_FACTORY_SECRET"] == client_secret:
            write_with_length("ok".encode("utf-8"), outfile)
            outfile.flush()
        else:
            write_with_length("err".encode("utf-8"), outfile)
            outfile.flush()
            sock.close()
            return 1

    exit_code = 0
    try:
        worker_main(infile, outfile)
    except SystemExit as exc:
        exit_code = compute_real_exit_code(exc.code)
    finally:
        try:
            outfile.flush()
        except Exception:
            pass
    return exit_code
772307
def run(self, handler):
        """"""
        import eventlet.patcher
        if not eventlet.patcher.is_monkey_patched(os):
            msg = ("%s requires eventlet.monkey_patch() (before "
                   "import)" % self.__class__.__name__)
            raise RuntimeError(msg)

        # Separate out wsgi.server arguments
        wsgi_args = {}
        for arg in ('log', 'environ', 'max_size', 'max_http_version',
                    'protocol', 'server_event', 'minimum_chunk_size',
                    'log_x_forwarded_for', 'custom_pool', 'keepalive',
                    'log_output', 'log_format', 'url_length_limit', 'debug',
                    'socket_timeout', 'capitalize_response_headers'):
            try:
                wsgi_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        if 'log_output' not in wsgi_args:
            wsgi_args['log_output'] = not self.quiet

        import eventlet.wsgi
        sock = self.options.pop('shared_socket', None) or self.get_socket()
        eventlet.wsgi.server(sock, handler, **wsgi_args)
889349
def active(display_progress=False):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    try:
        active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
    except SaltClientError as client_error:
        print(client_error)
        return ret

    if display_progress:
        __jid_event__.fire_event({
            'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
            }, 'progress')
    for minion, data in six.iteritems(active_):
        if display_progress:
            __jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
        if not isinstance(data, list):
            continue
        for job in data:
            if not job['jid'] in ret:
                ret[job['jid']] = _format_jid_instance(job['jid'], job)
                ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
            else:
                ret[job['jid']]['Running'].append({minion: job['pid']})

    mminion = salt.minion.MasterMinion(__opts__)
    for jid in ret:
        returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
        data = mminion.returners['{0}.get_jid'.format(returner)](jid)
        if data:
            for minion in data:
                if minion not in ret[jid]['Returned']:
                    ret[jid]['Returned'].append(minion)

    return ret
799091
def run_sync(self):
    """"""
    # Switch log output to the daemon's log stream from here forward.
    self._close_stdio()
    with self._pantsd_logging() as (log_stream, log_filename):

      # Register an exiter using os._exit to ensure we only close stdio streams once.
      ExceptionSink.reset_exiter(Exiter(exiter=os._exit))

      # We don't have any stdio streams to log to anymore, so we log to a file.
      # We don't override the faulthandler destination because the stream we get will proxy things
      # via the rust logging code, and faulthandler needs to be writing directly to a real file
      # descriptor. When pantsd logging was originally initialised, we already set up faulthandler
      # to log to the correct file descriptor, so don't override it.
      #
      # We can get tracebacks of the pantsd process by tailing the pantsd log and sending it
      # SIGUSR2.
      ExceptionSink.reset_interactive_output_stream(
        log_stream,
        override_faulthandler_destination=False,
      )

      # Reset the log location and the backtrace preference from the global bootstrap options.
      global_bootstrap_options = self._bootstrap_options.for_global_scope()
      ExceptionSink.reset_should_print_backtrace_to_terminal(
        global_bootstrap_options.print_exception_stacktrace)
      ExceptionSink.reset_log_location(global_bootstrap_options.pants_workdir)

      self._native.set_panic_handler()

      # Set the process name in ps output to 'pantsd' vs './pants compile src/etc:: -ldebug'.
      set_process_title('pantsd [{}]'.format(self._build_root))

      # Write service socket information to .pids.
      self._write_named_sockets(self._services.port_map)

      # Enter the main service runner loop.
      self._setup_services(self._services)
      self._run_services(self._services)
429881
function ListenEvents (server) {
    var count =0;  // Simple counter to make easier to follow message flow


    // Events from queued jobs
    function EventHandlerQueue (status, job){
        console.log ("#%d- Queue Status=%s DevId=%s Command=%s JobReq=%d Retry=%d", count, status, job.devId, job.command, job.request, job.retry);
    };
    // Events successful process by tracker adapter
    function EventHandlerAccept (device, data){
        console.log ("#%d- Action Devid:[%s] Name:[%s] Cmd:[%s] Lat:%d Lon:%d Speed=%d", count, device.devid, device.name, data.cmd, data.lat, data.lon, data.sog);
    };
    // Events on action refused by tracker adapter
    function EventHandlerError (status, info, id, msg){
        console.log ("#%d- Notice Info=%s Data=%s Id=%s Msg:%s", count, status, info, id, msg );
    };

    // let's use the same event handler for all gpsdTracker
    server.event.on("queue",EventHandlerQueue);
    server.event.on("accept",EventHandlerAccept);
    server.event.on("notice",EventHandlerError);
}
683509
function readCallback(err, event) {
    if (err) {
      self.terminate();
      return;
    }
    if (self.finished) {
      self.push(null);
      return;
    }
    var data = event.read;
    var deserialized;
    try {
      deserialized = self.deserialize(data);
    } catch (e) {
      e.code = constants.status.INTERNAL;
      self.emit('error', e);
      return;
    }
    if (self.push(deserialized) && data !== null) {
      var read_batch = {};
      read_batch[grpc.opType.RECV_MESSAGE] = true;
      self.call.startBatch(read_batch, readCallback);
    } else {
      self.reading = false;
    }
  }
850950
def stream_data(self, host=HOST, port=GPSD_PORT, enable=True, gpsd_protocol=PROTOCOL, devicepath=None):
        
        self.socket.connect(host, port)
        self.socket.watch(enable, gpsd_protocol, devicepath)
908960
async def debug(self, conn_id, name, cmd_args):
        

        progress_callback = functools.partial(_on_progress, self, 'debug', conn_id)

        resp = await self._execute(self._adapter.debug_sync, conn_id, name, cmd_args, progress_callback)
        _raise_error(conn_id, 'send_rpc', resp)

        return resp.get('return_value')
985702
def tail(self, stack_name, cancel, log_func=_tail_print, sleep_time=5,
             include_initial=True):
        """"""
        # First dump the full list of events in chronological order and keep
        # track of the events we've seen already
        seen = set()
        initial_events = self.get_events(stack_name)
        for e in initial_events:
            if include_initial:
                log_func(e)
            seen.add(e['EventId'])

        # Now keep looping through and dump the new events
        while True:
            events = self.get_events(stack_name)
            for e in events:
                if e['EventId'] not in seen:
                    log_func(e)
                    seen.add(e['EventId'])
            if cancel.wait(sleep_time):
                return
1363188
def server_main(loop, path):
    """"""
    loop.fork()
    logger.debug('forked function')
    sigintwatcher = pyev.Signal(signal.SIGINT, loop, lambda watcher, events: logger.info('interrupt ignored'))
    sigintwatcher.start()
    sigtermwatcher = pyev.Signal(signal.SIGTERM, loop, server_stop)
    sigtermwatcher.start()
    adder = AdderService()
    dispatcher = ObjectDispatch(adder)
    pickle_factory = PickleProtocolFactory(dispatcher)
    pickle_server = UnixServer(loop, pickle_factory, path)
    pickle_server.start()
    msgpack_factory = MsgPackProtocolFactory(dispatcher)
    msgpack_server = UnixServer(loop, msgpack_factory, path + '_mp')
    msgpack_server.start()

    logger.debug('running server loop')

    import cProfile
    cProfile.runctx('loop.loop()', None, {'loop':loop}, 'server_profile')

    logger.debug('server unlooped')
1183906
function onEvent (watcher) {
    // Wait for write stream to end if write has been delayed.
    if (writeDelayed) { return undefined; }

    // If any watch events occur while writing to dest then restart
    // write stream with new changes.
    if (stream.isWriting()) {
        writeDelayed = true;

        stream.endWriteStream();
    // Initial write of files to dest.
    } else {
        writeStartTime = Date.now();

        writeFiles();
    }
}
709176
def Run(self, args):
    """"""
    # Make sure we limit the size of our output
    if args.length > constants.CLIENT_MAX_BUFFER_SIZE:
      raise RuntimeError("Can not read buffers this large.")

    try:
      fd = vfs.VFSOpen(args.pathspec, progress_callback=self.Progress)

      fd.Seek(args.offset)
      offset = fd.Tell()

      data = fd.Read(args.length)

    except (IOError, OSError) as e:
      self.SetStatus(rdf_flows.GrrStatus.ReturnedStatus.IOERROR, e)
      return

    # Now return the data to the server
    self.SendReply(
        rdf_client.BufferReference(
            offset=offset, data=data, length=len(data), pathspec=fd.pathspec))
391761
def _run(self):
        
        # dispatch auth data on first scheduling after start
        state_change = ActionUpdateTransportAuthData(
            f'{self._user_id}/{self._client.api.token}',
        )
        self.greenlet.name = f'MatrixTransport._run node:{pex(self._raiden_service.address)}'
        self._raiden_service.handle_and_track_state_change(state_change)
        try:
            # waits on _stop_event.ready()
            self._global_send_worker()
            # children crashes should throw an exception here
        except gevent.GreenletExit:  # killed without exception
            self._stop_event.set()
            gevent.killall(self.greenlets)  # kill children
            raise  # re-raise to keep killed status
        except Exception:
            self.stop()  # ensure cleanup and wait on subtasks
            raise
934647
def run(self):
        '''
        
        '''
        context = zmq.Context()
        # the socket for outgoing timer events
        socket = context.socket(zmq.PUB)
        socket.setsockopt(zmq.LINGER, 100)
        socket.bind('ipc://' + self.timer_sock)

        count = 0
        log.debug('ConCache-Timer started')
        while not self.stopped.wait(1):
            socket.send(self.serial.dumps(count))

            count += 1
            if count >= 60:
                count = 0