void watchchildren(zhandle_t *zzh, int type, int state, const char *path,
             void* context)
{
    struct String_vector str;
    int rc;

    printf("The event path %s, event type %d\n", path, type);
    if (type == ZOO_SESSION_EVENT) {
        if (state == ZOO_CONNECTED_STATE) {
            return;
        } else if (state == ZOO_AUTH_FAILED_STATE) {
            zookeeper_close(zzh);
            exit(1);
        } else if (state == ZOO_EXPIRED_SESSION_STATE) {
            zookeeper_close(zzh);
            exit(1);
        }
    }
    // Put the watch again 
    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);
        }
    }
}
Beispiel #2
0
enum zoo_res zu_create_ephemeral(struct zoodis *z)
{
    int res;
    int bufsize = 512;
    char buffer[bufsize]; // no reason, added due to some of example, need to be done.
    int buffer_len = bufsize;
    memset(buffer, 0x00, bufsize);

    res = zoo_get(z->zh, z->zoo_nodepath->data, 0, buffer, &buffer_len, 0);

    if(res == ZOK)
    {
        if(buffer_len == z->zoo_nodedata->len && strncmp(z->zoo_nodedata->data, buffer, z->zoo_nodedata->len) == 0)
        {
            return ZOO_RES_OK;
        }else
        {
            zu_remove_ephemeral(z);
        }
    }else if(res != ZOK && res != ZNONODE)
    {
        ZU_RETURN_PRINT(res);
        if(res == ZINVALIDSTATE)
        {
            zookeeper_close(z->zh);
            zoodis.zoo_stat = ZOO_STAT_NOT_CONNECTED;
            z->zid = NULL;
            log_warn("Zookeeper: error, trying to re-connect.");
            zu_connect(z);
        }
        // exit_proc(-1);
    }

    res = zoo_create(z->zh, z->zoo_nodepath->data, z->zoo_nodedata->data, strlen(z->zoo_nodedata->data), &ZOO_READ_ACL_UNSAFE, ZOO_EPHEMERAL, buffer, sizeof(buffer)-1);
    if(res != ZOK)
    {
        ZU_RETURN_PRINT(res);
        if(res == ZINVALIDSTATE)
        {
            zookeeper_close(z->zh);
            zoodis.zoo_stat = ZOO_STAT_NOT_CONNECTED;
            z->zid = NULL;
            log_warn("Zookeeper: error, trying to re-connect.");
            zu_connect(z);
        }
    }

    return ZOO_RES_OK;
}
void watcher(zhandle_t *zzh, int type, int state, const char *path,
             void* context)
{
    if (type == ZOO_SESSION_EVENT) {
        if (state == ZOO_CONNECTED_STATE) {
            connected = 1;
        } else if (state == ZOO_AUTH_FAILED_STATE) {
            zookeeper_close(zzh);
            exit(1);
        } else if (state == ZOO_EXPIRED_SESSION_STATE) {
            zookeeper_close(zzh);
            exit(1);
        }
    }
}
zkServer::~zkServer()
{
    if(zkhandle != NULL)
    {
        zookeeper_close(zkhandle);
    }
};
ZKWrapper::~ZKWrapper()
{
	if (m_zkHandler)
	{
		zookeeper_close(m_zkHandler);
	}
}
/**
 * Watcher we use to process session events. In particular,
 * when it receives a ZOO_CONNECTED_STATE event, we set the
 * connected variable so that we know that the session has
 * been established.
 */
void main_watcher (zhandle_t *zkh,
                   int type,
                   int state,
                   const char *path,
                   void* context)
{
    /*
     * zookeeper_init might not have returned, so we
     * use zkh instead.
     */
    if (type == ZOO_SESSION_EVENT) {
        if (state == ZOO_CONNECTED_STATE) {
            connected = 1;

            LOG_DEBUG(("Received a connected event."));
        } else if (state == ZOO_CONNECTING_STATE) {
            if(connected == 1) {
                LOG_WARN(("Disconnected."));
            }
            connected = 0;
        } else if (state == ZOO_EXPIRED_SESSION_STATE) {
            expired = 1;
            connected = 0;
            zookeeper_close(zkh);
        }
    }
    LOG_DEBUG(("Event: %s, %d", type2string(type), state));
}
Beispiel #7
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);
}
Beispiel #8
0
//ZooKeeper Watcher
void watcher(zhandle_t *zzh, int type, int state, const char *path, void* context) {
    if (type == ZOO_SESSION_EVENT) {
        if (state == ZOO_CONNECTED_STATE) {
            const clientid_t *id = zoo_client_id(zzh);
            if (zkClientId.client_id == 0 || zkClientId.client_id != id->client_id) {
                zkClientId = *id; 
                completeZkInit = 1;
            }
        }
        } else if (state == ZOO_AUTH_FAILED_STATE || state == ZOO_EXPIRED_SESSION_STATE) {
                zookeeper_close(zzh);
                zh = 0;
        exit(-1);
        } else if (type == ZOO_CREATED_EVENT) {
                printf("\nZOO_CREATED_EVENT(%s)\n", path);
        } else if (type ==ZOO_DELETED_EVENT) {
                printf("\nZOO_DELETE_EVENT(%s)\n", path);
        } else if ( type == ZOO_CHANGED_EVENT) {
                printf("\nZOO_CHANGED_EVENT(%s)\n", path);
        } else if (type == ZOO_CHILD_EVENT) {
                printf("\nZOO_CHILD_CHANGED_EVENT(%s)\n", path);
                printChildren();
        } else {
                printf("ETC_EVENT(%d,%s)\n", type, path);
        }
}
Beispiel #9
0
    ZookeeperClient::~ZookeeperClient()
    {
	if (NULL != m_zk)
	{
	    zookeeper_close(m_zk);
	}
    }
Beispiel #10
0
ZooKeeperWatcher::~ZooKeeperWatcher()
{
  if (zk != NULL) {
    zookeeper_close(zk);
    zk = NULL;
  }
  events.clear();
}
Beispiel #11
0
int fini_zkhandle()
{
	int ret = 0;

	zookeeper_close(g_zhdl);

	return ret;
}
Beispiel #12
0
void watcher(zhandle_t *zzh, int type, int state, const char *path,
             void* context)
{
    /* Be careful using zh here rather than zzh - as this may be mt code
     * the client lib may call the watcher before zookeeper_init returns */

    fprintf(stderr, "Watcher %s state = %s", type2String(type), state2String(state));
    if (path && strlen(path) > 0) {
      fprintf(stderr, " for path %s", path);
    }
    fprintf(stderr, "\n");

    if (type == ZOO_SESSION_EVENT) {
        if (state == ZOO_CONNECTED_STATE) {
            const clientid_t *id = zoo_client_id(zzh);
            if (myid.client_id == 0 || myid.client_id != id->client_id) {
                myid = *id;
                fprintf(stderr, "Got a new session id: 0x%llx\n",
                        _LL_CAST_ myid.client_id);
                if (clientIdFile) {
                    FILE *fh = fopen(clientIdFile, "w");
                    if (!fh) {
                        perror(clientIdFile);
                    } else {
                        int rc = fwrite(&myid, sizeof(myid), 1, fh);
                        if (rc != sizeof(myid)) {
                            perror("writing client id");
                        }
                        fclose(fh);
                    }
                }
            }
        } else if (state == ZOO_AUTH_FAILED_STATE) {
            fprintf(stderr, "Authentication failure. Shutting down...\n");
            zookeeper_close(zzh);
            shutdownThisThing=1;
            zh=0;
        } else if (state == ZOO_EXPIRED_SESSION_STATE) {
            fprintf(stderr, "Session expired. Shutting down...\n");
            zookeeper_close(zzh);
            shutdownThisThing=1;
            zh=0;
        }
    }
}
Beispiel #13
0
void
ZHandleDeleter::operator() (zhandle_t* zhandle) const {
    CHECK(nullptr != zhandle) << "NULL zhandle";
    LOG(INFO) << "Destroying zhandle: " << zhandle;
    int result = zookeeper_close(zhandle);
    CHECK(ZOK == result)
            << "zookeeper_close() failed with error: "
            << zooErrorCodeToString(result);
}
Beispiel #14
0
// Destructor.
ZKClient::~ZKClient() {
  if (eventLoop_) {
    CHECK_EQ(eventLoop_->unRegisterForRead(pipers_[0]), 0);
  }
  close(pipers_[0]);
  close(pipers_[1]);
  delete zkaction_responses_;
  zookeeper_close(zk_handle_);
}
Beispiel #15
0
void
zenv_close(struct zenv_s *zenv)
{
    g_assert(zenv != NULL);

    zreactor_destroy(zenv->zr);
    zmq_ctx_destroy(zenv->zctx);
    zookeeper_close(zenv->zh);
}
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;
}  
Beispiel #17
0
Error_Info HBAgent::readZookeeper(){
          Error_Info err; 
	  string zk_snap;
	  const string ZK_SNAP="/wde/gbase/data/snapshot";
          zhandle_t * zh;
	  bool pingpong=false;
          zh=zookeeper_init(zookeeperAddress.c_str(),watcher, 10000, 0, &pingpong, 0);                              
          char buffer[8192];
          int buflen=sizeof(buffer);
          struct Stat stat;
 	  if(zh){
 	  	int rc;
		int sleeptimes=0;
		while(!pingpong){
			sleep(1);
			sleeptimes++;
			if(sleeptimes==10){
				err.code=-2;
				err.description="Can't Connected to Zookeeper: "+zookeeperAddress;
				return err;
			}
		}
		if(zoo_state(zh)!=ZOO_CONNECTED_STATE){
			err.code=HB_READZOOKEEPER_FAIL; 			err.description="Can't Connected to Zookeeper: "+zookeeperAddress;


			return err;
		}
          	rc=zoo_get(zh,ZK_SNAP.c_str(),0,buffer,&buflen,&stat);
		if(rc==ZOK){
          		zk_snap=string(buffer,buflen);
		}else{
			err.code=HB_BADZOOKEEPER_CONFIG;
			err.description="get snapshot from zookeeper fail";
			return err;
		}
          }else{
	      err.code=HB_READZOOKEEPER_FAIL;
              err.description="zookeeper init fail";
	      return err;
          }
          zookeeper_close(zh);
	  boost::replace_all(zk_snap,"\'","\"");
	  Json::Value root;
	  Json::Reader reader;
	  bool parseSuccess=reader.parse(zk_snap,root);
	  if(!parseSuccess){
		err.code=HB_READZOOKEEPER_FAIL;
		err.description="Bad Zookpeer Value for snapshot in Zookeeper";
	  }
	  collection=root["name"].asString();
	  columnfamily="contents";
	  err.code=HB_OK;
	  err.description="zookeeper init success";
	  return err;
}           
/**
 * ZKOP destructor
 * if not NULL
 * 1,delete handler
 * 2,delete context 
*/ 
ZKOP::~ZKOP()
{/*{{{*/
	if (zkhandle != NULL) {
		zookeeper_close(zkhandle);
		zkhandle = NULL;
	}

	if (context_ != NULL) {
		delete context_;
		context_ = NULL;
	}
}/*}}}*/
Beispiel #19
0
void zookeeper_init_watcher(zhandle_t *izh, int type, int state, const char *path, void *context)
{
    if (type == ZOO_SESSION_EVENT)
    {
        if (state == ZOO_CONNECTED_STATE)
        {
            is_connected = 1;
        } else if (state == ZOO_EXPIRED_SESSION_STATE) {
            is_connected = 0;
            zookeeper_close(izh);
        }
    }
}
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;
}
Beispiel #21
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;
}
Beispiel #22
0
    void ZookeeperClient::Close()
    {
	if (NULL != m_zk)
	{
	    if (-1 != m_zk_fd)
	    {
		aeDeleteFileEvent(m_serv.GetRawEventLoop(), m_zk_fd,
				AE_READABLE | AE_WRITABLE);
		m_zk_fd = -1;
	    }
	    zookeeper_close(m_zk);
	    m_zk = NULL;
	}
    }
Beispiel #23
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;
}
Beispiel #24
0
 void Cluster::OnInitWatcher(zhandle_t *zzh, int type, int state, const char *path)
 {
     INFO_LOG("Watcher %s state = %s for path %s", type2String(type), state2String(state), (path && strlen(path) > 0) ? path : "");
     if (type == ZOO_SESSION_EVENT)
     {
         if (state == ZOO_CONNECTED_STATE)
         {
             const clientid_t *id = zoo_client_id(zzh);
             if (m_zk_clientid.client_id == 0 || m_zk_clientid.client_id != id->client_id)
             {
                 m_zk_clientid = *id;
                 INFO_LOG("Got a new session id: 0x%llx", (long long )m_zk_clientid.client_id);
                 if (!g_db->GetConf().zk_clientid_file.empty())
                 {
                     std::string content;
                     content.assign((const char*) (&m_zk_clientid), sizeof(m_zk_clientid));
                     file_write_content(g_db->GetConf().zk_clientid_file, content);
                 }
             }
             m_state = ZK_STATE_CONNECTED;
         }
         else if (state == ZOO_AUTH_FAILED_STATE)
         {
             WARN_LOG("Zookeeper server authentication failure. Shutting down...");
             zookeeper_close(zzh);
             m_zk = NULL;
             m_state = ZK_STATE_DISCONNECT;
         }
         else if (state == ZOO_EXPIRED_SESSION_STATE)
         {
             WARN_LOG("Session expired. Shutting down...");
             zookeeper_close(zzh);
             m_zk = NULL;
             m_state = ZK_STATE_DISCONNECT;
         }
     }
 }
Beispiel #25
0
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;
}
static void zookeeper_shutdown(grpc_exec_ctx *exec_ctx,
                               grpc_resolver *resolver) {
  zookeeper_resolver *r = (zookeeper_resolver *)resolver;
  grpc_closure *call = NULL;
  gpr_mu_lock(&r->mu);
  if (r->next_completion != NULL) {
    *r->target_config = NULL;
    call = r->next_completion;
    r->next_completion = NULL;
  }
  zookeeper_close(r->zookeeper_handle);
  gpr_mu_unlock(&r->mu);
  if (call != NULL) {
    call->cb(exec_ctx, call->cb_arg, 1);
  }
}
Beispiel #27
0
static int destroy_zkrb_instance(struct zkrb_instance_data* ptr) {
  int rv = ZOK;

  if (ptr->zh) {
    const void *ctx = zoo_get_context(ptr->zh);
    /* Note that after zookeeper_close() returns, ZK handle is invalid */
    rv = zookeeper_close(ptr->zh);
    free((void *) ctx);
  }

#warning [wickman] TODO: fire off warning if queue is not empty
  if (ptr->queue) zkrb_queue_free(ptr->queue);

  ptr->zh = NULL;
  ptr->queue = NULL;
  return rv;
}
Beispiel #28
0
    int ZookeeperClient::Connect(const std::string& servers,
		    const ZKOptions& options)
    {
	if (NULL != m_zk)
	{
	    zookeeper_close(m_zk);
	    m_zk = NULL;
	}
	m_zk = zookeeper_init(servers.c_str(), ZookeeperClient::WatchCallback,
			options.recv_timeout, &options.clientid, this, 0);
	if (NULL == m_zk)
	{
	    ERROR_LOG("Failed to init zokkeeper.");
	    return -1;
	}
	m_callback = options.cb;
	CheckConn();
	return 0;
    }
Beispiel #29
0
// TODO: factorize with the similar function in sqliterepo/synchro.h
static void
zk_main_watch(zhandle_t *zh, int type, int state, const char *path,
		void *watcherCtx)
{
	metautils_ignore_signals();

	GRID_DEBUG("%s(%p,%d,%d,%s,%p)", __FUNCTION__,
			zh, type, state, path, watcherCtx);

	struct zk_manager_s *manager = watcherCtx;
	const char *zkurl = manager->zk_url;

	if (type != ZOO_SESSION_EVENT)
		return;

	if (state == ZOO_EXPIRED_SESSION_STATE) {
		GRID_WARN("Zookeeper: (re)connecting to [%s]", zkurl);
		if (manager->zh)
			zookeeper_close(manager->zh);

		/* XXX(jfs): forget the previous ID and reconnect */
		manager->zh = zookeeper_init(manager->zk_url, zk_main_watch,
				SQLX_SYNC_DEFAULT_ZK_TIMEOUT, NULL, manager, 0);
		if (!manager->zh) {
			GRID_ERROR("ZooKeeper init failure: (%d) %s",
					errno, strerror(errno));
			abort();
		}
	}
	else if (state == ZOO_AUTH_FAILED_STATE) {
		GRID_WARN("Zookeeper: auth problem to [%s]", zkurl);
	}
	else if (state == ZOO_ASSOCIATING_STATE) {
		GRID_DEBUG("Zookeeper: associating to [%s]", zkurl);
	}
	else if (state == ZOO_CONNECTED_STATE) {
		GRID_INFO("Zookeeper: connected to [%s]", zkurl);
	}
	else {
		GRID_INFO("Zookeeper: unmanaged event [%s]", zkurl);
	}
}
Beispiel #30
0
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;
}