コード例 #1
0
ファイル: util.cpp プロジェクト: joewan/mitsuba-renderer
std::string getFQDN() {
	struct addrinfo *addrInfo = NULL, hints;
	memset(&hints, 0, sizeof(addrinfo));
	// Only look for IPv4 addresses -- perhaps revisit this later
	hints.ai_family = AF_INET; // AF_UNSPEC
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	int retVal = getaddrinfo(getHostName().c_str(), NULL, &hints, &addrInfo);
	if (addrInfo == NULL || retVal != 0) {
		SLog(EWarn, "Could not retrieve the computer's fully "
			"qualified domain name: could not resolve host address \"%s\"!",
			getHostName().c_str());
		return getHostName();
	}

	char fqdn[NI_MAXHOST];
	retVal = getnameinfo(addrInfo->ai_addr, sizeof(struct sockaddr_in), 
		fqdn, NI_MAXHOST, NULL, 0, 0);
	if (retVal != 0) {
		freeaddrinfo(addrInfo);
#if defined(WIN32)
		SLog(EWarn, "Could not retrieve the computer's fully "
			"qualified domain name: error %i!", WSAGetLastError());
#else
		SLog(EWarn, "Could not retrieve the computer's fully "
			"qualified domain name: error %i!", gai_strerror(retVal));
#endif
		return getHostName();
	}
		
	freeaddrinfo(addrInfo);

	return fqdn;
}
コード例 #2
0
ファイル: OsSocket.cpp プロジェクト: ClydeFroq/sipxecs
void OsSocket::getHostIp(UtlString* hostAddress)
{
      socketInit();
      UtlString thisHost;

#ifdef _VXWORKS /* [ */

      char ipAddr[100];
      ipAddr[0] = '\0';
      hostAddress->remove(0);
      if(!ifAddrGet("csp0", ipAddr))
         hostAddress->append(ipAddr);

#elif defined(__pingtel_on_posix__) /* ] [ */

#ifdef __linux__
      char ipAddr[100];
      unsigned int ip_int = ntohl(getExternalHostAddressLinux());
      sprintf(ipAddr, "%d.%d.%d.%d", ip_int >> 24, (ip_int >> 16) & 255, (ip_int >> 8) & 255, ip_int & 255);
      hostAddress->remove(0);
      hostAddress->append(ipAddr);
#else
      getHostName(&thisHost);
      getHostIpByName(thisHost.data(), hostAddress);
#endif /* __linux__ */

#elif defined(_WIN32) /* ] [ */

      unsigned long address_val = OsSocket::getDefaultBindAddress();

      if (address_val == htonl(INADDR_ANY))
      {
         getHostName(&thisHost);
         getHostIpByName(thisHost.data(), hostAddress);
      }
      else
      {
         struct in_addr in;
         char tmp[50];
         in.S_un.S_addr = address_val;
         strcpy(tmp,inet_ntoa(in));
         *hostAddress = tmp;
      }

#else /* ] [ */
#error Unsupported target platform.
#endif /* ] */

      thisHost.remove(0);
}
コード例 #3
0
    void SyncSourceFeedback::ensureMe(OperationContext* txn) {
        string myname = getHostName();
        {
            Lock::DBLock dlk(txn->lockState(), "local", MODE_X);
            WriteUnitOfWork wunit(txn);
            Client::Context ctx(txn, "local");

            // local.me is an identifier for a server for getLastError w:2+
            if (!Helpers::getSingleton(txn, "local.me", _me) ||
                !_me.hasField("host") ||
                _me["host"].String() != myname) {

                // clean out local.me
                Helpers::emptyCollection(txn, "local.me");

                // repopulate
                BSONObjBuilder b;
                b.appendOID("_id", 0, true);
                b.append("host", myname);
                _me = b.obj();
                Helpers::putSingleton(txn, "local.me", _me);
            }
            wunit.commit();
            // _me is used outside of a read lock, so we must copy it out of the mmap
            _me = _me.getOwned();
        }
    }
コード例 #4
0
void Server::newConnectionHandler() {
	int newConnSd;
	char remoteIP[32];
	struct sockaddr_in remoteaddr;
	memset(&remoteaddr, 0, sizeof(remoteaddr));
	remoteaddr.sin_family = AF_INET;
	int addrlen = sizeof(remoteaddr);
	if((newConnSd = accept(m_nListenSd, (struct sockaddr*)&remoteaddr, (socklen_t*)&addrlen)) == -1) {
		perror("accept");
		exit(EXIT_FAILURE);
	}
	printf("new connection from %s on ""socket %d\n", inet_ntop(AF_INET, &remoteaddr.sin_addr, remoteIP, 32), newConnSd);

	// process Register message from client
	char buffer[64];
	int nbytes;
	if((nbytes = recv(newConnSd, buffer, sizeof(buffer), 0)) > 0)
	{
		buffer[nbytes] = 0;
		//printf("%s", buffer);
	}
	// register message format: REGISTER PORT
	if(strstr(buffer, "REGISTER") != NULL) {
		strtok(buffer," ");
		char *port=strtok(NULL," ");
		// find the first unused node and update the client details
		for(int i=0; i<10; i++) {
			if(m_nodeList[i].state == INACTIVE) {
				m_nodeList[i].state=ACTIVE;
				m_nodeList[i].listenPort =strtol(port, NULL, 10);
				m_nodeList[i].sockFd = newConnSd;
				strcpy(m_nodeList[i].ip_addr,remoteIP);
				getHostName(m_nodeList[i].ip_addr, m_nodeList[i].hostName);
				m_nodeList[i].id = m_nLatestIndex+1;
				m_nLatestIndex += 1;
				break;
			}
		}

		// send REGISTER OK message to the client
		memset(buffer, 0 ,sizeof(buffer));
		strcat(buffer, "REGISTER OK");
		cout << "Sending Message " << buffer << " to client " << remoteIP << endl;

		int len = strlen(buffer);
		if(sendall(newConnSd, buffer, &len) == -1) {
			cout << "Message sending failed. Please retry" << endl;
			return;
		}

		// update all the clients with the new list
		updateNodesinList();
	}

	// add the client to masterSet such that server can read messages from clients, if any.
	FD_SET(newConnSd, &m_masterSet);
	if (newConnSd > m_nMaxFd) {
		m_nMaxFd = newConnSd;
	}
}
コード例 #5
0
void ClientInterface::updateLobby(){
	NetworkMessageType networkMessageType= getNextMessageType();
	
	switch(networkMessageType){
		case nmtInvalid:
			break;

		case nmtIntro:{
			NetworkMessageIntro networkMessageIntro;

			if(receiveMessage(&networkMessageIntro)){
				
				//check consistency
				if(Config::getInstance().getBool("NetworkConsistencyChecks")){
					if(networkMessageIntro.getVersionString()!=getNetworkVersionString()){
						throw runtime_error("Server and client versions do not match (" + networkMessageIntro.getVersionString() + "). You have to use the same binaries.");
					}	
				}

				//send intro message
				NetworkMessageIntro sendNetworkMessageIntro(getNetworkVersionString(), getHostName(), -1);

				playerIndex= networkMessageIntro.getPlayerIndex();
				serverName= networkMessageIntro.getName();
				sendMessage(&sendNetworkMessageIntro);
					
				assert(playerIndex>=0 && playerIndex<GameConstants::maxPlayers);
				introDone= true;
			}
		}
		break;

		case nmtLaunch:{
			NetworkMessageLaunch networkMessageLaunch;

			if(receiveMessage(&networkMessageLaunch)){
				networkMessageLaunch.buildGameSettings(&gameSettings);

				//replace server player by network
				for(int i= 0; i<gameSettings.getFactionCount(); ++i){
					
					//replace by network
					if(gameSettings.getFactionControl(i)==ctHuman){
						gameSettings.setFactionControl(i, ctNetwork);
					}

					//set the faction index
					if(gameSettings.getStartLocationIndex(i)==playerIndex){
						gameSettings.setThisFactionIndex(i);
					}
				}
				launchGame= true;
			}
		}
		break;

		default:
			throw runtime_error("Unexpected network message: " + intToStr(networkMessageType));
	}
}
コード例 #6
0
ファイル: oplogreader.cpp プロジェクト: Lucky7Studio/mongo
    void getMe(BSONObj& me) {
        const string myname = getHostName();
        Client::Transaction transaction(0);            

        // local.me is an identifier for a server for getLastError w:2+
        if (!Collection::findOne("local.me", BSONObj(), me) ||
                !me.hasField("host") || me["host"].String() != myname) {
        
            // cleaning out local.me requires write
            // lock. This is a rare operation, so it should
            // be ok
            if (!Lock::isWriteLocked("local")) {
                throw RetryWithWriteLock();
            }

            // clean out local.me
            deleteObjects("local.me", BSONObj(), false, false);
        
            // repopulate
            BSONObjBuilder b;
            b.appendOID( "_id" , 0 , true );
            b.append( "host", myname );
            me = b.obj();
            updateObjects("local.me", me, BSONObj(), true, false);
        }
        transaction.commit(0);
    }
コード例 #7
0
ファイル: main.c プロジェクト: sagidayan/cshell
int main()
{
	int exitCode = 0;
	char* host_n = (char *)malloc(sizeof(char));
	char* user_n = (char *)malloc(sizeof(char));
	char** args;
	int writeToFile = false;
	
	if(getHostName(host_n) == ERROR)
		goto quit;
	if(getUserName(user_n) == ERROR)
		goto quit;

	signal(SIGINT, sigHandler); // Change the default SIGINT handler

	while(1)
	{
		printf("%d %s@%s$ ",exitCode, user_n, host_n); // Print Prompt
		args = ReadTokens(stdin, &writeToFile); // get user command and tokenize it to args, check if there is a redirect to file.
		if(args != NULL) // if user did enter a command do the following
		{
			exitCode = runExec(args, writeToFile); // fork and run the process, return child exit code
			FreeTokens(args); //in case of error while trying to create process - this method will free the memory already
			if(exitCode == ERROR) // in case we need to exit.
				goto quit;
		}
		writeToFile = false; // set the "boolean" back to default
	}

	quit:
	free(host_n);
	free(user_n);
	return 0;
}
コード例 #8
0
    OID ReplicationCoordinatorExternalStateImpl::ensureMe(OperationContext* txn) {
        std::string myname = getHostName();
        OID myRID;
        {
            ScopedTransaction transaction(txn, MODE_IX);
            Lock::DBLock lock(txn->lockState(), meDatabaseName, MODE_X);

            BSONObj me;
            // local.me is an identifier for a server for getLastError w:2+
            // TODO: handle WriteConflictExceptions below
            if (!Helpers::getSingleton(txn, meCollectionName, me) ||
                    !me.hasField("host") ||
                    me["host"].String() != myname) {

                myRID = OID::gen();

                // clean out local.me
                Helpers::emptyCollection(txn, meCollectionName);

                // repopulate
                BSONObjBuilder b;
                b.append("_id", myRID);
                b.append("host", myname);
                Helpers::putSingleton(txn, meCollectionName, b.done());
            } else {
                myRID = me["_id"].OID();
            }
        }
        return myRID;
    }
コード例 #9
0
ファイル: hostdialog.cpp プロジェクト: Aconex/pcp
QString
HostDialog::getHostSpecification(void) const
{
    QString host = getHostName();

    if (hostLineEdit->isModified())
        host = hostLineEdit->text().trimmed();
    if (host.length() == 0)
        return QString::null;

    if (proxyLineEdit->isModified()) {
        QString proxy = proxyLineEdit->text().trimmed();
        if (proxy.length() > 0)
            host.prepend("@").prepend(proxy);
    }

    if (authenticateCheckBox->isChecked()) {
	QString username = usernameLineEdit->text().trimmed();
	QString password = passwordLineEdit->text().trimmed();
	QString realm = realmLineEdit->text().trimmed();

	host.append("?username="******"&password="******"&realm=").append(realm);
    }

    return host;
}
コード例 #10
0
Status initializeGlobalShardingState(const ConnectionString& configCS) {
    auto network = executor::makeNetworkInterface();
    auto networkPtr = network.get();
    auto shardRegistry(
        stdx::make_unique<ShardRegistry>(stdx::make_unique<RemoteCommandTargeterFactoryImpl>(),
                                         makeTaskExecutor(std::move(network)),
                                         networkPtr,
                                         configCS));

    std::unique_ptr<ForwardingCatalogManager> catalogManager;
    try {
        catalogManager = stdx::make_unique<ForwardingCatalogManager>(
            getGlobalServiceContext(),
            configCS,
            shardRegistry.get(),
            str::stream() << getHostName() << ":" << serverGlobalParams.port << ":" << time(0)
                          << ":" << rand());
    } catch (const DBException& ex) {
        return ex.toStatus();
    }

    shardRegistry->startup();
    grid.init(std::move(catalogManager),
              std::move(shardRegistry),
              stdx::make_unique<ClusterCursorManager>(getGlobalServiceContext()->getClockSource()));

    return Status::OK();
}
コード例 #11
0
ファイル: socket_utils.cpp プロジェクト: zpzxgcr/mongo
/** we store our host name once */
std::string getHostNameCached() {
    std::string temp = _hostNameCached.get();
    if (_hostNameCached.empty()) {
        temp = getHostName();
        _hostNameCached = temp;
    }
    return temp;
}
コード例 #12
0
std::string generateDistLockProcessId(OperationContext* txn) {
    std::unique_ptr<SecureRandom> rng(SecureRandom::create());

    return str::stream()
        << HostAndPort(getHostName(), serverGlobalParams.port).toString() << ':'
        << durationCount<Seconds>(
               txn->getServiceContext()->getPreciseClockSource()->now().toDurationSinceEpoch())
        << ':' << rng->nextInt64();
}
コード例 #13
0
ConnectionPtr SocketConnection::acceptSync()
{
    LB_TS_THREAD( _recvThread );
    if( !isListening( ))
        return 0;

    LBASSERT( _overlappedAcceptData );
    LBASSERT( _overlappedSocket != INVALID_SOCKET );
    if( _overlappedSocket == INVALID_SOCKET )
        return 0;

    // complete accept
    DWORD got   = 0;
    DWORD flags = 0;

    if( !WSAGetOverlappedResult( _readFD, &_overlappedRead, &got, TRUE,
                                 &flags ))
    {
        LBWARN << "Accept completion failed: " << lunchbox::sysError
               << ", closing socket" << std::endl;
        close();
        return 0;
    }

    sockaddr_in* local     = 0;
    sockaddr_in* remote    = 0;
    int          localLen  = 0;
    int          remoteLen = 0;
    GetAcceptExSockaddrs( _overlappedAcceptData, 0, sizeof( sockaddr_in ) + 16,
                          sizeof( sockaddr_in ) + 16, (sockaddr**)&local,
                          &localLen, (sockaddr**)&remote, &remoteLen );
    _tuneSocket( _overlappedSocket );

    ConstConnectionDescriptionPtr description = getDescription();
    SocketConnection* newConnection = new SocketConnection;
    ConnectionPtr connection( newConnection ); // to keep ref-counting correct

    newConnection->_readFD  = _overlappedSocket;
    newConnection->_writeFD = _overlappedSocket;

#ifndef _WIN32
    //fcntl( _overlappedSocket, F_SETFL, O_NONBLOCK );
#endif

    newConnection->_initAIORead();
    _overlappedSocket       = INVALID_SOCKET;

    newConnection->_setState( STATE_CONNECTED );
    ConnectionDescriptionPtr newDescription = newConnection->_getDescription();
    newDescription->bandwidth = description->bandwidth;
    newDescription->port = ntohs( remote->sin_port );
    newDescription->setHostname( getHostName( *remote ));

    LBDEBUG << "accepted connection from " << newDescription->getHostname()
           << ":" << newDescription->port << std::endl;
    return connection;
}
コード例 #14
0
ファイル: NdbBackup.cpp プロジェクト: 4T-Shirt/mysql
int  
NdbBackup::execRestore(bool _restore_data,
		       bool _restore_meta,
		       int _node_id,
		       unsigned _backup_id){
  const int buf_len = 1000;
  char buf[buf_len];

  ndbout << "getBackupDataDir "<< _node_id <<endl;

  const char* path = getBackupDataDirForNode(_node_id);
  if (path == NULL)
    return -1;  

  ndbout << "getHostName "<< _node_id <<endl;
  const char *host;
  if (!getHostName(_node_id, &host)){
    return -1;
  }

  /* 
   * Copy  backup files to local dir
   */ 

  BaseString::snprintf(buf, buf_len,
	   "scp %s:%s/BACKUP/BACKUP-%d/BACKUP-%d*.%d.* .",
	   host, path,
	   _backup_id,
	   _backup_id,
	   _node_id);

  ndbout << "buf: "<< buf <<endl;
  int res = system(buf);  
  
  ndbout << "scp res: " << res << endl;
  
  BaseString::snprintf(buf, 255, "%sndb_restore -c \"%s:%d\" -n %d -b %d %s %s .", 
#if 1
	   "",
#else
	   "valgrind --leak-check=yes -v "
#endif
	   ndb_mgm_get_connected_host(handle),
	   ndb_mgm_get_connected_port(handle),
	   _node_id, 
	   _backup_id,
	   _restore_data?"-r":"",
	   _restore_meta?"-m":"");

  ndbout << "buf: "<< buf <<endl;
  res = system(buf);

  ndbout << "ndb_restore res: " << res << endl;

  return res;
  
}
コード例 #15
0
ファイル: common.hpp プロジェクト: wolftype/freesphere
std::string configPath() {
	std::string host = getHostName();
	if (host.substr(0,2).compare("gr") == 0) {
		std::string pre = "/home/sphere/calibration-current/";
		std::string post = ".txt";
        return pre + host + post;
	}
    return "OmniRender/configFiles/projectorConfigurationTemplate.txt";
}
コード例 #16
0
ファイル: common.hpp プロジェクト: wolftype/freesphere
static const char* broadcastIP() {
    std::string host = getHostName();
    if (host.compare("gr01") == 0
        || host.compare("audio.10g") == 0)
    {
        return "192.168.10.255";
    }
    return "127.0.0.1";
}
コード例 #17
0
Status initializeGlobalShardingState(OperationContext* txn,
                                     const ConnectionString& configCS,
                                     bool allowNetworking) {
    if (configCS.type() == ConnectionString::INVALID) {
        return {ErrorCodes::BadValue, "Unrecognized connection string."};
    }

    auto network =
        executor::makeNetworkInterface("NetworkInterfaceASIO-ShardRegistry",
                                       stdx::make_unique<ShardingNetworkConnectionHook>(),
                                       stdx::make_unique<ShardingEgressMetadataHook>());
    auto networkPtr = network.get();
    auto shardRegistry(
        stdx::make_unique<ShardRegistry>(stdx::make_unique<RemoteCommandTargeterFactoryImpl>(),
                                         makeTaskExecutorPool(std::move(network)),
                                         networkPtr,
                                         makeTaskExecutor(executor::makeNetworkInterface(
                                             "NetworkInterfaceASIO-ShardRegistry-TaskExecutor")),
                                         configCS));

    auto catalogManager = makeCatalogManager(getGlobalServiceContext(),
                                             shardRegistry.get(),
                                             HostAndPort(getHostName(), serverGlobalParams.port));

    shardRegistry->startup();
    grid.init(std::move(catalogManager),
              std::move(shardRegistry),
              stdx::make_unique<ClusterCursorManager>(getGlobalServiceContext()->getClockSource()));

    while (!inShutdown()) {
        try {
            Status status = grid.catalogManager(txn)->startup(txn, allowNetworking);
            uassertStatusOK(status);

            if (serverGlobalParams.configsvrMode == CatalogManager::ConfigServerMode::NONE) {
                grid.shardRegistry()->reload(txn);
            }
            return Status::OK();
        } catch (const DBException& ex) {
            Status status = ex.toStatus();
            if (status == ErrorCodes::ReplicaSetNotFound) {
                // ReplicaSetNotFound most likely means we've been waiting for the config replica
                // set to come up for so long that the ReplicaSetMonitor stopped monitoring the set.
                // Rebuild the config shard to force the monitor to resume monitoring the config
                // servers.
                grid.shardRegistry()->rebuildConfigShard();
            }
            log() << "Error initializing sharding state, sleeping for 2 seconds and trying again"
                  << causedBy(status);
            sleepmillis(2000);
            continue;
        }
    }

    return Status::OK();
}
コード例 #18
0
ファイル: qtmysqlconnection.cpp プロジェクト: tbikfalvi/watta
void cQTMySQLConnection::setHostName( const QString &p_qsHost ) throw()
/* This function sets the Host Name for the MySQL database access.
 * If the database is already open, it will be closed first. */
{
    if( getHostName() != p_qsHost )
    {
        close();
        m_poDB->setHostName( p_qsHost );
    }
}
コード例 #19
0
ファイル: ImR_Activator_i.cpp プロジェクト: rushgun/ATCD
ImR_Activator_i::ImR_Activator_i (void)
: registration_token_(0)
, debug_(0)
, notify_imr_ (false)
, induce_delay_ (0)
, name_ (getHostName ())
, env_buf_len_ (Activator_Options::ENVIRONMENT_BUFFER)
, max_env_vars_ (Activator_Options::ENVIRONMENT_MAX_VARS)
{
}
コード例 #20
0
ファイル: ImR_Activator_i.cpp プロジェクト: bjovke/ACE_TAO
ImR_Activator_i::ImR_Activator_i (void)
  : registration_token_(0)
  , debug_(0)
  , notify_imr_ (false)
  , induce_delay_ (0)
  , name_ (getHostName ())
  , env_buf_len_ (Activator_Options::ENVIRONMENT_BUFFER)
  , max_env_vars_ (Activator_Options::ENVIRONMENT_MAX_VARS)
  , detach_child_ (false)
  , active_check_pid_ (ACE_INVALID_PID)
{
}
コード例 #21
0
void Peer::queueMessage(const MessagePtr& message, uint8 channel)
{
    if( !message ) return;
    message->prepare();

    int status = enet_peer_send(peer, channel, message->getPacket());

    if(status  != 0)
    {
        LogWarn("Error sending packet to peer '%s'", getHostName().c_str());
        return;
    }
}
コード例 #22
0
ファイル: net.c プロジェクト: rhencke/mozilla-cvs-history
int
netListen(App *app, unsigned char **host, unsigned short *port)
{
	unsigned char		*hostName;
	struct sockaddr_in	name;
	socklen_t		namelen = sizeof(name);
	int			fd;

	hostName = (unsigned char *) getHostName();
	if (!hostName)
	{
		return -1;
	}

	fd = getSocketAndIPAddress(app, hostName, *port, &name);
	if (fd < 0)
	{
		return -1;
	}
	if (host)
	{
		*host = hostName;
	}
	else
	{
		free(hostName);
	}

	if (bind(fd, (struct sockaddr *) &name, sizeof(name)))
	{
		perror("bind");
		return -1;
	}

	if (listen(fd, 5))
	{
		perror("listen");
		return -1;
	}

	if (!*port)
	{
		if (getsockname(fd, (struct sockaddr *) &name, &namelen))
		{
			return -1;
		}
		*port = ntohs(name.sin_port);
	}

	return fd;
}
コード例 #23
0
ファイル: socket.cpp プロジェクト: MoLAoS/Mandate
void ServerSocket::sendAnnounce(int port) {
	struct sockaddr_in their_addr;
	their_addr.sin_family = AF_INET; //host byte order
	their_addr.sin_port = htons(port); //short, network byte order
	their_addr.sin_addr.s_addr = inet_addr(broadcastAddr.getString().c_str());
	memset(&(their_addr.sin_zero), 0, 8); //zero the rest of the struct

	string message = getHostName();

	int numbytes = sendto(udpsockfd, message.c_str(), strlen(message.c_str()), 0,
			(struct sockaddr*)&their_addr, sizeof(struct sockaddr));
	if (numbytes == SOCKET_ERROR) {
		throw SocketException("problem sending announce");
	}
}
コード例 #24
0
const char* SystemCall::getHostAddr()
{
  static const char* hostaddr = 0;
  if(!hostaddr)
  {
    static char buf[100];
    hostent* hostAddr = (hostent*) gethostbyname(getHostName());
    if(hostAddr && *hostAddr->h_addr_list)
      strcpy(buf, inet_ntoa(*(in_addr*) *hostAddr->h_addr_list));
    else
      strcpy(buf, "127.0.0.1");
    hostaddr = buf;
  }
  return hostaddr;
}
コード例 #25
0
void UNIX_PROVIDER::__initialize(CIMOMHandle &ch)
{
   _cimomHandle = ch;

  // call platform-specific routine to get values
  if (getHostName(_hostName))
  {
  	// LOG HOSTNAME FETCH ERROR
  }
  if (getOSName(_osName))
  {
  	// LOG HOSTNAME FETCH ERROR
  }
  return;
}  /* initialize */
コード例 #26
0
ファイル: oplogreader.cpp プロジェクト: lufeng1102/mongo
    bool replHandshake(DBClientConnection *conn, const BSONObj& me) {
        string myname = getHostName();

        BSONObjBuilder cmd;
        cmd.appendAs( me["_id"] , "handshake" );
        if (theReplSet) {
            cmd.append("member", theReplSet->selfId());
            cmd.append("config", theReplSet->myConfig().asBson());
        }

        BSONObj res;
        bool ok = conn->runCommand( "admin" , cmd.obj() , res );
        // ignoring for now on purpose for older versions
        LOG( ok ? 1 : 0 ) << "replHandshake res not: " << ok << " res: " << res << endl;
        return true;
    }
コード例 #27
0
Status initializeGlobalShardingState(OperationContext* txn,
                                     const ConnectionString& configCS,
                                     bool allowNetworking) {
    SyncClusterConnection::setConnectionValidationHook(
        [](const HostAndPort& target, const executor::RemoteCommandResponse& isMasterReply) {
            return ShardingNetworkConnectionHook::validateHostImpl(target, isMasterReply);
        });
    auto network =
        executor::makeNetworkInterface(stdx::make_unique<ShardingNetworkConnectionHook>(),
                                       stdx::make_unique<ShardingEgressMetadataHook>());
    auto networkPtr = network.get();
    auto shardRegistry(
        stdx::make_unique<ShardRegistry>(stdx::make_unique<RemoteCommandTargeterFactoryImpl>(),
                                         makeTaskExecutorPool(std::move(network)),
                                         networkPtr,
                                         makeTaskExecutor(executor::makeNetworkInterface()),
                                         configCS));

    try {
        std::unique_ptr<ForwardingCatalogManager> catalogManager =
            stdx::make_unique<ForwardingCatalogManager>(
                getGlobalServiceContext(),
                configCS,
                shardRegistry.get(),
                HostAndPort(getHostName(), serverGlobalParams.port));

        shardRegistry->startup();
        grid.init(
            std::move(catalogManager),
            std::move(shardRegistry),
            stdx::make_unique<ClusterCursorManager>(getGlobalServiceContext()->getClockSource()));

        auto status = grid.catalogManager(txn)->startup(txn, allowNetworking);
        if (!status.isOK()) {
            return status;
        }

        // ShardRegistry::reload may throw, in which case we will just fail the initialization
        if (serverGlobalParams.configsvrMode == CatalogManager::ConfigServerMode::NONE) {
            grid.shardRegistry()->reload(txn);
        }
    } catch (const DBException& ex) {
        return ex.toStatus();
    }

    return Status::OK();
}
コード例 #28
0
ファイル: web-server.c プロジェクト: zero-point/webserver
int checkHostHeader(char buffer[]){

        char *finalHost = (char *)malloc(1000);
        strcat(finalHost,getHostName());
	if(!strcmp(finalHost, "serendipity"))	
        strcat(finalHost, ".dcs.gla.ac.uk");
	else
		finalHost = "localhost";

        char *tempbuffer = calloc(strlen(buffer)+1, sizeof(char));
	if(!tempbuffer)	printf("Error: %s\n",  strerror(errno));

        strcpy(tempbuffer, buffer);

        return 1;

}
コード例 #29
0
ファイル: hostdialog.cpp プロジェクト: aeppert/pcp
QString
HostDialog::getHostSpecification(void) const
{
    QString host = getHostName();
    bool need_separator = false;
    bool need_delimiter = false;

    if (hostLineEdit->isModified())
        host = hostLineEdit->text().trimmed();
    if (host.length() == 0)
        return QString::null;

    if (proxyLineEdit->isModified()) {
        QString proxy = proxyLineEdit->text().trimmed();
        if (proxy.length() > 0)
            host.prepend("@").prepend(proxy);
    }

    if (containerCheckBox->isChecked() ||
	authenticateCheckBox->isChecked())
	need_delimiter = true;

    if (need_delimiter)
	host.append("?");

    if (containerCheckBox->isChecked()) {
	QString container = containerLineEdit->text().trimmed();
	host.append("container=").append(container);
	need_separator = true;
    }

    if (authenticateCheckBox->isChecked()) {
	QString username = usernameLineEdit->text().trimmed();
	QString password = passwordLineEdit->text().trimmed();
	QString realm = realmLineEdit->text().trimmed();

	if (need_separator)
	    host.append("&");
	host.append("username="******"&password="******"&realm=").append(realm);
	need_separator = true;
    }
    return host;
}
コード例 #30
0
ファイル: OscKinectServer.cpp プロジェクト: expokorea/korea
void OscKinectServer::init(){
	gui.setup("kinect at " + getHostName() + ":" + ofToString(getPort()));
	gui.add(tilt.setup("tilt",0,-30,30,300));
	gui.add(nearThreshold.setup("nearThreshold",0,0,255,300));
	gui.add(farThreshold.setup("farThreshold",0,0,255,300));
	gui.add(nearClip.setup("nearClip",3000,0,10000,300));
	gui.add(farClip.setup("farClip",6500,0,10000,300));
	gui.add(record.setup("record",false));
	gui.add(player.setup("use player",false));

	tilt.addListener(this,&OscKinectServer::tiltChanged);
	nearThreshold.addListener(this,&OscKinectServer::nearThresholdChanged);
	farThreshold.addListener(this,&OscKinectServer::farThresholdChanged);
	nearClip.addListener(this,&OscKinectServer::clipChanged);
	farClip.addListener(this,&OscKinectServer::clipChanged);
	record.addListener(this,&OscKinectServer::recordPressed);
	player.addListener(this,&OscKinectServer::usePlayer);
}