Exemplo n.º 1
0
    int RedisAsyncConn::DoConnect() {
        m_state = CONNECTING;
        int retry = 0;
        while (true) {
            m_async_context = redisAsyncConnect(m_server_ip.c_str(), m_server_port);
            if (m_async_context->err) {
                LOG(ERROR) << "RedisAsyncConn::DoConnect() error=" << m_async_context->errstr
                    << ", retry=" << retry;
                redisAsyncDisconnect(m_async_context);
                if (++retry > m_max_retry_times) {
                    return REDIS_ASYNC_CONN_ERR;
                }
            } else {
                break;
            }
        }
        g_async_conn_map.insert(make_pair(m_async_context, this));

        RedisNetlibAttach(m_async_context, NetEventLoop::GetInstance());
        redisAsyncSetConnectCallback(m_async_context, ConnectCallback);
        redisAsyncSetDisconnectCallback(m_async_context, DisconnectCallback);

        LOG(DEBUG) << "RedisAsyncConn::DoConnect() server_ip=" << m_server_ip << ", server_port="
            << m_server_port << ", handle=" << m_async_context->c.fd;
        return REDIS_ASYNC_CONN_OK;
    }
Exemplo n.º 2
0
// async
bool RedisClientPool::ReconnectAsync(redisAsyncContext* rc, aeEventLoop *loop)
{
	DestroyAsync(rc);
	try
	{
		rc = redisAsyncConnect(address_.c_str(), port_);
		//fprintf(stderr, "connect redisContext->err: %d\n", rc->err);
		if (rc != NULL && rc->err != 0)
		{
			stringstream stream;
			stream << "reconnect Error: " << rc->errstr;
			LOG(ERROR, stream.str());
			// 建立错误直接返回NULL
			// FIXME: no need to free?
			//      redisFree(rc);
			return false;
		}
		redisAsyncSetDisconnectCallback(rc, redisAsyncDisconnectCallback);
		// 在重连成功后做Attach操作
		redisAeAttach(loop, rc);
	} catch (std::exception &e)
	{
		stringstream stream;
		stream << "reconnect server faild!!";
		LOG(ERROR, stream.str());

		return false;
	}
	return true;
}
Exemplo n.º 3
0
int main(int argc, char **argv) {
	if(argc != 2) {
		fprintf(stderr, "Usage: %s /dev/<ssp-port>\n", argv[0]);
		return 1;
	}

	signal(SIGPIPE, SIG_IGN);
	signal(SIGINT, interrupt);

	fprintf(stderr, "eSSP starting up (port %s)...\n", argv[1]);
	if(!sspConnectToValidator(argv[1])) {
		return 3;
	}
	eventBase = event_base_new();
	atexit(cleanup);
	setupDatabase();

	redisLibeventAttach(db, eventBase);
	redisAsyncSetConnectCallback(db, connectCallback);
	redisAsyncSetDisconnectCallback(db, disconnectCallback);

	event_base_dispatch(eventBase);

	return 0;
}
Exemplo n.º 4
0
int rxs_signal_init(rxs_signal* s, const char* ip, uint16_t port) {
  if (!s)    { return -1; } 
  if (!ip)   { return -2; } 
  if (!port) { return -3; } 

  s->connected = 0;
  s->loop = (uv_loop_t*)uv_default_loop();
  if (!s->loop) {
    printf("Error: cannot get default uv loop for signaling.\n");
    return -4;
  }

  s->redis = redisAsyncConnect(ip, port);
  if (!s->redis) {
    printf("Error: cannot create hiredis context for signaling.\n");
    return -5;
  }

  if (s->redis->err) {
    printf("Error: something went wrong when trying to connect to redis: %s\n", s->redis->errstr);
    return -6;
  }



  /* @todo - add error checks */
  redisLibuvAttach(s->redis, s->loop);
  redisAsyncSetConnectCallback(s->redis, connect_callback);
  redisAsyncSetDisconnectCallback(s->redis, disconnect_callback);

  return 0;
}
Exemplo n.º 5
0
// async
redisAsyncContext* RedisClientPool::createAsync(aeEventLoop *loop)
{
	try
	{
		redisAsyncContext * ret = redisAsyncConnect(address_.c_str(), port_);

		if (ret != NULL && ret->err)
		{
			stringstream stream;
			stream << "reconnect Error: " << ret->err;
			LOG(ERROR, stream.str());
			// FIXME: no need to free
			//      redisFree(ret);
			// 建立错误直接返回NULL
			ret = NULL;
			return ret;
		}
		// 设置连接断开的回调函数
		redisAsyncSetDisconnectCallback(ret, redisAsyncDisconnectCallback);
		// 在第一次创建链接的时候做Attach操作
		redisAeAttach(loop, ret);
		return ret;
	} catch (std::exception &e)
	{
		return NULL;
	}
}
Exemplo n.º 6
0
    void connect() {
        if(redisContext_) {
            throw IllegalStateException("Error redisContext already created");
        }
        state_ = REDISREQUEST_CONNECTING;
        ScopedMutexLock(lockRedis_);
        redisContext_ = redisAsyncConnect(host_.c_str(), port_);

        if (redisContext_->err) {
            _LOG_DEBUG("REDIS CONNECT FAILED (CREATE ERROR): %s:%d, err = %x, this = %p"
                       , host_.c_str(), port_, redisContext_->err, this);

            state_ = REDISREQUEST_CONNECTFAILED;
            //fire_onRedisRequest_Error(redisContext_->err, "connect error", NULL);
            // disconnectCallback() is called later soon..
            // error process will be executed by that function.
        }

        redisContext_->data = this;
        redisLibeventAttach(redisContext_, (struct event_base *)ioService_->coreHandle());
        redisAsyncSetConnectCallback(redisContext_, connectCallback);
        redisAsyncSetDisconnectCallback(redisContext_, disconnectCallback);
        timerObj_->setTimer(TIMER_ID_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT, false);

        _LOG_DEBUG("redis connect start : %s:%d, flag = 0x%x, fd = %d, context = %p, this = %p"
                   , host_.c_str(), port_, redisContext_->c.flags, redisContext_->c.fd, redisContext_, this);
    }
Exemplo n.º 7
0
void redis_disconnect_callback(const redisAsyncContext* c, int status)
{
    struct nbd_handle* handle;

    if (c->data)
    {
       handle = (struct nbd_handle*) c->data;
    }
    else
    {
        fprintf_light_red(stderr, "FATAL: Handle not passed to disconnect "
                                  "callback.\n");
        assert(c->data != NULL);
        return;
    }

    if (status != REDIS_OK)
    {
        if (c->err == REDIS_ERR_EOF) /* probably standard timeout, reconnect */
        {
            fprintf_red(stderr, "Redis server disconnected us.\n");
            if ((handle->redis_c = redisAsyncConnect(handle->redis_server,
                 handle->redis_port)) != NULL)
            {
                fprintf_blue(stderr, "New Redis context, attaching to "
                                    "libevent.\n");
                handle->redis_c->data = c->data;
                redisLibeventAttach(handle->redis_c, handle->eb);
                fprintf_blue(stderr, "Setting disconnect callback.\n");
                if (redisAsyncSetDisconnectCallback(handle->redis_c,
                    &redis_disconnect_callback) != REDIS_ERR)
                {
                    assert(redisAsyncCommand(handle->redis_c,
                           &redis_async_callback, NULL, "select %d",
                           handle->redis_db) == REDIS_OK);
                    fprintf_light_blue(stderr, "Successfully reconnected to "
                                               "the Redis server.\n");
                }
                else
                {
                    fprintf_light_red(stderr, "Error setting disconnect "
                                              "callback handler for Redis.\n");
                }
            }
            else
            {
                fprintf_light_red(stderr, "Error trying to reconnect to "
                                          "Redis.\n");
            }
            return;
        }
        fprintf_light_red(stderr, "FATAL ERROR DISCONNECTION FROM REDIS\n");
        fprintf_light_blue(stderr, "Error: %s\n", c->errstr);
        assert(false);
    }
}
Exemplo n.º 8
0
void connectAsyncRedis(redisAsyncContext *ctx, EventLoop *loop)
{
	if(redisSayanAttach(ctx, loop)!=REDIS_OK)
		die("Error: %s\n", ctx->errstr);
	redisAsyncSetConnectCallback(ctx, connectCallback);
	redisAsyncSetDisconnectCallback(ctx, disconnectCallback);
	char *test="bonjour";
	redisAsyncCommand(ctx, getCallback, NULL, "SET key %b", test, strlen(test));
	redisAsyncCommand(ctx, getCallback, (char*)"end-1", "GET key");
}
Exemplo n.º 9
0
int main (int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    struct event_base *base = event_base_new();

    const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
    int port = (argc > 2) ? atoi(argv[2]) : 6379;
    const char *subname = (argc > 3) ? argv[3] : "test";

    redisAsyncContext *c = redisAsyncConnect(hostname, port);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    g_yuv_size = 1920*1080*3/2;
    g_yuv = malloc(g_yuv_size);
    start_time = time((time_t*)NULL);
    now_time = time((time_t*)NULL);


    // init pipe
    if(pipe(pipe_fd)){
        printf("pipe error\n");
        return -1;
    }

    // create thread
    pthread_attr_t attr;
    struct sched_param param;
    pthread_t tsk_id;

    pthread_attr_init(&attr);
    pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
    pthread_attr_getschedparam(&attr, &param);
     
    pthread_create(&tsk_id, &attr, (void *)thread_function, NULL);



    // event
    redisLibeventAttach(c,base);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);
    redisAsyncCommand(c, subCallback, (char*) "sub", "SMEMSUBSCRIBE %s", subname);

    event_base_dispatch(base);
    return 0;
}
Exemplo n.º 10
0
void RedisProxy::connect()
{
    if(_connected) {
        return;
    }
    SLOG(DEBUG) << "redis connect begin...";

    _context = redisAsyncConnect(_ip.c_str(), _port);
    if(!_context)
    {
        SLOG(WARNING) << "allocate redis async connection fail!";
        return;
    }

    if(_context->err != 0)
    {
        SLOG(WARNING) << "connect fail[" << _context->err << "]";
        redisAsyncFree(_context);
        _context = nullptr;
        return;
    }

    _context->data = this;
    _context->ev.data = this;
    _context->ev.addRead = RedisProxy::redis_add_read;
    _context->ev.delRead = RedisProxy::redis_del_read;
    _context->ev.addWrite = RedisProxy::redis_add_write;
    _context->ev.delWrite = RedisProxy::redis_del_write;
    _context->ev.cleanup = RedisProxy::redis_cleanup;

    
    _read_io = std::make_shared<IO>(_context->c.fd, EV_READ, false);//FIXME:add EV_ET in future
    _read_io->on_read([this]() {
        LOG(INFO) << "on read";
        redisAsyncHandleRead(_context);        
    });
    _write_io = std::make_shared<IO>(_context->c.fd, EV_WRITE, false);//FIXME:add EV_ET in future
    LOG(INFO) << "redis fd:" << _context->c.fd;
    _write_io->on_write([this]() {
        LOG(INFO) << "on write";
        redisAsyncHandleWrite(_context);
    });

    _connected = get_local_loop()->add_io(_read_io, false)
        && get_local_loop()->add_io(_write_io, false);

    redisAsyncSetConnectCallback(_context, RedisProxy::handle_connect);
    redisAsyncSetDisconnectCallback(_context, RedisProxy::handle_disconnect);
}
Exemplo n.º 11
0
static int lua_client_on_disconnect(lua_State *L)
{
  lua_redis_client_t *lua_redis_client = (lua_redis_client_t *)
                                    luaL_checkudata(L, 1, LUA_REDIS_CLIENT_MT);

  if (lua_redis_client->redis_async_context == NULL)
  {
    return luaL_error(L, "RedisAsyncContext is null");
  }

  luv_register_event(L, 1, "disconnect", 2);
  redisAsyncSetDisconnectCallback(lua_redis_client->redis_async_context,
                                  disconnectCallback);
  return 0;
}
Exemplo n.º 12
0
bool Redox::initHiredis() {

  ctx_->data = (void *)this; // Back-reference

  if (ctx_->err) {
    logger_.fatal() << "Could not create a hiredis context: " << ctx_->errstr;
    {
      unique_lock<mutex> lk(connect_lock_);
      connect_state_ = INIT_ERROR;
    }
    connect_waiter_.notify_all();
    return false;
  }

  // Attach event loop to hiredis
  if (redisLibevAttach(evloop_, ctx_) != REDIS_OK) {
    logger_.fatal() << "Could not attach libev event loop to hiredis.";
    {
      unique_lock<mutex> lk(connect_lock_);
      connect_state_ = INIT_ERROR;
    }
    connect_waiter_.notify_all();
    return false;
  }

  // Set the callbacks to be invoked on server connection/disconnection
  if (redisAsyncSetConnectCallback(ctx_, Redox::connectedCallback) != REDIS_OK) {
    logger_.fatal() << "Could not attach connect callback to hiredis.";
    {
      unique_lock<mutex> lk(connect_lock_);
      connect_state_ = INIT_ERROR;
    }
    connect_waiter_.notify_all();
    return false;
  }

  if (redisAsyncSetDisconnectCallback(ctx_, Redox::disconnectedCallback) != REDIS_OK) {
    logger_.fatal() << "Could not attach disconnect callback to hiredis.";
    {
      unique_lock<mutex> lk(connect_lock_);
      connect_state_ = INIT_ERROR;
    }
    connect_waiter_.notify_all();
    return false;
  }

  return true;
}
Exemplo n.º 13
0
static client createClient(void) {
    client c = zmalloc(sizeof(struct _client));

    c->context = redisAsyncConnect(config.hostip,config.hostport);
    c->context->data = c;
    redisAsyncSetDisconnectCallback(c->context,clientDisconnected);
    if (c->context->err) {
        fprintf(stderr,"Connect: %s\n",c->context->errstr);
        exit(1);
    }

    redisAeAttach(config.el,c->context);
    listAddNodeTail(config.clients,c);
    issueRequest(c);
    return c;
}
Exemplo n.º 14
0
bool AsyncRedisMgr::redis_connect()
{	

	if(redisAsyncSetConnectCallback(m_redis_context,connect_callback) != REDIS_OK)
	{
		LOG4CPLUS_ERROR(logger,"when we set connect callback fail.");
		return false;
	}

	if(redisAsyncSetDisconnectCallback(m_redis_context,dis_connect_callback) != REDIS_OK)
	{
		LOG4CPLUS_ERROR(logger,"when we set disconnect callback fail.");
		return false;
	}
	
	return true;	
}
Exemplo n.º 15
0
int main (int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);

    redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    redisLibevAttach(EV_DEFAULT_ c);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);
    redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
    redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
    ev_loop(EV_DEFAULT_ 0);
    return 0;
}
Exemplo n.º 16
0
static int new_connect( struct cnt_pool *pool, uintptr_t **cite, va_list *ap )
{
	char *host = va_arg(*ap, char *);
	int port = va_arg(*ap, int);
	redisAsyncContext *c = redisAsyncConnect (host, port);
	if (!c || c->err) {
		/* Let *c leak for now... */
		x_printf (E, "Error: %s\n", c->errstr);
		free (c);
		*cite = NULL;
		return -1;
	}
	redisLibevAttach(NULL, c);
	redisAsyncSetConnectCallback(c, _connectCallback);
	redisAsyncSetDisconnectCallback(c, _disconnectCallback);
	*cite = (uintptr_t *)c;
	return 0;
}
Exemplo n.º 17
0
int main() {
    signal(SIGPIPE, SIG_IGN);

    redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    redisLibevAttach(EV_DEFAULT_ c);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);

    // redisAsyncCommand(c, getCallback, (char*)"sub", "SUBSCRIBE name");
    new ChatRoom(c, {"79153060652", "79030072726", "79853672651"});
    ev_loop(EV_DEFAULT_ 0);
    return 0;
}
Exemplo n.º 18
0
/*Inicia conexao com o Redis e configura as funcoes de callback no libEvent*/
void initRedis( const char * channel, char * id) {
    signal(SIGPIPE, SIG_IGN);
    struct event_base *base = event_base_new();
    strcpy(globalChannel, channel);    
    setMyID(id); 
    redisAsyncContext * redis = redisAsyncConnect("127.0.0.1", 6379);
    if ( redis->err ) {
	   printf("Erro conectando no redis %s\n", redis->errstr);
	   exit(EXIT_FAILURE);
    }
   
    initStdin( channel);

    redisLibeventAttach( redis,base);
    redisAsyncSetConnectCallback(redis, connectCallback);
    redisAsyncSetDisconnectCallback( redis,disconnectCallback);
    event_base_dispatch(base);

}
Exemplo n.º 19
0
int main (int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);

    redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    loop = aeCreateEventLoop();
    redisAeAttach(loop, c);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);
    redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
    redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
    aeMain(loop);
    return 0;
}
Exemplo n.º 20
0
int main (int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    struct event_base *base = event_base_new();

    redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    redisLibeventAttach(c,base);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);
    redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
    redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
    event_base_dispatch(base);
    return 0;
}
Exemplo n.º 21
0
void func(const std::string& commandStr)
{
	g_SubscribeMutex.lock();
	struct event_base *m_base = event_base_new();

	redisAsyncContext *m_redis = redisAsyncConnect("127.0.0.1", 6379);
	if (m_redis->err) {
		/* Let *c leak for now... */
		printf("Error: %s\n", m_redis->errstr);
	}
	redisAsyncCommand(m_redis,authCallback, (char*) "auth", "auth %s", "014006");

	redisLibeventAttach(m_redis, m_base);
	redisAsyncSetConnectCallback(m_redis, connectCallback);
	redisAsyncSetDisconnectCallback(m_redis, disconnectCallback);

	redisAsyncCommand(m_redis, subscribeCallback, (char*) "sub", commandStr.c_str());
	g_SubscribeMutex.unlock();
	event_base_dispatch(m_base);
}
Exemplo n.º 22
0
int AsyncConnection::connect(const string& host, const int port, const int db)
{
    async_context_ = redisAsyncConnect(host.c_str(), port);
    async_context_->data = this;
    if (async_context_->err)
    {
        cout << "error: " << async_context_->errstr << endl;
        return -1;
    }

    host_ = host;
    port_ = port;
    db_ = db;

    AsyncService::instance().attach(async_context_);

    redisAsyncSetConnectCallback(async_context_, connect_callback);
    redisAsyncSetDisconnectCallback(async_context_, disconnect_callback);

    return 0;
}
Exemplo n.º 23
0
void build_async_conn()
{
    if (actx) {
        redisAsyncDisconnect(actx);
    }

    actx = redisAsyncConnect(REDIS_SERVER_IP, REDIS_SERVER_PORT);
    if (actx == NULL || actx->err) {
        if (actx) {
            log_error("redisAsyncConnect fails: %s", actx->errstr);
            //redisFree(actx);
        } else {
            log_error("redisAsyncConnect fails: can't allocate redis context");
        }
        return;
    }

    redisLibevAttach(EV_DEFAULT_ actx);
    redisAsyncSetConnectCallback(actx, on_connect);
    redisAsyncSetDisconnectCallback(actx, on_disconnect);
    redisAsyncCommand(actx, on_expire, NULL, "SUBSCRIBE __keyevent@0__:expired");
}
Exemplo n.º 24
0
int RedisConnectionAsync::asyncConnect()
{
    _ac = redisAsyncConnect(_host.c_str(), _port);
    if (_ac == nullptr) return -1;
    _ac->data = (void*)this;

    if (_ac->err) {
        redisAsyncFree(_ac);
        _ac = nullptr;
        return -1;
        // throw RedisException((std::string)"RedisAsyncConnect: "+_ac->errstr);
    }
    if (redisAsyncSetConnectCallback(_ac, &connected)!=REDIS_OK ||
        redisAsyncSetDisconnectCallback(_ac, &disconnected)!=REDIS_OK) {
        redisAsyncFree(_ac);
        _ac = nullptr;
        return -1;
        // throw RedisException("RedisAsyncConnect: Can't register callbacks");
    }

#if HIREDISPP_USE_LIBEVENT
    if (redisLibeventAttach(_ac, (struct event_base *)_loopbase)!=REDIS_OK) {
        redisAsyncFree(_ac);
        _ac = nullptr;
        return -1;
        // throw RedisException("redisLibeventAttach: nothing should be attached when something is already attached");
    }
    // Send PING command, so libevent start working
    redisAsyncCommand(_ac, nullptr, nullptr, "PING");
#else
    // actually start io proccess
    ev_io_start(EV_DEFAULT, &((((redisLibevEvents*)(_ac->ev.data)))->rev));
    ev_io_start(EV_DEFAULT, &((((redisLibevEvents*)(_ac->ev.data)))->wev));
#endif
    return 0;
}
Exemplo n.º 25
0
    int GatewayDataMgr::startRedisCliProcLoop() {
        int iRet = 0;
        
        //init redis script sha1
        sha1sumScript();

        mPtRedisAC = redisAsyncConnect(mRedisSvrIPAddr.c_str(), mPort);
        if (mPtRedisAC->err) {
            /* Let *c leak for now... */
            LOG(ERROR)<<"Error: "<<mPtRedisAC->errstr;
            iRet = -1;
            return iRet;
        }

        mPtEventLoop = aeCreateEventLoop(64);
        mPtRedisAC->data = mPtEventLoop;//used on connect/disconnect callback
        redisAeAttach(mPtEventLoop, mPtRedisAC);
        redisAsyncSetConnectCallback(mPtRedisAC, connectCallback);
        redisAsyncSetDisconnectCallback(mPtRedisAC,disconnectCallback);

        std::thread loopThread(std::mem_fn(&GatewayDataMgr::loopThread), this);
        loopThread.detach();
        return iRet;
    } 
Exemplo n.º 26
0
static struct redis *__redis_connect_async(struct redis *redis)
{
	redis->eb = event_base_new();

	LM_INFO("Connecting (ASYNC) to Redis at %s:%d\n", redis->ip, redis->port);

	redis->async_ctxt = redisAsyncConnect(redis->ip, redis->port);

	if(redis->async_ctxt->err) {
		LM_ERR("%s\n", redis->async_ctxt->errstr);
		return NULL;
	}

	redisLibeventAttach(redis->async_ctxt, redis->eb);

	redisAsyncSetConnectCallback(redis->async_ctxt, __async_connect_cb);
	redisAsyncSetDisconnectCallback(redis->async_ctxt, __async_disconnect_cb);

	redisAsyncCommand(redis->async_ctxt, NULL, NULL, "SELECT %d", redis->db);
	__redis_subscribe_to_kill_list(redis);

	event_base_dispatch(redis->eb);
	return redis;
}
Exemplo n.º 27
0
struct nbd_handle* nbd_init_redis(char* export_name, char* redis_server,
                                  int redis_port, int redis_db, uint64_t fsize,
                                  char* nodename, char* port, bool old)
{
    struct addrinfo hints;
    struct addrinfo* server = NULL;
    struct event_base* eb = NULL;
    struct nbd_handle* ret = NULL;
    struct event* evsignal = NULL;
    struct evconnlistener* conn = NULL;
    struct redisAsyncContext* redis_c = NULL;

    /* sanity check */
    if (redis_server == NULL || nodename == NULL || port == NULL ||
        export_name == NULL)
        return NULL;

    /* setup network socket */
    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if (getaddrinfo(nodename, port, &hints, &server))
    {
        if (server)
            freeaddrinfo(server);
        return NULL;
    }

    /* initialize libevent */
    if ((eb = event_base_new()) == NULL)
    {
        freeaddrinfo(server);
        return NULL;
    }

    /* initialize libhiredis */
    if ((redis_c = redisAsyncConnect(redis_server, redis_port)) == NULL)
    {
        freeaddrinfo(server);
        event_base_free(eb);
        return NULL;
    }

    redisLibeventAttach(redis_c, eb);

    /* set disconnect handler */
    if (redisAsyncSetDisconnectCallback(redis_c, &redis_disconnect_callback) ==
        REDIS_ERR)
    {
        redisAsyncDisconnect(redis_c);
        freeaddrinfo(server);
        event_base_free(eb);
        return NULL;
    }

    /* initialize this nbd module */
    if ((ret = (struct nbd_handle*) malloc(sizeof(struct nbd_handle))) == NULL)
    {
        freeaddrinfo(server);
        event_base_free(eb);
        return NULL;
    }

    redis_c->data = ret; /* set unused field for disconnect callback */
    evsignal = evsignal_new(eb, SIGINT, nbd_signal_handler, (void *)ret);

    if (!evsignal || event_add(evsignal, NULL) < 0)
    {
        freeaddrinfo(server);
        event_base_free(eb);
        return NULL;
    }

    /* setup network connection */
    if ((conn = evconnlistener_new_bind(eb, old ? &nbd_old_conn :
                                        &nbd_new_conn, ret,
                                        LEV_OPT_CLOSE_ON_FREE |
                                        LEV_OPT_REUSEABLE, -1,
                                        server->ai_addr,
                                        server->ai_addrlen)) == NULL)
    {
        freeaddrinfo(server);
        event_base_free(eb);
        free(ret);
        return NULL;
    }

    evconnlistener_set_error_cb(conn, nbd_event_error);

    ret->fd = -1;
    ret->size = fsize;
    ret->export_name = export_name;
    ret->redis_server = redis_server;
    ret->name_len = strlen(export_name);
    ret->redis_port = redis_port;
    ret->redis_db = redis_db;
    ret->eb = eb;
    ret->conn = conn;
    ret->redis_c = redis_c;

    assert(redisAsyncCommand(redis_c, &redis_async_callback, NULL, "select %d",
                             redis_db) == REDIS_OK);

    freeaddrinfo(server);

    return ret;
}
Exemplo n.º 28
0
static PHP_METHOD(swoole_redis, connect)
{
    char *host;
    zend_size_t host_len;
    long port;
    zval *callback;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "slz", &host, &host_len, &port, &callback) == FAILURE)
    {
        RETURN_FALSE;
    }

    if (host_len <= 0)
    {
        swoole_php_error(E_WARNING, "host is empty.");
        RETURN_FALSE;
    }

    if (port <= 1 || port > 65535)
    {
        swoole_php_error(E_WARNING, "port is invalid.");
        RETURN_FALSE;
    }

    swRedisClient *redis = emalloc(sizeof(swRedisClient));
    bzero(redis, sizeof(swRedisClient));

#if PHP_MAJOR_VERSION < 7
    redis->object = getThis();
#else
    redis->object = &redis->_object;
    memcpy(redis->object, getThis(), sizeof(zval));
#endif
    sw_zval_add_ref(&redis->object);

    swoole_set_object(getThis(), redis);

    redisAsyncContext *context = redisAsyncConnect(host, (int) port);
    if (context->err)
    {
        swoole_php_error(E_WARNING, "connect to redis-server[%s:%d] failed, Erorr: %s[%d]", host, (int) port, context->errstr, context->err);
        RETURN_FALSE;
    }

    php_swoole_check_reactor();
    if (!isset_event_callback)
    {
        SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_READ, swoole_redis_onRead);
        SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE, swoole_redis_onWrite);
        isset_event_callback = 1;
    }

    redisAsyncSetConnectCallback(context, swoole_redis_onConnect);
    redisAsyncSetDisconnectCallback(context, swoole_redis_onClose);

#if PHP_MAJOR_VERSION < 7
    redis->connect_callback = callback;
#else
    redis->connect_callback = &redis->_connect_callback;
    memcpy(redis->connect_callback, callback, sizeof(zval));
#endif

    sw_zval_add_ref(&redis->connect_callback);

    redis->context = context;
    context->ev.addRead = swoole_redis_event_AddRead;
    context->ev.delRead = swoole_redis_event_DelRead;
    context->ev.addWrite = swoole_redis_event_AddWrite;
    context->ev.delWrite = swoole_redis_event_DelWrite;
    context->ev.cleanup = swoole_redis_event_Cleanup;
    context->ev.data = redis;

    zend_update_property_string(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("host"), host TSRMLS_CC);
    zend_update_property_long(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("port"), port TSRMLS_CC);

    if (SwooleG.main_reactor->add(SwooleG.main_reactor, redis->context->c.fd, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE) < 0)
    {
        swoole_php_fatal_error(E_WARNING, "swoole_event_add failed. Erorr: %s[%d].", redis->context->errstr, redis->context->err);
        RETURN_FALSE;
    }

    swConnection *conn = swReactor_get(SwooleG.main_reactor, redis->context->c.fd);
    conn->object = redis;
}
Exemplo n.º 29
0
static PHP_METHOD(swoole_redis, connect)
{
    char *host;
    zend_size_t host_len;
    long port;
    zval *callback;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "slz", &host, &host_len, &port, &callback) == FAILURE)
    {
        RETURN_FALSE;
    }

    if (host_len <= 0)
    {
        swoole_php_error(E_WARNING, "redis server host is empty.");
        RETURN_FALSE;
    }

    swRedisClient *redis = swoole_get_object(getThis());
    redisAsyncContext *context;

    if (strncasecmp(host, ZEND_STRL("unix:/")) == 0)
    {
        context = redisAsyncConnectUnix(host + 5);
    }
    else
    {
        if (port <= 1 || port > 65535)
        {
            swoole_php_error(E_WARNING, "redis server port is invalid.");
            RETURN_FALSE;
        }
        context = redisAsyncConnect(host, (int) port);
    }

    if (context->err)
    {
        swoole_php_error(E_WARNING, "failed to connect to the redis-server[%s:%d], Erorr: %s[%d]", host, (int) port, context->errstr, context->err);
        RETURN_FALSE;
    }

    php_swoole_check_reactor();
    if (!swReactor_handle_isset(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS))
    {
        SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_READ, swoole_redis_onRead);
        SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE, swoole_redis_onWrite);
        SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_REDIS | SW_EVENT_ERROR, swoole_redis_onError);
    }

    redisAsyncSetConnectCallback(context, swoole_redis_onConnect);
    redisAsyncSetDisconnectCallback(context, swoole_redis_onClose);

    zend_update_property_long(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("sock"), context->c.fd TSRMLS_CC);
    zend_update_property(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("onConnect"), callback TSRMLS_CC);

    redis->context = context;
    context->ev.addRead = swoole_redis_event_AddRead;
    context->ev.delRead = swoole_redis_event_DelRead;
    context->ev.addWrite = swoole_redis_event_AddWrite;
    context->ev.delWrite = swoole_redis_event_DelWrite;
    context->ev.cleanup = swoole_redis_event_Cleanup;
    context->ev.data = redis;

    zend_update_property_string(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("host"), host TSRMLS_CC);
    zend_update_property_long(swoole_redis_class_entry_ptr, getThis(), ZEND_STRL("port"), port TSRMLS_CC);

    if (SwooleG.main_reactor->add(SwooleG.main_reactor, redis->context->c.fd, PHP_SWOOLE_FD_REDIS | SW_EVENT_WRITE) < 0)
    {
        swoole_php_fatal_error(E_WARNING, "swoole_event_add failed. Erorr: %s[%d].", redis->context->errstr, redis->context->err);
        RETURN_FALSE;
    }

    if (redis->timeout > 0)
    {
        php_swoole_check_timer((int) (redis->timeout * 1000));
        redis->timer = SwooleG.timer.add(&SwooleG.timer, (int) (redis->timeout * 1000), 0, redis, swoole_redis_onTimeout);
    }

    sw_zval_add_ref(&redis->object);

    swConnection *conn = swReactor_get(SwooleG.main_reactor, redis->context->c.fd);
    conn->object = redis;
}
Exemplo n.º 30
0
/* Internal host connect - Sync or Async */
  static int
_host_connect( host_t *h, eredis_reader_t *r )
{
  redisContext *c;

  if (r) {
    /* Sync - not in EV context */
    c = (h->port) ?
      redisConnect( h->target, h->port )
      :
      redisConnectUnix( h->target );

    if (! c) {
      fprintf(stderr,
              "eredis: error: connect sync %s NULL\n",
              h->target);
      return 0;
    }
    if (c->err) {
#if EREDIS_VERBOSE>0
      printf( "eredis: error: connect sync %s %d\n",
              h->target, c->err);
#endif
      redisFree( c );
      return 0;
    }

    r->ctx   = c;
    r->host  = h;
  }

  else {
    redisAsyncContext *ac;

    /* ASync - in EV context */
    ac = (h->port) ?
      redisAsyncConnect( h->target, h->port )
      :
      redisAsyncConnectUnix( h->target );

    if (! ac) {
      printf( "eredis: error: connect async %s undef\n",
              h->target);
      return 0;
    }
    if (ac->err) {
#if EREDIS_VERBOSE>0
      printf( "eredis: error: connect async %s %d\n",
              h->target, ac->err);
#endif
      redisAsyncFree( ac );
      return 0;
    }

    h->async_ctx = ac;

    /* data for _redis_*_cb */
    ac->data = h;

    /* Order is important here */

    /* attach */
    redisLibevAttach( h->e->loop, ac );

    /* set callbacks */
    redisAsyncSetDisconnectCallback( ac, _redis_disconnect_cb );
    redisAsyncSetConnectCallback( ac, _redis_connect_cb );

    c = (redisContext*) ac;
  }

  /* Apply keep-alive */
#ifdef HOST_TCP_KEEPALIVE
  if (h->port) {
    redisEnableKeepAlive( c );
    if (r && (h->e->sync_to.tv_sec||h->e->sync_to.tv_usec)) {
      redisSetTimeout( c, h->e->sync_to );
    }
  }
#endif

  /* Override the maxbuf */
  c->reader->maxbuf = EREDIS_READER_MAX_BUF;

  return 1;
}