コード例 #1
0
ファイル: zookeeper.c プロジェクト: NessComputing/memcached
/**
 * 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;
}
コード例 #2
0
ファイル: zookeeper_c.c プロジェクト: slyphon/zookeeper-fork
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;
}
コード例 #3
0
 ZooKeeperSessionManager::ZooKeeperSessionManager( const std::string& host, int connectionTimeout, int sessionExpirationTimeout, int deterministicConnectionOrder ) :
   m_host( host ),
   m_connectionTimeout( connectionTimeout ),
   m_expirationTimeout( sessionExpirationTimeout ),
   m_deterministicConnectionOrder( deterministicConnectionOrder ),
   m_handle( nullptr ),
   m_isInitialized( false )
 {
   zoo_deterministic_conn_order( deterministicConnectionOrder );
 }
コード例 #4
0
ファイル: load_gen.c プロジェクト: Felix-Pobaby/zookeeper
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;
}
コード例 #5
0
ファイル: zkclient.cpp プロジェクト: 10fish/heron
void ZKClient::Init() {
  zkaction_responses_ = new PCQueue();
  auto zkaction_response_cb = [this](EventLoop::Status status) {
    this->OnZkActionResponse(status);
  };

  if (pipe(pipers_) < 0) {
    LOG(FATAL) << "Pipe failed in ZKClient";
  }
  sp_int32 flags;
  if ((flags = fcntl(pipers_[0], F_GETFL, 0)) < 0 ||
      fcntl(pipers_[0], F_SETFL, flags | O_NONBLOCK) < 0 ||
      eventLoop_->registerForRead(pipers_[0], std::move(zkaction_response_cb), true) != 0) {
    LOG(FATAL) << "fcntl failed in ZKClient";
  }
  zoo_deterministic_conn_order(0);  // even distribution of clients on the server
  InitZKHandle();
}
コード例 #6
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;
}
コード例 #7
0
ファイル: c_test.c プロジェクト: erich0929/programming
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);
        }
}
コード例 #8
0
ファイル: cli.c プロジェクト: spilchen/zookeeper
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;
}
コード例 #9
0
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;
}
コード例 #10
0
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
      {
コード例 #11
0
ファイル: zookeeper_c.c プロジェクト: slyphon/zookeeper-fork
static VALUE method_deterministic_conn_order(VALUE self, VALUE yn) {
  zoo_deterministic_conn_order(yn == Qtrue);
  return Qnil;
}
コード例 #12
0
ファイル: zkrb.c プロジェクト: ClarityServices/zookeeper
static VALUE method_zkrb_init(int argc, VALUE* argv, VALUE self) {
  VALUE hostPort=Qnil;
  VALUE options=Qnil;

  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(FIX2INT(log_level));
  }

  volatile VALUE data;
  zkrb_instance_data_t *zk_local_ctx;
  data = Data_Make_Struct(CZookeeper, zkrb_instance_data_t, 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),        // const char *host
          zkrb_state_callback,          // watcher_fn
          session_timeout_msec(self),   // recv_timeout
          &zk_local_ctx->myid,          // cilentid_t
          ctx,                          // void *context
          0);                           // flags

  zkrb_debug("method_zkrb_init, zk_local_ctx: %p, zh: %p, queue: %p, calling_ctx: %p",
      zk_local_ctx, zk_local_ctx->zh, zk_local_ctx->queue, ctx);

  if (!zk_local_ctx->zh) {
    rb_raise(rb_eRuntimeError, "error connecting to zookeeper: %d", errno);
  }

  zk_local_ctx->orig_pid = getpid();

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

  return Qnil;
}