static void
Bucket_dtor(pycbc_Bucket *self)
{
    if (self->flags & PYCBC_CONN_F_CLOSED) {
        lcb_destroy(self->instance);
        self->instance = NULL;
    }

    if (self->instance) {
        lcb_set_cookie(self->instance, NULL);
        pycbc_schedule_dtor_event(self);
    }

    Py_XDECREF(self->dtorcb);
    Py_XDECREF(self->dfl_fmt);
    Py_XDECREF(self->tc);
    Py_XDECREF(self->bucket);
    Py_XDECREF(self->conncb);
    Py_XDECREF(self->dur_testhook);
    Py_XDECREF(self->iopswrap);

    if (self->instance) {
        lcb_destroy(self->instance);
    }

#ifdef WITH_THREAD
    if (self->lock) {
        PyThread_free_lock(self->lock);
        self->lock = NULL;
    }
#endif

    Py_TYPE(self)->tp_free((PyObject*)self);
}
static lcb_error_t http_setup(lcb_t instance)
{
    char buffer[1024];
    lcb_ssize_t offset = 0;
    lcb_error_t err;
    lcb_connection_t conn = &instance->bootstrap.via.http.connection;
    struct lcb_http_bootstrap_st *http = &instance->bootstrap.via.http;

    http->weird_things_threshold = LCB_DEFAULT_CONFIG_ERRORS_THRESHOLD;
    http->bummer = 0;

    switch (instance->type) {
    case LCB_TYPE_BUCKET:
        offset = snprintf(buffer, sizeof(buffer),
                          "GET /pools/default/bucketsStreaming/%s HTTP/1.1\r\n",
                          instance->bucket);
        break;
    case LCB_TYPE_CLUSTER:
        offset = snprintf(buffer, sizeof(buffer), "GET /pools/ HTTP/1.1\r\n");
        break;
    default:
        return LCB_EINVAL;
    }

    err = lcb_connection_init(conn, instance);
    if (err != LCB_SUCCESS) {
        return err;
    }
    conn->data = instance;

    if (instance->password) {
        char cred[256];
        char base64[256];
        snprintf(cred, sizeof(cred), "%s:%s", instance->username, instance->password);
        if (lcb_base64_encode(cred, base64, sizeof(base64)) == -1) {
            lcb_destroy(instance);
            return LCB_EINTERNAL;
        }
        offset += snprintf(buffer + offset, sizeof(buffer) - (lcb_size_t)offset,
                           "Authorization: Basic %s\r\n", base64);
    }

    offset += snprintf(buffer + offset, sizeof(buffer) - (lcb_size_t)offset,
                       "%s", LCB_LAST_HTTP_HEADER);

    /* Add space for: Host: \r\n\r\n" */
    http->uri = malloc(strlen(buffer) + strlen(instance->config.backup_nodes[0]) + 80);
    if (http->uri == NULL) {
        lcb_destroy(instance);
        return LCB_CLIENT_ENOMEM;
    }
    strcpy(http->uri, buffer);

    return LCB_SUCCESS;
}
static PyObject *
Bucket__close(pycbc_Bucket *self)
{
    lcb_error_t err;

    if (self->flags & PYCBC_CONN_F_CLOSED) {
        Py_RETURN_NONE;
    }

    self->flags |= PYCBC_CONN_F_CLOSED;

    lcb_destroy(self->instance);

    if (self->iopswrap) {
        Py_XDECREF(self->iopswrap);
        self->iopswrap = NULL;
    }

    err = lcb_create(&self->instance, NULL);
    pycbc_assert(err == LCB_SUCCESS);
    if (err != LCB_SUCCESS) {
        PYCBC_EXC_WRAP(PYCBC_EXC_LCBERR,
                       err,
                       "Internal error while closing object");
        return NULL;
    }

    Py_RETURN_NONE;
}
static void
Connection_dtor(pycbc_Connection *self)
{
    if (self->instance) {
        lcb_destroy(self->instance);
        self->instance = NULL;
    }

    Py_XDECREF(self->dfl_fmt);
    Py_XDECREF(self->errors);
    Py_XDECREF(self->tc);
    Py_XDECREF(self->bucket);

    if (self->iops) {
        pycbc_iops_free(self->iops);
        self->iops = NULL;
    }

#ifdef WITH_THREAD
    if (self->lock) {
        PyThread_free_lock(self->lock);
        self->lock = NULL;
    }
#endif

    Py_TYPE(self)->tp_free((PyObject*)self);
}
Exemple #5
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;
}
int _tmain(int argc, _TCHAR* argv[])
{
	// initializing

	struct lcb_create_st cropts = { 0 };
	cropts.version = 3;
	cropts.v.v3.connstr = "couchbase://localhost/default";
	lcb_error_t err;
	lcb_t instance;
	err = lcb_create(&instance, &cropts);
	if (err != LCB_SUCCESS) {
		printf("Couldn't create instance!\n");
		exit(1);
	}

	// connecting

	lcb_connect(instance);
	lcb_wait(instance);
	if ((err = lcb_get_bootstrap_status(instance)) != LCB_SUCCESS) {
		printf("Couldn't bootstrap!\n");
		exit(1);
	}

	// installing callbacks

	lcb_set_store_callback(instance, storage_callback);
	lcb_set_get_callback(instance, get_callback);


	// scheduling operations

	lcb_store_cmd_t scmd;
	const lcb_store_cmd_t *scmdlist = &scmd;
	scmd.v.v0.key = "Hello";
	scmd.v.v0.nkey = 5;
	scmd.v.v0.bytes = "Couchbase";
	scmd.v.v0.nbytes = 9;
	scmd.v.v0.operation = LCB_SET;
	err = lcb_store(instance, NULL, 1, &scmdlist);
	if (err != LCB_SUCCESS) {
		printf("Couldn't schedule storage operation!\n");
		exit(1);
	}
	lcb_wait(instance); //storage_callback is invoked here

	lcb_get_cmd_t gcmd = { 0 };
	const lcb_get_cmd_t *gcmdlist = &gcmd;
	gcmd.v.v0.key = "Hello";
	gcmd.v.v0.nkey = 5;
	err = lcb_get(instance, NULL, 1, &gcmdlist);
	if (err != LCB_SUCCESS) {
		printf("Couldn't schedule get operation!\n");
		exit(1);
	}
	lcb_wait(instance); // get_callback is invoked here
	lcb_destroy(instance);
	return 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 = "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);
}
static void teardown(void)
{
    lcb_destroy(session);
    lcb_destroy_io_ops(io);
    session = NULL;
    io = NULL;
    shutdown_mock_server(mock);
    mock = NULL;
}
Exemple #9
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);
}
int main(int argc, char *argv[])
{
    lcb_error_t err;
    lcb_t instance;

    {
        struct lcb_create_st create_options = {};
        create_options.version = 3;

        if (argc < 2) {
            fprintf(stderr, "Usage: %s couchbase://host/bucket [ password [ username ] ]\n", argv[0]);
            exit(EXIT_FAILURE);
        }

        create_options.v.v3.connstr = argv[1];
        if (argc > 2) {
            create_options.v.v3.passwd = argv[2];
        }
        if (argc > 3) {
            create_options.v.v3.username = argv[3];
        }

        err = lcb_create(&instance, &create_options);
        if (err != LCB_SUCCESS) {
            die(NULL, "Couldn't create couchbase handle", err);
        }

        err = lcb_connect(instance);
        if (err != LCB_SUCCESS) {
            die(instance, "Couldn't schedule connection", err);
        }

        lcb_wait(instance);

        err = lcb_get_bootstrap_status(instance);
        if (err != LCB_SUCCESS) {
            die(instance, "Couldn't bootstrap from cluster", err);
        }

        lcb_install_callback3(instance, LCB_CALLBACK_GET, op_callback);
    }

    lcbcrypto_register(instance, "AES-256-HMAC-SHA256", osp_create());

    get_encrypted(instance, "secret-1");
    printf("\n");
    get_encrypted(instance, "secret-2");
    printf("\n");
    get_encrypted(instance, "secret-3");
    printf("\n");
    get_encrypted(instance, "secret-4");
    printf("\n");
    get_encrypted(instance, "secret-5");

    lcb_destroy(instance);
    return 0;
}
Exemple #11
0
/*
 * Name:	couchdb_destroy
 * Input Args:
 *	handle - handle to the lcb instance
 *
 * Description: Destroys the lcb instance
 */
int
couchdb_destroy(void)
{

	couchdb_flush();

	lcb_destroy(couchdb_handle);

	return (1);
}
/** Delete a conneciton pool handle and free related resources
 *
 * Destroys the underlying Couchbase connection handle freeing any related
 * resources and closes the socket connection.
 *
 * @param  chandle The connection handle to destroy.
 * @return         Always returns 0 (success) in all conditions.
 */
static int _mod_conn_free(rlm_couchbase_handle_t *chandle)
{
	lcb_t cb_inst = chandle->handle;                /* couchbase instance */

	/* destroy/free couchbase instance */
	lcb_destroy(cb_inst);

	/* return */
	return 0;
}
void AdFeedbackMgr::stop()
{
    boost::unique_lock<boost::mutex> dmp_pool_lock_;
    while (!dmp_conn_pool_.empty())
    {
        lcb_t ret = dmp_conn_pool_.front();
        dmp_conn_pool_.pop_front();
        lcb_destroy(ret);
    }
}
void couchbase_free_connection(cachedb_pool_con *con)
{
	couchbase_con * c;

	LM_DBG("in couchbase_free_connection\n");

	if (!con) return;
	c = (couchbase_con *)con;
	lcb_destroy(c->couchcon);
	pkg_free(c);
}
static lcb_error_t test_connect(char **argv, const char *username,
                                const char *password,
                                const char *bucket)
{
    const char *endpoint;
    lcb_error_t rc;
    struct lcb_create_st options;

    lcb_assert(session == NULL);
    lcb_assert(mock == NULL);
    lcb_assert(io == NULL);

    if (lcb_create_io_ops(&io, NULL) != LCB_SUCCESS) {
        fprintf(stderr, "Failed to create IO instance\n");
        exit(1);
    }

    mock = start_test_server(argv);
    if (mock == NULL) {
        err_exit("Failed to start mock server");
    }

    endpoint = get_mock_http_server(mock);

    memset(&options, 0, sizeof(options));
    options.version = 2;
    options.v.v2.host = endpoint;
    options.v.v2.user = username;
    options.v.v2.passwd = password;
    options.v.v2.bucket = bucket;
    options.v.v2.io = io;
    options.v.v2.transports = enabled_transports;

    if (lcb_create(&session, &options) != LCB_SUCCESS) {
        err_exit("Failed to create libcouchbase session");
    }

    (void)lcb_set_error_callback(session, error_callback2);

    if (lcb_connect(session) != LCB_SUCCESS) {
        err_exit("Failed to connect to server");
    }
    lcb_wait(session);
    rc = global_error;

    lcb_destroy(session);
    lcb_destroy_io_ops(io);
    session = NULL;
    io = NULL;
    shutdown_mock_server(mock);
    mock = NULL;

    return rc;
}
AdFeedbackMgr::~AdFeedbackMgr()
{
    for(std::list<lcb_t>::const_iterator it = dmp_conn_pool_.begin();
        it != dmp_conn_pool_.end(); ++it)
    {
        if (*it != NULL)
        {
            lcb_destroy(*it);
        }
    }
    dmp_conn_pool_.clear();
}
Exemple #17
0
/* free couchbase instance handle and any additional context memory */
int mod_conn_delete(UNUSED void *instance, void *handle) {
	rlm_couchbase_handle_t *chandle = handle;       /* connection instance handle */
	lcb_t cb_inst = chandle->handle;                /* couchbase instance */

	/* destroy/free couchbase instance */
	lcb_destroy(cb_inst);

	/* free handle */
	talloc_free(chandle);

	/* return */
	return true;
}
int main(int argc, char *argv[])
{
    lcb_STATUS err;
    lcb_INSTANCE *instance;
    char *bucket = NULL;
    size_t ii;

    if (argc < 2) {
        printf("Usage: %s couchbase://host/beer-sample [ password [ username ] ]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    {
        struct lcb_create_st create_options = {0};
        create_options.version = 3;
        create_options.v.v3.connstr = argv[1];
        if (argc > 2) {
            create_options.v.v3.passwd = argv[2];
        }
        if (argc > 3) {
            create_options.v.v3.username = argv[3];
        }
        check(lcb_create(&instance, &create_options), "create couchbase handle");
        check(lcb_connect(instance), "schedule connection");
        lcb_wait(instance);
        check(lcb_get_bootstrap_status(instance), "bootstrap from cluster");
        check(lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_BUCKETNAME, &bucket), "get bucket name");
        if (strcmp(bucket, "beer-sample") != 0) {
            fail("expected bucket to be \"beer-sample\"");
        }
    }

    {
        const char *stmt = "SELECT * FROM breweries LIMIT 2";
        lcb_CMDANALYTICS *cmd;
        int idx = 0;
        lcb_cmdanalytics_create(&cmd);
        lcb_cmdanalytics_callback(cmd, row_callback);
        lcb_cmdanalytics_statement(cmd, stmt, strlen(stmt));
        lcb_cmdanalytics_deferred(cmd, 1);
        check(lcb_analytics(instance, &idx, cmd), "schedule analytics query");
        printf("----> \x1b[36m%s\x1b[0m\n", stmt);
        lcb_cmdanalytics_destroy(cmd);
        lcb_wait(instance);
    }

    /* Now that we're all done, close down the connection handle */
    lcb_destroy(instance);
    return 0;
}
Exemple #19
0
void couchbase_shutdown_bucket(SHUTDOWN_FUNC_ARGS) {
    pcbc_lcb *cur, *next;
    next = PCBCG(first_bconn);
    while (next) {
        cur = next;
        next = cur->next;
        lcb_destroy(cur->lcb);
        free(cur->key);
        free(cur->bucket);
        free(cur);
    }
    PCBCG(first_bconn) = NULL;
    PCBCG(last_bconn) = NULL;
}
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;
}
int
main(int argc, char **argv)
{
    lcb_t instance;
    struct lcb_create_st cropts;
    lcb_error_t rc;

    memset(&cropts, 0, sizeof cropts);
    cropts.version = 3;
    cropts.v.v3.connstr = "couchbases://10.0.0.31/default?certpath=/tmp/couchbase-ssl-certificate.pem";

    rc = lcb_create(&instance, &cropts);
    if (rc != LCB_SUCCESS) {
        die(rc, "Creating instance");
    }

    rc = lcb_connect(instance);
    if (rc != LCB_SUCCESS) {
        die(rc, "Connection scheduling");
    }

    /* This function required to actually schedule the operations on the network */
    lcb_wait(instance);

    /* Determines if the bootstrap/connection succeeded */
    rc = lcb_get_bootstrap_status(instance);
    if (rc != LCB_SUCCESS) {
        die(rc, "Connection bootstraping");
    } else {
        printf("Connection succeeded. Cluster has %d nodes\n",
            lcb_get_num_nodes(instance));
    }

    /* SSL connections use different ports. For example, the REST API
     * connection will use port 18091 rather than 8091 when using SSL */
    const char *node = lcb_get_node(instance, LCB_NODE_HTCONFIG, 0);
    printf("First node address for REST API: %s\n", node);

    lcb_destroy(instance);
    return 0;
}
Exemple #22
0
/** Create a new connection pool handle
 *
 * Create a new connection to Couchbase within the pool and initialize
 * information associated with the connection instance.
 *
 * @param  ctx      The connection parent context.
 * @param  instance The module instance.
 * @param  timeout  Maximum time to establish the connection.
 * @return
 *	- New connection handle.
 *	- NULL on error.
 */
void *mod_conn_create(TALLOC_CTX *ctx, void *instance, struct timeval const *timeout)
{
	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;			    /* couchbase error status */

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

	/* check couchbase instance */
	if (cb_error != 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(ctx, rlm_couchbase_handle_t);
	talloc_set_destructor(chandle, _mod_conn_free);

	/* allocate cookie off handle */
	cookie = talloc_zero(chandle, cookie_t);

	/* init tokener error and json object */
	cookie->jerr = json_tokener_success;
	cookie->jobj = NULL;

	/* populate handle */
	chandle->cookie = cookie;
	chandle->handle = cb_inst;

	/* return handle struct */
	return chandle;
}
couchbase_con* couchbase_new_connection(struct cachedb_id* id)
{
	couchbase_con *con;
	struct lcb_create_st options;
	lcb_t instance;
	lcb_error_t rc;

	last_error = LCB_SUCCESS;

	if (id == NULL) {
		LM_ERR("null cachedb_id\n");
		return 0;
	}

	con = pkg_malloc(sizeof(couchbase_con));
	if (con == NULL) {
		LM_ERR("no more pkg \n");
		return 0;
	}

	memset(con,0,sizeof(couchbase_con));
	con->id = id;
	con->ref = 1;

	/* TODO - support custom ports - couchbase expects host:port in id->host */
	memset(&options,0,sizeof(struct lcb_create_st));
	options.version = 0;
	options.v.v0.host = id->host;
	options.v.v0.user = id->username;
	options.v.v0.passwd = id->password;
	options.v.v0.bucket = id->database;
	rc=lcb_create(&instance, &options);
	if (rc!=LCB_SUCCESS) {
		LM_ERR("Failed to create libcouchbase instance: 0x%02x, %s\n",
		       rc, lcb_strerror(NULL, rc));
		return 0;
	}


	(void)lcb_set_error_callback(instance,
			couchbase_error_cb);
	(void)lcb_set_get_callback(instance,
			couchbase_get_cb);
	(void)lcb_set_store_callback(instance,
			couchbase_store_cb);
	(void)lcb_set_remove_callback(instance,
			couchbase_remove_cb);
	(void)lcb_set_arithmetic_callback(instance,couchbase_arithmetic_cb);
	(void)lcb_set_timeout(instance,couch_timeout_usec);

	rc=lcb_connect(instance);
	if (rc != LCB_SUCCESS) {
		LM_ERR("Failed to connect to the Couchbase. Host: %s Bucket: %s Error: %s\n",
		       id->host, id->database, lcb_strerror(instance, rc));
		lcb_destroy(instance);
		return 0;
	}

	/* Wait for the connect to complete */
	lcb_wait(instance);

	/*Check connection*/
	if (last_error != LCB_SUCCESS) {
		/*Consider these connect failurs as fatal*/
		if(last_error == LCB_AUTH_ERROR || last_error == LCB_INVALID_HOST_FORMAT || last_error == LCB_INVALID_CHAR) {
			LM_ERR("Fatal connection error to Couchbase. Host: %s Bucket: %s Error: %s", 
				id->host, id->database, lcb_strerror(instance, last_error));
			lcb_destroy(instance);
			return 0;
		} else {
		/* Non-fatal errors, we may be able to connect later */
			LM_ERR("Non-Fatal connection error to Couchbase. Host: %s Bucket: %s Error: %s", 
				id->host, id->database, lcb_strerror(instance, last_error));
		}
	} else {
		LM_DBG("Succesfully connected to Couchbase Server. Host: %s Bucket: %s\n", id->host, id->database);
	}

	con->couchcon = instance;
	return con;
}
Exemple #24
0
int main(void)
{
  struct lcb_create_st create_options;
  memset(&create_options, 0, sizeof create_options);
  create_options.version = 3;
  create_options.v.v3.connstr = "couchbase://10.141.95.101/default";
  // create_options.v.v3.passwd = "testbucket";
  lcb_error_t err;

  lcb_t instance = NULL;
  err = lcb_create(&instance, &create_options);
  if (err != LCB_SUCCESS) {
    fprintf(stderr, "Failed to create a couchbase instance: %s\n", lcb_strerror(instance,err));
    return 1;
  }
  // Default timeout values and settings:
  //http://developer.couchbase.com/documentation/server/current/sdks/c-2.4/options.html
  //Enable details error codes:
  lcb_cntl_string(instance,"detailed_errcodes","1");

  //Connecting
  lcb_connect(instance);
  lcb_wait(instance);
  if ( (err = lcb_get_bootstrap_status(instance)) != LCB_SUCCESS ) {
    printf("Couldn't bootstrap. Exiting!\n");
    exit(1);
  }

  // installing callbacks
  lcb_set_store_callback(instance, storage_callback);
  lcb_set_durability_callback(instance, durability_callback);

  // scheduling set operations with elements that expire
  lcb_store_cmd_t scmd = { 0 };
  const lcb_store_cmd_t *scmdlist = &scmd;
/*
    INSERT, Loop through x number of keys and insert them with expiry
*/
  for( int counter=1; counter <= NUMBER_OF_DOCUMENTS; counter++){
      // Setting keys and values
      const char *doc = "{\"json\" : \"data\" }";
      char key [12];
      sprintf(key, "%s%d", "test", counter);
      scmd.v.v0.key = key;
      scmd.v.v0.nkey = strlen(key);
      scmd.v.v0.bytes = doc;
      scmd.v.v0.nbytes = strlen(doc);
      scmd.v.v0.exptime = 300; //expiry of 5 minutes
      scmd.v.v0.operation = LCB_SET;

      err = lcb_store(instance, NULL, 1, (const lcb_store_cmd_t * const *)&scmdlist);
      if (err != LCB_SUCCESS) {
        printf("Couldn't schedule storage operation!\n");
        exit(1);
      }
      lcb_wait(instance);

      //Durability is invoked here
      lcb_durability_opts_t options;
      lcb_durability_cmd_t cmd = { 0 };
      const lcb_durability_cmd_t *cmdp = &cmd;
      cmd.v.v0.key = key;
      cmd.v.v0.nkey = strlen(key);
      options.v.v0.persist_to = 1;
      options.v.v0.replicate_to = 1;

      err = lcb_durability_poll(instance,NULL,&options,1,&cmdp);
      if (err != LCB_SUCCESS) {
        printf("couldn't schedule durability operation %s \n", lcb_strerror(instance, err));
      }
    lcb_wait(instance);
  }
  //closing the connection
  lcb_destroy(instance);
  return 0;
}
// Main 
int main(int argc, char* argv[])
{
  printf("Welcome.\n");

  // Do this once
  srand(time(NULL));

  // initializing
  struct lcb_create_st cropts = { 0 };
  cropts.version = 3;
  cropts.v.v3.connstr = "couchbase://localhost/default";
  // cropts.v.v3.connstr = "couchbase://192.168.38.101/default";
  lcb_error_t create_err;
  lcb_t instance;
  create_err = lcb_create(&instance, &cropts);
  if (create_err != LCB_SUCCESS) {
    printf("Couldn't create instance!\n");
    exit(1);
  }
  
  // connecting
  lcb_connect(instance);
  lcb_wait(instance);
  lcb_error_t bootstrap_status_err;
  if ( (bootstrap_status_err = lcb_get_bootstrap_status(instance)) != LCB_SUCCESS ) {
    printf("Couldn't bootstrap!\n");
    exit(1);
  }
  
  // installing callbacks
  lcb_set_store_callback(instance, storage_callback);
  lcb_set_get_callback(instance, get_callback);
  lcb_set_arithmetic_callback(instance, arithmetic_callback); 
  lcb_set_touch_callback(instance, touch_callback); 
  lcb_set_remove_callback(instance, remove_callback); 

  // Main part of the program
  int numTimesToRun = 10;   // specify how many times to iterate
  int useARandomKey = 1;    // specify whether to use a random or sequential key

  char keyNameBuffer[100];

  int i = 0;

  for (i = 0; i < numTimesToRun; i++) {

    if (useARandomKey == 0) {
	// Do NOT use a random key
        sprintf(keyNameBuffer, "NonRandomKey%d", i);
    }
    else {
	// Use a random key, generate a new one for each iteration of the loop
        int randomNumber = rand();
        sprintf(keyNameBuffer, "randomKey%d", randomNumber);
    }

    printf("#### Iteration: %5d Key: %10s\n", i, keyNameBuffer);

    // Create-Increment
    blockingArithmeticIncrement2(instance, keyNameBuffer); 

    // Make sure its there
    blockingGet(instance, keyNameBuffer); 

    // Delete
    blockingRemove(instance, keyNameBuffer); 

    // Sleep 60
    printf("About to sleep...\n");
    sleep(1);
    printf("Done with sleep...\n");
    
    // Touch, should fail
    blockingTouch2(instance, 60, keyNameBuffer);

    // Increment
    blockingArithmeticIncrement2(instance, keyNameBuffer); 
    
    // Touch
    blockingTouch2(instance, 60, keyNameBuffer);

    printf("##### touches that worked: %d touches that failed %d\n", touchesWorked, touchesFailed);

  } // loop for numTimesToRun

  printf("Almost done.  Calling lcb_destroy()\n");
  lcb_destroy(instance);

  printf("Goodbye\n");

  return 0;
}
Exemple #26
0
int main(int argc, char*argv[]) 
{
	//couchbase error type
	lcb_error_t err;
	//couchbase type
	lcb_t instance;
	// couchbase create struct? its a struct with options to create what? a cb cluster, bucket or something else?
	struct lcb_create_st create_options = {0};
	memset(&create_options,0,sizeof(create_options));
	// set command type, and creating a list of store commands?
	lcb_store_cmd_t scmd = {0};
	const lcb_store_cmd_t *scmdlist[1];
	// get command type, and list of get commands!
	lcb_get_cmd_t gcmd = {0};
	const lcb_get_cmd_t *gcmdlist[1];

	create_options.version = 3; // cb version 3?

	if (argc < 2) 
	{
		fprintf(stderr, "Usage: %s couchbase://host/bucket [password] \n",argv[0] );
		exit(EXIT_FAILURE);		
	}

	create_options.v.v3.connstr = argv[1];
	if (argc >=3)
	{
		create_options.v.v3.passwd = argv[2];
	}
	
	//fprintf(stderr, "\n %s,%s,%s\n",create_options.v.v3.connstr,create_options.v.v3.passwd,"test" );
	/*
	create_options.version = 3;
	create_options.v.v3.connstr = "couchbase://192.168.56.101/pramod";
	create_options.v.v3.passwd = "couchbase";
	*/
	err = lcb_create(&instance, &create_options);
	if(err != LCB_SUCCESS)
	{
		die(instance, "Couldn't create couchbase handle", err);
	}

	err = lcb_connect(instance);
	if(err != LCB_SUCCESS) 
	{
		die(instance, "Couldn't schedule connection", err);
	}
	lcb_wait(instance);	// It says this will be blocking wait and won't execute in a async fashion


	err = lcb_get_bootstrap_status(instance);
	if (err != LCB_SUCCESS) 
	{
		die(instance, "Couldn't bootstrap from cluster", err);
	}
	// Assign the handlers to be called for the operations types
	lcb_set_get_callback(instance, get_callback);
	lcb_set_store_callback(instance, store_callback);
	//what are these callbacks for ? I thought callbacks are for getting results of asynchronous exectution of jobs?
	

	// what is happening in here? setting values? to the source command ? 
	//let my try to wrap this up in a loop to set a 1000 values?

	
	scmd.v.v0.operation = LCB_SET;
	scmd.v.v0.key = "foo";		scmd.v.v0.nkey = 3 ;
	scmd.v.v0.bytes = "barbeque";	scmd.v.v0.nbytes = 8;
	scmdlist[0] = &scmd;

	err = lcb_store(instance, NULL, 1, scmdlist);	// so here is where the data is getting written!!
	if (err != LCB_SUCCESS) 
	{
		die (instance, "Coudn't schedule storage operations", err);
	}

	// the store_callback is involed from lcb_wait()
	fprintf(stderr, "Will wait for storage operation to complete\n");
	lcb_wait(instance);




	//now fetch the items back
	gcmd.v.v0.key = "foo";
	gcmd.v.v0.nkey = 3;
	gcmd.v.v0.exptime = 60;
	gcmdlist[0] = &gcmd;
	err = lcb_get(instance, NULL, 1, gcmdlist);
	if (err != LCB_SUCCESS) 
	{
		die(instance, "Couldn't schedule retrieval operation", err);
	}

	// get callback invoked from here.
	fprintf(stderr, "Will wait to retrieve the set item!\n");
	lcb_wait(instance);

	// close the connection handle after everything is done
	lcb_destroy(instance);
	return 0;
}
Exemple #27
0
int main(int argc, char *argv[])
{
    char *method = NULL;
    char *key = NULL;
    lcb_error_t err;
    lcb_t instance;
    struct lcb_create_st create_options;
    struct lcb_create_io_ops_st io_opts;

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

    memset(&create_options, 0, sizeof(create_options));
    err = lcb_create_io_ops(&create_options.v.v0.io, &io_opts);
    if (err != LCB_SUCCESS) {
        fprintf(stderr, "Failed to create IO instance: %s\n",
                lcb_strerror(NULL, err));
        return 1;
    }

    if (argc > 1) {
        create_options.v.v0.host = argv[1];
    }
    if (argc > 2) {
        create_options.v.v0.user = argv[2];
        create_options.v.v0.bucket = argv[2];
    }
    if (argc > 3) {
        create_options.v.v0.passwd = argv[3];
    }
    if (argc > 4) {
        method = argv[4];
    }
    if (argc > 5) {
        key = argv[5];
    }
    int count = 1;
    if (argc > 6) {
        count = atoi(argv[6]);
    }
    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;
    }
    (void)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));
        lcb_destroy(instance);
        return 1;
    }
    (void)lcb_set_get_callback(instance, get_callback);
    (void)lcb_set_store_callback(instance, store_callback);
    /* Run the event loop and wait until we've connected */
    lcb_wait(instance);
    if (method == NULL || strcmp(method, "set") == 0)
    {
		err = form_command(err, instance, key, count);
        if (err != LCB_SUCCESS) {
            fprintf(stderr, "Failed to store: %s\n", lcb_strerror(NULL, err));
            return 1;
        }

        form_command(err, instance, "fra", 1);

    }
    lcb_wait(instance);

    lcb_wait(instance);
    if (method == NULL || strcmp(method, "fset") == 0)
    {
    	err = form_command_fset(err, instance, "fra");
    	if (err != LCB_SUCCESS) {
    		fprintf(stderr, "Failed to fragment store: %s\n", lcb_strerror(NULL, err));
    		return 1;
    	}
    }
    if (method == NULL || strcmp(method, "get") == 0)
    {
		err = form_command_get(count, err, instance, key);
        if (err != LCB_SUCCESS) {
            fprintf(stderr, "Failed to get: %s\n", lcb_strerror(NULL, err));
            return 1;
        }
    }
    lcb_wait(instance);
    lcb_destroy(instance);

    return 0;
}
LIBCOUCHBASE_API
lcb_error_t lcb_create(lcb_t *instance,
                       const struct lcb_create_st *options)
{
    const char *host = NULL;
    const char *user = NULL;
    const char *passwd = NULL;
    const char *bucket = NULL;

    struct lcb_io_opt_st *io = NULL;
    struct lcb_create_st options_container;
    struct lcb_create_st2 *e_options = &options_container.v.v2;

    lcb_type_t type = LCB_TYPE_BUCKET;
    lcb_t obj;
    lcb_error_t err;
    lcb_settings *settings;

    err = normalize_options(&options_container, options);

    if (err != LCB_SUCCESS) {
        return err;
    }

    host = get_nonempty_string(e_options->host);
    user = get_nonempty_string(e_options->user);
    passwd = get_nonempty_string(e_options->passwd);
    bucket = get_nonempty_string(e_options->bucket);
    io = e_options->io;
    type = e_options->type;

    if (type == LCB_TYPE_CLUSTER && user == NULL && passwd == NULL) {
        return LCB_EINVAL;
    }

    if (host == NULL) {
        host = "localhost";
    }

    if (bucket == NULL) {
        bucket = "default";
    }

    /* Do not allow people use Administrator account for data access */
    if (type == LCB_TYPE_BUCKET && user && strcmp(user, bucket) != 0) {
        return LCB_INVALID_USERNAME;
    }

    if ((obj = calloc(1, sizeof(*obj))) == NULL) {
        return LCB_CLIENT_ENOMEM;
    }

    obj->type = type;
    obj->compat.type = (lcb_compat_t)0xdead;

    if (io == NULL) {
        lcb_io_opt_t ops;
        if ((err = lcb_create_io_ops(&ops, NULL)) != LCB_SUCCESS) {
            /* You can't initialize the library without a io-handler! */
            free(obj);
            return err;
        }
        io = ops;
        io->v.v0.need_cleanup = 1;
    }

    settings = &obj->settings;
    settings->randomize_bootstrap_nodes = 1;
    settings->bummer = 0;
    settings->io = io;
    obj->syncmode = LCB_ASYNCHRONOUS;
    settings->ipv6 = LCB_IPV6_DISABLED;

    settings->operation_timeout = LCB_DEFAULT_TIMEOUT;
    settings->config_timeout = LCB_DEFAULT_CONFIGURATION_TIMEOUT;
    settings->config_node_timeout = LCB_DEFAULT_NODECONFIG_TIMEOUT;
    settings->views_timeout = LCB_DEFAULT_VIEW_TIMEOUT;
    settings->rbufsize = LCB_DEFAULT_RBUFSIZE;
    settings->wbufsize = LCB_DEFAULT_WBUFSIZE;
    settings->durability_timeout = LCB_DEFAULT_DURABILITY_TIMEOUT;
    settings->durability_interval = LCB_DEFAULT_DURABILITY_INTERVAL;
    settings->http_timeout = LCB_DEFAULT_HTTP_TIMEOUT;
    settings->weird_things_threshold = LCB_DEFAULT_CONFIG_ERRORS_THRESHOLD;
    settings->weird_things_delay = LCB_DEFAULT_CONFIG_ERRORS_DELAY;
    settings->max_redir = LCB_DEFAULT_CONFIG_MAXIMUM_REDIRECTS;
    settings->grace_next_cycle = LCB_DEFAULT_CLCONFIG_GRACE_CYCLE;
    settings->grace_next_provider = LCB_DEFAULT_CLCONFIG_GRACE_NEXT;
    settings->bc_http_stream_time = LCB_DEFAULT_BC_HTTP_DISCONNTMO;
    settings->bucket = strdup(bucket);
    settings->logger = lcb_init_console_logger();
    settings->iid = lcb_instance_index++;


    if (user) {
        settings->username = strdup(user);
    } else {
        settings->username = strdup(settings->bucket);
    }

    if (passwd) {
        settings->password = strdup(passwd);
    }

    lcb_initialize_packet_handlers(obj);

    obj->memd_sockpool = connmgr_create(settings, io);
    obj->memd_sockpool->max_idle = 1;
    obj->memd_sockpool->idle_timeout = 10000000;

    obj->confmon = lcb_confmon_create(settings);
    obj->usernodes = hostlist_create();

    /** We might want to sanitize this a bit more later on.. */
    if (strstr(host, "://") != NULL && strstr(host, "http://") == NULL) {
        lcb_destroy(obj);
        return LCB_INVALID_HOST_FORMAT;
    }


    err = hostlist_add_string(obj->usernodes, host, -1, LCB_CONFIG_HTTP_PORT);
    if (err != LCB_SUCCESS) {
        lcb_destroy(obj);
        return err;
    }

    err = lcb_init_providers(obj, e_options);
    if (err != LCB_SUCCESS) {
        lcb_destroy(obj);
        return err;
    }

    lcb_initialize_packet_handlers(obj);

    obj->timers = hashset_create();
    obj->http_requests = hashset_create();
    obj->durability_polls = hashset_create();
    /* No error has occurred yet. */
    obj->last_error = LCB_SUCCESS;
    if ((obj->cmdht = lcb_hashtable_szt_new(32)) == NULL) {
        lcb_destroy(obj);
        return LCB_CLIENT_ENOMEM;
    }


    if (!ringbuffer_initialize(&obj->purged_buf, 4096)) {
        lcb_destroy(obj);
        return LCB_CLIENT_ENOMEM;
    }
    if (!ringbuffer_initialize(&obj->purged_cookies, 4096)) {
        lcb_destroy(obj);
        return LCB_CLIENT_ENOMEM;
    }

    *instance = obj;
    return LCB_SUCCESS;
}
Exemple #29
0
PHP_METHOD(Bucket, __construct)
{
    bucket_object *data = PCBC_PHP_THISOBJ();
    zval *zdsn = NULL;
    zval *zname = NULL;
    zval *zpassword = NULL;
    char *dsn = NULL;
    char *name = NULL;
    char *password = NULL;
    lcb_error_t err;
    lcb_t instance;
    struct lcb_create_st create_options;
    char *connkey = NULL;
    pcbc_lcb *conn_iter, *conn;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zzz",
                              &zdsn, &zname, &zpassword) == FAILURE) {
        RETURN_NULL();
    }

    if (zap_zval_is_undef(zdsn)) {
        zdsn = NULL;
    }
    if (zap_zval_is_undef(zname)) {
        zname = NULL;
    }
    if (zap_zval_is_undef(zpassword)) {
        zpassword = NULL;
    }

    if (zdsn) {
        if (Z_TYPE_P(zdsn) == IS_STRING) {
            dsn = estrndup(Z_STRVAL_P(zdsn), Z_STRLEN_P(zdsn));
        } else {
            throw_pcbc_exception("Expected dsn as string", LCB_EINVAL);
            RETURN_NULL();
        }
    }

    if (zname) {
        if (Z_TYPE_P(zname) == IS_STRING) {
            name = estrndup(Z_STRVAL_P(zname), Z_STRLEN_P(zname));
        } else {
            throw_pcbc_exception("Expected bucket name as string", LCB_EINVAL);
            if (dsn) efree(dsn);
            RETURN_NULL();
        }
    }

    if (zpassword) {
        if (Z_TYPE_P(zpassword) == IS_STRING) {
            password = estrndup(Z_STRVAL_P(zpassword), Z_STRLEN_P(zpassword));
        } else {
            throw_pcbc_exception("Expected bucket password as string", LCB_EINVAL);
            if (dsn) efree(dsn);
            if (name) efree(name);
            RETURN_NULL();
        }
    }

    spprintf(&connkey, 512, "%s|%s|%s",
             dsn ? dsn : "",
             name ? name : "",
             password ? password : "");

    conn_iter = PCBCG(first_bconn);
    while (conn_iter) {
        if (strcmp(conn_iter->key, connkey) == 0) {
            break;
        }
        conn_iter = conn_iter->next;
    }

    if (!conn_iter)
    {
        memset(&create_options, 0, sizeof(create_options));
        create_options.version = 3;
        create_options.v.v3.connstr = dsn;
        create_options.v.v3.username = name;
        create_options.v.v3.passwd = password;
        create_options.v.v3.type = LCB_TYPE_BUCKET;
        err = lcb_create(&instance, &create_options);

        if (dsn) efree(dsn);
        if (password) efree(password);

        if (err != LCB_SUCCESS) {
            efree(connkey);
            efree(name);
            throw_lcb_exception(err);
            RETURN_NULL();
        }
        lcb_cntl(instance, LCB_CNTL_SET, LCB_CNTL_CLIENT_STRING, pcbc_client_string);

        lcb_install_callback3(instance, LCB_CALLBACK_GET, get_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_UNLOCK, unlock_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_STORE, store_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_STOREDUR, store_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_REMOVE, remove_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_TOUCH, touch_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_COUNTER, counter_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_SDLOOKUP, subdoc_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_SDMUTATE, subdoc_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_HTTP, http_callback);

        lcb_set_durability_callback(instance, durability_callback);


        err = lcb_connect(instance);
        if (err != LCB_SUCCESS) {
            efree(connkey);
            efree(name);
            lcb_destroy(instance);
            throw_lcb_exception(err);
            RETURN_NULL();
        }

        // We use lcb_wait here as no callbacks are invoked by connect.
        lcb_wait(instance);

        err = lcb_get_bootstrap_status(instance);
        if (err != LCB_SUCCESS) {
            efree(connkey);
            efree(name);
            lcb_destroy(instance);
            throw_lcb_exception(err);
            RETURN_NULL();
        }

        conn = pemalloc(sizeof(pcbc_lcb), 1);
        conn->bucket = pestrdup(name, 1);
        efree(name);
        conn->key = pestrdup(connkey, 1);
        conn->lcb = instance;
        conn->next = NULL;
        data->conn = conn;

        if (PCBCG(last_bconn)) {
            PCBCG(last_bconn)->next = conn;
            PCBCG(last_bconn) = conn;
        } else {
            PCBCG(first_bconn) = conn;
            PCBCG(last_bconn) = conn;
        }
    } else {
        if (dsn) efree(dsn);
        if (name) efree(name);
        if (password) efree(password);

        data->conn = conn_iter;
    }

    efree(connkey);
}
Exemple #30
0
int main(void)
{

  // initializing
  struct lcb_create_st create_options;
  memset(&create_options, 0, sizeof create_options);
  create_options.version = 3;
  create_options.v.v3.connstr = "couchbase://10.141.110.101,10.141.110.102,10.141.110.103/testbucket";
  create_options.v.v3.passwd = "testbucket";
  lcb_error_t err;
  lcb_t instance = NULL;
  err = lcb_create(&instance, &create_options);
  if (err != LCB_SUCCESS) {
    fprintf(stderr, "Failed to create a couchbase instance: %s\n", lcb_strerror(instance,err));
    return 1;
  }
// Default timeout values and settings: http://developer.couchbase.com/documentation/server/current/sdks/java-2.2/env-config.html
//Enable details error codes:
//http://developer.couchbase.com/documentation/server/current/sdks/c-2.4/options.html
  lcb_cntl_string(instance,"detailed_errcodes","1");

  //connecting
  lcb_connect(instance);
  lcb_wait(instance);
  if ( (err = lcb_get_bootstrap_status(instance)) != LCB_SUCCESS ) {
    printf("Couldn't bootstrap. Exiting!\n");
    exit(1);
  }
  sleep(20);
  
  // installing callbacks
  lcb_set_store_callback(instance, storage_callback);
  lcb_set_get_callback(instance, get_callback);

  
  // scheduling set operations with elements that expire
  lcb_store_cmd_t scmd = { 0 };
  const lcb_store_cmd_t *scmdlist = &scmd;
/*
    INSERT, Loop through x number of keys and insert them with expiry
*/

  for( int counter=0; counter <NUMBER_OF_DOCUMENTS; counter ++){
      // Setting keys and values
      const char *doc = "{\"json\" : \"data\" }";
      char key [12];
      sprintf(key, "%s%d", "test", counter);
      scmd.v.v0.key = key;
      scmd.v.v0.nkey = strlen(key);
      scmd.v.v0.bytes = doc;
      scmd.v.v0.nbytes = strlen(doc);
//      scmd.v.v0.exptime = 300; //expiry of 5 minutes
      scmd.v.v0.operation = LCB_SET;

      err = lcb_store(instance, NULL, 1, &scmdlist);
      if (err != LCB_SUCCESS) {
        printf("Couldn't schedule storage operation!\n");
        exit(1);
      }
      lcb_wait(instance); //storage_callback is invoked here
  }


/*
    GET section
*/
  lcb_get_cmd_t gcmd = { 0 };
  const lcb_get_cmd_t *gcmdlist = &gcmd;
    for( int counter=0; counter <NUMBER_OF_DOCUMENTS; counter ++){
         char key[12];
//         sleep(3);
         sprintf(key,"%s%d", "test", counter);
         gcmd.v.v0.key = key;
         gcmd.v.v0.nkey = strlen(key);
         fprintf(stderr, "GET : %s\n", key);
//         printf("GET %s\n", key);
         err = lcb_get(instance, NULL, 1, &gcmdlist);
         lcb_wait(instance); // get_callback is invoked here
    }

  //closing the connection
  lcb_destroy(instance);
  return 0;
}