Watch docker events. Will call callback with each new event (dict).

        url can be either tcp://<host>:port or ipc://<path>
191623
def watch(callback, url=default_sock_url):
    
    sock, hostname = connect(url)
    request = 'GET /events HTTP/1.1\nHost: %s\n\n' % hostname
    request = request.encode('utf-8')

    with closing(sock):
        sock.sendall(request)
        header, payload = read_http_header(sock)
        status, reason = header_status(header)
        if status != HTTP_OK:
            raise DockermonError('bad HTTP status: %s %s' % (status, reason))

        # Messages are \r\n<size in hex><JSON payload>\r\n
        buf = [payload]
        while True:
            chunk = sock.recv(bufsize)
            if not chunk:
                raise EOFError('socket closed')
            buf.append(chunk.decode('utf-8'))
            data = ''.join(buf)
            i = data.find('\r\n')
            if i == -1:
                continue

            size = int(data[:i], 16)
            start = i + 2  # Skip initial \r\n

            if len(data) < start + size + 2:
                continue
            payload = data[start:start+size]
            callback(json.loads(payload))
            buf = [data[start+size+2:]]
842420
def trigger (self, event, *args, **kwargs):
        
        if self._events.has_key(event):
            for _callback in self._events[event]:
                try:
                    _callback(args, kwargs)
                except TypeError:
                    _callback()
174189
function startWatchIPCServer(callback, configIndices) {
        ipc.config.id = serverName;
        ipc.config.retry = 3;
        ipc.config.silent = true;

        ipc.serve(
            function() {
                ipc.server.on(
                    'done',
                    watchDoneHandler.bind(this, callback, ipc, configIndices)
                );
            }
        );
        ipc.server.start();
    }
1011689
def _readable(self, watcher, events):
        
        protocol = self.factory.build(self.loop)
        try:
            sock, address = self.sock.accept()
            connection = Connection(self.loop, sock, address, protocol, self)
            self.connections.add(connection)
            connection.make_connection()
            logger.debug("added connection")
        except IOError as e:
            self.shutdown(e)
1082293
def launch_monitor_server(host, port, logger):
    
    logger.info('Starting monitor server on host %s port %d' % (host, port))
    server = ThreadedTCPServer((host, port), MonitorHandler)
    server.serve_forever()
674166
def watch_one_event(event_filter, callback, timeout_callback, timeout, args,
                        start_time=None):
        
        if timeout and not start_time:
            start_time = int(datetime.now().timestamp())

        if not args:
            args = []

        while True:
            try:
                events = event_filter.get_all_entries()
                if events:
                    callback(events[0], *args)
                    return

            except (ValueError, Exception) as err:
                # ignore error, but log it
                logger.debug(f'Got error grabbing keeper events: {str(err)}')

            time.sleep(0.1)
            if timeout:
                elapsed = int(datetime.now().timestamp()) - start_time
                if elapsed > timeout:
                    if timeout_callback:
                        timeout_callback(*args)
                    else:
                        callback(None, *args)
                    break
1213393
def start_event_stream(self):
        
        if not self._stream:
            self._stream = GerritStream(self, ssh_client=self._ssh_client)
            self._stream.start()
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)
274738
def register_watchers(self, type_callback_dict, register_timeout=None):
        
        for event_type, callback in type_callback_dict.items():
            self._push_watchers[event_type].add(callback)
        self.wait_for_response(
            RegisterMessage(event_list=type_callback_dict.keys()),
            timeout=register_timeout)
592831
def http(container = None):
    ""
    def decorator(func):
        @functools.wraps(func)
        def handler(self, event):
            return _handler(self if container is None else container, event, lambda env: func(self, env))
        return handler
    return decorator
1216837
def run(cutouts, hostname="localhost", port=DEFAULT_PORT):
  """"""
  def handler(*args):
    return ViewerServerHandler(cutouts, *args)

  myServer = HTTPServer((hostname, port), handler)
  print("Viewer server listening to http://{}:{}".format(hostname, port))
  try:
    myServer.serve_forever()
  except KeyboardInterrupt:
    # extra \n to prevent display of "^CContinuing"
    print("\nContinuing program execution...")
  finally:
    myServer.server_close()
921406
function getPort (port, callback) {
  const server = net.createServer()

  server.on('error', () => {
    getPort(++port, callback)
  })

  // Explicitly listen on 0.0.0.0 to detect ports used by Docker
  // See: https://github.com/nodejs/node/issues/14034
  server.listen(port, '0.0.0.0', () => {
    server.once('close', () => {
      callback(port)
    })
    server.close()
  })
}
643317
def loop(sock, config=None):

    

    if config is None:
        config = {}

    client = docker.Client(base_url=sock)

    # fake a running event for all running containers
    for container in client.containers():
        event_data = {
            'status': "running",
            'id': container['Id'],
            'from': container['Image'],
            'time': container['Created'],
        }

        LOG.debug("incomming event: %s", event_data)

        callbacks = event.filter_callbacks(client, event_data)

        # spawn all callbacks
        gevent.joinall([gevent.spawn(cb, event_data, config) for cb in callbacks])

    # listen for further events
    for raw_data in client.events():

        event_data = json.loads(raw_data)

        LOG.debug("incomming event: %s", event_data)

        callbacks = event.filter_callbacks(client, event_data)

        # spawn all callbacks
        gevent.joinall([gevent.spawn(cb, client, event_data, config) for cb in callbacks])
1060401
function listen() {
  var args = []
    , port = this.conf.get(ConfigKey.PORT)
    , socket = this.conf.get(ConfigKey.UNIXSOCKET)
    , perm = this.conf.get(ConfigKey.UNIXSOCKETPERM)
    , backlog = this.conf.get(ConfigKey.TCP_BACKLOG)
    , cb = typeof arguments[arguments.length - 1] === 'function'
      ? arguments[arguments.length - 1] : null
    , tcp
    , unix;

  if(socket) {
    unix = this._unix = new UnixServer(this);
  }

  // tcp: server.listen(port, [host], [backlog], [callback])
  // unix socket: server.listen(path, [callback])

  // port zero means don't listen on a tcp port
  if(port !== 0) {
    tcp = this._tcp = new TcpServer(this);

    // port comes first
    args.unshift(port);

    // backlog is penultimate argument
    if(typeof backlog === 'number') {
      args.push(backlog);
    }

    //console.dir(args);

    // cb is last argument
    if(cb) args.push(cb);

    function onListen() {
      // for server info, the actual port or socket in use
      // stored on the state, null if listen was never called
      // or if the bind failed, could also be a unix socket
      var addr = tcp.address();
      var port = addr.port;
      this.state.addr = addr;

      // only write pid if we listen
      if(this._daemonized) {
        daemon.pid.write(this.conf);
      }

      this.emit('listen', port);
      this.log.notice('accepting connections on port %s', port);

      // might be listening on a unix socket too
      if(unix) unix.listen(socket, perm);
    }

    tcp.once('listening', onListen.bind(this));
    tcp.listen.apply(tcp, args);
  // just a unix socket
  }else if(unix) {
    unix.listen(socket, perm);
  }
}
126888
async def arun_process(path: Union[Path, str], target: Callable, *,
                       args: Tuple[Any]=(),
                       kwargs: Dict[str, Any]=None,
                       callback: Callable[[Set[Tuple[Change, str]]], Awaitable]=None,
                       watcher_cls: Type[AllWatcher]=PythonWatcher,
                       debounce=400,
                       min_sleep=100):
    
    watcher = awatch(path, watcher_cls=watcher_cls, debounce=debounce, min_sleep=min_sleep)
    start_process = partial(_start_process, target=target, args=args, kwargs=kwargs)
    process = await watcher.run_in_executor(start_process)
    reloads = 0

    async for changes in watcher:
        callback and await callback(changes)
        await watcher.run_in_executor(_stop_process, process)
        process = await watcher.run_in_executor(start_process)
        reloads += 1
    return reloads
187470
def monitor(name, callback):
    '''
     
    '''
    global _monitor 
    if not exists(name):
        raise ContainerNotExists("The container (%s) does not exist!" % name)
    if _monitor:
        if _monitor.is_monitored(name):
            raise Exception("You are already monitoring this container (%s)" % name)
    else:
        _monitor = _LXCMonitor()
        logging.info("Starting LXC Monitor")
        _monitor.start()
        def kill_handler(sg, fr):
            stop_monitor()
        signal.signal(signal.SIGTERM, kill_handler)
        signal.signal(signal.SIGINT, kill_handler)
    _monitor.add_monitor(name, callback)
961532
def _call_watcher(self_, watcher, event):
        
        if self_.self_or_cls.param._TRIGGER:
            pass
        elif watcher.onlychanged and (not self_._changed(event)):
            return

        if self_.self_or_cls.param._BATCH_WATCH:
            self_._events.append(event)
            if watcher not in self_._watchers:
                self_._watchers.append(watcher)
        elif watcher.mode == 'args':
            with batch_watch(self_.self_or_cls, run=False):
                watcher.fn(self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER))
        else:
            with batch_watch(self_.self_or_cls, run=False):
                event = self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER)
                watcher.fn(**{event.name: event.new})