Пример #1
0
static void get_callback(lcb_t instance, const void *cookie, lcb_error_t err, 
   const lcb_get_resp_t *resp)
{
    //  If you can't read from active, read from replica.
    if (err != LCB_SUCCESS && flag == 0 ) {
        printf("REPLICA\t");
        printf("Failed to read from active copy: %s\n", lcb_strerror(instance,err));
        fprintf(stderr, "Reading from REPLICA. Failed to read from active copy: %s\n", lcb_strerror(instance,err));

        lcb_get_replica_cmd_t rcmd = {0};
        const lcb_get_replica_cmd_t *rcmdlist = &rcmd;
        rcmd.v.v1.key = resp->v.v0.key;
        rcmd.v.v1.nkey = (int)resp->v.v0.nkey;
        rcmd.v.v1.strategy = LCB_REPLICA_FIRST;
        err = lcb_get_replica(instance, NULL, 1, &rcmdlist);
        flag=1;
        lcb_wait(instance); // get_replica_callback is invoked here

    }
    else if (err != LCB_SUCCESS && flag == 1){
        // If you fail to read from active and replica, just print the below message and the key.
        flag=0;
        printf("Failed to read from replica too: %s \n",lcb_strerror(instance,err));
        fprintf(stderr, "Failed to read from replica too: %s\n", lcb_strerror(instance, err));
        }
    else {
        // If you were able to get the key, print the key and value.
        printf("Retrieved key %.*s\t\t", (int)resp->v.v0.nkey, resp->v.v0.key);
        printf("Value is %.*s\n", (int)resp->v.v0.nbytes, resp->v.v0.bytes);
        fprintf(stderr, "Retrieved key %.*s\t value is %.*s\n", (int)resp->v.v0.nkey, resp->v.v0.key, (int)resp->v.v0.nbytes, resp->v.v0.bytes);
        flag=0;
    }

}
Пример #2
0
SV *
PLCB__n1qlhandle_new(PLCB_t *parent, lcb_N1QLPARAMS *params, const char *host)
{
    AV *req;
    SV *blessed;
    lcb_CMDN1QL cmd = { 0 };
    lcb_error_t rc;

    rc = lcb_n1p_mkcmd(params, &cmd);
    if (rc != LCB_SUCCESS) {
        die("Error encoding N1QL parameters: %s", lcb_strerror(NULL, rc));
    }

    if (host && *host) {
        cmd.host = host;
    }
    cmd.callback = n1ql_callback;

    req = newAV();
    rowreq_init_common(parent, req);
    blessed = newRV_noinc((SV*)req);
    sv_bless(blessed, parent->n1ql_stash);

    rc = lcb_n1ql_query(parent->instance, req, &cmd);
    if (rc != LCB_SUCCESS) {
        SvREFCNT_dec(blessed);
        die("Couldn't issue N1QL query: (0x%x): %s", rc, lcb_strerror(NULL, rc));
    } else {
        SvREFCNT_inc(req);
    }

    return blessed;
}
int main(void)
{
    struct lcb_create_st create_options;
    lcb_t instance;
    lcb_error_t err;

    memset(&create_options, 0, sizeof(create_options));
    create_options.v.v0.host = "ec2-204-236-172-232.us-west-1.compute.amazonaws.com:8091";
    create_options.v.v0.user = "******";
    create_options.v.v0.passwd = "password";
    create_options.v.v0.bucket = "default";

    err = lcb_create(&instance, &create_options);
    if (err != LCB_SUCCESS) {
        fprintf(stderr, "Failed to create libcouchbase instance: %s\n",
                lcb_strerror(NULL, err));
        return 1;
    }
    else {
        fprintf(stdout, "Successful in creating libCouchbase instance: %s\n");
    }
    if ((err = lcb_connect(instance)) != LCB_SUCCESS) {
        fprintf(stderr, "Failed to initiate connect: %s\n",
                lcb_strerror(NULL, err));
        return 1;
    }
    else {
        fprintf(stdout, "Successful in initializing libCouchbase instance: %s\n");
    }

    /* Run the event loop and wait until we've connected */
    lcb_wait(instance);

    lcb_arithmetic_cmd_t arithmetic;
    memset(&arithmetic, 0, sizeof(arithmetic));
    arithmetic.version = 0;
    arithmetic.v.v0.key = "036";
    arithmetic.v.v0.nkey = sizeof(arithmetic.v.v0.key);
    arithmetic.v.v0.create = 1;
    arithmetic.v.v0.delta = -10;
    arithmetic.v.v0.initial = 036;
    const lcb_arithmetic_cmd_t* const commands[1] = { &arithmetic };
    err = lcb_arithmetic(instance, NULL, 1, commands);
    if (err != LCB_SUCCESS) {
        fprintf(stderr, "Failed to incr %s\n",
            lcb_strerror(NULL, err));
        return 1;
    }
    else {
        fprintf(stdout, "Successful in incrementingthe keys and Values: %s\n");
    }

    lcb_wait(instance);

    lcb_destroy(instance);
    exit(EXIT_SUCCESS);
}
Пример #4
0
int main(void)
{
	struct lcb_create_st create_options;
	lcb_t instance;
	lcb_error_t err;

	memset(&create_options, 0, sizeof(create_options));
	create_options.v.v0.host = "10.128.34.251:8091";
	create_options.v.v0.user = "******";
	create_options.v.v0.passwd = "jiubugaosuni";
	create_options.v.v0.bucket = "beer-sample";

	err = lcb_create(&instance, &create_options);
	if (err != LCB_SUCCESS) {
		fprintf(stderr, "Failed to create libcouchbase instance: %s\n",
				lcb_strerror(NULL, err));
		return 1;
	}

	/* Set up the handler to catch all errors! */
	lcb_set_error_callback(instance, error_callback);

	/*
	 *      * Initiate the connect sequence in libcouchbase
	 *           */
	if ((err = lcb_connect(instance)) != LCB_SUCCESS) {
		fprintf(stderr, "Failed to initiate connect: %s\n",
				lcb_strerror(NULL, err));
		return 1;
	}

	/* Run the event loop and wait until we've connected */
	lcb_wait(instance);

	/*
	 *      * Set up a callback for our get requests
	 *           */
	lcb_set_get_callback(instance, get_callback);

	lcb_get_cmd_t cmd;
	const lcb_get_cmd_t * const commands[1] = { &cmd };
	memset(&cmd, 0, sizeof(cmd));
	cmd.v.v0.key = "foo";
	cmd.v.v0.nkey = 3;

	err = lcb_get(instance, NULL, 1, commands);
	if (err != LCB_SUCCESS) {
		fprintf(stderr, "Failed to get: %s\n",
				lcb_strerror(NULL, err));
		return 1;
	}

	lcb_wait(instance);

	lcb_destroy(instance);
	exit(EXIT_SUCCESS);
}
Пример #5
0
int couchbase_remove(cachedb_con *connection,str *attr)
{
	lcb_t instance;
	lcb_error_t oprc;
	lcb_remove_cmd_t cmd;
	const lcb_remove_cmd_t *commands[1];
	struct timeval start;

	start_expire_timer(start,couch_exec_threshold);
	instance = COUCHBASE_CON(connection);
	commands[0] = &cmd;
	memset(&cmd, 0, sizeof(cmd));
	cmd.v.v0.key = attr->s;
	cmd.v.v0.nkey = attr->len;
	oprc = lcb_remove(instance, NULL, 1, commands);

	if (oprc != LCB_SUCCESS) {
		if (oprc == LCB_KEY_ENOENT) {
			stop_expire_timer(start,couch_exec_threshold,
			"cachedb_couchbase remove",attr->s,attr->len,0);
			return -1;
		}

		LM_ERR("Failed to send the remove query - %s\n", lcb_strerror(instance, oprc));
		if (couchbase_conditional_reconnect(connection, oprc) != 1) {
			stop_expire_timer(start,couch_exec_threshold,
			"cachedb_couchbase remove",attr->s,attr->len,0);
			return -2;
		};

		instance = COUCHBASE_CON(connection);
		oprc = lcb_remove(instance, NULL, 1, commands);

		if (oprc != LCB_SUCCESS) {
			if (oprc == LCB_KEY_ENOENT) {
				LM_ERR("Remove command successfully retried\n");
				stop_expire_timer(start,couch_exec_threshold,
				"cachedb_couchbase remove",attr->s,attr->len,0);
				return -1;
			}
			LM_ERR("Remove command retry failed - %s\n", lcb_strerror(instance, oprc));
			stop_expire_timer(start,couch_exec_threshold,
			"cachedb_couchbase remove",attr->s,attr->len,0);
			return -2;
		}
		LM_ERR("Remove command successfully retried\n");
	}

	LM_DBG("Succesfully removed\n");
	stop_expire_timer(start,couch_exec_threshold,
	"cachedb_couchbase remove",attr->s,attr->len,0);
	return 1;
}
int couchbase_add(cachedb_con *connection,str *attr,int val,int expires,int *new_val)
{
	lcb_t instance;
	lcb_error_t oprc;
	lcb_arithmetic_cmd_t cmd;
	const lcb_arithmetic_cmd_t *commands[1];

	instance = COUCHBASE_CON(connection);

	commands[0] = &cmd;
	memset(&cmd, 0, sizeof(cmd));
	cmd.v.v0.key = attr->s;
	cmd.v.v0.nkey = attr->len;
	cmd.v.v0.delta = val;
	cmd.v.v0.create = 1;
	cmd.v.v0.initial = val;
	cmd.v.v0.exptime = expires;
	oprc = lcb_arithmetic(instance, NULL, 1, commands);

	if (oprc != LCB_SUCCESS) {
		if (oprc == LCB_KEY_ENOENT) {
			return -1;
		}

		LM_ERR("Failed to send the arithmetic query - %s\n", lcb_strerror(instance, oprc));
		//Attempt reconnect
		if (couchbase_conditional_reconnect(connection, oprc) != 1) {
			return -2;
		}

		//Try again
		instance = COUCHBASE_CON(connection);
		oprc = lcb_arithmetic(instance, NULL, 1, commands);

		if (oprc != LCB_SUCCESS) {
			if (oprc == LCB_KEY_ENOENT) {
				LM_ERR("Arithmetic command successfully retried\n");
				return -1;
			}
			LM_ERR("Arithmetic command retry failed - %s\n", lcb_strerror(instance, oprc));
			return -2;
		}
		LM_ERR("Arithmetic command successfully retried\n");
	}

	if (new_val)
		*new_val = arithmetic_res;

	return 1;
}
Пример #7
0
int couchbase_set(cachedb_con *connection,str *attr,
		str *val,int expires)
{
	lcb_t instance;
	lcb_error_t oprc;
	lcb_store_cmd_t cmd;
	const lcb_store_cmd_t *commands[1];
	struct timeval start;

	start_expire_timer(start,couch_exec_threshold);
	instance = COUCHBASE_CON(connection);

	commands[0] = &cmd;
	memset(&cmd, 0, sizeof(cmd));
	cmd.v.v0.operation = LCB_SET;
	cmd.v.v0.key = attr->s;
	cmd.v.v0.nkey = attr->len;
	cmd.v.v0.bytes = val->s;
	cmd.v.v0.nbytes = val->len;
	cmd.v.v0.exptime = expires;

	oprc = lcb_store(instance, NULL, 1, commands);

	if (oprc != LCB_SUCCESS) {
		LM_ERR("Set request failed - %s\n", lcb_strerror(instance, oprc));
		//Attempt reconnect
		if(couchbase_conditional_reconnect(connection, oprc) != 1) {
			stop_expire_timer(start,couch_exec_threshold,
			"cachedb_couchbase set",attr->s,attr->len,0);
			return -2;
		}

		//Try again
		instance = COUCHBASE_CON(connection);
		oprc = lcb_store(instance, NULL, 1, commands);

		if (oprc != LCB_SUCCESS) {
			LM_ERR("Set command retry failed - %s\n", lcb_strerror(instance, oprc));
			stop_expire_timer(start,couch_exec_threshold,
			"cachedb_couchbase set",attr->s,attr->len,0);
			return -2;
		}
		LM_ERR("Set command successfully retried\n");
	}
	LM_DBG("Succesfully stored\n");
	stop_expire_timer(start,couch_exec_threshold,
	"cachedb_couchbase set",attr->s,attr->len,0);
	return 1;
}
Пример #8
0
static void 
die(lcb_t instance, const char  *msg, lcb_error_t err) 
{
	fprintf(stderr, "%s. Received code 0x%X (%s)\n",
		msg, err, lcb_strerror(instance, err) );
	exit(EXIT_FAILURE);
}
Пример #9
0
/*
 * Name:	couchdb_flush
 * Input Args:
 *	handle - handle to the lcb instance
 *
 * Description: Flushes the entire cluster
 */
int
couchdb_flush(void)
{
	lcb_error_t ret;
	int	lock_result;
	lcb_flush_cmd_t *cmd = malloc(sizeof(*cmd));
	const lcb_flush_cmd_t *const flush_cmd[] = { cmd };

	cmd->version = 0;

	lock_result = pthread_rwlock_wrlock(&db_rwlock);
	if (lock_result != 0) {
		syslog(LOG_ERR, "%s: Failed to obtain writelock. Error = %d\n",
			__FUNCTION__, errno);
		return -errno;
	}

	ret = lcb_flush(couchdb_handle, NULL, 1, flush_cmd);
	if (ret != LCB_SUCCESS) {
		syslog(LOG_ERR, "%s: lcb_flush failed with error %s\n",
			__FUNCTION__, lcb_strerror(couchdb_handle, ret));
		return -ret;
	}

	/* Block the thread till this operation completes */
	lcb_wait(couchdb_handle);

	pthread_rwlock_unlock(&db_rwlock);
	USYSLOG(LOG_INFO, "\n%s: lflushed siuccess\n", __FUNCTION__);

	return (1);
}
Пример #10
0
PHP_COUCHBASE_LOCAL
void php_couchbase_unlock_impl(INTERNAL_FUNCTION_PARAMETERS, int oo)
{
	char *key;
	char *cas = NULL;
	char *cas_e;
	long klen = 0;
	long cas_len = 0;
	lcb_cas_t cas_v = 0;
	php_couchbase_res *couchbase_res;
	lcb_error_t retval;

	int arg = (oo) ? PHP_COUCHBASE_ARG_F_OO : PHP_COUCHBASE_ARG_F_FUNCTIONAL;

	PHP_COUCHBASE_GET_PARAMS(couchbase_res,  arg,
							 "ss", &key, &klen, &cas, &cas_len);

	if (klen == 0) {
		couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
							   cb_illegal_key_exception,
							   "Failed to schedule set request: Empty key");
		return ;
	}

	if (cas_len == 0) {
		couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
							   cb_illegal_key_exception,
							   "No CAS specified: Empty cas");
		return ;
	}

	cas_v = (lcb_cas_t)strtoull(cas, &cas_e, 10);
	if (*cas_e != '\0') {
		couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
							   cb_illegal_key_exception,
							   "Invalid CAS specified");
		return;
	}


	if (couchbase_res->prefix_key_len) {
		klen = spprintf(&key, 0, "%s_%s", couchbase_res->prefix_key, key);
	}

	retval = do_unlock(couchbase_res->handle, key, klen, cas_v);
	couchbase_res->rc = retval;

	if (couchbase_res->prefix_key_len) {
		efree(key);
	}

	if (retval == LCB_SUCCESS) {
		RETVAL_TRUE;
	} else {
		couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
							   cb_lcb_exception,
							   "Failed to unlock the document: %s",
							   lcb_strerror(couchbase_res->handle, retval));
	}
}
Пример #11
0
/* create new connection pool handle */
void *mod_conn_create(void *instance) {
	rlm_couchbase_t *inst = instance;           /* module instance pointer */
	rlm_couchbase_handle_t *chandle = NULL;     /* connection handle pointer */
	cookie_t *cookie = NULL;                    /* couchbase cookie */
	lcb_t cb_inst;                              /* couchbase connection instance */
	lcb_error_t cb_error = LCB_SUCCESS;         /* couchbase error status */

	/* create instance */
	cb_inst = couchbase_init_connection(inst->server, inst->bucket, inst->password);

	/* check couchbase instance status */
	if ((cb_error = lcb_get_last_error(cb_inst)) != LCB_SUCCESS) {
		ERROR("rlm_couchbase: failed to initiate couchbase connection: %s (0x%x)", lcb_strerror(NULL, cb_error), cb_error);
		/* destroy/free couchbase instance */
		lcb_destroy(cb_inst);
		/* fail */
		return NULL;
	}

	/* allocate memory for couchbase connection instance abstraction */
	chandle = talloc_zero(inst, rlm_couchbase_handle_t);
	cookie = talloc_zero(chandle, cookie_t);

	/* initialize cookie error holder */
	cookie->jerr = json_tokener_success;

	/* populate handle with allocated structs */
	chandle->cookie = cookie;
	chandle->handle = cb_inst;

	/* return handle struct */
	return chandle;
}
Пример #12
0
static void process_file(const char *fname)
{
    char *ptr = NULL;
    size_t size;
    cJSON *json, *id;
    lcb_error_t ret;
    int error = 0;
    lcb_store_cmd_t cmd;
    const lcb_store_cmd_t* const cmds[1] = { &cmd };

    if (fname[0] == '.') {
        if (strcmp(fname, ".dump_stats") == 0) {
            fprintf(stdout, "Dumping stats:\n");
            lcb_get_timings(instance, stdout, timings_callback);
            fprintf(stdout, "----\n");
            remove(fname);
        }
        return;
    }

    if (loadit(fname, &ptr, &size) == -1) {
        /* Error message already printed */
        return;
    }

    if ((json = cJSON_Parse(ptr)) == NULL) {
        invalid_file(INVALID_JSON, fname);
        free(ptr);
        return;
    }

    id = cJSON_GetObjectItem(json, "_id");
    if (id == NULL || id->type != cJSON_String) {
        invalid_file(UNKNOWN_JSON, fname);
        free(ptr);
        return;
    }

    memset(&cmd, 0, sizeof(cmd));
    cmd.v.v0.key = id->valuestring;
    cmd.v.v0.nkey = strlen(id->valuestring);
    cmd.v.v0.bytes = ptr;
    cmd.v.v0.nbytes = size;
    cmd.v.v0.operation = LCB_SET;

    ret = lcb_store(instance, &error, 1, cmds);
    if (ret == LCB_SUCCESS) {
        lcb_wait(instance);
    } else {
        error = 1;
    }

    free(ptr);
    if (error) {
        fprintf(stderr, "Failed to store %s: %s\n", fname,
                lcb_strerror(instance, ret));
    } else {
        remove(fname);
    }
}
Пример #13
0
SV *
PLCB__viewhandle_new(PLCB_t *parent,
    const char *ddoc, const char *view, const char *options, int flags)
{
    AV *req = NULL;
    SV *blessed;
    lcb_CMDVIEWQUERY cmd = { 0 };
    lcb_VIEWHANDLE vh = NULL;
    lcb_error_t rc;

    req = newAV();
    rowreq_init_common(parent, req);
    blessed = newRV_noinc((SV*)req);
    sv_bless(blessed, parent->view_stash);

    lcb_view_query_initcmd(&cmd, ddoc, view, options, viewrow_callback);
    cmd.cmdflags = flags; /* Trust lcb on this */
    cmd.handle = &vh;

    rc = lcb_view_query(parent->instance, req, &cmd);

    if (rc != LCB_SUCCESS) {
        SvREFCNT_dec(blessed);
        die("Couldn't issue view query: (0x%x): %s", rc, lcb_strerror(NULL, rc));
    } else {
        SvREFCNT_inc(req); /* For the callback */
        av_store(req, PLCB_VHIDX_VHANDLE, newSVuv(PTR2UV(vh)));
    }
    return blessed;
}
Пример #14
0
int main(void) {
    lcb_pool_t pool;
    lcb_t instance;
    struct lcb_create_st options;
    lcb_error_t error;

    /* set up the options to represent your cluster (hostname etc) */
    /* ... */

    /* Create the pool */
    error = pool_create(10, &options, &pool, initiate);
    if (error != LCB_SUCCESS) {
        fprintf(stderr, "Failed to create pool: %s\n",
                lcb_strerror(NULL, error));
        exit(EXIT_FAILURE);
    }

    /*
     * Every time you want to use libcouchbase you would grab an instance
     * from the pool by:
     */
    instance = pool_pop(pool);

    /* use the instance for whatever you wanted to do */


    /*
     * When you're done using the instance you would put it back into the
     * pool (and ready for others to use) by:
     */
    pool_push(pool, instance);

    return 0;
}
static void
ngx_lcb_upstream_init(ngx_http_request_t *r)
{
    ngx_http_core_loc_conf_t *clcf;
    ngx_lcb_connection_t *conn;
    ngx_connection_t *c;

    c = r->connection;
    if (c->read->timer_set) {
        ngx_del_timer(c->read);
    }
    if (ngx_event_flags & NGX_USE_CLEAR_EVENT) {
        if (!c->write->active) {
            if (ngx_add_event(c->write, NGX_WRITE_EVENT, NGX_CLEAR_EVENT) == NGX_ERROR) {
                ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
                return;
            }
        }
    }

    clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
    conn = ngx_http_get_couchbase_connection(clcf->name);
    if (conn == NULL) {
        ngx_log_error(NGX_LOG_ERR, c->log, 0,
                      "couchbase: connection not found: \"%V\"", &clcf->name);
        ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
        return;
    }
    if (conn->connected) {
        /* the instance has been connected */
        ngx_log_debug3(NGX_LOG_DEBUG_HTTP, c->log, 0,
                       "couchbase(%p): connection to \"%s:%s\" ready. process request",
                       (void *)conn->lcb, lcb_get_host(conn->lcb), lcb_get_port(conn->lcb));
        ngx_lcb_process(r);
    } else {
        lcb_error_t err;
        ngx_http_request_t **rp;

        rp = ngx_array_push(&conn->backlog);
        if (rp == NULL) {
            ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
            return;
        }
        *rp = r;
        if (!conn->connect_scheduled) {
            ngx_log_debug3(NGX_LOG_DEBUG_HTTP, c->log, 0,
                           "couchbase(%p): connecting to \"%s:%s\"",
                           (void *)conn->lcb, lcb_get_host(conn->lcb), lcb_get_port(conn->lcb));
            err = lcb_connect(conn->lcb);
            if (err != LCB_SUCCESS) {
                ngx_log_error(NGX_LOG_EMERG, c->log, 0,
                              "couchbase(%p): failed to initiate connection: 0x%02xd \"%s\"",
                              conn->lcb, err, lcb_strerror(NULL, err));
                ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
                return;
            }
            conn->connect_scheduled = 1;
        }
    }
}
Пример #16
0
static void do_memcached_flush(INTERNAL_FUNCTION_PARAMETERS,
							   int oo,
							   php_couchbase_res *res)
{
	lcb_error_t retval;
	lcb_error_t cberr = LCB_SUCCESS;
	php_couchbase_ctx *ctx;
	lcb_flush_cmd_t cmd;
	const lcb_flush_cmd_t *const commands[] = { &cmd };
	lcb_t instance;

	instance = res->handle;

	memset(&cmd, 0, sizeof(cmd));
	lcb_set_flush_callback(instance, memcached_flush_callback);
	retval = lcb_flush(instance, (const void *)&cberr, 1, commands);

	if (retval == LCB_SUCCESS) {
		retval = cberr;
	}
	res->rc = retval;

	if (retval == LCB_SUCCESS) {
		RETURN_TRUE;
	} else {
		char errmsg[256];
		sprintf(errmsg, "Failed to flush bucket: %s",
				lcb_strerror(instance, retval));
		couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
							   cb_lcb_exception, errmsg);
	}
}
Пример #17
0
/*opaque_t*/
int
couchdb_create(void)
{
	struct lcb_create_st create_opt;
	struct lcb_create_io_ops_st io_opts;
	lcb_error_t	ret;

	io_opts.version = 0;
	io_opts.v.v0.type = LCB_IO_OPS_DEFAULT;
	io_opts.v.v0.cookie = NULL;

	ret = lcb_create_io_ops(&create_opt.v.v0.io, &io_opts);
	if (ret != LCB_SUCCESS) {
		syslog(LOG_ERR, "%s:Failed to create IO instance: %s\n",
			__FUNCTION__, lcb_strerror(NULL, ret));
		return -1;
	}

	memset(&create_opt, 0, sizeof(struct lcb_create_st));
	create_opt.v.v0.host = "127.0.0.1:8091";
	create_opt.v.v0.user = "******";
	create_opt.v.v0.passwd = "123456";
	create_opt.v.v0.bucket = "default";

	ret = lcb_create(&couchdb_handle, &create_opt);

	if (ret != LCB_SUCCESS) {
		COUCHDB_LOG("Error creating couchbase DB instance\n");
		return (-1);
	}

	/* Setup the Global variables */
	value = (void *) malloc(DATA_SIZE *  sizeof(char));
	if (NULL == value) {
		syslog(LOG_ERR, "%s: Failed to allocate memory for value\n",
			__FUNCTION__);
		return -ENOMEM;
	}
	pthread_rwlock_init(&db_rwlock, NULL);

	/* Once a valid handle is obtained, set up all the callbacks */
	lcb_set_error_callback(couchdb_handle, error_cb);
	lcb_set_get_callback(couchdb_handle, get_cb);
	lcb_set_store_callback(couchdb_handle, set_cb);
	lcb_set_flush_callback(couchdb_handle, flush_cb);
	lcb_set_remove_callback(couchdb_handle, remove_cb);

	/* Now connect to the cluster having the server node on the "host" ip */
	ret = lcb_connect(couchdb_handle);
	if (ret != LCB_SUCCESS) {
		COUCHDB_LOG("Error connecting to the cluster\n");
		return (-1);
	}

	/* Since the couchbase APIs are all asynchronous calls, we need
	   to block the thread until the connect succeeds */
	lcb_wait(couchdb_handle);

	return (0);
}
/*Conditionally reconnect based on the error code*/
void couchbase_conditional_reconnect(cachedb_con *con, lcb_error_t err) {
	cachedb_pool_con *tmp;
	void *newcon;

	if (!con) return;

	switch (err) {
		/* Error codes to attempt reconnects on */
		case LCB_EINTERNAL:
		case LCB_CLIENT_ETMPFAIL:
		case LCB_EBADHANDLE:
		break;
		default:
			/*nothing to do*/
			return;
		break;
	}

	tmp = (cachedb_pool_con*)(con->data);
	LM_ERR("Attempting reconnect to Couchbase. Host: %s Bucket: %s On Error: %s",
		tmp->id->host, tmp->id->database, lcb_strerror(COUCHBASE_CON(con), err));

	newcon = couchbase_new_connection(tmp->id);

	/*Successful reconnect, get rid of the old handle*/
	if (newcon != NULL) {
		tmp->id = NULL;
		couchbase_free_connection(tmp);
		con->data = newcon;
	}
}
void
ngx_lcb_error_callback(lcb_t instance, lcb_error_t error, const char *errinfo)
{
    ngx_log_error(NGX_LOG_EMERG, lcb_cookie.log, 0,
                  "couchbase(%p): general error: %s (0x%xd), %s", instance,
                  lcb_strerror(instance, error), error, errinfo);
    exit(-1);
}
Пример #20
0
static void error_callback(lcb_t instance,
		lcb_error_t err,
		const char *errinfo)
{
	fprintf(stderr, "Error %s: %s", lcb_strerror(instance, err),
			errinfo ? errinfo : "");
	exit(EXIT_FAILURE);
}
Пример #21
0
static void couchbase_store_cb(lcb_t instance, const void *cookie,
							lcb_storage_t operation,
							lcb_error_t err,
							const lcb_store_resp_t *item)
{
	if (err != LCB_SUCCESS) {
		LM_ERR("Failure to store %.*s - %s\n",(int)item->v.v0.nkey,(char*)item->v.v0.key,lcb_strerror(instance, err));
	}
}
Пример #22
0
/** Couchbase callback for cluster statistics requests
 *
 * @param instance Couchbase connection instance.
 * @param cookie   Couchbase cookie for returning information from callbacks.
 * @param error    Couchbase error object.
 * @param resp     Couchbase statistics response object.
 */
void couchbase_stat_callback(lcb_t instance, const void *cookie, lcb_error_t error, const lcb_server_stat_resp_t *resp) {
	if (error != LCB_SUCCESS) {
		/* log error */
		ERROR("rlm_couchbase: (stats_callback) %s (0x%x)", lcb_strerror(instance, error), error);
	}
	/* silent compiler */
	(void)cookie;
	(void)resp;
}
Пример #23
0
static void storage_callback(lcb_t instance, const void *cookie, lcb_storage_t op,
   lcb_error_t err, const lcb_store_resp_t *resp)
{
  if (err != LCB_SUCCESS) {

    fprintf(stderr, "Got error in store callback: %s\n", lcb_strerror(instance,err));
  }
  fprintf(stderr, "set done, %s\n", resp->v.v0.key );
}
lcb_t AdFeedbackMgr::get_conn_from_pool()
{
    lcb_t ret;
    {
        boost::unique_lock<boost::mutex> dmp_pool_lock_;
        if (!dmp_conn_pool_.empty())
        {
            ret = dmp_conn_pool_.front();
            dmp_conn_pool_.pop_front();
            return ret;
        }
    }

    lcb_error_t err;
    struct lcb_create_st options;
    memset(&options, 0, sizeof(options));
    options.v.v0.host = dmp_server_ip_.c_str();
    options.v.v0.user = "******";
    options.v.v0.passwd = "";
    options.v.v0.bucket = "user_profile";
    err = lcb_create(&ret, &options);
    if (err != LCB_SUCCESS)
    {
        LOG(ERROR) << "failed to create couchbase connection." << lcb_strerror(NULL, err);
        return NULL;
    }
    lcb_set_error_callback(ret, err_callback);
    err = lcb_connect(ret);
    if (err != LCB_SUCCESS)
    {
        LOG(ERROR) << "failed to connect to couchbase." << lcb_strerror(NULL, err);
        lcb_destroy(ret);
        ret = NULL;
        return ret;
    }
    lcb_wait(ret);
    // usec for timeout.
    lcb_set_timeout(ret, 1000*100);
    lcb_set_get_callback(ret, get_callback);
    LOG(INFO) << "a new connection to DMP established";
    return ret;
}
static void get_callback(lcb_t instance, const void* cookie, lcb_error_t error, const lcb_get_resp_t *resp)
{
    if (error == LCB_SUCCESS)
    {
        std::string body((const char*)resp->v.v0.bytes, resp->v.v0.nbytes);
        AdFeedbackMgr::get()->setDMPRsp(std::string((const char*)cookie), body);
    }
    else if (error != LCB_KEY_ENOENT)
    {
        LOG(WARNING) << "couchbase get error." << lcb_strerror(instance, error);
    }
}
static void couchbase_remove_cb(lcb_t instance,
							const void *cookie,
							lcb_error_t err,
							const lcb_remove_resp_t *item)
{
	if (err != LCB_SUCCESS) {
		if (err != LCB_KEY_ENOENT) {
			LM_ERR("Failure to remove %.*s - %s\n",(int)item->v.v0.nkey,(char*)item->v.v0.key,lcb_strerror(instance, err));
		}
		last_error = err;
	}
}
Пример #27
0
/**
 * Whenever libcoucbase encounters an error it will call the error
 * callback. The error callback will also be called if a timeout
 * occur, so that we could generate alarms instead of having to
 * populate all of that logic into our callback handlers.
 *
 * In our example we'll ignore all timeouts, but treat any other error
 * fatal and terminate the program.
 *
 * @param instance the instance who threw the error
 * @param error the error condition that just happened
 * @param errinfo possibly more information about the error
 */
static void error_callback(lcb_t instance,
                           lcb_error_t error,
                           const char *errinfo)
{
    /* Ignore timeouts... */
    if (error != LCB_ETIMEDOUT) {
        fprintf(stderr, "\rFATAL ERROR: %s\n",
                lcb_strerror(instance, error));
        if (errinfo && strlen(errinfo) != 0) {
            fprintf(stderr, "\t\"%s\"\n", errinfo);
        }
        exit(EXIT_FAILURE);
    }
}
Пример #28
0
/** Check the health of a connection handle
 *
 * Attempt to determing the state of the Couchbase connection by requesting
 * a cluster statistics report.  Mark the connection as failed if the request
 * returns anything other than success.
 *
 * @param  instance The module instance (currently unused).
 * @param  handle   The connection handle.
 * @return          Returns 0 on success (alive) and -1 on error (unavailable).
 */
int mod_conn_alive(UNUSED void *instance, void *handle)
{
	rlm_couchbase_handle_t *chandle = handle;   /* connection handle pointer */
	lcb_t cb_inst = chandle->handle;            /* couchbase instance */
	lcb_error_t cb_error = LCB_SUCCESS;         /* couchbase error status */

	/* attempt to get server stats */
	if ((cb_error = couchbase_server_stats(cb_inst, NULL)) != LCB_SUCCESS) {
		/* log error */
		ERROR("rlm_couchbase: failed to get couchbase server stats: %s (0x%x)", lcb_strerror(NULL, cb_error), cb_error);
		/* error out */
		return -1;
	}
	return 0;
}
Пример #29
0
int couchbase_get(cachedb_con *connection,str *attr,str *val)
{
	lcb_t instance;
	lcb_error_t oprc;
	lcb_get_cmd_t cmd;
	const lcb_get_cmd_t *commands[1];

	instance = COUCHBASE_CON(connection);

	commands[0] = &cmd;
	memset(&cmd, 0, sizeof(cmd));
	cmd.v.v0.key = attr->s;
	cmd.v.v0.nkey = attr->len;
	oprc = lcb_get(instance, NULL, 1, commands);

	if (oprc != LCB_SUCCESS) {
		/* Key not present, record does not exist */
		if (oprc == LCB_KEY_ENOENT) {
			return -1;
		}

		//Attempt reconnect
		if (couchbase_conditional_reconnect(connection, oprc) != 1) {
			return -2;
		}

		//Try Again
		instance = COUCHBASE_CON(connection);
		oprc = lcb_get(instance, NULL, 1, commands);
		if (oprc != LCB_SUCCESS) {
			if (oprc == LCB_KEY_ENOENT) {
				LM_ERR("Get command successfully retried\n");
				return -1;
			}
			LM_ERR("Get command retry failed - %s\n", lcb_strerror(instance, oprc));
			return -2;
		}
		LM_ERR("Get command successfully retried\n");
	}

	//Incase of malloc failure
	if (!get_res.s) {
		return -2;
	}

	*val = get_res;
	return 1;
}
Пример #30
0
/** Couchbase callback for get (read) operations
 *
 * @param instance Couchbase connection instance.
 * @param cookie   Couchbase cookie for returning information from callbacks.
 * @param error    Couchbase error object.
 * @param resp     Couchbase get operation response object.
 */
void couchbase_get_callback(lcb_t instance, const void *cookie, lcb_error_t error, const lcb_get_resp_t *resp)
{
	cookie_u cu;                            /* union of const and non const pointers */
	cu.cdata = cookie;                      /* set const union member to cookie passed from couchbase */
	cookie_t *c = (cookie_t *) cu.data;     /* set our cookie struct using non-const member */
	const char *bytes = resp->v.v0.bytes;   /* the payload of this chunk */
	lcb_size_t nbytes = resp->v.v0.nbytes;  /* length of this data chunk */

	/* check error */
	switch (error) {
	case LCB_SUCCESS:
		/* check for valid bytes */
		if (bytes && nbytes > 1) {
			/* debug */
			DEBUG("rlm_couchbase: (get_callback) got %zu bytes", nbytes);
			/* parse string to json object */
			c->jobj = json_tokener_parse_ex(c->jtok, bytes, nbytes);
			/* switch on tokener error */
			switch ((c->jerr = json_tokener_get_error(c->jtok))) {
			case json_tokener_continue:
				/* check object - should be null */
				if (c->jobj != NULL) {
					ERROR("rlm_couchbase: (get_callback) object not null on continue!");
				}
				break;
			case json_tokener_success:
				/* do nothing */
				break;
			default:
				/* log error */
				ERROR("rlm_couchbase: (get_callback) json parsing error: %s",
				      json_tokener_error_desc(c->jerr));
				break;
			}
		}
		break;

	case LCB_KEY_ENOENT:
		/* ignored */
		DEBUG("rlm_couchbase: (get_callback) key does not exist");
		break;

	default:
		/* log error */
		ERROR("rlm_couchbase: (get_callback) %s (0x%x)", lcb_strerror(instance, error), error);
		break;
	}
}