release a single redis node
489682
def release_node(self, node):
        
        # use the lua script to release the lock in a safe way
        try:
            node._release_script(keys=[self.resource], args=[self.lock_key])
        except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError):
            pass
333271
def kill_redis(self, check_alive=True):
        
        self._kill_process_type(
            ray_constants.PROCESS_TYPE_REDIS_SERVER, check_alive=check_alive)
1146331
static void releaseTicket(ZooKeeper zookeeper, String lockNode, String ticket)
            throws KeeperException, InterruptedException {

        logger.debug("Releasing ticket {}.", ticket);
        try {
            zookeeper.delete(lockNode + "/" + ticket, -1);
        } catch (KeeperException e) {
            if (e.code() != KeeperException.Code.NONODE) {
                // If it the node is already gone, than that is fine, otherwise:
                throw e;
            }
        }
    }
1264918
function doMulti(connObj, cmds, callback) {
    if (!this.isConnected()) {
      return callback(thorin.error('REDIS.NOT_CONNECTED', 'Redis connection is not ready.', 500));
    }
    if (cmds.length === 0) return callback();
    // check commands first.
    for (let i = 0; i < cmds.length; i++) {
      let cmd = cmds[i][0];
      if (typeof connObj[cmd] !== 'function') {
        return callback(thorin.error('REDIS.COMMAND_NOT_FOUND', 'Invalid redis command:' + cmd, 500));
      }
    }
    var mObj = connObj.multi();
    cmds.forEach((item) => {
      let cmd = item.splice(0, 1)[0];
      mObj[cmd].apply(mObj, item);
      item.splice(0, 0, cmd);
    });
    this[connections].default.emit('multi', cmds);
    mObj.exec((err, results) => {
      if (err) {
        return callback(thorin.error('REDIS.MULTI', 'Redis transaction encountered an error.', err, 500));
      }
      let finalResults = [];
      for (let i = 0, len = results.length; i < len; i++) {
        let t = results[i];
        if (t[0] === null) {
          finalResults.push(t[1]);
        }
      }
      callback(null, finalResults);
    });
  }
260024
def release(key, session, options = {})
      custom_params = []
      custom_params << use_named_parameter('release', session)
      custom_params << use_named_parameter('dc', options[:dc]) if options[:dc]
      custom_params << use_named_parameter('flags', options[:flags]) if options && options[:flags]
      raw = send_put_request(@conn, ["/v1/kv/#{key}"], options, nil, custom_params)
      raw.body
    end
1141211
function onExit(exitCode) {
  console.log('Shutting down http-server...')
  httpServer.close(function(err) {
    if(err) console.warn('HTTP server close failed: %s', err)
    else console.log('HTTP server closed.')
  })

  if (!Swarm.host) {
    console.log('Swarm host not created yet...')
    return process.exit(exitCode)
  }

  console.log('Closing swarm host...')
  let forcedExit = setTimeout(function() {
    console.log('Swarm host close timeout, forcing exit.')
    process.exit(exitCode)
  }, 5000)

  Swarm.host.close(function() {
    console.log('Swarm host closed.')
    clearTimeout(forcedExit)
    process.exit(exitCode)
  })
}
701389
def publish(self):
        """"""
        while not self.ws.closed:
            # Sleep to prevent *constant* context-switches.
            gevent.sleep(self.lag_tolerance_secs)
            message = self.ws.receive()
            if message is not None:
                channel_name, data = message.split(":", 1)
                redis_conn.publish(channel_name, data)
1264695
def on_release(callback, suppress=False):
    
    return hook(lambda e: e.event_type == KEY_DOWN or callback(e), suppress=suppress)
114144
def lock(timeout = nil, &block)
      Scripts.call(:lock, redis_pool,
                   keys: [exists_key, grabbed_key, available_key, UNIQUE_SET, unique_digest],
                   argv: [jid, ttl, lock_type])

      grab_token(timeout) do |token|
        touch_grabbed_token(token)
        return_token_or_block_value(token, &block)
      end
    end
1150244
def perform_operation
      redis = nil
      Timeout.timeout(MAX_OP_WAIT_TIME) do
        redis = new_client
        yield redis
      end
    rescue Exception => ex
      raise NodeUnavailableError, "#{ex.class}: #{ex.message}", ex.backtrace
    ensure
      if redis
        begin
          redis.client.disconnect
        rescue Exception => ex
          raise NodeUnavailableError, "#{ex.class}: #{ex.message}", ex.backtrace
        end
      end
    end
814137
def unlock!(token = nil)
      token ||= jid

      Scripts.call(
        :unlock,
        redis_pool,
        keys: [exists_key, grabbed_key, available_key, version_key, UNIQUE_SET, unique_digest],
        argv: [token, ttl, lock_type],
      )
    end
46932
def one_instance(function=None, key='', timeout=DEFAULT_ONE_INSTANCE_TIMEOUT):
    
    def _dec(run_func):
        def _caller(*args, **kwargs):
            ret_value = None
            have_lock = False
            # Use Redis AOF for persistent lock.
            if REDIS_CLIENT.config_get('appendonly').values()[0] == 'no':
                REDIS_CLIENT.config_set('appendonly', 'yes')
            lock = REDIS_CLIENT.lock(key, timeout=timeout)
            try:
                logger.debug(
                    '%s: trying to acquire lock (PID %d).'
                    % (key, os.getpid()))
                have_lock = lock.acquire(blocking=False)
                if have_lock:
                    logger.debug(
                        '%s: acquired lock (PID %d).' % (key, os.getpid()))
                    ret_value = run_func(*args, **kwargs)
                else:
                    logger.error(
                        '%s: did not acquire lock (PID %d).'
                        % (key, os.getpid()))
            finally:
                if have_lock:
                    lock.release()
                    logger.debug(
                        '%s: released lock (PID %d).' % (key, os.getpid()))
            return ret_value
        return _caller
    return _dec(function) if function is not None else _dec
1008172
def _release(self):
        """"""
        if self._in_use is None:
            # The holder is not checked out.
            return

        if not self._in_use.done():
            self._in_use.set_result(None)
        self._in_use = None

        # Deinitialize the connection proxy.  All subsequent
        # operations on it will fail.
        if self._proxy is not None:
            self._proxy._detach()
            self._proxy = None

        # Put ourselves back to the pool queue.
        self._pool._queue.put_nowait(self)
1074345
def close_node(self, node_id, *args, **kwargs):
        

        node = self.get_node(node_id)
        if node_id in self._used_mac_ids:
            i = self._used_mac_ids[node_id]
            self._free_mac_ids[node.project.id].insert(0, i)
            del self._used_mac_ids[node_id]
        yield from super().close_node(node_id, *args, **kwargs)
        return node
65040
def repl(host,port):
  ""
  client=redis.StrictRedis(host,port,socket_timeout=0.1) # timeout is for pubsub -- it shares the connection_pool
  pubsub=client.pubsub()
  snt=SubNotifyThread(host,port); snt.start()
  while 1:
    try: command=raw_input('command> ') # this has up/down command history on windows. How?
    except KeyboardInterrupt: print 'ctrl+c'; break
    if command=='exit': break
    if not command: continue
    toks=command.split()
    try: f=dict(get=client.get,set=client.set,pub=client.publish,sub=snt.subscribe,unsub=snt.unsubscribe,ping=client.ping)[toks[0]]
    except KeyError: print 'unk_command %s'%toks[0]; continue
    try: print f(*toks[1:])
    except Exception as e: print 'error %s %s'%(e.__class__.__name__,str(e))
  snt.dead=True
  print 'waiting for pubsub thread'
  snt.join()
827468
async def _call_redis(self, meth, *args, **kwargs):
        """"""
        while True:
            try:
                if not self._redis:
                    self._redis = await self._make_connection()
                return await meth(self._redis, *args, **kwargs)
            except aioredis.RedisError:
                logger.exception("Redis connection error")
                if self._redis:
                    self._redis.close()
                    await self._redis.wait_closed()
                    self._redis = None
                await asyncio.sleep(3)
1197990
def disconnect(self):
        
        if not self.is_connected() and not self.is_connecting():
            return
        LOG.debug("disconnecting from %s...", self._redis_server())
        self.__periodic_callback.stop()
        try:
            self._ioloop.remove_handler(self.__socket_fileno)
            self._listened_events = 0
        except Exception:
            pass
        self.__socket_fileno = -1
        try:
            self.__socket.close()
        except Exception:
            pass
        self._state.set_disconnected()
        self._close_callback()
        LOG.debug("disconnected from %s", self._redis_server())