//-------------------------------------------------------------------------------------
bool KBEEmailVerificationTableRedis::logAccount(DBInterface * pdbi, int8 type, const std::string& name, 
												const std::string& datas, const std::string& code)
{
	/*
	kbe_email_verification:code = hashes(accountName, type, datas, logtime)
	kbe_email_verification:accountName = code
	*/
	
	redis::DBTransaction transaction(pdbi);
	
	// 如果查询失败则返回存在, 避免可能产生的错误
	if(!pdbi->query(fmt::format("HSET kbe_email_verification:{} accountName {} type {} datas {} logtime {}", 
		code, name, type, datas, time(NULL)), false))
	{
		ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::logAccount({}): cmd({}) is failed({})!\n", 
				code, pdbi->lastquery(), pdbi->getstrerror()));
		
		transaction.rollback();
		return false;
	}

	// 如果查询失败则返回存在, 避免可能产生的错误
	if(!pdbi->query(fmt::format("SET kbe_email_verification:{} {}", name, code), false))
	{
		ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::logAccount({}): cmd({}) is failed({})!\n", 
				code, pdbi->lastquery(), pdbi->getstrerror()));	
		
		transaction.rollback();	
		return false;
	}

	// 如果查询失败则返回存在, 避免可能产生的错误
	if(!pdbi->query(fmt::format("EXPIRE kbe_email_verification:{} {}", 
		code.c_str(), getDeadline(type)), false))
	{
		ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::logAccount({}): cmd({}) is failed({})!\n", 
				code, pdbi->lastquery(), pdbi->getstrerror()));
		
		transaction.rollback();	
		return false;
	}
	
	// 如果查询失败则返回存在, 避免可能产生的错误
	if(!pdbi->query(fmt::format("EXPIRE kbe_email_verification:{} {}", 
		name.c_str(), getDeadline(type)), false))
	{
		ERROR_MSG(fmt::format("KBEEmailVerificationTableMysql::logAccount({}): cmd({}) is failed({})!\n", 
				code, pdbi->lastquery(), pdbi->getstrerror()));
		
		transaction.rollback();	
		return false;
	}
	
	transaction.commit();
	
	redisReply* pRedisReply = transaction.pRedisReply();

	return pRedisReply && pRedisReply->type == REDIS_REPLY_ARRAY && pRedisReply->elements == 4;
}
示例#2
0
// Theory of operation for waitForConditionOrInterruptNoAssertUntil and markKilled:
//
// An operation indicates to potential killers that it is waiting on a condition variable by setting
// _waitMutex and _waitCV, while holding the lock on its parent Client. It then unlocks its Client,
// unblocking any killers, which are required to have locked the Client before calling markKilled.
//
// When _waitMutex and _waitCV are set, killers must lock _waitMutex before setting the _killCode,
// and must signal _waitCV before releasing _waitMutex. Unfortunately, they must lock _waitMutex
// without holding a lock on Client to avoid a deadlock with callers of
// waitForConditionOrInterruptNoAssertUntil(). So, in the event that _waitMutex is set, the killer
// increments _numKillers, drops the Client lock, acquires _waitMutex and then re-acquires the
// Client lock. We know that the Client, its OperationContext and _waitMutex will remain valid
// during this period because the caller of waitForConditionOrInterruptNoAssertUntil will not return
// while _numKillers > 0 and will not return until it has itself reacquired _waitMutex. Instead,
// that caller will keep waiting on _waitCV until _numKillers drops to 0.
//
// In essence, when _waitMutex is set, _killCode is guarded by _waitMutex and _waitCV, but when
// _waitMutex is not set, it is guarded by the Client spinlock. Changing _waitMutex is itself
// guarded by the Client spinlock and _numKillers.
//
// When _numKillers does drop to 0, the waiter will null out _waitMutex and _waitCV.
//
// This implementation adds a minimum of two spinlock acquire-release pairs to every condition
// variable wait.
StatusWith<stdx::cv_status> OperationContext::waitForConditionOrInterruptNoAssertUntil(
    stdx::condition_variable& cv, stdx::unique_lock<stdx::mutex>& m, Date_t deadline) noexcept {
    invariant(getClient());
    {
        stdx::lock_guard<Client> clientLock(*getClient());
        invariant(!_waitMutex);
        invariant(!_waitCV);
        invariant(0 == _numKillers);

        // This interrupt check must be done while holding the client lock, so as not to race with a
        // concurrent caller of markKilled.
        auto status = checkForInterruptNoAssert();
        if (!status.isOK()) {
            return status;
        }
        _waitMutex = m.mutex();
        _waitCV = &cv;
    }

    if (hasDeadline()) {
        deadline = std::min(deadline, getDeadline());
    }

    const auto waitStatus = [&] {
        if (Date_t::max() == deadline) {
            cv.wait(m);
            return stdx::cv_status::no_timeout;
        }
        return getServiceContext()->getPreciseClockSource()->waitForConditionUntil(cv, m, deadline);
    }();

    // Continue waiting on cv until no other thread is attempting to kill this one.
    cv.wait(m, [this] {
        stdx::lock_guard<Client> clientLock(*getClient());
        if (0 == _numKillers) {
            _waitMutex = nullptr;
            _waitCV = nullptr;
            return true;
        }
        return false;
    });

    auto status = checkForInterruptNoAssert();
    if (!status.isOK()) {
        return status;
    }
    if (hasDeadline() && waitStatus == stdx::cv_status::timeout && deadline == getDeadline()) {
        // It's possible that the system clock used in stdx::condition_variable::wait_until
        // is slightly ahead of the FastClock used in checkForInterrupt. In this case,
        // we treat the operation as though it has exceeded its time limit, just as if the
        // FastClock and system clock had agreed.
        markKilled(ErrorCodes::ExceededTimeLimit);
        return Status(ErrorCodes::ExceededTimeLimit, "operation exceeded time limit");
    }
    return waitStatus;
}
示例#3
0
    void Grub::executing_recharging()
    {
	DBGENTER(_SERVER_DBG_LEV);
	updateBudget();
	status = RECHARGING;
	if (getDeadline() < SIMUL.getTime()) 
	    _rechargingEvt.post(SIMUL.getTime()); 
	else 
	    _rechargingEvt.post(getDeadline());
    }
//----------------------------------------------------------------------
// affect
//----------------------------------------------------------------------
void EffectTransportCreature::affect(Creature* pCreature)
	throw(Error)
{
	__BEGIN_TRY

	Timeval      nextTime   = getNextTime();
	Timeval      deadLine   = getDeadline();
	Turn_t       RemainTime = deadLine.tv_sec - nextTime.tv_sec;

//	StringStream msg;
//	msg << (int)RemainTime << "초 후에 " << m_ZoneName << "로 이동됩니다.";

    char msg[50];
    sprintf(msg, g_pStringPool->c_str(STRID_TRANSPORT_CREATURE ),
                    (int)RemainTime,
                    m_ZoneName.c_str());

	string sMsg(msg);

	GCSystemMessage gcSystemMessage;
	gcSystemMessage.setMessage(sMsg);
	pCreature->getPlayer()->sendPacket(&gcSystemMessage);

	setNextTime(m_MessageTick);

	__END_CATCH
}
Milliseconds OperationContext::getRemainingMaxTimeMillis() const {
    if (!hasDeadline()) {
        return Milliseconds::max();
    }

    return std::max(Milliseconds{0},
                    getDeadline() - getServiceContext()->getFastClockSource()->now());
}
示例#6
0
/*
 * TimerBase
 */
void TimerBase::handleDeadline(MonotonicTime current)
{
    UAVCAN_ASSERT(!isRunning());

    const MonotonicTime scheduled_time = getDeadline();

    if (period_ < MonotonicDuration::getInfinite())
    {
        startWithDeadline(scheduled_time + period_);
    }

    // Application can re-register the timer with different params, it's OK
    handleTimerEvent(TimerEvent(scheduled_time, current));
}
bool OperationContext::hasDeadlineExpired() const {
    if (!hasDeadline()) {
        return false;
    }
    if (MONGO_FAIL_POINT(maxTimeNeverTimeOut)) {
        return false;
    }
    if (MONGO_FAIL_POINT(maxTimeAlwaysTimeOut)) {
        return true;
    }

    // TODO: Remove once all OperationContexts are properly connected to Clients and ServiceContexts
    // in tests.
    if (MONGO_unlikely(!getClient() || !getServiceContext())) {
        return false;
    }

    const auto now = getServiceContext()->getFastClockSource()->now();
    return now >= getDeadline();
}
示例#8
0
//单击“添加旅客”按钮,开始运行
void Widget::addTravelerButtonClicked()
{
    //添加旅客,初始化旅客信息
    qDebug() << "Add new traveler, reset all elements in widget";
    std::vector<bool> temp(12, false);
    throughcity = temp;
    qDebug() << "throughcity creat success.";
    travelers.push_back(Traveler(addtravelertimes-1, getStartTime(), getDeadline(),
                                 getStrategy(), getStart(), getDestination(),
                                 ui->ThroughCityCheckBox->isChecked(), throughcity));
    qDebug() << "travelers.pushback...";
    startclicked.push_back(false);
    addtravelertimes += 1;
    startclickedtimes = 0;

    //将界面右侧各栏初始化显示
    ui->TravelerComboBox->addItem(QString::number(addtravelertimes));
    ui->TravelerComboBox->setCurrentText(QString::number(addtravelertimes));

    ui->StartButton->setText(QString::fromWCharArray(L"开始"));
    ui->TravelerComboBox->setEnabled(true);
    ui->StartComboBox->setEnabled(true);
    ui->StrategyComboBox->setEnabled(true);
    ui->DestinationComboBox->setEnabled(true);
    ui->StrategyComboBox->setCurrentIndex(0);
    ui->StartComboBox->setCurrentIndex(0);
    ui->DestinationComboBox->setCurrentIndex(1);
    ui->ThroughCityCheckBox->setEnabled(true);
    ui->DeadlineDateTimeEdit->setEnabled(false);
    ui->StartDateTimeEdit->setEnabled(true);
    ui->StartButton->setEnabled(true);

    ui->StartDateTimeEdit->setDateTime(QDateTime::currentDateTime());
    int deaDay = QDateTime::currentDateTime().date().day();
    deaDay += 1;
    QDateTime deadlineDateTime;
    deadlineDateTime.setDate(QDate(QDateTime::currentDateTime().date().year(), QDateTime::currentDateTime().date().month(), deaDay));
    deadlineDateTime.setTime(QTime(QDateTime::currentDateTime().time()));
    ui->DeadlineDateTimeEdit->setDateTime(deadlineDateTime);
}
// Theory of operation for waitForConditionOrInterruptNoAssertUntil and markKilled:
//
// An operation indicates to potential killers that it is waiting on a condition variable by setting
// _waitMutex and _waitCV, while holding the lock on its parent Client. It then unlocks its Client,
// unblocking any killers, which are required to have locked the Client before calling markKilled.
//
// When _waitMutex and _waitCV are set, killers must lock _waitMutex before setting the _killCode,
// and must signal _waitCV before releasing _waitMutex. Unfortunately, they must lock _waitMutex
// without holding a lock on Client to avoid a deadlock with callers of
// waitForConditionOrInterruptNoAssertUntil(). So, in the event that _waitMutex is set, the killer
// increments _numKillers, drops the Client lock, acquires _waitMutex and then re-acquires the
// Client lock. We know that the Client, its OperationContext and _waitMutex will remain valid
// during this period because the caller of waitForConditionOrInterruptNoAssertUntil will not return
// while _numKillers > 0 and will not return until it has itself reacquired _waitMutex. Instead,
// that caller will keep waiting on _waitCV until _numKillers drops to 0.
//
// In essence, when _waitMutex is set, _killCode is guarded by _waitMutex and _waitCV, but when
// _waitMutex is not set, it is guarded by the Client spinlock. Changing _waitMutex is itself
// guarded by the Client spinlock and _numKillers.
//
// When _numKillers does drop to 0, the waiter will null out _waitMutex and _waitCV.
//
// This implementation adds a minimum of two spinlock acquire-release pairs to every condition
// variable wait.
StatusWith<stdx::cv_status> OperationContext::waitForConditionOrInterruptNoAssertUntil(
    stdx::condition_variable& cv, stdx::unique_lock<stdx::mutex>& m, Date_t deadline) noexcept {
    invariant(getClient());
    {
        stdx::lock_guard<Client> clientLock(*getClient());
        invariant(!_waitMutex);
        invariant(!_waitCV);
        invariant(0 == _numKillers);

        // This interrupt check must be done while holding the client lock, so as not to race with a
        // concurrent caller of markKilled.
        auto status = checkForInterruptNoAssert();
        if (!status.isOK()) {
            return status;
        }
        _waitMutex = m.mutex();
        _waitCV = &cv;
    }

    // If the maxTimeNeverTimeOut failpoint is set, behave as though the operation's deadline does
    // not exist. Under normal circumstances, if the op has an existing deadline which is sooner
    // than the deadline passed into this method, we replace our deadline with the op's. This means
    // that we expect to time out at the same time as the existing deadline expires. If, when we
    // time out, we find that the op's deadline has not expired (as will always be the case if
    // maxTimeNeverTimeOut is set) then we assume that the incongruity is due to a clock mismatch
    // and return _timeoutError regardless. To prevent this behaviour, only consider the op's
    // deadline in the event that the maxTimeNeverTimeOut failpoint is not set.
    bool opHasDeadline = (hasDeadline() && !MONGO_FAIL_POINT(maxTimeNeverTimeOut));

    if (opHasDeadline) {
        deadline = std::min(deadline, getDeadline());
    }

    const auto waitStatus = [&] {
        if (Date_t::max() == deadline) {
            Waitable::wait(_baton.get(), getServiceContext()->getPreciseClockSource(), cv, m);
            return stdx::cv_status::no_timeout;
        }
        return getServiceContext()->getPreciseClockSource()->waitForConditionUntil(
            cv, m, deadline, _baton.get());
    }();

    // Continue waiting on cv until no other thread is attempting to kill this one.
    Waitable::wait(_baton.get(), getServiceContext()->getPreciseClockSource(), cv, m, [this] {
        stdx::lock_guard<Client> clientLock(*getClient());
        if (0 == _numKillers) {
            _waitMutex = nullptr;
            _waitCV = nullptr;
            return true;
        }
        return false;
    });

    auto status = checkForInterruptNoAssert();
    if (!status.isOK()) {
        return status;
    }
    if (opHasDeadline && waitStatus == stdx::cv_status::timeout && deadline == getDeadline()) {
        // It's possible that the system clock used in stdx::condition_variable::wait_until
        // is slightly ahead of the FastClock used in checkForInterrupt. In this case,
        // we treat the operation as though it has exceeded its time limit, just as if the
        // FastClock and system clock had agreed.
        if (!_hasArtificialDeadline) {
            markKilled(_timeoutError);
        }
        return Status(_timeoutError, "operation exceeded time limit");
    }

    return waitStatus;
}
示例#10
0
//单击“开始”按钮,获取用户输入信息
void Widget::startButtonClicked()
{
    QDateTime startDateTime;
    //对于当前旅客,初次点击开始按钮
    if (startclicked[ui->TravelerComboBox->currentIndex()] == false)
    {
        qDebug() << "StartButton clicked 1st time for CurrentTraveler";
        strategy = getStrategy();
        start = getStart();
        destination = getDestination();
        //始发地和目的地相同则弹框报错,不作操作
        if (start == destination)
        {
            qDebug() << "Start and Dedtination is the same one, wait for  another command";
            QMessageBox::information(this, "Error", QString::fromWCharArray(L"出发地和目的地相同"));
            return;
        }
        //(策略三的情况下)截止时间早于当前时间报错,不作操作
        if (!(ui->StartDateTimeEdit->dateTime() < ui->DeadlineDateTimeEdit->dateTime()))
        {
            qDebug() << "Deadline ahead of StratTime, wait for another command";
            QMessageBox::information(this, "Error", QString::fromWCharArray(L"截止时间早于当前时间"));
            return;
        }

        startDateTime = getStartTime();

        travelers[ui->TravelerComboBox->currentIndex()] = (Traveler(addtravelertimes-1, startDateTime,
                                                                    getDeadline(), strategy, start, destination, ui->ThroughCityCheckBox->isChecked(), throughcity));
        std::vector<Attribute> path = travelers[ui->TravelerComboBox->currentIndex()].getPlan();
        if (path.size() == 0)
        {
            qDebug() << "No legal path";
            QMessageBox::information(this, "Error", QString::fromWCharArray(L"无有效路径"));
            startclicked[ui->TravelerComboBox->currentIndex()] = false;
            return;
        }

        startclicked[ui->TravelerComboBox->currentIndex()] = true;
        currentTraveler = ui->TravelerComboBox->currentIndex();

        displayTotalTime();
        displayFare(path);
        displayPath(path);

        qDebug() << "StartButton rename as ChangePlan for CurrentTraveler";
        ui->StartButton->setText(QString::fromWCharArray(L"更改"));
        ui->StartComboBox->setEnabled(false);
        ui->StartDateTimeEdit->setEnabled(false);
        startclickedtimes += 1;
        startclicked[ui->TravelerComboBox->currentIndex()] = true;
        return;
    }
    //对于当前旅客,执行更改计划操作
    if (startclicked[ui->TravelerComboBox->currentIndex()] == true)
    {
        qDebug() << "StartButton clicked for CurrentTraveler";
        strategy = getStrategy();
        destination = getDestination();

        if (!(ui->StartDateTimeEdit->dateTime() < ui->DeadlineDateTimeEdit->dateTime()))
        {
            qDebug() << "Deadline ahead of StartTime, reset the DeadlineDateTimeEdit,wait for another command";
            QMessageBox::information(this, "Error", QString::fromWCharArray(L"截止时间早于当前时间"));

            int deaDay = ui->StartDateTimeEdit->dateTime().date().day();
            deaDay += 1;
            QDateTime deadlineDateTime;
            deadlineDateTime.setDate(QDate(ui->StartDateTimeEdit->dateTime().date().year(), ui->StartDateTimeEdit->dateTime().date().month(), deaDay));
            deadlineDateTime.setTime(QTime(ui->StartDateTimeEdit->dateTime().time()));
            ui->DeadlineDateTimeEdit->setDateTime(deadlineDateTime);

            return;
        }

        //获得新计划的始发地,即原计划的当前停留地/运行途中即将到达地
        int nextCity2Arrive = ui->LeftWidget->nextCity();
        if (nextCity2Arrive != -1)
        {
            std::vector<Attribute> path = travelers[ui->TravelerComboBox->currentIndex()].changePlan(nextCity2Arrive, strategy, destination, getDeadline(),
                                                                                                     ui->ThroughCityCheckBox->isChecked(),throughcity);
            if (path.size() == 0)
            {
                qDebug() << "No legal path";
                QMessageBox::information(this, "Error", QString::fromWCharArray(L"无有效路径"));
                return;
            }
            qDebug() << "Change plan success.";
            currentTraveler = ui->TravelerComboBox->currentIndex();
            displayTotalTime();
            displayFare(path);
            displayPath(path);
        }
    }
}