Exemplo n.º 1
0
/**
 * Called from the main memcached code to initialize zookeeper code.
 */
bool mc_zookeeper_init() {
    //
    // Initialize Zookeeper stuff
    //
    switch (settings.verbose) {
    case 0:
        zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
        break;
    case 1:
        zoo_set_debug_level(ZOO_LOG_LEVEL_INFO);
        break;
    default:
        zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);
        break;
    }

    // enable deterministic order
    zoo_deterministic_conn_order(1);

    // Build the name of the announcement name and the path on the zookeeper service

    bool result = true;

    result &= build_announcement_info();
    result &= build_announcement_content();

    LOG_DEBUG(("Init called,%s starting zookeeper!", result ? "" : "not "));

    return result;
}
Exemplo n.º 2
0
static VALUE method_zkrb_init(int argc, VALUE* argv, VALUE self) {
  VALUE hostPort;
  VALUE options;

  rb_scan_args(argc, argv, "11", &hostPort, &options);

  if (NIL_P(options)) {
    options = rb_hash_new();
  } else {
    Check_Type(options, T_HASH);
  }

  Check_Type(hostPort, T_STRING);

  // Look up :zkc_log_level
  VALUE log_level = rb_hash_aref(options, ID2SYM(rb_intern("zkc_log_level")));
  if (NIL_P(log_level)) {
    zoo_set_debug_level(0); // no log messages
  } else {
    Check_Type(log_level, T_FIXNUM);
    zoo_set_debug_level((int)log_level);
  }


  VALUE data;
  struct zkrb_instance_data *zk_local_ctx;
  data = Data_Make_Struct(Zookeeper, struct zkrb_instance_data, 0, free_zkrb_instance_data, zk_local_ctx);
  zk_local_ctx->queue = zkrb_queue_alloc();

  if (zk_local_ctx->queue == NULL)
    rb_raise(rb_eRuntimeError, "could not allocate zkrb queue!");

  zoo_deterministic_conn_order(0);

  zkrb_calling_context *ctx =
    zkrb_calling_context_alloc(ZKRB_GLOBAL_REQ, zk_local_ctx->queue);

  zk_local_ctx->object_id = FIX2LONG(rb_obj_id(self));

  zk_local_ctx->zh =
      zookeeper_init(
          RSTRING_PTR(hostPort),
          zkrb_state_callback,
          session_timeout_msec(self),
          &zk_local_ctx->myid,
          ctx,
          0);

#warning [wickman] TODO handle this properly on the Ruby side rather than C side
  if (!zk_local_ctx->zh) {
    rb_raise(rb_eRuntimeError, "error connecting to zookeeper: %d", errno);
  }

  rb_iv_set(self, "@_data", data);
  rb_funcall(self, rb_intern("zkc_set_running_and_notify!"), 0);

error:
  return Qnil;
}
Exemplo n.º 3
0
void ZooKeeperTest::SetUpTestCase()
{
  if (!Jvm::created()) {
    std::string zkHome = flags.build_dir +
      "/3rdparty/zookeeper-" ZOOKEEPER_VERSION;

    std::string classpath = "-Djava.class.path=" +
      zkHome + "/zookeeper-" ZOOKEEPER_VERSION ".jar:" +
      zkHome + "/lib/log4j-1.2.15.jar";

    LOG(INFO) << "Using classpath setup: " << classpath << std::endl;

    std::vector<std::string> options;
    options.push_back(classpath);
    Try<Jvm*> jvm = Jvm::create(options);
    CHECK_SOME(jvm);

    if (!flags.verbose) {
      // Silence server logs.
      org::apache::log4j::Logger::getRootLogger()
        .setLevel(org::apache::log4j::Level::OFF);

      // Silence client logs.
      // TODO(jsirois): Create C++ ZooKeeper::setLevel.
      zoo_set_debug_level(ZOO_LOG_LEVEL_ERROR);
    }
  }
}
Exemplo n.º 4
0
int DevCtlServiceReg::RegService() {

    int timeout = 30000;
    zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);
    
    if (NULL == mZKHdl) {
        mZKHdl = zookeeper_init(mZKAddrList.c_str(), NULL, timeout, 0, (char *)"Config dev_controller", 0);
    }

    if (mZKHdl ==NULL)  
    {  
        LOG(ERROR)<<"Error when connecting to zookeeper servers...";
        return -1;
    }

    int ret = mkdirp(mZKHdl, mNodePath.c_str(), mNodePath.c_str());
    if (ret != 0) {
        LOG(ERROR)<<"mkdirp fail";
        return -1;
    }

    ret = zoo_set(mZKHdl, mNodeRealPath.c_str(),  mNodeValue.c_str(), mNodeValue.size(), -1);
    if(ret != ZOK){
        LOG(ERROR)<<"failed to set the data of path:"<<mNodeRealPath.c_str();
        return -1;
    }

    return 0;
}
Exemplo n.º 5
0
int main(int argc, const char *argv[])
{
    const char* host = "127.0.0.1:2181";
    int timeout = 30000;
    char buffer[512];
    int *bufferlen;

    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN); //设置日志级别,避免出现一些其他信息
    zhandle_t* zkhandle = zookeeper_init(host,zktest_watcher_g, timeout, 0, (void *)"hello zookeeper.", 0);
    if (zkhandle ==NULL)
    {
        fprintf(stderr, "Error when connecting to zookeeper servers...\n");
        exit(EXIT_FAILURE);
    }


    char str[]="/xyz30000000014";
    // wexists(zkhandle,str);
    // printf("---------------\n");
//    create(zkhandle,str);
    get(zkhandle);
     getChildren(zkhandle,str);
    getACL(zkhandle,str);
    while (1) {
        set(zkhandle, str);
        sleep(1);
    }
    //ddelete(zkhandle,str);


}
Exemplo n.º 6
0
int main(int argc, const char *argv[])
{

    const char* host = "127.0.0.1:2181";
    char *data = "alive";

    //const char* host = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183,127.0.0.1:2184,127.0.0.1:2185";
    int timeout = 30000;
    
    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
    zhandle_t* zkhandle = zookeeper_init(host,
            watcher_g, timeout, 0, "hello zookeeper.", 0);
    if (zkhandle == NULL) {
        fprintf(stderr, "Error when connecting to zookeeper servers...\n");
        exit(EXIT_FAILURE);
    }

    int ret = zoo_acreate(zkhandle, "/server", data, strlen(data),
           &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL,
           completion, "zoo_acreate");
    if (ret) {
        fprintf(stderr, "Error %d for %s\n", ret, "acreate");
        exit(EXIT_FAILURE);
    }

    do {
        //sleep 5, then down
        accept_query();
        sleep(5);
    } while(false);

    zookeeper_close(zkhandle);
}
Exemplo n.º 7
0
int main(int argc, const char *argv[])  
{  
    int timeout = 30000;  
  
    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN); //设置日志级别,避免出现一些其他信息  

    get_option(argc,argv);

    zhandle_t* zkhandle = zookeeper_init(g_host,NULL, timeout, 0, (char *)"Load Balancing Test", 0);  

    if (zkhandle ==NULL){ 
        fprintf(stderr, "Error when connecting to zookeeper servers...\n");  
        exit(EXIT_FAILURE);  
    }  
    
    char consumer_path[512] = "/Consumer";
    char topic_path[512] = {0};
    char group_path[512] = {0};
    char client_path[512] = {0};
    
    sprintf(topic_path,"%s/%s",consumer_path,g_topic);
    sprintf(group_path,"%s/group-%d",topic_path,g_groupid);
    sprintf(client_path,"%s/client-",group_path);
    

    create(zkhandle,consumer_path,0,"");
    create(zkhandle,topic_path,0,"");
    create(zkhandle,group_path,0,"00000000");
    
    int bufferlen = sizeof(g_my_path);

    int ret = zoo_create(zkhandle,client_path,NULL,0,
                          &ZOO_OPEN_ACL_UNSAFE,ZOO_SEQUENCE|ZOO_EPHEMERAL,
                          g_my_path,bufferlen);
  
    if (ret != ZOK){  
        printf("节点创建失败:%s \n",client_path);  
        exit(EXIT_FAILURE);  
    }else {  
        printf("创建的节点名称为:%s\n",g_my_path);  
    }

    char self_name[512] = {0};
    
    strcpy(self_name,rindex(g_my_path,'/')+1);

    
    choose_mater(zkhandle,group_path,self_name);

    do_work(zkhandle);

    getchar();

    zookeeper_close(zkhandle); 

    return 0;
}  
Exemplo n.º 8
0
END_TEST

START_TEST(test_zookeeper)
{
	assert_ret(init_event(4096), 0);
#ifdef BUILD_ZOOKEEPER
	zoo_set_debug_level(0);
#endif
	do_test("zookeeper:localhost:2181,timeout=1000");
}
int ZKWrapper::Init(const char *host)
{
	zoo_set_debug_level(ZOO_LOG_LEVEL_ERROR);

	m_zkHandler = zookeeper_init((char*)host, zkWatcherCallback, m_nTimeout, 0, this, 0);
	if (m_zkHandler == NULL) 
	{
		std::cerr << "ERROR: connect to zookeeper server failed!!" << std::endl;
		return -1;
	}
	return 0;
}
Exemplo n.º 10
0
void zu_set_log_level(int level)
{

    switch(level)
    {
    case _LOG_DEBUG:
        zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);
        break;
    case _LOG_INFO:
        zoo_set_debug_level(ZOO_LOG_LEVEL_INFO);
        break;
    case _LOG_WARN:
        zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
        break;
    case _LOG_ERR:
        zoo_set_debug_level(ZOO_LOG_LEVEL_ERROR);
        break;
    default:
        zoo_set_debug_level(ZOO_LOG_LEVEL_INFO);
        break;
    }
}
Exemplo n.º 11
0
int main(int argc, char **argv) {
    int nodeCount;
    int cleaning=0;
    if (argc < 4) {
        usage(argv);
    }
    if(strcmp("clean",argv[3])==0){
        cleaning=1;
    }
    zoo_set_debug_level(ZOO_LOG_LEVEL_INFO);
    zoo_deterministic_conn_order(1); // enable deterministic order

    zh = zookeeper_init(argv[1], listener, 10000, 0, 0, 0);
    if (!zh)
        return errno;

    LOG_INFO(LOGSTREAM, "Checking server connection...");
    ensureConnected();
    if(cleaning==1){
        int rc = 0;
        deletedCounter=0;
        rc=recursiveDelete(argv[2]);
        if(rc==ZOK){
            LOG_INFO(LOGSTREAM, "Successfully deleted a subtree starting at %s (%d nodes)",
                    argv[2],deletedCounter);
            exit(0);
        }
        exit(1);
    }
    nodeCount=atoi(argv[3]);
    createRoot(argv[2]);
    while(1) {
        ensureConnected();
        LOG_INFO(LOGSTREAM, "Creating children for path %s",argv[2]);
        doCreateNodes(argv[2],nodeCount);
        waitCounter();
        
        LOG_INFO(LOGSTREAM, "Starting the write cycle for path %s",argv[2]);
        doWrites(argv[2],nodeCount);
        waitCounter();
        LOG_INFO(LOGSTREAM, "Starting the read cycle for path %s",argv[2]);
        doReads(argv[2],nodeCount);
        waitCounter();

        LOG_INFO(LOGSTREAM, "Starting the delete cycle for path %s",argv[2]);
        doDeletes(argv[2],nodeCount);
        waitCounter();
    }
    zookeeper_close(zh);
    return 0;
}
Exemplo n.º 12
0
int main(int argc, const char *argv[])  
{  
    int timeout = 30000;  
    char path_buffer[512];  
    int bufferlen=sizeof(path_buffer);  
  
    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN); //设置日志级别,避免出现一些其他信息  

    get_option(argc,argv);

    zhandle_t* zkhandle = zookeeper_init(g_host,NULL, timeout, 0, (char *)"Load Balancing Test", 0);  

    if (zkhandle ==NULL){ 
        fprintf(stderr, "Error when connecting to zookeeper servers...\n");  
        exit(EXIT_FAILURE);  
    }  
    
    char breaker_path[512] = "/Breaker";
    char topic_path[512] = {0};
    char partition_path[512] = {0};
    
    sprintf(topic_path,"%s/%s",breaker_path,g_topic);

    //init environment
    create(zkhandle,breaker_path,0,"");  
    create(zkhandle,topic_path,0,"");  

    int i = 0;
    for(i = 0; i < g_partition_num ; ++i){
        sprintf(partition_path,"%s/Partition-%d",topic_path,i);
        create(zkhandle,partition_path,0,"");
    }
    
    //send message by rand time
    srand(time(NULL));
    char msg_path[512] = {0};
    for(i = 0; i <  g_repeated_num; ++i){
        sprintf(msg_path,"%s/Partition-%d/msg-",topic_path,i % g_partition_num);
        // create seq msg node
        create(zkhandle,msg_path,ZOO_SEQUENCE,g_msg);
        int time = rand()%10;
        printf("sleep time:%d\n",time);
        sleep(time);
    }



    zookeeper_close(zkhandle); 

    return 0;
}
Exemplo n.º 13
0
int main(int argc, char **argv) {
  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_DEBUG);

  zh = zookeeper_init("localhost:2181", watcher, 10000, 0, 0, 0);
  if (!zh) {
	fprintf(stderr, "Error1: %s\n", strerror(errno));
    return errno;
  }
  if (zoo_add_auth(zh, "foo", p, strlen(p), 0, 0) != ZOK) {
    fprintf(stderr, "Error2: %s\n", strerror(errno));
    return 2;
  }

  struct ACL CREATE_ONLY_ACL[] = {{ZOO_PERM_CREATE, ZOO_AUTH_IDS}};
  struct ACL_vector CREATE_ONLY = {1, CREATE_ONLY_ACL};
  int rc = zoo_create(zh, "/xyz", "value", 5, &CREATE_ONLY, ZOO_EPHEMERAL, (char*)&buffer, sizeof(buffer) - 1);
  if (!rc) {
    fprintf(stderr, "Error3: %s\n", strerror(errno));
    return errno;
  }

  /** this operation will fail with a ZNOAUTH error */
  int buflen= sizeof(buffer);
  struct Stat stat;
  rc = zoo_get(zh, "/xyz", 0, buffer, &buflen, &stat);
  if (rc) {
    fprintf(stderr, "Error4: %d for %s\n", rc, __LINE__);
  } else {
	fprintf(stdout, "Got %s\n", (char*)&buffer);
  }

  zookeeper_close(zh);
  return 0;
}
Exemplo n.º 14
0
static zhandle_t* initialize_zookeeper(const char * zookeeper, void* param)
{
    zoo_set_debug_level(ZOO_LOG_LEVEL_ERROR);
    ((kafka_t*) param)->no_brokers = 1;
    ((kafka_t*) param)->broker_list = NULL;
    zhandle_t *zh;
    zh = zookeeper_init(zookeeper, watcher, 10000, 0, param, 0);
    if (zh == NULL)
    {
        fprintf(stderr, "Zookeeper connection not established.");
        //exit(1);
    }
    return zh;
}
Exemplo n.º 15
0
int init (char * hostPort) {
    srand(time(NULL));
    server_id  = rand();
    
    zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);
    
    zh = zookeeper_init(hostPort,
                        main_watcher,
                        15000,
                        0,
                        0,
                        0);
    
    return errno;
}
Exemplo n.º 16
0
    int ZkHelper::registe_service(const std::string& sevice_name, const std::string& endpoint)
    {
        zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
        zk_ = zookeeper_init("127.0.0.1:2181", &g_zk_watcher, 1000, 0, 0, 0);
        if( NULL == zk_ )
        {
            printf("zookeeper_init error\n");
            return errno;
        }

        int flag = ZOO_EPHEMERAL;
        int rc = zoo_acreate(zk_, sevice_name.c_str(), endpoint.c_str(), endpoint.size(),
                            &ZOO_OPEN_ACL_UNSAFE, flag, acreate_completion, endpoint.c_str());
        return rc;
    }
Exemplo n.º 17
0
static zhandle_t* initialize_zookeeper(const char * zookeeper, const int debug)
{
	zhandle_t *zh;
	if (debug)
	{
		zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);
	}
	zh = zookeeper_init(zookeeper, watcher, 10000, 0, 0, 0);
	if (zh == NULL)
	{
		fprintf(stderr, "Zookeeper connection not established.");
		exit(1);
	}
	return zh;
}
Exemplo n.º 18
0
int Register::connect()
{
	  zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);
	zh=zookeeper_init(zookeeper_addr.c_str(),watcher,10000,&myid,0,0);
	if(!zh)
	{

	}

	LOG(INFO)<<"InitSucc\n";



	return 0;

}
Exemplo n.º 19
0
 int ZKAgent::Init(ArdbServer* serv)
 {
     m_server = serv;
     ArdbServerConfig& cfg = serv->m_cfg;
     if (cfg.zookeeper_servers.empty())
     {
         WARN_LOG("No zookeeper servers specified, zookeeper agent would not start.");
         return 0;
     }
     ZooLogLevel z_log_loevel;
     if (DEBUG_ENABLED())
     {
         z_log_loevel = ZOO_LOG_LEVEL_DEBUG;
     }
     else if (INFO_ENABLED())
     {
         z_log_loevel = ZOO_LOG_LEVEL_INFO;
     }
     else if (WARN_ENABLED())
     {
         z_log_loevel = ZOO_LOG_LEVEL_WARN;
     }
     else if (ERROR_ENABLED())
     {
         z_log_loevel = ZOO_LOG_LEVEL_ERROR;
     }
     else
     {
         z_log_loevel = ZOO_LOG_LEVEL_DEBUG;
     }
     zoo_set_debug_level(z_log_loevel);
     zoo_set_log_stream(ArdbLogger::GetLogStream());
     std::string zkidfile = cfg.home + "/.zkcid";
     FILE* idfile = fopen(zkidfile.c_str(), "r");
     if (idfile != NULL)
     {
         if (fread(&m_zk_clientid, sizeof(m_zk_clientid), 1, idfile) != 1)
         {
             memset(&m_zk_clientid, 0, sizeof(m_zk_clientid));
         }
         fclose(idfile);
     }
     Reconnect();
     return 0;
 }
Exemplo n.º 20
0
static VALUE method_initialize(VALUE self, VALUE hostPort) {
  VALUE data;
  struct zk_rb_data* zk = NULL;

  Check_Type(hostPort, T_STRING);

  data = Data_Make_Struct(ZooKeeper, struct zk_rb_data, 0, free_zk_rb_data, zk);

  zoo_set_debug_level(ZOO_LOG_LEVEL_INFO);
  zoo_deterministic_conn_order(0);
  zk->zh = zookeeper_init(RSTRING(hostPort)->ptr, watcher, 10000, &zk->myid, (void*)self, 0);
  if (!zk->zh) {
    rb_raise(rb_eRuntimeError, "error connecting to zookeeper: %d", errno);
  }

  rb_iv_set(self, "@data", data);

  return Qnil;
}
Exemplo n.º 21
0
static grpc_resolver *zookeeper_create(grpc_resolver_args *args,
                                       const char *lb_policy_name) {
  zookeeper_resolver *r;
  size_t length;
  char *path = args->uri->path;

  if (0 == strcmp(args->uri->authority, "")) {
    gpr_log(GPR_ERROR, "No authority specified in zookeeper uri");
    return NULL;
  }

  /** Removes the trailing slash if exists */
  length = strlen(path);
  if (length > 1 && path[length - 1] == '/') {
    path[length - 1] = 0;
  }

  r = gpr_malloc(sizeof(zookeeper_resolver));
  memset(r, 0, sizeof(*r));
  gpr_ref_init(&r->refs, 1);
  gpr_mu_init(&r->mu);
  grpc_resolver_init(&r->base, &zookeeper_resolver_vtable);
  r->name = gpr_strdup(path);

  r->client_channel_factory = args->client_channel_factory;
  grpc_client_channel_factory_ref(r->client_channel_factory);

  r->lb_policy_name = gpr_strdup(lb_policy_name);

  /** Initializes zookeeper client */
  zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
  r->zookeeper_handle =
      zookeeper_init(args->uri->authority, zookeeper_global_watcher,
                     GRPC_ZOOKEEPER_SESSION_TIMEOUT, 0, 0, 0);
  if (r->zookeeper_handle == NULL) {
    gpr_log(GPR_ERROR, "Unable to connect to zookeeper server");
    return NULL;
  }

  return &r->base;
}
Exemplo n.º 22
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);
        }
}
Exemplo n.º 23
0
int
main(int argc, const char *argv[])
{
    const char *host = "127.0.0.1:2181";
    int timeout = 30000;

    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
    zhandle_t *zkhandle = zookeeper_init(host,
         watcher_global, timeout, 0, "watcher_global", 0);

    if (zkhandle == NULL) {
        fprintf(stderr, "Error when connecting to zookeeper servers...\n");
        exit(EXIT_FAILURE);
    }


    /*
    1.
    int ret = zoo_exists(zkhandle, "/server", 0, &s);

    2.
    int ret = zoo_exists(zkhandle, "/server", 10, &s);

    3.

    */
    
    int ret = zoo_wexists(zkhandle, "/server", watcher_wexists, 
        "watch_wexists", &s);
    
    if (ret) { fprintf(stderr, "Error %d for %s\n", ret, "aexists");
    }

    getchar(); //hold 

    zookeeper_close(zkhandle);

    return 0;
}
Exemplo n.º 24
0
int main(int argc, char** argv)
{
	char buffer[512];
	char p[2048];
	char *cert=0;
	char appId[64];
	strcpy(p, "dummy");
	zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);
	zh = zookeeper_init("localhost:2181", watcher, 10000,0,0,0);
	while(zoo_state(zh) == 0);
	if(zoo_add_auth(zh,"digest",p,strlen(p),0,0) != ZOK)
	{
		printf("auto failed\n");
		return 2;
	}

	printf("auto success\n");
	struct ACL CREATE_ONLY_ACL[] = {{ZOO_PERM_CREATE, ZOO_AUTH_IDS}};
	struct ACL_vector CREATE_ONLY = {1, CREATE_ONLY_ACL};
	int rc = zoo_create(zh, "/zookeeper/xyz","value",5,&ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL,buffer, sizeof(buffer) -1);

	int buflen = sizeof(buffer);
	struct Stat stat;
	while(true)
	{
		rc = zoo_get(zh, "/zookeeper/xyz", 0, buffer, &buflen, &stat);
		if(rc)
		{
			fprintf(stderr, "Error %d, for %d\n",rc, __LINE__);
		}

		printf("%s", buffer);
		sleep(5);
	}
	zookeeper_close(zh);
	return 0;
}
/**
 * 1,set debug level of log
 * 2,init zookeeper(connect host and set timeout and callback func)
 * 3,if fail then false else true 
 * \param host indicate zookeeper server lists
 * \param fun indicate callback func
 * \param timeout indicate timeout of zookeeper
*/ 
bool ZKOP::zkInit(const std::string& host, const wrapFunc& func, const int timeout)
{/*{{{*/
	zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
	m_host = host;
	m_timeout = timeout;
	m_func = func;

	context_ = new detail::ZooKeeperWatcher(func);
	zkhandle = zookeeper_init(host.data(), 
			detail::watcher, 
			timeout,
			&clientid_,
			context_,
			0);

	//if (zoo_state(zkhandle) != ZOO_CONNECTED_STATE) ???
	if (NULL == zkhandle) {
		LOG(INFO) << "init zookeeper handle fail!\t"<< "host:" << host;
		return false;
	}else{
		LOG(INFO) << "init zookeeper successful!";
		return true;
	}
}/*}}}*/
Exemplo n.º 26
0
int 
main(int argc, const char *argv[])
{
    const char* host = "127.0.0.1:2181";
    zhandle_t* zkhandle;
    int timeout = 5000;
    char node[512] = {0};
    char tables[][64] = {
        {"employee_info_tab"},
        {"boss_info_tab"}
    };
    
    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
    zkhandle = zookeeper_init(host, NULL, timeout, 
                              0, "Zookeeper examples: config center services", 0);
    if (zkhandle == NULL) {
        fprintf(stderr, "Connecting to zookeeper servers error...\n");
        exit(EXIT_FAILURE);
    }

    /* join the election group */
    struct watch_func_para_t para;
    int ret = join_the_election(zkhandle, node, &para);
    if (zkhandle == NULL) {
        fprintf(stderr, "join the election error...\n");
        exit(EXIT_FAILURE);
    }

    /* leader election */
    if (is_leader(zkhandle, node)) {
        i_am_leader = true;
        printf("This is [%s], i am a leader\n", node);
        (void)create_tables(zkhandle, tables, sizeof(tables)/sizeof(tables[0]));
    } else {
        i_am_leader = false;
        printf("This is [%s], i am a follower\n", node);
    }

    /* start the trigger listen thread */
    pthread_attr_t attr1;
    ret = pthread_attr_init(&attr1);
    if (ret != 0) {
        fprintf(stderr, "pthread_attr_init error...\n");
        exit(EXIT_FAILURE);
    }

    pthread_t trigger_listen_thr;
    ret = pthread_create(&trigger_listen_thr, &attr1, trigger_listen_thread, zkhandle);
    if (ret != 0) {
        fprintf(stderr, "pthread_create error...\n");
        exit(EXIT_FAILURE);
    }

    ret = pthread_attr_destroy(&attr1);
    if (ret != 0) {
        fprintf(stderr, "pthread_attr_destroy error...\n");
        exit(EXIT_FAILURE);
    }
    
    /* start the item expire thread */
    pthread_attr_t attr2;
    ret = pthread_attr_init(&attr2);
    if (ret != 0) {
        fprintf(stderr, "pthread_attr_init error...\n");
        exit(EXIT_FAILURE);
    }

    pthread_t expire_thr;
    ret = pthread_create(&expire_thr, &attr2, item_expire_thread, zkhandle);
    if (ret != 0) {
        fprintf(stderr, "pthread_create error...\n");
        exit(EXIT_FAILURE);
    }

    ret = pthread_attr_destroy(&attr2);
    if (ret != 0) {
        fprintf(stderr, "pthread_attr_destroy error...\n");
        exit(EXIT_FAILURE);
    }

    void *res;
    ret = pthread_join(trigger_listen_thr, (void**)&res);
    if (ret != 0) {
        fprintf(stderr, "pthread_join error...\n");
        exit(EXIT_FAILURE);
    }

    ret = pthread_join(expire_thr, (void**)&res);
    if (ret != 0) {
        fprintf(stderr, "pthread_join error...\n");
        exit(EXIT_FAILURE);
    }

    zookeeper_close(zkhandle);
}
Exemplo n.º 27
0
int main(int argc, char **argv) {
#ifndef THREADED
    fd_set rfds, wfds, efds;
    int processed=0;
#endif
    char buffer[4096];
    char p[2048];
#ifdef YCA  
    char *cert=0;
    char appId[64];
#endif
    int bufoff = 0;
    FILE *fh;

    if (argc < 2) {
        fprintf(stderr,
                "USAGE %s zookeeper_host_list [clientid_file|cmd:(ls|ls2|create|od|...)]\n", 
                argv[0]);
        fprintf(stderr,
                "Version: ZooKeeper cli (c client) version %d.%d.%d\n", 
                ZOO_MAJOR_VERSION,
                ZOO_MINOR_VERSION,
                ZOO_PATCH_VERSION);
        return 2;
    }
    if (argc > 2) {
      if(strncmp("cmd:",argv[2],4)==0){
        size_t cmdlen = strlen(argv[2]);
        if (cmdlen > sizeof(cmd)) {
          fprintf(stderr,
                  "Command length %zu exceeds max length of %zu\n",
                  cmdlen,
                  sizeof(cmd));
          return 2;
        }
        strncpy(cmd, argv[2]+4, sizeof(cmd));
        batchMode=1;
        fprintf(stderr,"Batch mode: %s\n",cmd);
      }else{
        clientIdFile = argv[2];
        fh = fopen(clientIdFile, "r");
        if (fh) {
            if (fread(&myid, sizeof(myid), 1, fh) != sizeof(myid)) {
                memset(&myid, 0, sizeof(myid));
            }
            fclose(fh);
        }
      }
    }
#ifdef YCA
    strcpy(appId,"yahoo.example.yca_test");
    cert = yca_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");
    }
#else
    strcpy(p, "dummy");
#endif
    verbose = 0;
    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
    zoo_deterministic_conn_order(1); // enable deterministic order
    hostPort = argv[1];
    zh = zookeeper_init(hostPort, watcher, 30000, &myid, 0, 0);
    if (!zh) {
        return errno;
    }

#ifdef YCA
    if(zoo_add_auth(zh,"yca",p,strlen(p),0,0)!=ZOK)
    return 2;
#endif

#ifdef THREADED
    while(!shutdownThisThing) {
        int rc;
        int len = sizeof(buffer) - bufoff -1;
        if (len <= 0) {
            fprintf(stderr, "Can't handle lines that long!\n");
            exit(2);
        }
        rc = read(0, buffer+bufoff, len);
        if (rc <= 0) {
            fprintf(stderr, "bye\n");
            shutdownThisThing=1;
            break;
        }
        bufoff += rc;
        buffer[bufoff] = '\0';
        while (strchr(buffer, '\n')) {
            char *ptr = strchr(buffer, '\n');
            *ptr = '\0';
            processline(buffer);
            ptr++;
            memmove(buffer, ptr, strlen(ptr)+1);
            bufoff = 0;
        }
    }
#else
    FD_ZERO(&rfds);
    FD_ZERO(&wfds);
    FD_ZERO(&efds);
    while (!shutdownThisThing) {
        int fd;
        int interest;
        int events;
        struct timeval tv;
        int rc;
        zookeeper_interest(zh, &fd, &interest, &tv);
        if (fd != -1) {
            if (interest&ZOOKEEPER_READ) {
                FD_SET(fd, &rfds);
            } else {
                FD_CLR(fd, &rfds);
            }
            if (interest&ZOOKEEPER_WRITE) {
                FD_SET(fd, &wfds);
            } else {
                FD_CLR(fd, &wfds);
            }
        } else {
            fd = 0;
        }
        FD_SET(0, &rfds);
        rc = select(fd+1, &rfds, &wfds, &efds, &tv);
        events = 0;
        if (rc > 0) {
            if (FD_ISSET(fd, &rfds)) {
                events |= ZOOKEEPER_READ;
            }
            if (FD_ISSET(fd, &wfds)) {
                events |= ZOOKEEPER_WRITE;
            }
        }
        if(batchMode && processed==0){
          //batch mode
          processline(cmd);
          processed=1;
        }
        if (FD_ISSET(0, &rfds)) {
            int rc;
            int len = sizeof(buffer) - bufoff -1;
            if (len <= 0) {
                fprintf(stderr, "Can't handle lines that long!\n");
                exit(2);
            }
            rc = read(0, buffer+bufoff, len);
            if (rc <= 0) {
                fprintf(stderr, "bye\n");
                break;
            }
            bufoff += rc;
            buffer[bufoff] = '\0';
            while (strchr(buffer, '\n')) {
                char *ptr = strchr(buffer, '\n');
                *ptr = '\0';
                processline(buffer);
                ptr++;
                memmove(buffer, ptr, strlen(ptr)+1);
                bufoff = 0;
            }
        }
        zookeeper_process(zh, events);
    }
#endif
    if (to_send!=0)
        fprintf(stderr,"Recvd %d responses for %d requests sent\n",recvd,sent);
    zookeeper_close(zh);
    return 0;
}
Exemplo n.º 28
0
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);
    }
}
Exemplo n.º 29
0
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[])
{
    int rc;
    int fd;
    int interest;
    int events;
    struct timeval tv;
    fd_set rfds, wfds, efds;

    if (argc != 2) {
        fprintf(stderr, "USAGE: %s host:port\n", argv[0]);
        exit(1);
    }

    FD_ZERO(&rfds);
    FD_ZERO(&wfds);
    FD_ZERO(&efds);

    zoo_set_debug_level(ZOO_LOG_LEVEL_INFO);
    zoo_deterministic_conn_order(1); 
    hostPort = argv[1];

    zh = zookeeper_init(hostPort, watcher, 30000, &myid, 0, 0);
    if (!zh) {
        return errno;
    }

    while (1) {
        zookeeper_interest(zh, &fd, &interest, &tv);
        usleep(10);
        if (connected == 1) {
            struct String_vector str;

            usleep(10);
            // watch existence of the node
            rc = zoo_wget_children(zh, "/testpath1", 
                    watchchildren , mycontext, &str);
            if (ZOK != rc){
                printf("Problems  %d\n", rc);
            } else {
                int i = 0;
                while (i < str.count) {
                    printf("Children %s\n", str.data[i++]);
                } 
                if (str.count) {
                    deallocate_String_vector(&str);
                }
            }
            connected++;
        }
        if (fd != -1) {
            if (interest & ZOOKEEPER_READ) {
                FD_SET(fd, &rfds);
            } else {
                FD_CLR(fd, &rfds);
            }
            if (interest & ZOOKEEPER_WRITE) {
                FD_SET(fd, &wfds);
            } else {
                FD_CLR(fd, &wfds);
            }
        } else {
            fd = 0;
        }
        FD_SET(0, &rfds);
        rc = select(fd+1, &rfds, &wfds, &efds, &tv);
        events = 0;
        if (rc > 0) {
            if (FD_ISSET(fd, &rfds)) {
           	    events |= ZOOKEEPER_READ;
            }
            if (FD_ISSET(fd, &wfds)) {
                events |= ZOOKEEPER_WRITE;
            }
        }
        zookeeper_process(zh, events);
    }
    return 0;
}