Ejemplo n.º 1
0
    void listen(int port) {
        //testTheDb();
        MessageServer::Options options;
        options.port = port;
        options.ipList = serverGlobalParams.bind_ip;

        MessageServer * server = createServer( options , new MyMessageHandler() );
        server->setAsTimeTracker();
        // we must setupSockets prior to logStartup() to avoid getting too high
        // a file descriptor for our calls to select()
        server->setupSockets();

        logStartup();
        startReplication();
        if (serverGlobalParams.isHttpInterfaceEnabled)
            boost::thread web( stdx::bind(&webServerThread,
                                           new RestAdminAccess(), // takes ownership
                                           OperationContextImpl::factory) ); // XXX SERVER-13931

#if(TESTEXHAUST)
        boost::thread thr(testExhaust);
#endif
        server->run();
    }
Ejemplo n.º 2
0
// Function that generates messages to clients.
void ServerThread(void* args)
{
    MessageServer server;
    char message[512];
    unsigned int loop = 0;
    if(server.Initialize(gServerID))
    {
        while(gQuitFlag == false)
        {
            // Wait until all clients are connected, then
            // start sending messages so we can get a better
            // performance measurement.
            if(server.GetNumClients() == gClientThreads)
            {
                sprintf(message, "Message #%d", loop++);
                if(server.SendToAllClients(message))
                {
                    gTotalMessages++;
                }
            }
            SleepMs(1);
        }
    }
}
Ejemplo n.º 3
0
Archivo: db.cpp Proyecto: WeetLee/mongo
static void _initAndListen(int listenPort) {
    Client::initThread("initandlisten");

    // Due to SERVER-15389, we must setupSockets first thing at startup in order to avoid
    // obtaining too high a file descriptor for our calls to select().
    MessageServer::Options options;
    options.port = listenPort;
    options.ipList = serverGlobalParams.bind_ip;

    MessageServer* server = createServer(options, new MyMessageHandler());
    server->setAsTimeTracker();

    // This is what actually creates the sockets, but does not yet listen on them because we
    // do not want connections to just hang if recovery takes a very long time.
    server->setupSockets();

    std::shared_ptr<DbWebServer> dbWebServer;
    if (serverGlobalParams.isHttpInterfaceEnabled) {
        dbWebServer.reset(new DbWebServer(
            serverGlobalParams.bind_ip, serverGlobalParams.port + 1000, new RestAdminAccess()));
        dbWebServer->setupSockets();
    }

    getGlobalServiceContext()->initializeGlobalStorageEngine();

    // 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());
        BSONObj storageParamsObj = storageElement.Obj();
        BSONObjIterator i = storageParamsObj.begin();
        while (i.more()) {
            BSONElement e = i.next();
            // 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 (getGlobalServiceContext()->isRegisteredStorageEngine(e.fieldName())) {
                warning() << "Detected configuration for non-active storage engine "
                          << e.fieldName() << " when current storage engine is "
                          << storageGlobalParams.engine;
            }
        }
    }

    getGlobalServiceContext()->setOpObserver(stdx::make_unique<OpObserver>());

    const repl::ReplSettings& replSettings = repl::getGlobalReplicationCoordinator()->getSettings();

    {
        ProcessId pid = ProcessId::getCurrent();
        LogstreamBuilder l = log(LogComponent::kControl);
        l << "MongoDB starting : pid=" << pid << " port=" << serverGlobalParams.port
          << " dbpath=" << storageGlobalParams.dbpath;
        if (replSettings.master)
            l << " master=" << replSettings.master;
        if (replSettings.slave)
            l << " slave=" << (int)replSettings.slave;

        const bool is32bit = sizeof(int*) == 4;
        l << (is32bit ? " 32" : " 64") << "-bit host=" << getHostNameCached() << endl;
    }

    DEV log(LogComponent::kControl) << "DEBUG build (which is slower)" << endl;
    logMongodStartupWarnings(storageGlobalParams);

#if defined(_WIN32)
    printTargetMinOS();
#endif

    logProcessDetails();

    {
        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));
    }

    {
        stringstream ss;
        ss << "repairpath (" << storageGlobalParams.repairpath << ") does not exist";
        uassert(12590, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.repairpath));
    }

    // TODO:  This should go into a MONGO_INITIALIZER once we have figured out the correct
    // dependencies.
    if (snmpInit) {
        snmpInit();
    }

    boost::filesystem::remove_all(storageGlobalParams.dbpath + "/_tmp/");

    if (mmapv1GlobalOptions.journalOptions & MMAPV1Options::JournalRecoverOnly)
        return;

    if (mongodGlobalParams.scriptingEnabled) {
        ScriptEngine::setup();
    }

    repairDatabasesAndCheckVersion();

    if (storageGlobalParams.upgrade) {
        log() << "finished checking dbs" << endl;
        exitCleanly(EXIT_CLEAN);
    }

    {
        OperationContextImpl txn;
        uassertStatusOK(getGlobalAuthorizationManager()->initialize(&txn));
    }

    /* this is for security on certain platforms (nonce generation) */
    srand((unsigned)(curTimeMicros64() ^ startupSrandTimer.micros()));

    // The snapshot thread provides historical collection level and lock statistics for use
    // by the web interface. Only needed when HTTP is enabled.
    if (serverGlobalParams.isHttpInterfaceEnabled) {
        statsSnapshotThread.go();

        invariant(dbWebServer);
        stdx::thread web(stdx::bind(&webServerListenThread, dbWebServer));
        web.detach();
    }

    {
        OperationContextImpl txn;

#ifndef _WIN32
        mongo::signalForkSuccess();
#endif

        Status status = authindex::verifySystemIndexes(&txn);
        if (!status.isOK()) {
            log() << status.reason();
            exitCleanly(EXIT_NEED_UPGRADE);
        }

        // SERVER-14090: Verify that auth schema version is schemaVersion26Final.
        int foundSchemaVersion;
        status =
            getGlobalAuthorizationManager()->getAuthorizationVersion(&txn, &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.toString() << endl;
            exitCleanly(EXIT_NEED_UPGRADE);
        }
        if (foundSchemaVersion < AuthorizationManager::schemaVersion26Final) {
            log() << "Auth schema version is incompatible: "
                  << "User and role management commands require auth data to have "
                  << "at least schema version " << AuthorizationManager::schemaVersion26Final
                  << " but found " << foundSchemaVersion << ". In order to upgrade "
                  << "the auth schema, first downgrade MongoDB binaries to version "
                  << "2.6 and then run the authSchemaUpgrade command." << endl;
            exitCleanly(EXIT_NEED_UPGRADE);
        }

        getDeleter()->startWorkers();

        restartInProgressIndexesFromLastShutdown(&txn);

        repl::getGlobalReplicationCoordinator()->startReplication(&txn);

        const unsigned long long missingRepl = checkIfReplMissingFromCommandLine(&txn);
        if (missingRepl) {
            log() << startupWarningsLog;
            log() << "** WARNING: mongod started without --replSet yet " << missingRepl
                  << " documents are present in local.system.replset" << 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();
        }
    }

    startClientCursorMonitor();

    PeriodicTask::startRunningPeriodicTasks();

    logStartup();

    // MessageServer::run will return when exit code closes its socket
    server->run();
}
Ejemplo n.º 4
0
static ExitCode runMongosServer() {
    Client::initThread("mongosMain");
    printShardingVersionInfo(false);

    _initWireSpec();

    // Add sharding hooks to both connection pools - ShardingConnectionHook includes auth hooks
    globalConnPool.addHook(new ShardingConnectionHook(false));
    shardConnectionPool.addHook(new ShardingConnectionHook(true));

    ReplicaSetMonitor::setAsynchronousConfigChangeHook(
        &ConfigServer::replicaSetChangeConfigServerUpdateHook);
    ReplicaSetMonitor::setSynchronousConfigChangeHook(
        &ConfigServer::replicaSetChangeShardRegistryUpdateHook);

    // Mongos connection pools already takes care of authenticating new connections so the
    // replica set connection shouldn't need to.
    DBClientReplicaSet::setAuthPooledSecondaryConn(false);

    if (getHostName().empty()) {
        dbexit(EXIT_BADOPTIONS);
    }

    {
        auto txn = cc().makeOperationContext();
        Status status = initializeSharding(txn.get());
        if (!status.isOK()) {
            if (status == ErrorCodes::CallbackCanceled) {
                invariant(inShutdown());
                log() << "Shutdown called before mongos finished starting up";
                return EXIT_CLEAN;
            }
            error() << "Error initializing sharding system: " << status;
            return EXIT_SHARDING_ERROR;
        }

        ConfigServer::reloadSettings(txn.get());
    }

#if !defined(_WIN32)
    mongo::signalForkSuccess();
#endif

    if (serverGlobalParams.isHttpInterfaceEnabled) {
        std::shared_ptr<DbWebServer> dbWebServer(new DbWebServer(
            serverGlobalParams.bind_ip, serverGlobalParams.port + 1000, new NoAdminAccess()));
        dbWebServer->setupSockets();

        stdx::thread web(stdx::bind(&webServerListenThread, dbWebServer));
        web.detach();
    }

    HostnameCanonicalizationWorker::start(getGlobalServiceContext());

    Status status = getGlobalAuthorizationManager()->initialize(NULL);
    if (!status.isOK()) {
        error() << "Initializing authorization data failed: " << status;
        return EXIT_SHARDING_ERROR;
    }

    balancer.go();
    clusterCursorCleanupJob.go();

    UserCacheInvalidator cacheInvalidatorThread(getGlobalAuthorizationManager());
    {
        auto txn = cc().makeOperationContext();
        cacheInvalidatorThread.initialize(txn.get());
        cacheInvalidatorThread.go();
    }

    PeriodicTask::startRunningPeriodicTasks();

    MessageServer::Options opts;
    opts.port = serverGlobalParams.port;
    opts.ipList = serverGlobalParams.bind_ip;

    ShardedMessageHandler handler;
    MessageServer* server = createServer(opts, &handler);
    server->setAsTimeTracker();
    if (!server->setupSockets()) {
        return EXIT_NET_ERROR;
    }
    server->run();

    // MessageServer::run will return when exit code closes its socket
    return inShutdown() ? EXIT_CLEAN : EXIT_NET_ERROR;
}
Ejemplo n.º 5
0
int main(int argc, char* argv[]) {

	reactivision_settings config;
	sprintf(config.file,"none");

	const char *app_name = "reacTIVision";
	const char *version_no = "1.5.1";

	bool headless = false;

	std::cout << app_name << " " << version_no << " (" << __DATE__ << ")" << std::endl << std::endl;

	if (argc>1) {
		if (strcmp( argv[1], "-h" ) == 0 ) {
			printUsage();
			return 0;
		} else if( strcmp( argv[1], "-c" ) == 0 ) {
			if (argc==3) sprintf(config.file,"%s",argv[2]);
			else {
				printUsage();
				return 0;
			}
        } else if( strcmp( argv[1], "-n" ) == 0 ) {
            headless = true;
        } else if( strcmp( argv[1], "-l" ) == 0 ) {
            CameraTool::listDevices();
            MidiServer::listDevices();
            return 0;
        } else if ( (std::string(argv[1]).find("-NSDocumentRevisionsDebugMode")==0 ) || (std::string(argv[1]).find("-psn_")==0) ){
            // ignore mac specific arguments
        } else {
 			printUsage();
		}
	}

#ifndef WIN32
	signal(SIGINT,terminate);
	signal(SIGHUP,terminate);
	signal(SIGQUIT,terminate);
	signal(SIGTERM,terminate);
#endif

	readSettings(&config);
    config.headless = headless;

	CameraEngine *camera = setupCamera(config.camera_config);

	engine = new SDLinterface(app_name, camera, &config);

    if (!headless) {
        switch (config.display_mode) {
            case 0: engine->setDisplayMode(engine->NO_DISPLAY); break;
            case 1: engine->setDisplayMode(engine->SOURCE_DISPLAY); break;
            case 2: engine->setDisplayMode(engine->DEST_DISPLAY); break;
        }
    } else engine->setDisplayMode(engine->NO_DISPLAY);

	MessageServer  *server		= NULL;
	FrameProcessor *fiducialfinder	= NULL;
	FrameProcessor *thresholder	= NULL;
	FrameProcessor *equalizer	= NULL;
	FrameProcessor *calibrator	= NULL;

	if(config.midi) server = new MidiServer(config.midi_config);
	else server = new TuioServer(config.host,config.port);
	server->setInversion(config.invert_x, config.invert_y, config.invert_a);

    equalizer = new FrameEqualizer();
    engine->addFrameProcessor(equalizer);
    if (config.background) equalizer->toggleFlag(' ');

    thresholder = new FrameThresholder(config.gradient_gate, config.tile_size, config.thread_count);
    engine->addFrameProcessor(thresholder);

    if (config.amoeba) fiducialfinder = new FidtrackFinder(server, config.tree_config, config.grid_config, config.finger_size, config.finger_sensitivity);
    else if (config.classic) fiducialfinder = new FidtrackFinderClassic(server, config.grid_config);
	engine->addFrameProcessor(fiducialfinder);

	calibrator = new CalibrationEngine(config.grid_config);
	engine->addFrameProcessor(calibrator);

	engine->run();
	teardownCamera(camera);

	config.display_mode = engine->getDisplayMode();

	engine->removeFrameProcessor(calibrator);
	delete calibrator;

	if (config.amoeba) {
		config.finger_size = ((FidtrackFinder*)fiducialfinder)->getFingerSize();
		config.finger_sensitivity = ((FidtrackFinder*)fiducialfinder)->getFingerSensitivity();
	}

	engine->removeFrameProcessor(fiducialfinder);


    config.gradient_gate = ((FrameThresholder*)thresholder)->getGradientGate();
    config.tile_size = ((FrameThresholder*)thresholder)->getTileSize();
    engine->removeFrameProcessor(thresholder);
    delete thresholder;

    config.background = ((FrameEqualizer*)equalizer)->getState();
    engine->removeFrameProcessor(equalizer);
    delete equalizer;

	config.invert_x = server->getInvertX();
	config.invert_y = server->getInvertY();
	config.invert_a = server->getInvertA();

	delete fiducialfinder;
	delete engine;
	delete server;

	writeSettings(&config);
	return 0;
}