Return a tornado Future; resolves when any subordinate client is not synced
194011
def until_not_synced(self, timeout=None):
        """"""
        yield until_any(*[r.until_not_synced() for r in dict.values(self.children)],
                        timeout=timeout)
501206
def ensure_future(fut, *, loop=None):
    
    if sys.version_info < (3, 4, 4):
        # This is to avoid a SyntaxError on 3.7.0a2+
        func = getattr(asyncio, "async")
    else:
        func = asyncio.ensure_future

    return func(fut, loop=loop)
485621
def handle_stream(self, stream):
        '''
        
        '''
        @tornado.gen.coroutine
        def _null(msg):
            raise tornado.gen.Return(None)

        def write_callback(stream, header):
            if header.get('mid'):
                @tornado.gen.coroutine
                def return_message(msg):
                    pack = salt.transport.frame.frame_msg_ipc(
                        msg,
                        header={'mid': header['mid']},
                        raw_body=True,
                    )
                    yield stream.write(pack)
                return return_message
            else:
                return _null
        if six.PY2:
            encoding = None
        else:
            encoding = 'utf-8'
        unpacker = msgpack.Unpacker(encoding=encoding)
        while not stream.closed():
            try:
                wire_bytes = yield stream.read_bytes(4096, partial=True)
                unpacker.feed(wire_bytes)
                for framed_msg in unpacker:
                    body = framed_msg['body']
                    self.io_loop.spawn_callback(self.payload_handler, body, write_callback(stream, framed_msg['head']))
            except tornado.iostream.StreamClosedError:
                log.trace('Client disconnected from IPC %s', self.socket_path)
                break
            except socket.error as exc:
                # On occasion an exception will occur with
                # an error code of 0, it's a spurious exception.
                if exc.errno == 0:
                    log.trace('Exception occured with error number 0, '
                              'spurious exception: %s', exc)
                else:
                    log.error('Exception occurred while '
                              'handling stream: %s', exc)
            except Exception as exc:
                log.error('Exception occurred while '
                          'handling stream: %s', exc)
823675
def _select_next_server(self):
        

        # Continue trying to connect until there is an available server
        # or bail in case there are no more available servers.
        while True:
            if len(self._server_pool) == 0:
                self._current_server = None
                raise ErrNoServers

            now = time.time()
            s = self._server_pool.pop(0)
            if self.options["max_reconnect_attempts"] > 0:
                if s.reconnects > self.options["max_reconnect_attempts"]:
                    # Discard server since already tried to reconnect too many times.
                    continue

            # Not yet exceeded max_reconnect_attempts so can still use
            # this server in the future.
            self._server_pool.append(s)
            if s.last_attempt is not None and now < s.last_attempt + self.options["reconnect_time_wait"]:
                # Backoff connecting to server if we attempted recently.
                yield tornado.gen.sleep(self.options["reconnect_time_wait"])

            try:
                yield self._server_connect(s)
                self._current_server = s
                break
            except Exception as e:
                s.last_attempt = time.time()
                s.reconnects += 1

                self._err = e
                if self._error_cb is not None:
                    self._error_cb(e)
                self._status = Client.RECONNECTING
                continue
158025
def on_action(action):
    
    @wrapt.decorator
    @tornado.gen.coroutine
    def _execute(wrapped, instance, args, kwargs):
        return wrapped(*args, **kwargs)

    _execute.action = action
    return _execute
668806
def sync(coro, timeout=None):
    '''
    
    '''
    loop = initloop()
    return asyncio.run_coroutine_threadsafe(coro, loop).result(timeout)
975101
def _disbatch_runner_async(self, chunk):
        '''
        
        '''
        pub_data = self.saltclients['runner'](chunk)
        raise tornado.gen.Return(pub_data)
951121
def make_response(status, headers, payload, environ):
    
    tornado_handler = environ['tornado.handler']
    tornado_handler.set_status(int(status.split()[0]))
    for header, value in headers:
        tornado_handler.set_header(header, value)
    tornado_handler.write(payload)
    tornado_handler.finish()
91428
def send(self, message, timeout=None, tries=3, future=None, callback=None, raw=False):
        '''
        
        '''
        if future is None:
            future = tornado.concurrent.Future()
            future.tries = tries
            future.attempts = 0
            future.timeout = timeout
            # if a future wasn't passed in, we need to serialize the message
            message = self.serial.dumps(message)
        if callback is not None:
            def handle_future(future):
                response = future.result()
                self.io_loop.add_callback(callback, response)
            future.add_done_callback(handle_future)
        # Add this future to the mapping
        self.send_future_map[message] = future

        if self.opts.get('detect_mode') is True:
            timeout = 1

        if timeout is not None:
            send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message)
            self.send_timeout_map[message] = send_timeout

        if not self.send_queue:
            self.io_loop.spawn_callback(self._internal_send_recv)

        self.send_queue.append(message)

        return future
776721
def start(check_time: int = 500) -> None:
    
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}  # type: Dict[str, float]
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start()
1217593
def bind(self, __fun, *args, **kwargs):
    

    with self._lock:
      if self._running or self._completed or self._cancelled:
        raise RuntimeError('Future object can not be reused')
      if self._worker:
        raise RuntimeError('Future object is already bound')
      self._worker = functools.partial(__fun, *args, **kwargs)
    return self
1155160
function ensureClient(client) {
  var err;

  if(!client) {
    // Likely close() was called and now another step is happening
    // when it shouldn't. Create and log an error, so we get a stack
    // and can see why it happened.
    err = new Error('expected this.client to exist');
    log.error(err);
  }

  // If we're in an unexpected state for syncing (i.e., not a sync step), log that
  switch(client.state) {
    case ServerStates.CREATED:
    case ServerStates.CLOSED:
    case ServerStates.CLOSING:
    case ServerStates.CONNECTING:
    case ServerStates.ERROR:
      log.warn({client: client}, 'Unexpected client state for sync protocol handling: %s', client.state);
      break;
  }

  return client;
}
612552
def coroutine(func, replace_callback=True):
    
    # gen.coroutine in tornado 3.x.x and 5.x.x have a different signature than 4.x.x
    if TORNADO_MAJOR != 4:
        wrapper = gen.coroutine(func)
    else:
        wrapper = gen.coroutine(func, replace_callback)
    wrapper.__argspec_args = inspect.getargspec(func).args
    return wrapper
1298142
def sync_with_ioloop(self, timeout=None):
        
        in_ioloop = self._server.in_ioloop_thread()
        if in_ioloop:
            f = tornado_Future()
        else:
            f = Future()

        def cb():
            f.set_result(None)

        self.ioloop.add_callback(cb)

        if in_ioloop:
            return f
        else:
            f.result(timeout)
495158
def active(self):
        

        context = self._get_context()
        if not context:
            return super(TornadoScopeManager, self).active

        return context.active
261520
def error_future(self):
        
        fut = asyncio.Future(loop=self._loop)
        self._error_futures.append(fut)
        return fut
78015
def get_event(self,
                  request,
                  tag='',
                  matcher=prefix_matcher.__func__,
                  callback=None,
                  timeout=None
                  ):
        '''
        
        '''
        # if the request finished, no reason to allow event fetching, since we
        # can't send back to the client
        if request._finished:
            future = Future()
            future.set_exception(TimeoutException())
            return future

        future = Future()
        if callback is not None:
            def handle_future(future):
                tornado.ioloop.IOLoop.current().add_callback(callback, future)
            future.add_done_callback(handle_future)
        # add this tag and future to the callbacks
        self.tag_map[(tag, matcher)].append(future)
        self.request_map[request].append((tag, matcher, future))

        if timeout:
            timeout_future = tornado.ioloop.IOLoop.current().call_later(timeout, self._timeout_future, tag, matcher, future)
            self.timeout_map[future] = timeout_future

        return future