//---------------------------------------------------------------------- SFBool CSharedResource::createLock(SFBool createOnFail) { if (!g_locking) return TRUE; SFString lockFilename = m_filename + ".lck"; int i=0; while (i < maxSecondsLock) { if (!SFos::fileExists(lockFilename)) return createLockFile(lockFilename); SFos::sleep(1.0); i++; } // Someone has had the lock for maxSecondsLock seconds -- if told to blow that lock away if (createOnFail) { // Release the old lock and create a new one m_ownsLock = TRUE; Release(); return createLockFile(lockFilename); } return FALSE; }
int StaticFileCacheData::tryCreateGziped() { if ( !s_iAutoUpdateStaticGzip ) return -1; off_t size = m_fileData.getFileSize(); if (( size > s_iMaxFileSize )||( size < s_iMinFileSize )) return -1; char *p = m_gzippedPath.buf() + m_gzippedPath.len() + 4; int fd = createLockFile( m_gzippedPath.buf(), p ); if ( fd == -1 ) return -1; close( fd ); if ( size < 409600 ) { long ret = compressFile(); *p = 'l'; unlink( m_gzippedPath.buf() ); *p = 0; return ret; } else { //IMPROVE: move this to a standalone process, // fork() is too expensive. if ( D_ENABLED( DL_MORE )) { LOG_D(( "To compressed file %s in another process.", m_real.c_str() )); } int forkResult; forkResult = fork(); if( forkResult ) //error or parent process { return -1; } //child process setpriority( PRIO_PROCESS, 0, 5 ); long ret = compressFile(); if ( ret == -1 ) { LOG_WARN(( "Failed to compress file %s!", m_real.c_str() )); } *p = 'l'; unlink( m_gzippedPath.buf() ); *p = 0; exit(1); } }
/**************************************************************************** Desc: Creates a new 64-bit "file" ****************************************************************************/ RCODE F_MultiFileHdl::createFile( const char * pszPath) { RCODE rc = NE_FLM_OK; FLMBOOL bCreatedDir = FALSE; IF_FileSystem * pFileSystem = f_getFileSysPtr(); if( m_bOpen) { rc = RC_SET_AND_ASSERT( NE_FLM_FAILURE); goto Exit; } if( RC_BAD( rc = pFileSystem->createDir( pszPath))) { goto Exit; } f_strcpy( m_szPath, pszPath); bCreatedDir = TRUE; // Create the lock file if( RC_BAD( rc = createLockFile( m_szPath))) { goto Exit; } // Initialize the EOF to 0 and set the state to open m_ui64EOF = 0; m_bOpen = TRUE; Exit: // Release the lock file if( RC_BAD( rc)) { (void)releaseLockFile( m_szPath, TRUE); if( bCreatedDir) { (void)pFileSystem->removeDir( m_szPath); } } return( rc); }
v24_port_t* v24OpenPort ( const char* PortName, unsigned int OpenFlags ) { v24_port_t *handle=NULL; int open_mode; /* check for `null pointer' */ if ( PortName==NULL ) { if ( OpenFlags&V24_DEBUG_ON ) reportError(NULL,V24_E_NULL_POINTER,"v24OpenPort"); return NULL; } /* first we need to alloc and fill our handle structure */ handle = (v24_port_t*)malloc(sizeof(v24_port_t)); if ( handle==NULL) { if ( OpenFlags&V24_DEBUG_ON ) reportError(NULL,V24_E_NOMEM,"v24OpenPort"); return NULL; } handle->Errno=V24_E_OK; strncpy(handle->PortName,PortName,V24_SZ_PORTNAME); handle->PortName[V24_SZ_PORTNAME]='\0'; handle->Locked=0; handle->TimeoutValue=600; /* timeout after 600*0.1s */ handle->Initialized=0; handle->OpenFlags=OpenFlags; open_mode = O_RDWR|O_NOCTTY; if ( (OpenFlags&V24_NO_DELAY) ) /* don't want to wait? */ open_mode |= O_NDELAY; #if EZV24_WANT_LOCKFILE if ( handle->OpenFlags&V24_LOCK ) { if ( createLockFile(handle) != V24_E_OK ) { reportError(handle,handle->Errno,"v24OpenPort"); free(handle); handle=NULL; return NULL; } } #endif handle->fd = open(handle->PortName,open_mode); if ( handle->fd == -1 ) { reportError(handle,V24_E_OPEN,"v24OpenPort"); free(handle); handle=NULL; return NULL; } if ( v24SetParameters(handle,V24_B9600,V24_8BIT,V24_NONE)!=V24_E_OK ) { reportError(handle,handle->Errno,"v24OpenPort"); free(handle); handle=NULL; return NULL; } if ( v24SetTimeouts(handle,600)!=V24_E_OK ) { reportError(handle,handle->Errno,"v24OpenPort"); free(handle); handle=NULL; return NULL; } return handle; }
/**************************************************************************** Desc: Opens an existing 64-bit file ****************************************************************************/ RCODE F_MultiFileHdl::openFile( const char * pszPath) { RCODE rc = NE_FLM_OK; IF_FileSystem * pFileSystem = f_getFileSysPtr(); IF_DirHdl * pDir = NULL; FLMUINT uiTmp; FLMUINT uiHighFileNum = 0; FLMUINT64 ui64HighOffset = 0; if( m_bOpen) { rc = RC_SET_AND_ASSERT( NE_FLM_FAILURE); goto Exit; } if( RC_BAD( pFileSystem->doesFileExist( pszPath)) || !pFileSystem->isDir( pszPath)) { rc = RC_SET( NE_FLM_IO_PATH_NOT_FOUND); goto Exit; } f_strcpy( m_szPath, pszPath); // Create the lock file if( RC_BAD( rc = createLockFile( m_szPath))) { goto Exit; } // Need to determine the current EOF if( RC_BAD( rc = pFileSystem->openDir( m_szPath, (char *)"*.64", &pDir))) { goto Exit; } // Find all data files to determine the EOF for( rc = pDir->next(); !RC_BAD( rc); rc = pDir->next()) { if( RC_OK( getFileNum( pDir->currentItemName(), &uiTmp))) { if( uiTmp >= uiHighFileNum) { uiHighFileNum = uiTmp; ui64HighOffset = pDir->currentItemSize(); } } } rc = NE_FLM_OK; m_ui64EOF = (((FLMUINT64)uiHighFileNum) * m_uiMaxFileSize) + ui64HighOffset; m_bOpen = TRUE; Exit: if( pDir) { pDir->Release(); } // Release the lock file if( RC_BAD( rc)) { releaseLockFile( m_szPath, FALSE); } return( rc); }
/**************************************************************************** Desc: Creates a new 64-bit file with a unique, generated name ****************************************************************************/ RCODE F_MultiFileHdl::createUniqueFile( const char * pszPath, // Directory where the file is to be created const char * pszFileExtension) // Extension to be used on the new file. { RCODE rc = NE_FLM_OK; FLMUINT uiCount; FLMBOOL bModext = TRUE; FLMBOOL bCreatedDir = FALSE; FLMUINT uiBaseTime = 0; FLMBYTE ucHighByte = 0; char szDirName[ F_FILENAME_SIZE]; char szTmpPath[ F_PATH_MAX_SIZE]; char szBasePath[ F_PATH_MAX_SIZE]; IF_FileSystem * pFileSystem = f_getFileSysPtr(); if( m_bOpen) { rc = RC_SET_AND_ASSERT( NE_FLM_FAILURE); goto Exit; } if( !pszPath || pszPath[ 0] == '\0') { #if defined( FLM_UNIX) f_strcpy( szBasePath, "./"); #elif defined( FLM_NLM) f_strcpy( szBasePath, "SYS:_NETWARE"); #else szBasePath[ 0] = '\0'; #endif } else { f_strcpy( szBasePath, pszPath); } if ((pszFileExtension) && (f_strlen( pszFileExtension) >= 3)) { bModext = FALSE; } uiCount = 0; szDirName[ 0] = '\0'; do { pFileSystem->pathCreateUniqueName( &uiBaseTime, szDirName, pszFileExtension, &ucHighByte, bModext); f_strcpy( szTmpPath, szBasePath); pFileSystem->pathAppend( szTmpPath, szDirName); rc = pFileSystem->createDir( szTmpPath); } while ((rc != NE_FLM_OK) && (uiCount++ < 20)); if( RC_BAD( rc)) { goto Exit; } f_strcpy( m_szPath, szTmpPath); bCreatedDir = TRUE; // Create the lock file if( RC_BAD( rc = createLockFile( m_szPath))) { goto Exit; } // Initialize the EOF to 0 and set the state to open m_ui64EOF = 0; m_bOpen = TRUE; Exit: // Release the lock file if( RC_BAD( rc)) { releaseLockFile( m_szPath, TRUE); if( bCreatedDir) { (void)pFileSystem->removeDir( m_szPath); } } return( rc); }
/**************************************************************************** Desc: Removes a 64-bit file ****************************************************************************/ RCODE F_MultiFileHdl::deleteMultiFile( const char * pszPath) { RCODE rc = NE_FLM_OK; IF_DirHdl * pDir = NULL; char szTmpPath[ F_PATH_MAX_SIZE]; IF_FileSystem * pFileSystem = f_getFileSysPtr(); // Can't use this handle to delete something if we already // have a file open. if( m_bOpen) { // Can't jump to exit, because it calls releaseLockFile return( RC_SET_AND_ASSERT( NE_FLM_FAILURE)); } if( RC_BAD( rc = pFileSystem->doesFileExist( pszPath))) { goto Exit; } if( !pFileSystem->isDir( pszPath)) { // If the path specifies a single file rather than a // 64-bit directory, just go ahead and delete the file. rc = pFileSystem->deleteFile( pszPath); goto Exit; } if( RC_BAD( rc = createLockFile( pszPath))) { goto Exit; } if( RC_OK( pFileSystem->openDir( pszPath, "*.64", &pDir))) { // Remove all data files for( rc = pDir->next(); !RC_BAD( rc) ; rc = pDir->next()) { pDir->currentItemPath( szTmpPath); f_assert( f_strstr( szTmpPath, ".64") != 0); (void)pFileSystem->deleteFile( szTmpPath); } pDir->Release(); pDir = NULL; rc = NE_FLM_OK; } // Release and delete the lock file (void)releaseLockFile( pszPath, TRUE); // Remove the directory (void)pFileSystem->removeDir( pszPath); Exit: (void)releaseLockFile( pszPath, FALSE); return( rc); }
ExitCode _initAndListen(int listenPort) { Client::initThread("initandlisten"); initWireSpec(); auto serviceContext = checked_cast<ServiceContextMongoD*>(getGlobalServiceContext()); serviceContext->setFastClockSource(FastClockSourceFactory::create(Milliseconds(10))); auto opObserverRegistry = stdx::make_unique<OpObserverRegistry>(); opObserverRegistry->addObserver(stdx::make_unique<OpObserverImpl>()); opObserverRegistry->addObserver(stdx::make_unique<UUIDCatalogObserver>()); if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) { opObserverRegistry->addObserver(stdx::make_unique<ShardServerOpObserver>()); } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) { opObserverRegistry->addObserver(stdx::make_unique<ConfigServerOpObserver>()); } serviceContext->setOpObserver(std::move(opObserverRegistry)); DBDirectClientFactory::get(serviceContext).registerImplementation([](OperationContext* opCtx) { return std::unique_ptr<DBClientBase>(new DBDirectClient(opCtx)); }); const repl::ReplSettings& replSettings = repl::ReplicationCoordinator::get(serviceContext)->getSettings(); { ProcessId pid = ProcessId::getCurrent(); LogstreamBuilder l = log(LogComponent::kControl); l << "MongoDB starting : pid=" << pid << " port=" << serverGlobalParams.port << " dbpath=" << storageGlobalParams.dbpath; const bool is32bit = sizeof(int*) == 4; l << (is32bit ? " 32" : " 64") << "-bit host=" << getHostNameCached() << endl; } DEV log(LogComponent::kControl) << "DEBUG build (which is slower)" << endl; #if defined(_WIN32) VersionInfoInterface::instance().logTargetMinOS(); #endif logProcessDetails(); serviceContext->createLockFile(); serviceContext->setServiceEntryPoint( stdx::make_unique<ServiceEntryPointMongod>(serviceContext)); { auto tl = transport::TransportLayerManager::createWithConfig(&serverGlobalParams, serviceContext); auto res = tl->setup(); if (!res.isOK()) { error() << "Failed to set up listener: " << res; return EXIT_NET_ERROR; } serviceContext->setTransportLayer(std::move(tl)); } serviceContext->initializeGlobalStorageEngine(); #ifdef MONGO_CONFIG_WIREDTIGER_ENABLED if (EncryptionHooks::get(serviceContext)->restartRequired()) { exitCleanly(EXIT_CLEAN); } #endif // Warn if we detect configurations for multiple registered storage engines in the same // configuration file/environment. if (serverGlobalParams.parsedOpts.hasField("storage")) { BSONElement storageElement = serverGlobalParams.parsedOpts.getField("storage"); invariant(storageElement.isABSONObj()); for (auto&& e : storageElement.Obj()) { // Ignore if field name under "storage" matches current storage engine. if (storageGlobalParams.engine == e.fieldName()) { continue; } // Warn if field name matches non-active registered storage engine. if (serviceContext->isRegisteredStorageEngine(e.fieldName())) { warning() << "Detected configuration for non-active storage engine " << e.fieldName() << " when current storage engine is " << storageGlobalParams.engine; } } } // Disallow running WiredTiger with --nojournal in a replica set if (storageGlobalParams.engine == "wiredTiger" && !storageGlobalParams.dur && replSettings.usingReplSets()) { log() << "Running wiredTiger without journaling in a replica set is not " << "supported. Make sure you are not using --nojournal and that " << "storage.journal.enabled is not set to 'false'."; exitCleanly(EXIT_BADOPTIONS); } logMongodStartupWarnings(storageGlobalParams, serverGlobalParams, serviceContext); { std::stringstream ss; ss << endl; ss << "*********************************************************************" << endl; ss << " ERROR: dbpath (" << storageGlobalParams.dbpath << ") does not exist." << endl; ss << " Create this directory or give existing directory in --dbpath." << endl; ss << " See http://dochub.mongodb.org/core/startingandstoppingmongo" << endl; ss << "*********************************************************************" << endl; uassert(10296, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.dbpath)); } { std::stringstream ss; ss << "repairpath (" << storageGlobalParams.repairpath << ") does not exist"; uassert(12590, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.repairpath)); } initializeSNMP(); if (!storageGlobalParams.readOnly) { boost::filesystem::remove_all(storageGlobalParams.dbpath + "/_tmp/"); } if (mmapv1GlobalOptions.journalOptions & MMAPV1Options::JournalRecoverOnly) return EXIT_NET_ERROR; if (mongodGlobalParams.scriptingEnabled) { ScriptEngine::setup(); } auto startupOpCtx = serviceContext->makeOperationContext(&cc()); bool canCallFCVSetIfCleanStartup = !storageGlobalParams.readOnly && (storageGlobalParams.engine != "devnull"); if (canCallFCVSetIfCleanStartup && !replSettings.usingReplSets()) { Lock::GlobalWrite lk(startupOpCtx.get()); FeatureCompatibilityVersion::setIfCleanStartup(startupOpCtx.get(), repl::StorageInterface::get(serviceContext)); } auto swNonLocalDatabases = repairDatabasesAndCheckVersion(startupOpCtx.get()); if (!swNonLocalDatabases.isOK()) { // SERVER-31611 introduced a return value to `repairDatabasesAndCheckVersion`. Previously, // a failing condition would fassert. SERVER-31611 covers a case where the binary (3.6) is // refusing to start up because it refuses acknowledgement of FCV 3.2 and requires the // user to start up with an older binary. Thus shutting down the server must leave the // datafiles in a state that the older binary can start up. This requires going through a // clean shutdown. // // The invariant is *not* a statement that `repairDatabasesAndCheckVersion` must return // `MustDowngrade`. Instead, it is meant as a guardrail to protect future developers from // accidentally buying into this behavior. New errors that are returned from the method // may or may not want to go through a clean shutdown, and they likely won't want the // program to return an exit code of `EXIT_NEED_DOWNGRADE`. severe(LogComponent::kControl) << "** IMPORTANT: " << swNonLocalDatabases.getStatus().reason(); invariant(swNonLocalDatabases == ErrorCodes::MustDowngrade); exitCleanly(EXIT_NEED_DOWNGRADE); } // Assert that the in-memory featureCompatibilityVersion parameter has been explicitly set. If // we are part of a replica set and are started up with no data files, we do not set the // featureCompatibilityVersion until a primary is chosen. For this case, we expect the in-memory // featureCompatibilityVersion parameter to still be uninitialized until after startup. if (canCallFCVSetIfCleanStartup && (!replSettings.usingReplSets() || swNonLocalDatabases.getValue())) { invariant(serverGlobalParams.featureCompatibility.isVersionInitialized()); } if (storageGlobalParams.upgrade) { log() << "finished checking dbs"; exitCleanly(EXIT_CLEAN); } // Start up health log writer thread. HealthLog::get(startupOpCtx.get()).startup(); auto const globalAuthzManager = AuthorizationManager::get(serviceContext); uassertStatusOK(globalAuthzManager->initialize(startupOpCtx.get())); // This is for security on certain platforms (nonce generation) srand((unsigned)(curTimeMicros64()) ^ (unsigned(uintptr_t(&startupOpCtx)))); if (globalAuthzManager->shouldValidateAuthSchemaOnStartup()) { Status status = verifySystemIndexes(startupOpCtx.get()); if (!status.isOK()) { log() << redact(status); if (status == ErrorCodes::AuthSchemaIncompatible) { exitCleanly(EXIT_NEED_UPGRADE); } else { quickExit(EXIT_FAILURE); } } // SERVER-14090: Verify that auth schema version is schemaVersion26Final. int foundSchemaVersion; status = globalAuthzManager->getAuthorizationVersion(startupOpCtx.get(), &foundSchemaVersion); if (!status.isOK()) { log() << "Auth schema version is incompatible: " << "User and role management commands require auth data to have " << "at least schema version " << AuthorizationManager::schemaVersion26Final << " but startup could not verify schema version: " << status; exitCleanly(EXIT_NEED_UPGRADE); } if (foundSchemaVersion <= AuthorizationManager::schemaVersion26Final) { log() << "This server is using MONGODB-CR, an authentication mechanism which " << "has been removed from MongoDB 3.8. In order to upgrade the auth schema, " << "first downgrade MongoDB binaries to version 3.6 and then run the " << "authSchemaUpgrade command. " << "See http://dochub.mongodb.org/core/3.0-upgrade-to-scram-sha-1"; exitCleanly(EXIT_NEED_UPGRADE); } } else if (globalAuthzManager->isAuthEnabled()) { error() << "Auth must be disabled when starting without auth schema validation"; exitCleanly(EXIT_BADOPTIONS); } else { // If authSchemaValidation is disabled and server is running without auth, // warn the user and continue startup without authSchema metadata checks. log() << startupWarningsLog; log() << "** WARNING: Startup auth schema validation checks are disabled for the " "database." << startupWarningsLog; log() << "** This mode should only be used to manually repair corrupted auth " "data." << startupWarningsLog; } // This function may take the global lock. auto shardingInitialized = uassertStatusOK(ShardingState::get(startupOpCtx.get()) ->initializeShardingAwarenessIfNeeded(startupOpCtx.get())); if (shardingInitialized) { waitForShardRegistryReload(startupOpCtx.get()).transitional_ignore(); } if (!storageGlobalParams.readOnly) { logStartup(startupOpCtx.get()); startMongoDFTDC(); restartInProgressIndexesFromLastShutdown(startupOpCtx.get()); if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) { // Note: For replica sets, ShardingStateRecovery happens on transition to primary. if (!repl::ReplicationCoordinator::get(startupOpCtx.get())->isReplEnabled()) { uassertStatusOK(ShardingStateRecovery::recover(startupOpCtx.get())); } } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) { uassertStatusOK( initializeGlobalShardingStateForMongod(startupOpCtx.get(), ConnectionString::forLocal(), kDistLockProcessIdForConfigServer)); Balancer::create(startupOpCtx->getServiceContext()); ShardingCatalogManager::create( startupOpCtx->getServiceContext(), makeShardingTaskExecutor(executor::makeNetworkInterface("AddShard-TaskExecutor"))); } else if (replSettings.usingReplSets()) { // standalone replica set auto keysCollectionClient = stdx::make_unique<KeysCollectionClientDirect>(); auto keyManager = std::make_shared<KeysCollectionManager>( KeysCollectionManager::kKeyManagerPurposeString, std::move(keysCollectionClient), Seconds(KeysRotationIntervalSec)); keyManager->startMonitoring(startupOpCtx->getServiceContext()); LogicalTimeValidator::set(startupOpCtx->getServiceContext(), stdx::make_unique<LogicalTimeValidator>(keyManager)); } repl::ReplicationCoordinator::get(startupOpCtx.get())->startup(startupOpCtx.get()); const unsigned long long missingRepl = checkIfReplMissingFromCommandLine(startupOpCtx.get()); if (missingRepl) { log() << startupWarningsLog; log() << "** WARNING: mongod started without --replSet yet " << missingRepl << " documents are present in local.system.replset." << startupWarningsLog; log() << "** Database contents may appear inconsistent with the oplog and may " "appear to not contain" << startupWarningsLog; log() << "** writes that were visible when this node was running as part of a " "replica set." << startupWarningsLog; log() << "** Restart with --replSet unless you are doing maintenance and no " "other clients are connected." << startupWarningsLog; log() << "** The TTL collection monitor will not start because of this." << startupWarningsLog; log() << "** "; log() << " For more info see http://dochub.mongodb.org/core/ttlcollections"; log() << startupWarningsLog; } else { startTTLBackgroundJob(); } if (replSettings.usingReplSets() || !internalValidateFeaturesAsMaster) { serverGlobalParams.validateFeaturesAsMaster.store(false); } } startClientCursorMonitor(); PeriodicTask::startRunningPeriodicTasks(); // Set up the periodic runner for background job execution auto runner = makePeriodicRunner(); runner->startup().transitional_ignore(); serviceContext->setPeriodicRunner(std::move(runner)); SessionKiller::set(serviceContext, std::make_shared<SessionKiller>(serviceContext, killSessionsLocal)); // Set up the logical session cache LogicalSessionCacheServer kind = LogicalSessionCacheServer::kStandalone; if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) { kind = LogicalSessionCacheServer::kSharded; } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) { kind = LogicalSessionCacheServer::kConfigServer; } else if (replSettings.usingReplSets()) { kind = LogicalSessionCacheServer::kReplicaSet; } auto sessionCache = makeLogicalSessionCacheD(serviceContext, kind); LogicalSessionCache::set(serviceContext, std::move(sessionCache)); // MessageServer::run will return when exit code closes its socket and we don't need the // operation context anymore startupOpCtx.reset(); auto start = serviceContext->getServiceExecutor()->start(); if (!start.isOK()) { error() << "Failed to start the service executor: " << start; return EXIT_NET_ERROR; } start = serviceContext->getTransportLayer()->start(); if (!start.isOK()) { error() << "Failed to start the listener: " << start.toString(); return EXIT_NET_ERROR; } serviceContext->notifyStartupComplete(); #ifndef _WIN32 mongo::signalForkSuccess(); #else if (ntservice::shouldStartService()) { ntservice::reportStatus(SERVICE_RUNNING); log() << "Service running"; } #endif if (MONGO_FAIL_POINT(shutdownAtStartup)) { log() << "starting clean exit via failpoint"; exitCleanly(EXIT_CLEAN); } MONGO_IDLE_THREAD_BLOCK; return waitForShutdown(); }
//-------------------------------------------------------------------------------- Server::Server(std::size_t io_service_pool_size, const std::string& application_id, const std::string& application_instance, bool runAsDaemon /*= true*/, const std::string& config_root_path /*= ""*/, const std::string& address /*= "get_from_config"*/, const std::string& port /*= "get_from_config"*/) : io_service_pool_ (io_service_pool_size), stop_signals_ (io_service_pool_.get_io_service()), log_reopen_signals_(io_service_pool_.get_io_service()), acceptor_ (io_service_pool_.get_io_service()), new_connection_ (), request_router_ () { if (createLockFile(application_id, application_instance)) { std::cerr << "Lock file created for: [" << application_id << "] [" << application_instance << "]" << std::endl; if(runAsDaemon) { std::cerr << "Running as Daemon." << std::endl; becomeDaemonProcess(); } signalRegistrations(); std::cerr << "Signal registration completed." << std::endl; Config::instance(application_id, application_instance, config_root_path); std::cerr << "Configuration instance created." << std::endl; initializeLogging((!runAsDaemon)); std::cerr << "Initialized Logging." << std::endl; // create the stats keeper instance here. So that it's available as soon as the server is constructed. StatsKeeper::instance(Config::instance()->get<unsigned long int>("kcc-stats.gather-period" ,300), Config::instance()->get<unsigned long int>("kcc-stats.history-length",12)); std::cerr << "Initialized StatsKeeper." << std::endl; ErrorStateList::instance(); // same goes for the error state list. std::cerr << "Initialized ErrorStateList." << std::endl; initialize_standard_handlers(); std::cerr << "Initialized Standard Handlers." << std::endl; boost::asio::ip::tcp::resolver resolver(acceptor_.get_io_service()); // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). std::cerr << "Initialized resolver." << std::endl; boost::asio::ip::tcp::resolver::query query(Config::instance()->get<std::string>("kcc-server.address"), Config::instance()->get<std::string>("kcc-server.port")); std::cerr << "Initialized query object." << std::endl; boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); std::cerr << "Initialized endpoint." << std::endl; acceptor_.open(endpoint.protocol()); std::cerr << "Acceptor opened." << std::endl; acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); std::cerr << "Acceptor options set." << std::endl; acceptor_.bind(endpoint); std::cerr << "Acceptor bound." << std::endl; acceptor_.listen(); std::cerr << "Server started, now accepting connections." << std::endl; start_accept(); std::cerr << "Server Ready." << std::endl; } else { std::cerr << "Could not create Lockfile for this appid and instance: [" << lockFilePath.native() << "]" << std::endl << "If this message is not preceded by a message indicating that a lock file already exists, " << "you most likely have a permissions problem, or the directory in which you wish to create lock files, " << "does not exist." << std::endl; throw std::runtime_error("Could not create lock file: Terminating."); } }