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); }
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_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; }
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); } }
ERL_NIF_TERM cb_unlock(ErlNifEnv* env, handle_t* handle, void* obj) { unlock_args_t* args = (unlock_args_t*)obj; struct libcouchbase_callback cb; lcb_error_t ret; lcb_unlock_cmd_t unlock; memset(&unlock, 0, sizeof(unlock)); unlock.v.v0.key = args->key; unlock.v.v0.nkey = args->nkey; unlock.v.v0.cas = args->cas; const lcb_unlock_cmd_t* commands[] = { &unlock }; ret = lcb_unlock(handle->instance, &cb, 1, commands); free(args->key); if (ret != LCB_SUCCESS) { return return_lcb_error(env, ret); } lcb_wait(handle->instance); if(cb.error != LCB_SUCCESS) { return return_lcb_error(env, cb.error); } return A_OK(env); }
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; } }
/** Store a document by key in Couchbase * * Setup and execute a Couchbase set operation and wait for the result. * * @param instance Couchbase connection instance. * @param key Document key to store in the database. * @param document Document body to store in the database. * @param expire Expiration time for the document (0 = never) * @return Couchbase error object. */ lcb_error_t couchbase_set_key(lcb_t instance, const char *key, const char *document, int expire) { lcb_error_t error; /* couchbase command return */ lcb_store_cmd_t cmd; /* store command stuct */ const lcb_store_cmd_t *commands[1]; /* store commands array */ /* init commands */ commands[0] = &cmd; memset(&cmd, 0, sizeof(cmd)); /* populate command struct */ cmd.v.v0.key = key; cmd.v.v0.nkey = strlen(cmd.v.v0.key); cmd.v.v0.bytes = document; cmd.v.v0.nbytes = strlen(cmd.v.v0.bytes); cmd.v.v0.exptime = expire; cmd.v.v0.operation = LCB_SET; /* store key/document in couchbase */ if ((error = lcb_store(instance, NULL, 1, commands)) == LCB_SUCCESS) { /* enter event loop on success */ lcb_wait(instance); } /* return error */ return error; }
// Doing a touch will set the expiration time of the item // http://docs.couchbase.com/sdk-api/couchbase-c-client-2.4.6/group__lcb-touch.html void blockingTouch(lcb_t instance, int expTimeSeconds, char *keyName) { int keyLength = strlen(keyName); lcb_error_t touchErrorCode = 0; lcb_touch_cmd_t *touchCommand = calloc(1, sizeof(*touchCommand)); touchCommand->v.v0.key = keyName; touchCommand->v.v0.nkey = keyLength; touchCommand->v.v0.exptime = expTimeSeconds; touchCommand->v.v0.lock = 0; const lcb_touch_cmd_t *touchCommandList[] = { touchCommand }; touchErrorCode = lcb_touch(instance, NULL, 1, touchCommandList); if (touchErrorCode != LCB_SUCCESS) { printf("Couldn't schedule touch operation!\n"); printf("lcb_touch errorCode is 0x%.8X \n", touchErrorCode); exit(1); } printf("TOUCH: About to do lcb_wait()...\n"); lcb_wait(instance); printf("TOUCH: Back from lcb_wait()...\n"); } // end of blockingTouch()
static void blockingRemove(lcb_t instance, char*keyName) { int keyLength = strlen(keyName); lcb_error_t removeErrorCode = 0; lcb_remove_cmd_t *removeCommand = calloc(1,sizeof(*removeCommand)); removeCommand->version = 0; removeCommand->v.v0.key = keyName; removeCommand->v.v0.nkey = keyLength; removeCommand->v.v0.cas = 0; const lcb_remove_cmd_t* removeCommands[] = { removeCommand }; removeErrorCode = lcb_remove(instance, NULL, 1, removeCommands); if (removeErrorCode != LCB_SUCCESS) { printf("Couldn't schedule remove operation!\n"); printf("lcb_remove errorCode is 0x%.8X \n", removeErrorCode); exit(1); } printf("REMOVE: About to do lcb_wait()...\n"); lcb_wait(instance); printf("REMOVE: Back from lcb_wait()...\n"); }
// Given an LCB instance and a key name, create an arithmetic, and // wait until it finishes, and if there is an error, display it. static void OrigrBlockingArithmeticCreate(lcb_t instance, char *keyName, int expTimeSeconds) { int keyLength = strlen(keyName); lcb_error_t arithmeticCreateErrorCode = 0; lcb_arithmetic_cmd_t *arithmeticCommand = calloc(1, sizeof(*arithmeticCommand)); arithmeticCommand->version = 0; arithmeticCommand->v.v0.key = keyName; arithmeticCommand->v.v0.nkey = keyLength; arithmeticCommand->v.v0.exptime = expTimeSeconds; arithmeticCommand->v.v0.create = 1; arithmeticCommand->v.v0.delta = 1; arithmeticCommand->v.v0.initial = 1234500; const lcb_arithmetic_cmd_t* arithCommands[] = { arithmeticCommand }; arithmeticCreateErrorCode = lcb_arithmetic(instance, NULL, 1, arithCommands); if (arithmeticCreateErrorCode != LCB_SUCCESS) { printf("Couldn't schedule arithmeetic create operation!\n"); printf("lcb_arithmetic errorCode is 0x%.8X \n", arithmeticCreateErrorCode); exit(1); } printf("Arithmetic CREATE: About to do lcb_wait()...\n"); lcb_wait(instance); printf("Arithmetic CREATE: Back from lcb_wait()...\n"); } // end of blockingArithmeticCreate()
// Given an LCB instance and a key name, increment an arithmetic, and // wait until it finishes, and if there is an error, display it. static void OrigBlockingArithmeticIncrement(lcb_t instance, char *keyName) { int keyLength = strlen(keyName); lcb_error_t arithmeticIncrementErrorCode = 0; lcb_arithmetic_cmd_t *arithmeticCommand = calloc(1, sizeof(*arithmeticCommand)); arithmeticCommand->version = 0; // Determine if this is factor arithmeticCommand->v.v0.key = keyName; arithmeticCommand->v.v0.nkey = keyLength; arithmeticCommand->v.v0.create = 0; // as opposed to 1 arithmeticCommand->v.v0.delta = 1; // increment by one const lcb_arithmetic_cmd_t* arithCommands[] = { arithmeticCommand }; arithmeticIncrementErrorCode = lcb_arithmetic(instance, NULL, 1, arithCommands); if (arithmeticIncrementErrorCode != LCB_SUCCESS) { printf("Couldn't schedule arithmetic increment operation!\n"); printf("lcb_arithmetic errorCode is 0x%.8X \n", arithmeticIncrementErrorCode); exit(1); } printf("Arithmetic CREATE: About to do lcb_wait()...\n"); lcb_wait(instance); printf("Arithmetic CREATE: Back from lcb_wait()...\n"); } // end of blockingArithmeticIncrement()
// Given an LCB instance and a key name, increment an arithmetic, and // wait until it finishes, and if there is an error, display it. static void blockingArithmeticIncrement2(lcb_t instance, char *keyName) { int keyLength = strlen(keyName); lcb_error_t arithmeticIncrementErrorCode = 0; lcb_arithmetic_cmd_t *arithmeticCommand = calloc(1, sizeof(*arithmeticCommand)); // These are the exact values arithmeticCommand->version = 0; arithmeticCommand->v.v0.key = keyName; arithmeticCommand->v.v0.nkey = strlen(keyName); arithmeticCommand->v.v0.exptime = 0; arithmeticCommand->v.v0.create = 1; arithmeticCommand->v.v0.delta = 1; // Unknown since not printed in logs arithmeticCommand->v.v0.initial = 1; // Equal to delta const lcb_arithmetic_cmd_t* arithCommands[] = { arithmeticCommand }; arithmeticIncrementErrorCode = lcb_arithmetic(instance, NULL, 1, arithCommands); if (arithmeticIncrementErrorCode != LCB_SUCCESS) { printf("Couldn't schedule increment operation!\n"); printf("lcb_arithmetic errorCode is 0x%.8X \n", arithmeticIncrementErrorCode); exit(1); } printf("INCREMENT: About to do lcb_wait()...\n"); lcb_wait(instance); printf("INCREMENT: Back from lcb_wait()...\n"); } // end of blockingArithmeticIncrement2()
static void blockingGet(lcb_t instance, char*keyName) { int keyLength = strlen(keyName); lcb_error_t getErrorCode = 0; lcb_get_cmd_t *getCommand = calloc(1,sizeof(*getCommand)); getCommand->version = 0; getCommand->v.v0.key = keyName; getCommand->v.v0.nkey = keyLength; const lcb_get_cmd_t* getCommands[] = { getCommand }; getErrorCode = lcb_get(instance, NULL, 1, getCommands); if (getErrorCode != LCB_SUCCESS) { printf("Couldn't schedule get operation!\n"); printf("lcb_get errorCode is 0x%.8X \n", getErrorCode); exit(1); } printf("GET: About to do lcb_wait()...\n"); lcb_wait(instance); printf("GET: Back from lcb_wait()...\n"); } // blockingGet()
ERL_NIF_TERM cb_getl(ErlNifEnv* env, handle_t* handle, void* obj) { getl_args_t* args = (getl_args_t*)obj; struct libcouchbase_callback cb; lcb_error_t ret; lcb_get_cmd_t cmd; const lcb_get_cmd_t *commands[1]; commands[0] = &cmd; memset(&cmd, 0, sizeof(cmd)); cmd.v.v0.key = args->key; cmd.v.v0.nkey = args->nkey; cmd.v.v0.exptime = args->exp; cmd.v.v0.lock = 1; ret = lcb_get(handle->instance, &cb, 1, commands); free(args->key); if (ret != LCB_SUCCESS) { return return_lcb_error(env, ret); } lcb_wait(handle->instance); if(cb.error != LCB_SUCCESS) { return return_lcb_error(env, cb.error); } return enif_make_tuple2(env, A_OK(env), return_value(env, &cb)); }
/*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); }
ERL_NIF_TERM cb_arithmetic(ErlNifEnv* env, handle_t* handle, void* obj) { arithmetic_args_t* args = (arithmetic_args_t*)obj; struct libcouchbase_callback cb; lcb_error_t ret; //for checking responses lcb_arithmetic_cmd_t arithmetic; const lcb_arithmetic_cmd_t* commands[1]; commands[0] = &arithmetic; memset(&arithmetic, 0, sizeof(arithmetic)); arithmetic.v.v0.key = args->key; arithmetic.v.v0.nkey = args->nkey; arithmetic.v.v0.initial = args->initial; arithmetic.v.v0.create = args->create; arithmetic.v.v0.delta = args->delta; arithmetic.v.v0.exptime = args->exp; ret = lcb_arithmetic(handle->instance, &cb, 1, commands); free(args->key); if (ret != LCB_SUCCESS) { return return_lcb_error(env, ret); } lcb_wait(handle->instance); if(cb.error != LCB_SUCCESS) { return return_lcb_error(env, cb.error); } return enif_make_tuple2(env, A_OK(env), return_value(env, &cb)); }
ERL_NIF_TERM cb_remove(ErlNifEnv* env, handle_t* handle, void* obj) { remove_args_t* args = (remove_args_t*)obj; struct libcouchbase_callback cb; lcb_error_t ret; //for checking responses lcb_remove_cmd_t remove; const lcb_remove_cmd_t* commands[1]; commands[0] = &remove; memset(&remove, 0, sizeof(remove)); remove.v.v0.key = args->key; remove.v.v0.nkey = args->nkey; remove.v.v0.cas = args->cas; ret = lcb_remove(handle->instance, &cb, 1, commands); free(args->key); if (ret != LCB_SUCCESS) { return return_lcb_error(env, ret); } lcb_wait(handle->instance); if(cb.error != LCB_SUCCESS) { return return_lcb_error(env, cb.error); } return A_OK(env); }
ERL_NIF_TERM cb_http(ErlNifEnv* env, handle_t* handle, void* obj) { http_args_t* args = (http_args_t*)obj; struct libcouchbase_callback cb; lcb_error_t ret; lcb_http_request_t req; lcb_http_cmd_t cmd; cmd.version = 0; cmd.v.v0.path = args->path; cmd.v.v0.npath = strlen(args->path); cmd.v.v0.body = args->body; cmd.v.v0.nbody = strlen(args->body); cmd.v.v0.method = args->method; cmd.v.v0.chunked = 0; // no support for chunking cmd.v.v0.content_type = args->content_type; ret = lcb_make_http_request(handle->instance, &cb, args->type, &cmd, &req); if (ret != LCB_SUCCESS) { return return_lcb_error(env, ret); } lcb_wait(handle->instance); if(cb.error != LCB_SUCCESS) { return return_lcb_error(env, cb.error); } ErlNifBinary value_binary; enif_alloc_binary(cb.size, &value_binary); memcpy(value_binary.data, cb.data, cb.size); return enif_make_tuple2(env, A_OK(env), enif_make_binary(env, &value_binary)); }
/* * 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); }
/** Query a Couchbase design document view * * Setup and execute a Couchbase view request and wait for the result. * * @param instance Couchbase connection instance. * @param cookie Couchbase cookie for returning information from callbacks. * @param path The fully qualified view path including the design document and view name. * @param post The post payload (NULL for none). * @return Couchbase error object. */ lcb_error_t couchbase_query_view(lcb_t instance, const void *cookie, const char *path, const char *post) { lcb_error_t error; /* couchbase command return */ lcb_http_cmd_t cmd; /* http command struct */ const lcb_http_cmd_t *commands; /* http commands array */ commands = &cmd; memset(&cmd, 0, sizeof(cmd)); /* populate command struct */ cmd.v.v0.path = path; cmd.v.v0.npath = strlen(cmd.v.v0.path); cmd.v.v0.body = post; cmd.v.v0.nbody = post ? strlen(post) : 0; cmd.v.v0.method = post ? LCB_HTTP_METHOD_POST : LCB_HTTP_METHOD_GET; cmd.v.v0.chunked = 1; cmd.v.v0.content_type = "application/json"; /* query the view */ if ((error = lcb_make_http_request(instance, cookie, LCB_HTTP_TYPE_VIEW, commands, NULL)) == LCB_SUCCESS) { /* enter event loop on success */ lcb_wait(instance); } /* return error */ return error; }
VALUE cb_bucket_observe(int argc, VALUE *argv, VALUE self) { struct cb_bucket_st *bucket = DATA_PTR(self); struct cb_context_st *ctx; VALUE rv, proc, exc; lcb_error_t err; struct cb_params_st params; if (!cb_bucket_connected_bang(bucket, cb_sym_observe)) { return Qnil; } memset(¶ms, 0, sizeof(struct cb_params_st)); rb_scan_args(argc, argv, "0*&", ¶ms.args, &proc); if (!bucket->async && proc != Qnil) { rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks"); } params.type = cb_cmd_observe; params.bucket = bucket; cb_params_build(¶ms); ctx = cb_context_alloc_common(bucket, proc, params.cmd.observe.num); err = lcb_observe(bucket->handle, (const void *)ctx, params.cmd.observe.num, params.cmd.observe.ptr); cb_params_destroy(¶ms); exc = cb_check_error(err, "failed to schedule observe request", Qnil); if (exc != Qnil) { cb_context_free(ctx); rb_exc_raise(exc); } bucket->nbytes += params.npayload; if (bucket->async) { cb_maybe_do_loop(bucket); return Qnil; } else { if (ctx->nqueries > 0) { /* we have some operations pending */ lcb_wait(bucket->handle); } exc = ctx->exception; rv = ctx->rv; cb_context_free(ctx); if (exc != Qnil) { rb_exc_raise(exc); } exc = bucket->exception; if (exc != Qnil) { bucket->exception = Qnil; rb_exc_raise(exc); } if (params.cmd.observe.num > 1 || params.cmd.observe.array) { return rv; /* return as a hash {key => {}, ...} */ } else { VALUE vv = Qnil; rb_hash_foreach(rv, cb_first_value_i, (VALUE)&vv); return vv; /* return first value */ } } }
// remove($id {, $cas, $groupid}) : MetaDoc PHP_METHOD(Bucket, remove) { bucket_object *data = PCBC_PHP_THISOBJ(); int ii, ncmds, nscheduled; pcbc_pp_state pp_state; pcbc_pp_id id; opcookie *cookie; zval *zcas, *zgroupid; lcb_error_t err; // Note that groupid is experimental here and should not be used. if (pcbc_pp_begin(ZEND_NUM_ARGS() TSRMLS_CC, &pp_state, "id||cas,groupid", &id, &zcas, &zgroupid) != SUCCESS) { throw_pcbc_exception("Invalid arguments.", LCB_EINVAL); RETURN_NULL(); } ncmds = pcbc_pp_keycount(&pp_state); cookie = opcookie_init(); nscheduled = 0; for (ii = 0; pcbc_pp_next(&pp_state); ++ii) { lcb_CMDREMOVE cmd = {0}; PCBC_CHECK_ZVAL_STRING(zcas, "cas must be a string"); PCBC_CHECK_ZVAL_STRING(zgroupid, "groupid must be a string"); LCB_CMD_SET_KEY(&cmd, id.str, id.len); if (zcas) { cmd.cas = cas_decode(zcas TSRMLS_CC); } if (zgroupid) { LCB_KREQ_SIMPLE(&cmd._hashkey, Z_STRVAL_P(zgroupid), Z_STRLEN_P(zgroupid)); } err = lcb_remove3(data->conn->lcb, cookie, &cmd); if (err != LCB_SUCCESS) { break; } nscheduled++; } pcbc_assert_number_of_commands("remove", nscheduled, ncmds); if (nscheduled) { lcb_wait(data->conn->lcb); err = proc_remove_results(data, return_value, cookie, pcbc_pp_ismapped(&pp_state) TSRMLS_CC); } opcookie_destroy(cookie); if (err != LCB_SUCCESS) { throw_lcb_exception(err); } }
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; }
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; }
static void setup(char **argv, const char *username, const char *password, const char *bucket) { const char *endpoint; 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)); if (!mock->is_mock) { username = mock->username; password = mock->password; bucket = mock->bucket; } 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_callback); if (lcb_connect(session) != LCB_SUCCESS) { err_exit("Failed to connect to server"); } lcb_wait(session); if (!mock->is_mock) { const char *const *servers; total_node_count = 0; servers = lcb_get_server_list(session); for (; *servers; servers++, total_node_count++); } }
static void get_encrypted(lcb_t instance, const char *key) { lcb_CMDGET cmd = {}; lcb_error_t err; LCB_CMD_SET_KEY(&cmd, key, strlen(key)); printf("KEY: %s\n", key); err = lcb_get3(instance, NULL, &cmd); if (err != LCB_SUCCESS) { die(instance, "Couldn't schedule get operation", err); } lcb_wait(instance); }
/* * Returns versions of the server for each node in the cluster * * @since 1.1.0 * * @overload version * @yieldparam [Result] ret the object with +error+, +node+, +operation+ * and +value+ attributes. * * @return [Hash] node-version pairs * * @raise [Couchbase::Error::Connect] if connection closed (see {Bucket#reconnect}) * @raise [ArgumentError] when passing the block in synchronous mode * * @example Synchronous version request * c.version #=> will render version * * @example Asynchronous version request * c.run do * c.version do |ret| * ret.operation #=> :version * ret.success? #=> true * ret.node #=> "localhost:11211" * ret.value #=> will render version * end * end */ VALUE cb_bucket_version(int argc, VALUE *argv, VALUE self) { struct cb_bucket_st *bucket = DATA_PTR(self); struct cb_context_st *ctx; VALUE rv, exc, proc; lcb_error_t err; struct cb_params_st params; if (!cb_bucket_connected_bang(bucket, cb_sym_version)) { return Qnil; } memset(¶ms, 0, sizeof(struct cb_params_st)); rb_scan_args(argc, argv, "0*&", ¶ms.args, &proc); if (!bucket->async && proc != Qnil) { rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks"); } params.type = cb_cmd_version; params.bucket = bucket; cb_params_build(¶ms); ctx = cb_context_alloc_common(bucket, proc, params.cmd.version.num); err = lcb_server_versions(bucket->handle, (const void *)ctx, params.cmd.version.num, params.cmd.version.ptr); exc = cb_check_error(err, "failed to schedule version request", Qnil); cb_params_destroy(¶ms); if (exc != Qnil) { cb_context_free(ctx); rb_exc_raise(exc); } bucket->nbytes += params.npayload; if (bucket->async) { cb_maybe_do_loop(bucket); return Qnil; } else { if (ctx->nqueries > 0) { /* we have some operations pending */ lcb_wait(bucket->handle); } exc = ctx->exception; rv = ctx->rv; cb_context_free(ctx); if (exc != Qnil) { rb_exc_raise(exc); } exc = bucket->exception; if (exc != Qnil) { bucket->exception = Qnil; rb_exc_raise(exc); } return rv; } }
/* * Execute {Bucket::CouchRequest} * * @since 1.2.0 */ VALUE cb_http_request_perform(VALUE self) { struct http_request_st *req = DATA_PTR(self); struct context_st *ctx; VALUE rv, exc; lcb_error_t err; struct bucket_st *bucket; ctx = xcalloc(1, sizeof(struct context_st)); if (ctx == NULL) { rb_raise(eClientNoMemoryError, "failed to allocate memory"); } rv = Qnil; ctx->rv = &rv; ctx->bucket = bucket = req->bucket; ctx->proc = rb_block_given_p() ? rb_block_proc() : req->on_body_callback; ctx->extended = req->extended; ctx->request = req; ctx->headers_val = cb_gc_protect(bucket, rb_hash_new()); err = lcb_make_http_request(bucket->handle, (const void *)ctx, req->type, &req->cmd, &req->request); exc = cb_check_error(err, "failed to schedule document request", STR_NEW(req->cmd.v.v0.path, req->cmd.v.v0.npath)); if (exc != Qnil) { xfree(ctx); rb_exc_raise(exc); } req->running = 1; req->ctx = ctx; if (bucket->async) { return Qnil; } else { lcb_wait(bucket->handle); if (req->completed) { exc = ctx->exception; xfree(ctx); if (exc != Qnil) { cb_gc_unprotect(bucket, exc); rb_exc_raise(exc); } return rv; } else { return Qnil; } } return Qnil; }
/* * Execute {Bucket::CouchRequest} * * @since 1.2.0 */ VALUE cb_http_request_perform(VALUE self) { struct cb_http_request_st *req = DATA_PTR(self); struct cb_context_st *ctx; VALUE rv, exc; lcb_error_t err; struct cb_bucket_st *bucket = req->bucket; if (bucket->handle == NULL) { rb_raise(cb_eConnectError, "closed connection"); } ctx = cb_context_alloc(bucket); ctx->rv = Qnil; ctx->proc = rb_block_given_p() ? rb_block_proc() : req->on_body_callback; ctx->extended = req->extended; ctx->request = req; ctx->headers_val = rb_hash_new(); err = lcb_make_http_request(bucket->handle, (const void *)ctx, req->type, &req->cmd, &req->request); exc = cb_check_error(err, "failed to schedule document request", STR_NEW(req->cmd.v.v0.path, req->cmd.v.v0.npath)); if (exc != Qnil) { lcb_cancel_http_request(bucket->handle, req->request); rb_exc_raise(exc); } req->running = 1; req->ctx = ctx; if (bucket->async) { return Qnil; } else { lcb_wait(bucket->handle); if (req->completed) { rv = ctx->rv; exc = ctx->exception; cb_context_free(ctx); if (exc != Qnil) { rb_exc_raise(exc); } return rv; } else { return Qnil; } } return Qnil; }