static bool create_node_if_not_exists(service_location_t *service, int flags, const char *value, int value_len, const char *fmt, ...) { struct Stat stat; int status, retry_count; char node_key[512]; va_list args; if (service->connected_state == false) { return false; } va_start(args, fmt); vsnprintf(node_key, 512, fmt, args); va_end(args); retry_count = 3; do { status = zoo_exists(service->zk, node_key, 1, &stat); retry_count++; } while (status == ZCONNECTIONLOSS && retry_count--); if (status == ZNONODE) { LOG_INFO(service->log_fd, "Creating node=[%s] value=[%s]", node_key, value); retry_count = 3; do { status = zoo_create(service->zk, node_key, value, value_len, &ZOO_OPEN_ACL_UNSAFE, flags, 0, 0); retry_count++; } while (status == ZCONNECTIONLOSS && retry_count--); } return (status == ZOK) ? true : false; }
int create_root(const char* node_name, const char* data) { int ret = 0; struct Stat stat; ret = zoo_exists(g_zhdl, node_name, true, &stat); if(ret == ZOK) { printf("create_root %s already create\n", node_name); } else if(ret == ZNONODE) { ret = zoo_acreate(g_zhdl, node_name, data, strlen(data), &ZOO_OPEN_ACL_UNSAFE, 0, watcher_fn_create_root, "root node create"); if(ret) { printf("create_root %s error", node_name); } } else { printf("create_root error\n"); } return ret; }
int create_taskRootNode() { int ret = 0; const char* tasksRoot = "/TasksRoot"; struct Stat stat; ret = zoo_exists(g_zhdl, tasksRoot, true, &stat); if(ret == ZOK) { printf("create_taskRootNode %s already create\n", tasksRoot); } else if(ret == ZNONODE) { ret = zoo_acreate(g_zhdl, tasksRoot, "0", strlen("0"), &ZOO_OPEN_ACL_UNSAFE, 0, watcher_fn_create_taskroot, "TasksRoot data"); if(ret) { printf("create_taskRootNode%s error", tasksRoot); } } else { printf("create_root error\n"); } return ret; }
static VALUE method_exists(VALUE self, VALUE reqid, VALUE path, VALUE async, VALUE watch) { struct Stat stat; int rc; VALUE output; STANDARD_PREAMBLE(self, zk, reqid, path, async, watch, data_ctx, watch_ctx, call_type); switch (call_type) { case SYNC: rc = zoo_exists(zk->zh, RSTRING_PTR(path), 0, &stat); break; case SYNC_WATCH: rc = zoo_wexists(zk->zh, RSTRING_PTR(path), zkrb_state_callback, watch_ctx, &stat); break; case ASYNC: rc = zoo_aexists(zk->zh, RSTRING_PTR(path), 0, zkrb_stat_callback, data_ctx); break; case ASYNC_WATCH: rc = zoo_awexists(zk->zh, RSTRING_PTR(path), zkrb_state_callback, watch_ctx, zkrb_stat_callback, data_ctx); break; } output = rb_ary_new(); rb_ary_push(output, INT2FIX(rc)); if (IS_SYNC(call_type) && rc == ZOK) { rb_ary_push(output, zkrb_stat_to_rarray(&stat)); } return output; }
static VALUE method_exists(VALUE self, VALUE path, VALUE watch) { struct Stat stat; Check_Type(path, T_STRING); FETCH_DATA_PTR(self, zk); check_errors(zoo_exists(zk->zh, RSTRING(path)->ptr, (watch != Qfalse && watch != Qnil), &stat)); return array_from_stat(&stat); }
static VALUE method_exists(VALUE self, VALUE path, VALUE watch) { struct zk_rb_data* zk; struct Stat stat; Check_Type(path, T_STRING); Data_Get_Struct(rb_iv_get(self, "@data"), struct zk_rb_data, zk); check_errors(zoo_exists(zk->zh, RSTRING(path)->ptr, (watch != Qfalse && watch != Qnil), &stat)); return array_from_stat(&stat); }
int ZKOP::zkNodeExists(const std::string& node, int watch) {/*{{{*/ int ret = zoo_exists(zkhandle, node.data(), watch, NULL); /* if(ZNONODE == ret){ return ZNONODE; } if(ZOK == ret){ return ZOK; } */ return ret; }/*}}}*/
ZOOAPI int zkr_lock_lock(zkr_lock_mutex_t *mutex) { pthread_mutex_lock(&(mutex->pmutex)); zhandle_t *zh = mutex->zh; char *path = mutex->path; struct Stat stat; int exists = zoo_exists(zh, path, 0, &stat); int count = 0; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = (.5)*1000000; // retry to see if the path exists and // and create if the path does not exist while ((exists == ZCONNECTIONLOSS || exists == ZNONODE) && (count <4)) { count++; // retry the operation if (exists == ZCONNECTIONLOSS) exists = zoo_exists(zh, path, 0, &stat); else if (exists == ZNONODE) exists = zoo_create(zh, path, NULL, 0, mutex->acl, 0, NULL, 0); nanosleep(&ts, 0); } // need to check if we cannot still access the server int check_retry = ZCONNECTIONLOSS; count = 0; while (check_retry != ZOK && count <4) { check_retry = zkr_lock_operation(mutex, &ts); if (check_retry != ZOK) { nanosleep(&ts, 0); count++; } } pthread_mutex_unlock(&(mutex->pmutex)); return zkr_lock_isowner(mutex); }
void watcher(zhandle_t *zzh, int type, int state, const char *path, void *context) { /* quando um nó é deletado, verifica se é o nó cliente-1 (segundo cliente), * se for, sai também */ if (type == ZOO_DELETED_EVENT && !strcmp(path, "/fase1/cliente-1")) { fprintf(stdout, "cliente-1 desconectou, saindo...\n"); zookeeper_close(zh); exit(EXIT_SUCCESS); } else { /* caso o nó deletado não seja o esperado, reativa o watcher */ zoo_exists(zh, "/fase1/cliente-1", 1, &stat); } return; }
int main(int argc, char *argv[]) { char server_address[256]; char ephemeral_path[256]; int rc; /* verificação básica dos argumentos */ if (argc != 2) { fprintf(stderr, "Uso: ./program <endereço do servidor>\n"); exit(EXIT_FAILURE); } /* Primeiro argumento é o endereço do servidor */ strcpy(server_address, argv[1]); /* Inicializa a conexão com o servidor */ if ((zh = zookeeper_init(server_address, watcher, 10000, &myid, NULL, 0)) == NULL) { fprintf(stderr, "Não foi possível conectar-se ao servidor %s\n", server_address); exit(EXIT_FAILURE); } else { fprintf(stdout, "Conectado à %s\n", server_address); } fprintf(stdout, "Myid: %d\n", myid.client_id); sprintf(ephemeral_path, "/fase1/cliente-%d", myid.client_id); /* Cria um nó comum */ zoo_create(zh, "/fase1", NULL, 0, &ZOO_OPEN_ACL_UNSAFE, 0, NULL, 0); /* Cria um nó efêmero */ rc = zoo_create(zh, ephemeral_path, NULL, 0, &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL, NULL, 0); /* seta um watch em um arquivo criado por um processo diferente */ zoo_exists(zh, "/fase1/cliente-1", 1, &stat); while(1) { /* espera até que o watcher dispare */ } /* não deve chegar aqui nunca */ zookeeper_close(zh); return EXIT_SUCCESS; }
int Register::registe(const serviceinfo & info) { std::string name="/Register_"+info.servicename; char buf[1024]; int bufflen=sizeof(buf); struct Stat stat; //首先查询节点是否存在 int ret=zoo_exists(zh,name.c_str(),1,&stat); LOG(INFO)<<ret; switch(ret) { case ZOK:{ LOG(INFO)<<"OK\n"; } break; case ZNONODE:{ LOG(INFO)<<"ZNONODE\n"; }break; default: LOG(INFO)<<"other\n"; } LOG(INFO)<<stat.ctime; LOG(INFO)<<bufflen; /* * 创建节点 */ char path_buffer[64]; ret=zoo_create(zh,name.c_str(),"app",3,&ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL,path_buffer,sizeof(path_buffer)-1); LOG(INFO)<<ret; return 0; }
int DevCtlServiceReg::createNode(zhandle_t *zkhandle, const char * path, int flags) { char path_buffer[512]; int bufferlen=sizeof(path_buffer); int ret = zoo_exists(zkhandle, path,0,NULL); if(ret != ZOK){ ret = zoo_create(zkhandle,path, NULL,0,&ZOO_OPEN_ACL_UNSAFE, flags, path_buffer,bufferlen); LOG(TRACE)<<"path_buffer:"<<path_buffer; mNodeRealPath = path_buffer; if(ret != ZOK){ LOG(ERROR)<<"Error when create path :"<<path<<" retcode:"<<ret; return -1; } return 0; } else { return 0; } }
int main(int argc, char *argv[]) { char zkServers[100] = "127.0.0.1:2181"; zoo_set_debug_level(ZOO_LOG_LEVEL_WARN); zoo_deterministic_conn_order(1); zh = zookeeper_init(zkServers, watcher, 60000, &zkClientId, 0, 0); if (!zh) { printf("ZK Init error(%s)\n", zkServers); return 0; } while (true) { sleep(1); if (completeZkInit == 1) { break; } } char resultPath[1024] = {0,}; int resultLength; zoo_create(zh, "/test", "", 0, &ZOO_OPEN_ACL_UNSAFE, 0, resultPath, 1024); //watchctx_t ctxWC; Stat zooStat; int result = zoo_exists(zh, "/test", 1, &zooStat); if (result == ZOK) { printf("node exists\n"); } String_vector children; zoo_get_children(zh, "/test", 1, &children); zoo_create(zh, "/test/sub01", "", 0, &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL, resultPath, 1024); zoo_create(zh, "/test/sub02", "", 0, &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL, resultPath, 1024); zoo_delete(zh, "/test", -1); while(1) { sleep(20); } }
//同步方式创建节点 void create(zhandle_t *zkhandle,char *path,int flag,const char *ctx) { char path_buffer[512]; int bufferlen=sizeof(path_buffer); int ret = zoo_exists(zkhandle,path,0,NULL); if(ret != ZOK){ ret = zoo_create(zkhandle,path,ctx,strlen(ctx), &ZOO_OPEN_ACL_UNSAFE,flag, path_buffer,bufferlen); if (ret != ZOK){ printf("节点创建失败:%s \n",path); exit(EXIT_FAILURE); }else { printf("创建的节点名称为:%s\n",path_buffer); printf("创建的节点值为:%s\n",(char *)ctx); } }else{ printf("path:%s 已经存在,无需创建\n",path); } }
void processline(char *line) { int rc; int async = ((line[0] == 'a') && !(startsWith(line, "addauth "))); if (async) { line++; } if (startsWith(line, "help")) { fprintf(stderr, " create [+[e|s]] <path>\n"); fprintf(stderr, " delete <path>\n"); fprintf(stderr, " set <path> <data>\n"); fprintf(stderr, " get <path>\n"); fprintf(stderr, " ls <path>\n"); fprintf(stderr, " ls2 <path>\n"); fprintf(stderr, " sync <path>\n"); fprintf(stderr, " exists <path>\n"); fprintf(stderr, " wexists <path>\n"); fprintf(stderr, " myid\n"); fprintf(stderr, " verbose\n"); fprintf(stderr, " addauth <id> <scheme>\n"); fprintf(stderr, " quit\n"); fprintf(stderr, "\n"); fprintf(stderr, " prefix the command with the character 'a' to run the command asynchronously.\n"); fprintf(stderr, " run the 'verbose' command to toggle verbose logging.\n"); fprintf(stderr, " i.e. 'aget /foo' to get /foo asynchronously\n"); } else if (startsWith(line, "verbose")) { if (verbose) { verbose = 0; zoo_set_debug_level(ZOO_LOG_LEVEL_WARN); fprintf(stderr, "logging level set to WARN\n"); } else { verbose = 1; zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG); fprintf(stderr, "logging level set to DEBUG\n"); } } else if (startsWith(line, "get ")) { line += 4; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } rc = zoo_aget(zh, line, 1, my_data_completion, strdup(line)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "set ")) { char *ptr; line += 4; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } ptr = strchr(line, ' '); if (!ptr) { fprintf(stderr, "No data found after path\n"); return; } *ptr = '\0'; ptr++; if (async) { rc = zoo_aset(zh, line, ptr, strlen(ptr), -1, my_stat_completion, strdup(line)); } else { struct Stat stat; rc = zoo_set2(zh, line, ptr, strlen(ptr), -1, &stat); } if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "ls ")) { line += 3; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } gettimeofday(&startTime, 0); rc= zoo_aget_children(zh, line, 1, my_strings_completion, strdup(line)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "ls2 ")) { line += 4; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } gettimeofday(&startTime, 0); rc= zoo_aget_children2(zh, line, 1, my_strings_stat_completion, strdup(line)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "create ")) { int flags = 0; line += 7; if (line[0] == '+') { line++; if (line[0] == 'e') { flags |= ZOO_EPHEMERAL; line++; } if (line[0] == 's') { flags |= ZOO_SEQUENCE; line++; } line++; } if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } fprintf(stderr, "Creating [%s] node\n", line); // { // struct ACL _CREATE_ONLY_ACL_ACL[] = {{ZOO_PERM_CREATE, ZOO_ANYONE_ID_UNSAFE}}; // struct ACL_vector CREATE_ONLY_ACL = {1,_CREATE_ONLY_ACL_ACL}; // rc = zoo_acreate(zh, line, "new", 3, &CREATE_ONLY_ACL, flags, // my_string_completion, strdup(line)); // } rc = zoo_acreate(zh, line, "new", 3, &ZOO_OPEN_ACL_UNSAFE, flags, my_string_completion_free_data, strdup(line)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "delete ")) { line += 7; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } if (async) { rc = zoo_adelete(zh, line, -1, my_void_completion, strdup(line)); } else { rc = zoo_delete(zh, line, -1); } if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "sync ")) { line += 5; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } rc = zoo_async(zh, line, my_string_completion_free_data, strdup(line)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "wexists ")) { #ifdef THREADED struct Stat stat; #endif line += 8; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } #ifndef THREADED rc = zoo_awexists(zh, line, watcher, (void*) 0, my_stat_completion, strdup(line)); #else rc = zoo_wexists(zh, line, watcher, (void*) 0, &stat); #endif if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "exists ")) { #ifdef THREADED struct Stat stat; #endif line += 7; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } #ifndef THREADED rc = zoo_aexists(zh, line, 1, my_stat_completion, strdup(line)); #else rc = zoo_exists(zh, line, 1, &stat); #endif if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (strcmp(line, "myid") == 0) { printf("session Id = %llx\n", _LL_CAST_ zoo_client_id(zh)->client_id); } else if (strcmp(line, "reinit") == 0) { zookeeper_close(zh); // we can't send myid to the server here -- zookeeper_close() removes // the session on the server. We must start anew. zh = zookeeper_init(hostPort, watcher, 30000, 0, 0, 0); } else if (startsWith(line, "quit")) { fprintf(stderr, "Quitting...\n"); shutdownThisThing=1; } else if (startsWith(line, "od")) { const char val[]="fire off"; fprintf(stderr, "Overdosing...\n"); rc = zoo_aset(zh, "/od", val, sizeof(val)-1, -1, od_completion, 0); if (rc) fprintf(stderr, "od command failed: %d\n", rc); } else if (startsWith(line, "addauth ")) { char *ptr; line += 8; ptr = strchr(line, ' '); if (ptr) { *ptr = '\0'; ptr++; } zoo_add_auth(zh, line, ptr, ptr ? strlen(ptr) : 0, NULL, NULL); } }
void processline(char *line) { int rc; int async = ((line[0] == 'a') && !(startsWith(line, "addauth "))); if (async) { line++; } if (startsWith(line, "help")) { fprintf(stderr, " create [+[e|s]] <path>\n"); fprintf(stderr, " create2 [+[e|s]] <path>\n"); fprintf(stderr, " delete <path>\n"); fprintf(stderr, " set <path> <data>\n"); fprintf(stderr, " get <path>\n"); fprintf(stderr, " ls <path>\n"); fprintf(stderr, " ls2 <path>\n"); fprintf(stderr, " sync <path>\n"); fprintf(stderr, " exists <path>\n"); fprintf(stderr, " wexists <path>\n"); fprintf(stderr, " myid\n"); fprintf(stderr, " verbose\n"); fprintf(stderr, " addauth <id> <scheme>\n"); fprintf(stderr, " config\n"); fprintf(stderr, " reconfig [-file <path> | -members <serverId=host:port1:port2;port3>,... | " " -add <serverId=host:port1:port2;port3>,... | -remove <serverId>,...] [-version <version>]\n"); fprintf(stderr, " quit\n"); fprintf(stderr, "\n"); fprintf(stderr, " prefix the command with the character 'a' to run the command asynchronously.\n"); fprintf(stderr, " run the 'verbose' command to toggle verbose logging.\n"); fprintf(stderr, " i.e. 'aget /foo' to get /foo asynchronously\n"); } else if (startsWith(line, "verbose")) { if (verbose) { verbose = 0; zoo_set_debug_level(ZOO_LOG_LEVEL_WARN); fprintf(stderr, "logging level set to WARN\n"); } else { verbose = 1; zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG); fprintf(stderr, "logging level set to DEBUG\n"); } } else if (startsWith(line, "get ")) { line += 4; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } rc = zoo_aget(zh, line, 1, my_data_completion, strdup(line)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (strcmp(line, "config") == 0) { gettimeofday(&startTime, 0); rc = zoo_agetconfig(zh, 1, my_data_completion, strdup(ZOO_CONFIG_NODE)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "reconfig ")) { int syntaxError = 0; char* p = NULL; char* joining = NULL; char* leaving = NULL; char* members = NULL; size_t members_size = 0; int mode = 0; // 0 = not set, 1 = incremental, 2 = non-incremental int64_t version = -1; line += 9; p = strtok (strdup(line)," "); while (p != NULL) { if (strcmp(p, "-add")==0) { p = strtok (NULL," "); if (mode == 2 || p == NULL) { syntaxError = 1; break; } mode = 1; joining = strdup(p); } else if (strcmp(p, "-remove")==0){ p = strtok (NULL," "); if (mode == 2 || p == NULL) { syntaxError = 1; break; } mode = 1; leaving = strdup(p); } else if (strcmp(p, "-members")==0) { p = strtok (NULL," "); if (mode == 1 || p == NULL) { syntaxError = 1; break; } mode = 2; members = strdup(p); } else if (strcmp(p, "-file")==0){ FILE *fp = NULL; p = strtok (NULL," "); if (mode == 1 || p == NULL) { syntaxError = 1; break; } mode = 2; fp = fopen(p, "r"); if (fp == NULL) { fprintf(stderr, "Error reading file: %s\n", p); syntaxError = 1; break; } fseek(fp, 0L, SEEK_END); /* Position to end of file */ members_size = ftell(fp); /* Get file length */ rewind(fp); /* Back to start of file */ members = calloc(members_size + 1, sizeof(char)); if(members == NULL ) { fprintf(stderr, "\nInsufficient memory to read file: %s\n", p); syntaxError = 1; fclose(fp); break; } /* Read the entire file into members * NOTE: -- fread returns number of items successfully read * not the number of bytes. We're requesting one item of * members_size bytes. So we expect the return value here * to be 1. */ if (fread(members, members_size, 1, fp) != 1){ fprintf(stderr, "Error reading file: %s\n", p); syntaxError = 1; fclose(fp); break; } fclose(fp); } else if (strcmp(p, "-version")==0){ p = strtok (NULL," "); if (version != -1 || p == NULL){ syntaxError = 1; break; } #ifdef WIN32 version = _strtoui64(p, NULL, 16); #else version = strtoull(p, NULL, 16); #endif if (version < 0) { syntaxError = 1; break; } } else { syntaxError = 1; break; } p = strtok (NULL," "); } if (syntaxError) return; rc = zoo_areconfig(zh, joining, leaving, members, version, my_data_completion, strdup(line)); free(joining); free(leaving); free(members); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "set ")) { char *ptr; line += 4; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } ptr = strchr(line, ' '); if (!ptr) { fprintf(stderr, "No data found after path\n"); return; } *ptr = '\0'; ptr++; if (async) { rc = zoo_aset(zh, line, ptr, strlen(ptr), -1, my_stat_completion, strdup(line)); } else { struct Stat stat; rc = zoo_set2(zh, line, ptr, strlen(ptr), -1, &stat); } if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "ls ")) { line += 3; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } gettimeofday(&startTime, 0); rc= zoo_aget_children(zh, line, 1, my_strings_completion, strdup(line)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "ls2 ")) { line += 4; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } gettimeofday(&startTime, 0); rc= zoo_aget_children2(zh, line, 1, my_strings_stat_completion, strdup(line)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "create ") || startsWith(line, "create2 ")) { int flags = 0; int is_create2 = startsWith(line, "create2 "); line += is_create2 ? 8 : 7; if (line[0] == '+') { line++; if (line[0] == 'e') { flags |= ZOO_EPHEMERAL; line++; } if (line[0] == 's') { flags |= ZOO_SEQUENCE; line++; } line++; } if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } fprintf(stderr, "Creating [%s] node\n", line); // { // struct ACL _CREATE_ONLY_ACL_ACL[] = {{ZOO_PERM_CREATE, ZOO_ANYONE_ID_UNSAFE}}; // struct ACL_vector CREATE_ONLY_ACL = {1,_CREATE_ONLY_ACL_ACL}; // rc = zoo_acreate(zh, line, "new", 3, &CREATE_ONLY_ACL, flags, // my_string_completion, strdup(line)); // } if (is_create2) { rc = zoo_acreate2(zh, line, "new", 3, &ZOO_OPEN_ACL_UNSAFE, flags, my_string_stat_completion_free_data, strdup(line)); } else { rc = zoo_acreate(zh, line, "new", 3, &ZOO_OPEN_ACL_UNSAFE, flags, my_string_completion_free_data, strdup(line)); } if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "delete ")) { line += 7; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } if (async) { rc = zoo_adelete(zh, line, -1, my_void_completion, strdup(line)); } else { rc = zoo_delete(zh, line, -1); } if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "sync ")) { line += 5; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } rc = zoo_async(zh, line, my_string_completion_free_data, strdup(line)); if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "wexists ")) { #ifdef THREADED struct Stat stat; #endif line += 8; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } #ifndef THREADED rc = zoo_awexists(zh, line, watcher, (void*) 0, my_stat_completion, strdup(line)); #else rc = zoo_wexists(zh, line, watcher, (void*) 0, &stat); #endif if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (startsWith(line, "exists ")) { #ifdef THREADED struct Stat stat; #endif line += 7; if (line[0] != '/') { fprintf(stderr, "Path must start with /, found: %s\n", line); return; } #ifndef THREADED rc = zoo_aexists(zh, line, 1, my_stat_completion, strdup(line)); #else rc = zoo_exists(zh, line, 1, &stat); #endif if (rc) { fprintf(stderr, "Error %d for %s\n", rc, line); } } else if (strcmp(line, "myid") == 0) { printf("session Id = %llx\n", _LL_CAST_ zoo_client_id(zh)->client_id); } else if (strcmp(line, "reinit") == 0) { zookeeper_close(zh); // we can't send myid to the server here -- zookeeper_close() removes // the session on the server. We must start anew. zh = zookeeper_init(hostPort, watcher, 30000, 0, 0, 0); } else if (startsWith(line, "quit")) { fprintf(stderr, "Quitting...\n"); shutdownThisThing=1; } else if (startsWith(line, "od")) { const char val[]="fire off"; fprintf(stderr, "Overdosing...\n"); rc = zoo_aset(zh, "/od", val, sizeof(val)-1, -1, od_completion, 0); if (rc) fprintf(stderr, "od command failed: %d\n", rc); } else if (startsWith(line, "addauth ")) { char *ptr; line += 8; ptr = strchr(line, ' '); if (ptr) { *ptr = '\0'; ptr++; } zoo_add_auth(zh, line, ptr, ptr ? strlen(ptr) : 0, NULL, NULL); } }
int main(int argc, char *argv[], char *envp[]) { INITSRVRTRC CEE_status sts = CEE_SUCCESS; SRVR_INIT_PARAM_Def initParam; DWORD processId; char tmpString[128]; char tmpString2[32]; char tmpString3[512]; CEECFG_Transport transport; CEECFG_TcpPortNumber portNumber; BOOL retcode; IDL_OBJECT_def srvrObjRef; CEECFG_TcpProcessName TcpProcessName; int TransportTrace = 0; CALL_COMP_DOVERS(ndcs,argc,argv); try { regZnodeName[0] = '\x0'; zkHost[0] = '\x0'; zkRootNode[0] = '\x0'; // Initialize seabed int sbResult; char buffer[FILENAME_MAX] = {0}; bzero(buffer, sizeof(buffer)); sbResult = file_init_attach(&argc, &argv, true, buffer); if(sbResult != XZFIL_ERR_OK){ exit(3); } sbResult = file_mon_process_startup(true); if(sbResult != XZFIL_ERR_OK){ exit(3); } msg_mon_enable_mon_messages(true); } catch(SB_Fatal_Excep sbfe) { exit(3); } sigset_t newset, oldset; sigemptyset(&newset); sigaddset(&newset,SIGQUIT); sigaddset(&newset,SIGTERM); sigprocmask(SIG_BLOCK,&newset,&oldset); processId = GetCurrentProcessId(); retcode = getInitParamSrvr(argc, argv, initParam, tmpString, tmpString3); retcode = TRUE; mxosrvr_init_seabed_trace_dll(); atexit(mxosrvr_atexit_function); // +++ Todo: Duplicating calls here. Should try to persist in srvrGlobal MS_Mon_Process_Info_Type proc_info; msg_mon_get_process_info_detail(NULL, &proc_info); myNid = proc_info.nid; myPid = proc_info.pid; myProcName = proc_info.process_name; char logNameSuffix[32]; sprintf( logNameSuffix, "_%d_%d.log", myNid, myPid ); CommonLogger::instance().initLog4cxx("log4cxx.trafodion.masterexe.config", logNameSuffix); if(retcode == FALSE ) { //LCOV_EXCL_START SendEventMsg( MSG_SET_SRVR_CONTEXT_FAILED, EVENTLOG_ERROR_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 2, tmpString, tmpString3); exit(0); //LCOV_EXCL_STOP } GTransport.initialize(); if(GTransport.error != 0 ) { //LCOV_EXCL_START SendEventMsg( MSG_SET_SRVR_CONTEXT_FAILED, EVENTLOG_ERROR_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, GTransport.error_message); exit(0); //LCOV_EXCL_STOP } chdir(GTransport.myPathname); initParam.srvrType = CORE_SRVR; //LCOV_EXCL_START if (initParam.debugFlag & SRVR_DEBUG_BREAK) { volatile int done = 0; while (!done) { sleep(10); } } //LCOV_EXCL_STOP char zkErrStr[2048]; stringstream zk_ip_port; // zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG); if( zkHost[0] == '\x0' && regZnodeName[0] == '\x0' ) { sprintf(zkErrStr, "***** Cannot get Zookeeper properties or registered znode info from startup params"); SendEventMsg( MSG_SET_SRVR_CONTEXT_FAILED, EVENTLOG_ERROR_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); // exit(1); } else { zk_ip_port << zkHost; sprintf(zkErrStr, "zk_ip_port is: %s", zk_ip_port.str().c_str()); SendEventMsg(MSG_SERVER_TRACE_INFO, EVENTLOG_INFORMATION_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); } if (initParam.debugFlag & SRVR_DEBUG_BREAK) zkSessionTimeout = 600; zoo_deterministic_conn_order(1); // enable deterministic order zh = zookeeper_init(zk_ip_port.str().c_str(), watcher, zkSessionTimeout * 1000, &myid, 0, 0); if (zh == 0){ sprintf(zkErrStr, "***** zookeeper_init() failed for host:port %s",zk_ip_port.str().c_str()); SendEventMsg( MSG_SET_SRVR_CONTEXT_FAILED, EVENTLOG_ERROR_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); // exit(1); } bool found = false; int rc; stringstream ss; ss.str(""); ss << zkRootNode << "/dcs/master"; string dcsMaster(ss.str()); Stat stat; int startPortNum = 0, portRangeNum; char masterHostName[MAX_HOST_NAME_LEN]; char startPort[12], portRange[12], masterTS[24]; struct String_vector children; children.count = 0; children.data = NULL; // Get the instance ID from registered node char *tkn; char tmpStr[256]; strcpy( tmpStr, regZnodeName ); tkn = strtok(tmpStr, ":" ); if(tkn!=NULL) strcpy(hostname,tkn); tkn = strtok(NULL, ":" ); if( tkn != NULL ) strcpy( instanceId, tkn ); tkn = strtok(NULL, ":" ); if( tkn != NULL ) strcpy( childId, tkn ); else ; // +++ Todo handle error while(!found) { rc = zoo_exists(zh, dcsMaster.c_str(), 0, &stat); if( rc == ZNONODE ) continue; else if( rc == ZOK ) { rc = zoo_get_children(zh, dcsMaster.c_str(), 0, &children); if( children.count > 0 ) { char zknodeName[2048]; strcpy(zknodeName, children.data[0]); tkn = strtok(zknodeName, ":" ); if( tkn != NULL ) strcpy( masterHostName, tkn ); tkn = strtok(NULL, ":" ); if( tkn != NULL ) { strcpy( startPort, tkn ); startPortNum = atoi(tkn); } tkn = strtok(NULL, ":" ); if( tkn != NULL ) { strcpy( portRange, tkn ); portRangeNum = atoi(tkn); } tkn = strtok(NULL, ":" ); if( tkn != NULL ) strcpy( masterTS, tkn ); free_String_vector(&children); found = true; } else continue; } else // error { sprintf(zkErrStr, "***** zoo_exists() for %s failed with error %d",dcsMaster.c_str(), rc); SendEventMsg( MSG_SET_SRVR_CONTEXT_FAILED, EVENTLOG_ERROR_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); break; } } // Initialize initparam to defaults initParam.transport = CEE_TRANSPORT_TCP; // -T 3 initParam.majorVersion = 3; // -V 3 // Will need to remove $ZTC0 and NonStopODBC from below sprintf( initParam.asSrvrObjRef, "TCP:$ZTC0/%s:NonStopODBC", startPort); // -A TCP:$ZTC0/52500:NonStopODBC // Will need to remove this after we get rid off all existing AS related processing sprintf( initParam.ASProcessName, "$MXOAS" ); // -AS $MXOAS // Will need to remove this after we get rid off all existing WMS related processing sprintf( initParam.QSProcessName, "$ZWMGR" ); // -QS $ZWMGR // moved this here from begining of the function BUILD_OBJECTREF(initParam.asSrvrObjRef, srvrObjRef, "NonStopODBC", initParam.portNumber); ss.str(""); ss << zkRootNode << "/dcs/servers/registered"; string dcsRegistered(ss.str()); char realpath[1024]; bool zk_error = false; if( found ) { sprintf(zkErrStr, "Found master node in Zookeeper"); SendEventMsg(MSG_SERVER_TRACE_INFO, EVENTLOG_INFORMATION_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); found = false; while(!found) { rc = zoo_exists(zh, dcsRegistered.c_str(), 0, &stat); if( rc == ZNONODE ) continue; else if( rc == ZOK ) { int i; //This section is the original port finding mechanism. //All servers (the herd) start looking for any available port //between starting port number+2 through port range max. //This is mainly for backward compatability for DcsServers //that don't pass PORTMAPTOSECS and PORTBINDTOSECS param if(portMapToSecs == -1 && portBindToSecs == -1) { for(i = startPortNum+2; i < startPortNum+portRangeNum; i++) { if (GTransport.m_listener->verifyPortAvailable("SRVR", i)) break; } if( i == startPortNum+portRangeNum ) { zk_error = true; sprintf(zkErrStr, "***** No ports free"); break; } } else { //This section is for new port map params, PORTMAPTOSECS and PORTBINDTOSECS, //passed in by DcsServer. DcsMaster writes the port map to data portion of //<username>/dcs/servers/registered znode. Wait PORTMAPTOSECS for port map //to appear in registered znode. When it appears read it and scan looking for //match of instance and child Id. long retryTimeout = 500;//.5 second long long timeout = JULIANTIMESTAMP(); bool isPortsMapped = false; char *zkData = new char[1000000]; int zkDataLen = 1000000; while(! isPortsMapped) { memset(zkData,0,1000000); rc = zoo_get(zh, dcsRegistered.c_str(), false, zkData, &zkDataLen, &stat); if( rc == ZOK && zkDataLen > 0 ) { sprintf(zkErrStr, "DCS port map = %s", zkData); SendEventMsg(MSG_SERVER_TRACE_INFO, EVENTLOG_INFORMATION_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); int myInstanceId = atoi(instanceId); int myChildId = atoi(childId); sprintf(zkErrStr, "Searching for my id (%d:%d) in port map",myInstanceId,myChildId); SendEventMsg(MSG_SERVER_TRACE_INFO, EVENTLOG_INFORMATION_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); char portMapInstanceId[8]; char portMapChildId[8]; char portMapPortNum[8]; char* saveptr; char* token = strtok_r (zkData,":",&saveptr); while (token != NULL) { if( token != NULL )//instance Id strcpy( portMapInstanceId, token ); token = strtok_r(NULL, ":",&saveptr); if( token != NULL )//child id strcpy( portMapChildId, token ); token = strtok_r(NULL, ":",&saveptr); if( token != NULL )//port number strcpy( portMapPortNum, token ); int currPortMapInstanceId = atoi(portMapInstanceId); int currPortMapChildId = atoi(portMapChildId); int currPortMapPortNum = atoi(portMapPortNum); if(myInstanceId == currPortMapInstanceId && myChildId == currPortMapChildId) { i = currPortMapPortNum; sprintf(zkErrStr, "Found my port number = %d in port map", i); SendEventMsg(MSG_SERVER_TRACE_INFO, EVENTLOG_INFORMATION_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); break; } else { token = strtok_r (NULL, ":",&saveptr); } } timeout = JULIANTIMESTAMP(); bool isAvailable = false; while ( isAvailable == false ) { if (GTransport.m_listener->verifyPortAvailable("SRVR", i)) { isAvailable = true; } else { if((JULIANTIMESTAMP() - timeout) > (portBindToSecs * 1000000)) { sprintf(zkErrStr, "Port bind timeout...exiting"); zk_error = true; break; } else { sprintf(zkErrStr, "Port = %d is already in use...retrying", i); SendEventMsg(MSG_SERVER_TRACE_INFO, EVENTLOG_INFORMATION_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); DELAY(retryTimeout); } } } isPortsMapped = true; } else { if((JULIANTIMESTAMP() - timeout) > (portMapToSecs * 1000000)) { sprintf(zkErrStr, "Port map read timeout...exiting"); zk_error = true; break; } else { sprintf(zkErrStr, "Waiting for port map"); SendEventMsg(MSG_SERVER_TRACE_INFO, EVENTLOG_INFORMATION_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); DELAY(retryTimeout); rc = zoo_exists(zh, dcsRegistered.c_str(), 0, &stat); } } } delete[] zkData; } initParam.portNumber = i; stringstream newpath; newpath.str(""); newpath << dcsRegistered.c_str() << "/" << regZnodeName; // dcsRegisteredNode.str(""); // dcsRegisteredNode << dcsRegistered.c_str() << "/" << regZnodeName; dcsRegisteredNode = newpath.str(); ss.str(""); ss << myPid; string pid(ss.str()); ss.str(""); ss << "STARTING" << ":" << JULIANTIMESTAMP() << ":" << ":" // Dialogue ID << myNid << ":" << myPid << ":" << myProcName.c_str() << ":" // Server IP address << ":" // Server Port << ":" // Client computer name << ":" // Client address << ":" // Client port << ":" // Client Appl name << ":"; regSrvrData = ss.str(); rc = zoo_create(zh, dcsRegisteredNode.c_str(), regSrvrData.c_str(), regSrvrData.length(), &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL, realpath, sizeof(realpath)-1); if( rc != ZOK ) { zk_error = true; sprintf(zkErrStr, "***** zoo_create() failed with error %d", rc); break; } found = true; } else // error { zk_error = true; sprintf(zkErrStr, "***** zoo_exists() for %s failed with error %d",dcsRegistered.c_str(), rc); break; } } } if( zk_error ) { SendEventMsg( MSG_SET_SRVR_CONTEXT_FAILED, EVENTLOG_ERROR_TYPE, processId, ODBCMX_SERVER, srvrObjRef, 1, zkErrStr); exit(1); } //LCOV_EXCL_START // when a server dies, the MXOAS sends message to CFG. CFG creates the MXOSRVR process // and passess only one command line atribute: -SQL CLEANUP OBSOLETE VOLATILE TABLES // It is for cleanup resources (volatile tables). // Newly created MXOSRVR process executes CLEANUP OBSOLETE VOLATILE TABLES and exits. // (This process is not managed by AS!. It is only a helper. if (initParam.sql != NULL) { if (strncmp(initParam.sql, "SELECT COUNT", 12) == 0) { //You can specify a completion code with any positive value in a PROCESS_STOP_. //Negative completion codes are reserved for HP use. //Therefore negative codes will return as 1000 + abs(completionCode) short completionCode = -1; completionCode = SQL_EXECDIRECT_FETCH(&initParam); if (completionCode < 0) completionCode = 1000 + abs(completionCode); #ifdef NSK_PLATFORM PROCESS_STOP_(,,,completionCode,,,,); #else /* * TODO: * need to revisit this logic to return a value via exit code * */ #endif } else {
//exists void exists(zhandle_t *zkhandle,char *str) { int flag = zoo_exists(zkhandle,str,1,NULL); }
int main() { char buffer[512]; char p[2048]; char *cert=0; char appId[64]; strcpy(appId, "example.foo_test"); cert = foo_get_cert_once(appId); if(cert!=0) { fprintf(stderr, "Certificate for appid [%s] is [%s]\n",appId,cert); strncpy(p,cert, sizeof(p)-1); free(cert); } else { fprintf(stderr, "Certificate for appid [%s] not found\n",appId); strcpy(p, "dummy"); } zoo_set_debug_level(ZOO_LOG_LEVEL_ERROR); zh = zookeeper_init("127.0.0.1:2181", watcher, 10000, 0, 0, 0); zh2 = zookeeper_init("127.0.0.1:2181", watcher, 10000, 0, 0, 0); // zookeeper_init是一个异步函数需要等待zh->state非0 while(zoo_state(zh) == 0) {} while(zoo_state(zh2) == 0) {} // struct Id id_tmp = {(char*)"digest", (char*)"user:tpUq/4Pn5A64fVZyQ0gOJ8ZWqkY="}; int rc = zoo_add_auth(zh,"digest", "dbscale:dbscale",strlen("dbscale:dbscale"),0,0); if (rc == ZOK){ printf("zoo add auth sucess\n"); } else { printf("zoo add auth failed\n"); } // struct ACL CREATE_ONLY_ACL[] = {{ZOO_PERM_ALL, id_tmp}};//, {ZOO_PERM_READ, ZOO_AUTH_IDS}, {ZOO_PERM_WRITE, ZOO_AUTH_IDS}}; // struct ACL_vector CREATE_ONLY = {1, CREATE_ONLY_ACL}; rc = zoo_create(zh,"/xyz","value", 5, &ZOO_CREATOR_ALL_ACL/*&CREATE_ONLY*/, ZOO_EPHEMERAL, buffer, sizeof(buffer)-1); if (rc == ZOK) { printf("create ok \n"); } else { printf("create faild%d\n" ,rc); } struct ACL_vector ret; printf("zoo set acl %d\n", zoo_get_acl(zh, "/xyz", &ret, 0)); rc = zoo_exists(zh, "/xyz", 0, 0); if (rc != ZOK) { printf("%d exist fail\n", rc); } else { printf("/xyz is exist\n"); } /** this operation will fail with a ZNOAUTH error */ int buflen= sizeof(buffer); struct Stat stat; rc = zoo_exists(zh2, "/xyz", 0, 0); if (rc == ZNOAUTH) { fprintf(stderr, "Error %d for %d\n", rc, __LINE__); } else { printf("zh2 exist %s\n", buffer); } rc = zoo_get(zh2, "/xyz", 0, buffer, &buflen, &stat); if (rc == ZNOAUTH) { fprintf(stderr, "Error %d for %d\n", rc, __LINE__); } else { printf("get data %s\n", buffer); } if (rc == ZOK){ printf("zoo create xyz sucess\n"); } else { printf("zoo create xyz failed %s\n", zerror(rc)); } rc = zoo_add_auth(zh2,"digest", "dbscale:dbscale",strlen("dbscale:dbscale"),0,0); if (rc == ZOK){ printf("zoo add auth sucess\n"); } else { printf("zoo add auth failed\n"); } rc = zoo_get(zh2, "/xyz", 0, buffer, &buflen, &stat); if (rc == ZNOAUTH) { fprintf(stderr, "Error %d for %d\n", rc, __LINE__); } else { printf("get data %s\n", buffer); } rc = zoo_wget(zh2, "/xyz", watcher, NULL, buffer, &buflen, &stat); if (rc == ZNOAUTH) { fprintf(stderr, "Error %d for %d\n", rc, __LINE__); } else { printf("wget sucess %s\n", buffer); } zookeeper_close(zh); return 0; }
void exists(zhandle_t* zkHandler, char *path) { int flag = zoo_exists(zkHandler, path, 1, NULL); printf("'%s' exists flag: %d\n", path, flag); }
bool zk::exists(const string& path) { scoped_lock lk(m_); int rc = zoo_exists(zh_, path.c_str(), 0, NULL); return rc == ZOK; }