Example #1
0
void ClipboardServer::onCommandsSaved()
{
    const auto commands = loadEnabledCommands();

#ifndef NO_GLOBAL_SHORTCUTS
    removeGlobalShortcuts();

    QList<QKeySequence> usedShortcuts;

    for (const auto &command : commands) {
        if (command.type() & CommandType::GlobalShortcut) {
            for (const auto &shortcutText : command.globalShortcuts) {
                QKeySequence shortcut(shortcutText, QKeySequence::PortableText);
                if ( !shortcut.isEmpty() && !usedShortcuts.contains(shortcut) ) {
                    usedShortcuts.append(shortcut);
                    createGlobalShortcut(shortcut, command);
                }
            }
        }
    }
#endif

    const auto hash = monitorCommandStateHash(commands);
    if ( m_monitor && hash != m_monitorCommandsStateHash ) {
        m_monitorCommandsStateHash = hash;
        stopMonitoring();
        startMonitoring();
    }
}
Example #2
0
void CMMCStorageStatus::RunL()
{
#ifdef SYMBIAN_3_1
    TDriveInfo driveInfo;
    TDriveNumber driveLetter = EDriveE;  // Have to use hardcoded MMC drive letter for 3.1
    if (iFs.Drive(driveInfo, driveLetter) == KErrNone) {
        bool driveInserted = false;

        switch (driveInfo.iType) {
        case EMediaNotPresent:
            driveInserted = false;
            break;
        default:
            driveInserted = true;
            break;
        }

        TChar volumeChar;
        QString volume;
        if (RFs::DriveToChar(driveLetter, volumeChar) == KErrNone)
            volume = QChar(volumeChar).toAscii();

        foreach (MStorageStatusObserver *observer, m_observers)
            observer->storageStatusChanged(driveInserted, volume);
    }
#else // SYMBIAN_3_1
    CompareDriveLists(PopulateDriveList());
#endif // SYMBIAN_3_1
    startMonitoring();
}
Example #3
0
/******************************************************************************
* Starts or stops the alarm timer as necessary after a calendar is enabled/disabled.
*/
void AlarmDaemon::setTimerStatus()
{
#ifdef AUTOSTART_KALARM
    if(!mAlarmTimer)
    {
        // KAlarm is now running, so start monitoring alarms
        startMonitoring();
        return;    // startMonitoring() calls this method
    }

#endif
    // Count the number of currently loaded calendars whose names should be displayed
    int nLoaded = 0;
    for(ADCalendar::ConstIterator it = ADCalendar::begin();  it != ADCalendar::end();  ++it)
        if((*it)->loaded())
            ++nLoaded;

    // Start or stop the alarm timer if necessary
    if(!mAlarmTimer->isActive()  &&  nLoaded)
    {
        // Timeout every minute.
        // But first synchronise to one second after the minute boundary.
        int firstInterval = DAEMON_CHECK_INTERVAL + 1 - QTime::currentTime().second();
        mAlarmTimer->start(1000 * firstInterval);
        mAlarmTimerSyncing = (firstInterval != DAEMON_CHECK_INTERVAL);
        kdDebug(5900) << "Started alarm timer" << endl;
    }
    else if(mAlarmTimer->isActive()  &&  !nLoaded)
    {
        mAlarmTimer->stop();
        kdDebug(5900) << "Stopped alarm timer" << endl;
    }
}
Example #4
0
CFlipStatus::CFlipStatus() : CActive(EPriorityStandard),
    m_flipStatus(EPSHWRMGripStatusUninitialized),m_filpKeyBoard(-1),m_flipenabled(false),m_gripenabled(false)
{
    CActiveScheduler::Add(this);
    TInt status = KFlipStateUnknown;

    //In symbian3 devices KHWRMGripStatus is used for getting flip open/closed state
    RProperty::Get(KPSUidHWRM,  KHWRMGripStatus, status);
    if ( status != EPSHWRMGripStatusUninitialized ) {
        m_flipStatus = status;
        m_gripenabled = true;
        m_FlipProperty.Attach(KPSUidHWRM,  KHWRMGripStatus);
        m_filpKeyBoard = 1;
     }

    // In 5.0 devices KHWRMFlipStatus is used for getting flip open/closed state
    RProperty::Get(KPSUidHWRM,  KHWRMFlipStatus, status);
    if ( status != EPSHWRMFlipStatusUninitialized ) {
        m_flipStatus = status;
        m_flipenabled = true;
        m_FlipProperty.Attach(KPSUidHWRM,  KHWRMFlipStatus);
        m_filpKeyBoard = 1;
     }

    if ( m_flipenabled || m_gripenabled ) {
     startMonitoring();
    }

}
Example #5
0
void ClipboardServer::loadSettings()
{
    if (m_monitor) {
        stopMonitoring();
        startMonitoring();
    }
}
Example #6
0
void CKeylockStatus::RunL()
{
    TInt status = EKeyguardNotActive;
    m_keylockProperty.Get(status);
    m_currentStatus = status;
    foreach (MKeylockStatusObserver *observer, m_observers)
        observer->keylockStatusChanged(m_currentStatus);

    startMonitoring();
}
Example #7
0
CKeylockStatus::CKeylockStatus() : CActive(EPriorityStandard),
    m_currentStatus(EKeyguardNotActive)
{
    CActiveScheduler::Add(this);
    TInt err = m_keylockProperty.Attach(KPSUidAvkonDomain, KAknKeyguardStatus);
    if (err == KErrNone) {
        TInt status = EKeyguardNotActive;
        m_keylockProperty.Get(status);
        m_currentStatus = status;
        startMonitoring();
    }
}
QDriveWatcherEngine::QDriveWatcherEngine(QDriveWatcher *watcher)
    : CActive(EPriorityStandard),
      m_watcher(watcher)
{
    CActiveScheduler::Add(this);

    if (iFs.Connect() == KErrNone) {
#ifndef SYMBIAN_3_1
        m_previousDriveList.Copy(PopulateDriveList());
#endif
        startMonitoring();
    }
}
Example #9
0
CMMCStorageStatus::CMMCStorageStatus() : CActive(EPriorityStandard),
m_previousDriveList(TDriveList())
{
TRACES ( qDebug() << "CMMCStorageStatus::CMMCStorageStatus++");
    CActiveScheduler::Add(this);
    if (iFs.Connect() == KErrNone && iFs.ShareProtected() == KErrNone) {
#ifndef SYMBIAN_3_1
        m_previousDriveList.Copy(PopulateDriveList());
#endif //SYMBIAN_3_1
        startMonitoring();
    }
TRACES ( qDebug() << "CMMCStorageStatus::CMMCStorageStatus--");
}
Example #10
0
/*!
    Start monitoring \a uri for presence changes.  The monitoredPresence()
    signal will be emitted whenever the status changes.  Returns false if
    the \a uri was already being monitored by this object.

    Server implementations that inherit from QPresence should call this
    base implementation before performing any other action.

    \sa monitoredPresence(), stopMonitoring()
*/
bool QPresence::startMonitoring( const QString& uri )
{
    if ( d->monitored.contains( uri ) ) {
        ++( d->monitored[uri] );
        return false;
    } else {
        d->monitored.insert( uri, 1 );
        if ( mode() == Client )
            invoke( SLOT(startMonitoring(QString)), uri );
        else
            setValue( "allMonitoredUris", QStringList( d->monitored.keys() ) );
        return true;
    }
}
Example #11
0
HKEY RegUtil::startMonitoring(tstring regkey_name, tstring dword_name, HANDLE hEvent, BOOL bWatchSubtree, DWORD dwNotifyFilter, BOOL fAsynchronous)
{
	// the purpose of this function is to setup notifcation via a semaphore when a registry key has 
	// been modified 
	// its original purpose was to let us change the logging levels without having to poll the registry keys
	HKEY hKey=NULL;
	HKEY hKeyBASE=NULL;
	REGSAM samDesired;
	samDesired = KEY_NOTIFY;

	hKeyBASE=HKEY_LOCAL_MACHINE;
 
	hKey = startMonitoring(regkey_name, dword_name, hKeyBASE, hEvent, bWatchSubtree, dwNotifyFilter, fAsynchronous);

	return hKey;
}
Example #12
0
void CFlipStatus::RunL()
{
   TInt status = KFlipStateUnknown;
   if ( m_gripenabled ) {
    RProperty::Get(KPSUidHWRM,  KHWRMGripStatus, status);
   }

   if ( m_flipenabled ) {
    RProperty::Get(KPSUidHWRM,  KHWRMFlipStatus, status);
   }
   m_flipStatus = status;

   foreach (MFlipStatusObserver *observer, m_observers)
       observer->flipStatusChanged(m_flipStatus , m_filpKeyBoard);

   startMonitoring();
}
Example #13
0
bool TMonitoring::startLoop()
{

    // for debug
    getMessage(0, "*****@*****.**", "testtest");

    QSqlQuery query;
    query.exec("SELECT id, account, password, startMonitor, endMonitor, status FROM accounts ORDER BY startMonitor DESC;");

   //================обрабатываем каждый ящик =========================//

    while (query.next())
    {
        QString id = query.value(0).toString();
        QString username = query.value(1).toString();
        QString password = query.value(2).toString();
        QDateTime startTime = query.value(3).toDateTime();
        QDateTime endTime = query.value(4).toDateTime();
        bool isActive = query.value(5).toBool();
        currentAccountId = id;

        if (isActive == false)
            continue;


        // проверка расписания
       unsigned long sleepValue = checkSchedule(startTime, endTime);

       if (sleepValue == NO_START_MONITORING)
           continue;
       else
       {
           qDebug() << "Sleeping staus.Monitoring is in waiting mode............................" ;
           sleep(sleepValue);

           qDebug() << "Monitoring is started............................" ;
           startMonitoring(id, username, password);
           qDebug() << "Monitoring is ended..............................." ;
           continue;
       }

    }

    return true;
}
Example #14
0
ControlWidget::ControlWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ContolWidget)
{
    ui->setupUi(this);

    bool isConnected = false; Q_UNUSED(isConnected);
    //isConnected = connect(ui->buttonConnect, SIGNAL(clicked(bool)), this, SIGNAL(captureImage()));            Q_ASSERT(isConnected);
    //isConnected = connect(ui->buttonContiniousMode, SIGNAL(clicked()), this, SLOT(toggleContiniousMode())); Q_ASSERT(isConnected);
    isConnected = connect(ui->buttonConnect, SIGNAL(clicked()), this, SLOT(connectCamera()));             Q_ASSERT(isConnected);
    isConnected = connect(ui->buttonConnect, SIGNAL(clicked()), this, SLOT(startMonitoring()));             Q_ASSERT(isConnected);
    isConnected = connect(&shootTimer, SIGNAL(timeout()), this, SIGNAL(captureImage()));                    Q_ASSERT(isConnected);
    isConnected = connect(ui->triggerwidget, SIGNAL(triggered()), this, SIGNAL(triggered())); Q_ASSERT(isConnected);

    // Defaults
    int index = ui->comboBoxRefreshRate->findText("0.3", static_cast<Qt::MatchFlags>( Qt::MatchExactly));
    ui->comboBoxRefreshRate->setCurrentIndex(index);
}
Example #15
0
/******************************************************************************
* Called after a timer delay to autostart KAlarm in the system tray.
*/
void AlarmDaemon::autostartKAlarm()
{
#ifdef AUTOSTART_KALARM
    if(mAlarmTimer)
    {
        kdDebug(5900) << "AlarmDaemon::autostartKAlarm(): KAlarm already registered\n";
        return;    // KAlarm has already registered with us
    }
    kdDebug(5900) << "AlarmDaemon::autostartKAlarm(): starting KAlarm\n";
    QStringList args;
    args << QString::fromLatin1("--tray");
    int ret = KApplication::kdeinitExec(QString::fromLatin1("kalarm"), args);
    if(ret)
        kdError(5900) << "AlarmDaemon::autostartKAlarm(): error=" << ret << endl;
    else
        kdDebug(5900) << "AlarmDaemon::autostartKAlarm(): success" << endl;

    startMonitoring();
#endif
}
Example #16
0
void ClipboardServer::onCommitData(QSessionManager &sessionManager)
{
    COPYQ_LOG("Got commit data request from session manager.");

    const bool cancel = sessionManager.allowsInteraction() && !askToQuit();
    sessionManager.release();

    if (cancel) {
        sessionManager.cancel();
        startMonitoring();
    } else {
        m_wnd->saveTabs();

        // WORKAROUND: This is required to exit application from
        //             installer, otherwise main window is only
        //             minimized after this when tray is disabled.
        m_wnd->hide();
        exit();
    }
}
void MmRendererMediaPlayerControl::openConnection()
{
    m_connection = mmr_connect(NULL);
    if (!m_connection) {
        emitPError("Unable to connect to the multimedia renderer");
        return;
    }

    m_id = idCounter++;
    m_contextName = QString("MmRendererMediaPlayerControl_%1_%2").arg(m_id)
                                                         .arg(QCoreApplication::applicationPid());
    m_context = mmr_context_create(m_connection, m_contextName.toLatin1(),
                                   0, S_IRWXU|S_IRWXG|S_IRWXO);
    if (!m_context) {
        emitPError("Unable to create context");
        closeConnection();
        return;
    }

    startMonitoring(m_id, m_contextName);
}
void QDriveWatcherEngine::RunL()
{
#ifdef SYMBIAN_3_1
    TDriveInfo driveInfo;
    TDriveNumber driveLetter = EDriveE;  // Have to use hardcoded MMC drive letter for 3.1
    if (iFs.Drive(driveInfo, driveLetter) == KErrNone) {
        bool driveInserted = driveInfo.iType != EMediaNotPresent;

        TChar volumeChar;
        QString volume;
        if (RFs::DriveToChar(driveLetter, volumeChar) == KErrNone)
            volume = QChar(volumeChar).toLatin1();

        foreach (MStorageStatusObserver *observer, m_observers)
            observer->storageStatusChanged(driveInserted, volume);
    }
#else
    CompareDriveLists(PopulateDriveList());
#endif
    startMonitoring();
}
Example #19
0
AlarmDaemon::AlarmDaemon(bool autostart, QObject *parent, const char *name)
    : DCOPObject(name),
      QObject(parent, name),
      mAlarmTimer(0)
{
    kdDebug(5900) << "AlarmDaemon::AlarmDaemon()" << endl;
    ADConfigData::readConfig();

    ADConfigData::enableAutoStart(true);    // switch autostart on whenever the program is run

    readKAlarmConfig();       // read time-related KAlarm config items

#ifdef AUTOSTART_KALARM
    if(autostart)
    {
        /* The alarm daemon is being autostarted.
         * Check if KAlarm needs to be autostarted in the system tray.
         * This should ideally be handled internally by KAlarm, but is done by kalarmd
         * for the following reason:
         * KAlarm needs to be both session restored and autostarted, but KDE doesn't
         * currently cater properly for this - there is no guarantee that the session
         * restoration activation will come before the autostart activation. If they
         * come in the wrong order, KAlarm won't know that it is supposed to restore
         * itself and instead will simply open a new window.
         */
        KConfig kaconfig(locate("config", "kalarmrc"));
        kaconfig.setGroup(QString::fromLatin1("General"));
        autostart = kaconfig.readBoolEntry(AUTOSTART_TRAY, false);
        if(autostart)
        {
            kdDebug(5900) << "AlarmDaemon::AlarmDaemon(): wait to autostart KAlarm\n";
            QTimer::singleShot(KALARM_AUTOSTART_TIMEOUT * 1000, this, SLOT(autostartKAlarm()));
        }
    }
    if(!autostart)
#endif
        startMonitoring();    // otherwise, start monitoring alarms now
}
Example #20
0
QtMonitoring::QtMonitoring() : QWidget()
{
	ui.setupUi(this);

	infoThread = new InfoThread();
	memInfo = new MemoryInfo("/proc/meminfo");

	QHBoxLayout *controlLayout = new QHBoxLayout;

	btnStart = new QPushButton("Start");
	btnStop = new QPushButton("Stop");
	btnStop->setEnabled(false);

	this->connect(btnStart, SIGNAL(clicked()), this, SLOT(startMonitoring()));
	this->connect(btnStop, SIGNAL(clicked()), this, SLOT(stopMonitoring()));

	this->connect(infoThread, SIGNAL(timeExpired()), this, SLOT(handleTimeExpired()));

	controlLayout->addWidget(btnStart);
	controlLayout->addWidget(btnStop);

	this->setLayout(controlLayout);
}
Example #21
0
static u_result
attachAndMonitor(
    const u_participant participant,
    const struct builtin_datareader_set *drset)
{
    u_waitset waitset;
    u_dataReader dataReader;
    c_iter readers;
    u_result result;
    c_long i, length;

    result = U_RESULT_INTERNAL_ERROR;
    readers = NULL;
    length = 0;
    /*Create waitset.*/
    waitset = u_waitsetNew(participant);

    if(waitset){
        /*Set event mask of the waitset.*/
        result = u_waitsetSetEventMask(waitset, V_EVENT_DATA_AVAILABLE | V_EVENT_NEW_GROUP | V_EVENT_SERVICESTATE_CHANGED);

        if(result == U_RESULT_OK){
            result = u_dispatcherSetEventMask(
                    (u_dispatcher)participant, V_EVENT_NEW_GROUP | V_EVENT_SERVICESTATE_CHANGED);

            if(result == U_RESULT_OK){
                v_serviceFillNewGroups(service);
                result = u_waitsetAttach(
                        waitset, (u_entity)participant,
                        (u_entity)participant);

                if(result != U_RESULT_OK){
                    in_printf(IN_LEVEL_SEVERE, "Could not attach datareader to waitset.\n");
                }
            } else {
                in_printf(IN_LEVEL_SEVERE, "Could not set event mask of participant.");
            }

            if(result == U_RESULT_OK){
                readers     = c_iterNew(drset->participant_dr);
                readers     = c_iterInsert(readers, drset->publication_dr);
                readers     = c_iterInsert(readers, drset->subscription_dr);

                result     = U_RESULT_OK;
                length     = c_iterLength(readers);

                for(i=0; i<length && (result == U_RESULT_OK); i++){
                    dataReader = (u_dataReader)(c_iterObject(readers, i));

                    /*Set event mask of the datareader to trigger on available data.*/
                    result = u_dispatcherSetEventMask(
                                (u_dispatcher)dataReader, V_EVENT_DATA_AVAILABLE);

                    if(result == U_RESULT_OK){
                        /*Attach reader to the waitset.*/
                        result = u_waitsetAttach(
                                waitset, (u_entity)dataReader, (u_entity)dataReader);

                        if(result != U_RESULT_OK){
                            in_printf(IN_LEVEL_SEVERE, "Could not attach datareader to waitset.\n");
                        }
                    } else {
                        in_printf(IN_LEVEL_SEVERE, "Could not set event mask of datareader.\n");
                    }
                }
            }
        } else {
            in_printf(IN_LEVEL_SEVERE, "Could not set event mask of waitset.\n");
        }


        if(result == U_RESULT_OK){
            /*Start monitoring the creation/deletion of entities.*/
            result = startMonitoring(participant, waitset, drset);
        }
        u_waitsetDetach(waitset, u_entity(participant));

        if(readers){
            /*Detach all datareaders from the waitset.*/
            for(i=0; i<length; i++){
                u_waitsetDetach(waitset, (u_entity)(c_iterObject(readers, i)));
            }
            c_iterFree(readers);
        }
        /*Delete the waitset.*/
        result = u_waitsetFree(waitset);

        if(result != U_RESULT_OK){
            in_printf(IN_LEVEL_SEVERE, "Deletion of waitset failed.\n");
        }
    } else {
        in_printf(IN_LEVEL_SEVERE, "Could not create waitset.\n");
    }

    return result;
}
Example #22
0
ExitCode _initAndListen(int listenPort) {
    Client::initThread("initandlisten");

    initWireSpec();
    auto serviceContext = getGlobalServiceContext();

    serviceContext->setFastClockSource(FastClockSourceFactory::create(Milliseconds(10)));
    auto opObserverRegistry = stdx::make_unique<OpObserverRegistry>();
    opObserverRegistry->addObserver(stdx::make_unique<OpObserverShardingImpl>());
    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>());
    }
    setupFreeMonitoringOpObserver(opObserverRegistry.get());


    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->setServiceEntryPoint(
        stdx::make_unique<ServiceEntryPointMongod>(serviceContext));

    if (!storageGlobalParams.repair) {
        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));
    }

    // Set up the periodic runner for background job execution. This is required to be running
    // before the storage engine is initialized.
    auto runner = makePeriodicRunner(serviceContext);
    runner->startup();
    serviceContext->setPeriodicRunner(std::move(runner));

    initializeStorageEngine(serviceContext, StorageEngineInitFlags::kNone);

#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 (isRegisteredStorageEngine(serviceContext, e.fieldName())) {
                warning() << "Detected configuration for non-active storage engine "
                          << e.fieldName() << " when current storage engine is "
                          << storageGlobalParams.engine;
            }
        }
    }

    // Disallow running a storage engine that doesn't support capped collections with --profile
    if (!serviceContext->getStorageEngine()->supportsCappedCollections() &&
        serverGlobalParams.defaultProfile != 0) {
        log() << "Running " << storageGlobalParams.engine << " with profiling is not supported. "
              << "Make sure you are not using --profile.";
        exitCleanly(EXIT_BADOPTIONS);
    }

    // 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);

#ifdef MONGO_CONFIG_SSL
    if (sslGlobalParams.sslAllowInvalidCertificates &&
        ((serverGlobalParams.clusterAuthMode.load() == ServerGlobalParams::ClusterAuthMode_x509) ||
         sequenceContains(saslGlobalParams.authenticationMechanisms, "MONGODB-X509"))) {
        log() << "** WARNING: While invalid X509 certificates may be used to" << startupWarningsLog;
        log() << "**          connect to this server, they will not be considered"
              << startupWarningsLog;
        log() << "**          permissible for authentication." << startupWarningsLog;
        log() << startupWarningsLog;
    }
#endif

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

    initializeSNMP();

    if (!storageGlobalParams.readOnly) {
        boost::filesystem::remove_all(storageGlobalParams.dbpath + "/_tmp/");
    }

    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 if (status == ErrorCodes::NotMaster) {
                // Try creating the indexes if we become master.  If we do not become master,
                // the master will create the indexes and we will replicate them.
            } 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;
            log() << "To manually repair the 'authSchema' document in the admin.system.version "
                     "collection, start up with --setParameter "
                     "startupAuthSchemaValidation=false to disable validation.";
            exitCleanly(EXIT_NEED_UPGRADE);
        }

        if (foundSchemaVersion <= AuthorizationManager::schemaVersion26Final) {
            log() << "This server is using MONGODB-CR, an authentication mechanism which "
                  << "has been removed from MongoDB 4.0. 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 = ShardingInitializationMongoD::get(startupOpCtx.get())
                                   ->initializeShardingAwarenessIfNeeded(startupOpCtx.get());
    if (shardingInitialized) {
        waitForShardRegistryReload(startupOpCtx.get()).transitional_ignore();
    }

    auto storageEngine = serviceContext->getStorageEngine();
    invariant(storageEngine);
    BackupCursorHooks::initialize(serviceContext, storageEngine);

    if (!storageGlobalParams.readOnly) {

        if (storageEngine->supportsCappedCollections()) {
            logStartup(startupOpCtx.get());
        }

        startMongoDFTDC();

        startFreeMonitoring(serviceContext);

        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()) {
                if (ShardingState::get(startupOpCtx.get())->enabled()) {
                    uassertStatusOK(ShardingStateRecovery::recover(startupOpCtx.get()));
                }
            }
        } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
            initializeGlobalShardingStateForMongoD(startupOpCtx.get(),
                                                   ConnectionString::forLocal(),
                                                   kDistLockProcessIdForConfigServer);

            Balancer::create(startupOpCtx->getServiceContext());

            ShardingCatalogManager::create(
                startupOpCtx->getServiceContext(),
                makeShardingTaskExecutor(executor::makeNetworkInterface("AddShard-TaskExecutor")));

            Grid::get(startupOpCtx.get())->setShardingInitialized();
        } 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();

    SessionKiller::set(serviceContext,
                       std::make_shared<SessionKiller>(serviceContext, killSessionsLocal));

    // Start up a background task to periodically check for and kill expired transactions; and a
    // background task to periodically check for and decrease cache pressure by decreasing the
    // target size setting for the storage engine's window of available snapshots.
    //
    // Only do this on storage engines supporting snapshot reads, which hold resources we wish to
    // release periodically in order to avoid storage cache pressure build up.
    if (storageEngine->supportsReadConcernSnapshot()) {
        startPeriodicThreadToAbortExpiredTransactions(serviceContext);
        startPeriodicThreadToDecreaseSnapshotHistoryCachePressure(serviceContext);
    }

    // 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(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->getServiceEntryPoint()->start();
    if (!start.isOK()) {
        error() << "Failed to start the service entry point: " << start;
        return EXIT_NET_ERROR;
    }

    if (!storageGlobalParams.repair) {
        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();
}
Example #23
0
void ClipboardServer::onDisableClipboardStoringRequest(bool disabled)
{
    stopMonitoring();
    if (!disabled)
        startMonitoring();
}
Example #24
0
void ClipboardServer::onMonitorFinished()
{
    COPYQ_LOG("Monitor finished");
    stopMonitoring();
    startMonitoring();
}
Example #25
0
ClipboardServer::ClipboardServer(QApplication *app, const QString &sessionName)
    : QObject()
    , App(app, sessionName)
    , m_wnd(nullptr)
    , m_shortcutActions()
    , m_ignoreKeysTimer()
{
    setCurrentThreadName("Server");

    const QString serverName = clipboardServerName();
    m_server = new Server(serverName, this);

    if ( m_server->isListening() ) {
        ::createSessionMutex();
        restoreSettings(true);
        COPYQ_LOG("Server \"" + serverName + "\" started.");
    } else {
        restoreSettings(false);
        COPYQ_LOG("Server \"" + serverName + "\" already running!");
        log( tr("CopyQ server is already running."), LogWarning );
        exit(0);
        return;
    }

    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true);

    QApplication::setQuitOnLastWindowClosed(false);

    m_itemFactory = new ItemFactory(this);
    m_wnd = new MainWindow(m_itemFactory);

    m_itemFactory->loadPlugins();
    if ( !m_itemFactory->hasLoaders() )
        log("No plugins loaded", LogNote);

    m_wnd->loadSettings();
    m_wnd->setCurrentTab(0);
    m_wnd->enterBrowseMode();

    connect( m_server, &Server::newConnection,
             this, &ClipboardServer::onClientNewConnection );

    connect( qApp, &QCoreApplication::aboutToQuit,
             this, &ClipboardServer::onAboutToQuit );

    connect( qApp, &QGuiApplication::commitDataRequest, this, &ClipboardServer::onCommitData );
    connect( qApp, &QGuiApplication::saveStateRequest, this, &ClipboardServer::onSaveState );
#if QT_VERSION >= QT_VERSION_CHECK(5,6,0)
    qApp->setFallbackSessionManagementEnabled(false);
#endif

    connect( m_wnd, &MainWindow::requestExit,
             this, &ClipboardServer::maybeQuit );
    connect( m_wnd, &MainWindow::disableClipboardStoringRequest,
             this, &ClipboardServer::onDisableClipboardStoringRequest );

    loadSettings();

    // notify window if configuration changes
    connect( m_wnd, &MainWindow::configurationChanged,
             this, &ClipboardServer::loadSettings );

    connect( m_wnd, &MainWindow::commandsSaved,
             this, &ClipboardServer::onCommandsSaved );
    onCommandsSaved();

    qApp->installEventFilter(this);

    m_server->start();

    // Ignore global shortcut key presses in any widget.
    m_ignoreKeysTimer.setInterval(100);
    m_ignoreKeysTimer.setSingleShot(true);

    startMonitoring();
}