Пример #1
0
void
MainWin::Play() {
    printf("Playing.\n");

    if (sp && sp->HasData()) {
        sp->Start();
        return;
    }

    printf("Starting at position %d.\n", (int) position);

    status_t err;

    LibraryItem *item = dynamic_cast<LibraryItem *>(be_app->library->list->ItemAt(position));
    printf("Playing track %s.\n", item->entry.name);

    mediaFile = new BMediaFile(&item->entry);
    if ((err = mediaFile->InitCheck()) != B_OK) {
        printf("Play: Initiating media file failed: %s; skipping.\n", strerror(err));
        delete mediaFile;
        Next();
        return;
    }

    playTrack = 0;
    for (int i = 0; i < mediaFile->CountTracks(); i++) {
        playTrack = mediaFile->TrackAt(i);
        playFormat.type = B_MEDIA_RAW_AUDIO;

        if (playTrack->DecodedFormat(&playFormat) == B_OK)
            break;

        if (playTrack)
            mediaFile->ReleaseTrack(playTrack);
    }

    if (playTrack) {
        sp = new BSoundPlayer(&playFormat.u.raw_audio, "playfile", PlayBuffer, Notifier);
        sp->SetCookie(this);
        sp->SetVolume(1.0f);
        sp->SetHasData(true);
        sp->Start();

        char timestamp[100];
        Timestamp(timestamp, playTrack->Duration());

        progress->Reset(NULL, timestamp);
        progress->SetMaxValue(playTrack->Duration());

        BMessage *select = new BMessage(MSG_LIBRARY_HIGHLIGHT);
        select->AddUInt32("position", position);

        be_app->library->PostMessage(select);

        printf("Playback started.\n");
    } else {
        printf("ERROR: No valid track found. Skipping.\n");
        Next();
    }
}
Пример #2
0
bool Condition::safeWait(const Mutex& mutex, double seconds) const {
  bool result = true;
  Thread* self = 0;
  try {
    self = &Threads::getInstance().getSelf();
  }
  catch (...) {
    self = 0;
  }
  Thread::State threadState;
  if (self) {
    if (&mutex == &self->mMutex)
      threadState = self->safeSetState(Thread::waiting);
    else 
      threadState = self->setState(Thread::waiting);
  }
  if (seconds == Timer::eternal())
    result = safeEternalWait(mutex);
  else if (seconds > 0.0)
    result = safeWaitUntil(mutex, Timestamp(Timestamp::now() + seconds));
  if (self) {
    if (&mutex == &self->mMutex)
      self->safeSetState(threadState);
    else 
      self->setState(threadState);
  }
  return result;
}
Пример #3
0
bool _testOplogEntryIsForCappedCollection(OperationContext* txn,
                                          const NamespaceString& nss,
                                          const CollectionOptions& options) {
    auto writerPool = SyncTail::makeWriterPool();
    MultiApplier::Operations operationsApplied;
    auto applyOperationFn = [&operationsApplied](MultiApplier::OperationPtrs* operationsToApply) {
        for (auto&& opPtr : *operationsToApply) {
            operationsApplied.push_back(*opPtr);
        }
    };
    createCollection(txn, nss, options);

    auto op = makeInsertDocumentOplogEntry({Timestamp(Seconds(1), 0), 1LL}, nss, BSON("a" << 1));
    ASSERT_FALSE(op.isForCappedCollection);

    auto lastOpTime =
        unittest::assertGet(multiApply(txn, writerPool.get(), {op}, applyOperationFn));
    ASSERT_EQUALS(op.getOpTime(), lastOpTime);

    ASSERT_EQUALS(1U, operationsApplied.size());
    const auto& opApplied = operationsApplied.front();
    ASSERT_EQUALS(op, opApplied);
    // "isForCappedCollection" is not parsed from raw oplog entry document.
    return opApplied.isForCappedCollection;
}
Пример #4
0
TEST_F(SyncTailTest, MultiApplyReturnsBadValueOnNullOperationContext) {
    auto writerPool = SyncTail::makeWriterPool();
    auto op = makeCreateCollectionOplogEntry({Timestamp(Seconds(1), 0), 1LL});
    auto status = multiApply(nullptr, writerPool.get(), {op}, noopApplyOperationFn).getStatus();
    ASSERT_EQUALS(ErrorCodes::BadValue, status);
    ASSERT_STRING_CONTAINS(status.reason(), "invalid operation context");
}
Пример #5
0
Mp3PspStream::Mp3PspStream(Common::SeekableReadStream *inStream, DisposeAfterUse::Flag dispose) :
	_inStream(inStream),
	_disposeAfterUse(dispose),
	_pcmLength(0),
	_posInFrame(0),
	_state(MP3_STATE_INIT),
	_length(0, 1000),
	_sampleRate(0),
	_totalTime(mad_timer_zero) {

	DEBUG_ENTER_FUNC();

	assert(_decoderInit);	// must be initialized by now

	// let's leave the buffer guard -- who knows, it may be good?
	memset(_buf, 0, sizeof(_buf));
	memset(_codecInBuffer, 0, sizeof(_codecInBuffer));

	initStream();	// init needed stuff for the stream

	findValidHeader();	// get a first header so we can read basic stuff

	_sampleRate = _header.samplerate;	// copy it before it gets destroyed
	_stereo = (MAD_NCHANNELS(&_header) == 2);

	while (_state != MP3_STATE_EOS)
		findValidHeader();	// get a first header so we can read basic stuff

	_length = Timestamp(mad_timer_count(_totalTime, MAD_UNITS_MILLISECONDS), getRate());

	deinitStream();

	_state = MP3_STATE_INIT;
}
TEST_F(KeysManagerShardedTest, GetKeyForValidationErrorsIfKeyDoesntExist) {
    keyManager()->startMonitoring(getServiceContext());

    auto keyStatus =
        keyManager()->getKeyForValidation(operationContext(), 1, LogicalTime(Timestamp(100, 0)));
    ASSERT_EQ(ErrorCodes::KeyNotFound, keyStatus.getStatus());
}
Пример #7
0
void testObj::test<6>(void)
{
  Persistency::MetaAlertPtrNN maPtr( new Persistency::MetaAlert( Persistency::MetaAlert::Name(name_),
                                                                 0.1, 0.2,
                                                                 makeNewReferenceURL().shared_ptr(),
                                                                 Timestamp(),
                                                                 42u ) );
  Persistency::IO::Postgres::MetaAlert malert(maPtr, t_, dbh_);
  malert.save();
  const  DataBaseID malertID = dbh_->getIDCache()->get( maPtr );
  double delta = 0.1;
  stringstream ss;
  ss << "SELECT * FROM meta_alerts WHERE id = " << malertID << ";";
  {
    const result r = t_.getAPI<TransactionAPI>().exec(ss);
    ensure_equals("invalid size",r.size(), 1u);
    ensure_equals("invalid certainty delta", ReaderHelper<double>::readAsNotNull(r[0]["certainty_delta"]), 0.2);
  }
  malert.updateCertaintyDelta(delta);
  {
    const result r = t_.getAPI<TransactionAPI>().exec(ss);
    ensure_equals("invalid size",r.size(), 1u);
    ensure("invalid certainty delta",
           ( ReaderHelper<double>::readAsNotNull(r[0]["certainty_delta"]) - (0.2+delta) ) < 0.01 );
  }
  t_.commit();
}
Пример #8
0
Status ModifierCurrentDate::apply() const {
    const bool destExists = (_preparedState->elemFound.ok() &&
                             _preparedState->idxFound == (_updatePath.numParts() - 1));

    mutablebson::Document& doc = _preparedState->doc;
    StringData lastPart = _updatePath.getPart(_updatePath.numParts() - 1);
    // If the element exists and is the same type, then that is what we want to work with
    mutablebson::Element elemToSet = destExists ? _preparedState->elemFound : doc.end();

    if (!destExists) {
        // Creates the final element that's going to be $set in 'doc'.
        // fills in the value with place-holder/empty

        elemToSet = _typeIsDate ? doc.makeElementDate(lastPart, Date_t())
                                : doc.makeElementTimestamp(lastPart, Timestamp());

        if (!elemToSet.ok()) {
            return Status(ErrorCodes::InternalError, "can't create new element");
        }

        // Now, we can be in two cases here, as far as attaching the element being set goes:
        // (a) none of the parts in the element's path exist, or (b) some parts of the path
        // exist but not all.
        if (!_preparedState->elemFound.ok()) {
            _preparedState->elemFound = doc.root();
            _preparedState->idxFound = 0;
        } else {
            _preparedState->idxFound++;
        }

        // createPathAt() will complete the path and attach 'elemToSet' at the end of it.
        Status s = pathsupport::createPathAt(
                       _updatePath, _preparedState->idxFound, _preparedState->elemFound, elemToSet)
                       .getStatus();
        if (!s.isOK())
            return s;
    }

    dassert(elemToSet.ok());

    // By the time we are here the element is in place and we just need to update the value
    if (_typeIsDate) {
        const mongo::Date_t now = mongo::jsTime();
        Status s = elemToSet.setValueDate(now);
        if (!s.isOK())
            return s;
    } else {
        ServiceContext* service = getGlobalServiceContext();
        auto ts = LogicalClock::get(service)->reserveTicks(1).asTimestamp();
        Status s = elemToSet.setValueTimestamp(ts);
        if (!s.isOK())
            return s;
    }

    // Set the elemFound, idxFound to the changed element for oplog logging.
    _preparedState->elemFound = elemToSet;
    _preparedState->idxFound = (_updatePath.numParts() - 1);

    return Status::OK();
}
Пример #9
0
	void PeersManager::dumpConnectionMap()
	{
		// 这里上锁仅仅是为了锁住对ApplicationData的访问
		cacti::RecursiveMutex::ScopedLock sclock(m_applock);

		m_connMap.info("\n%s:\n", 
			Timestamp::getNowTime().getFormattedTime("%m%d %H:%M:%S").c_str());

		std::map<u32, ApplicationData>::iterator it = m_applications.begin();
		while(it != m_applications.end())
		{
			ApplicationData& ad = it->second;
			m_connMap.info("[%d, %s] \n", 
				ad.m_appid, ad.m_appName.c_str());
			m_connMap.info("\t addr=%s|%s:%d\n", 
				ad.m_primAddress.c_str(), ad.m_backAddress.c_str(), ad.m_connectPort);
			m_connMap.info("\t pasv=%08X\n", ad.m_passiveConnection);
			m_connMap.info("\t svrs=");
			u32 starttime = 0;
			for(size_t i=0; i<ad.m_activeServices.size(); ++i)
			{
				m_connMap.info("%d ", ad.m_activeServices[i]);
				starttime = ad.m_starttimes[ad.m_activeServices[i]];
			}
			m_connMap.info("\n\t boot timestamp:%s\n", Timestamp((time_t)starttime).getFormattedTime("%Y%m%d %H:%M:%S").c_str());
			++it;
		}

		// check anonymous
		for(size_t i=0; i<m_anonymousApps.size(); ++i)
		{
			ApplicationData& ad = m_anonymousApps[i];
			m_connMap.info("[%d, %s] \n", 
				ad.m_appid, ad.m_appName.c_str());
			m_connMap.info("\t addr=%s|%s:%d\n", 
				ad.m_primAddress.c_str(), ad.m_backAddress.c_str(), ad.m_connectPort);
			m_connMap.info("\t pasv=%08X\n", ad.m_passiveConnection);
			m_connMap.info("\t svrs=");
			u32 starttime = 0;
			for(size_t i=0; i<ad.m_activeServices.size(); ++i)
			{
				m_connMap.info("%d ", ad.m_activeServices[i]);
				starttime = ad.m_starttimes[ad.m_activeServices[i]];
			}
			m_connMap.info("\n\t boot timestamp:%s\n", Timestamp((time_t)starttime).getFormattedTime("%Y%m%d %H:%M:%S").c_str());
		}
	}
Пример #10
0
TEST_F(OplogBufferCollectionTest, extractEmbeddedOplogDocumentChangesIdToTimestamp) {
    auto nss = makeNamespace(_agent);
    OplogBufferCollection oplogBuffer(_storageInterface, nss);

    const BSONObj expectedOp = makeOplogEntry(1);
    BSONObj originalOp = BSON("_id" << Timestamp(1, 1) << "entry" << expectedOp);
    ASSERT_BSONOBJ_EQ(expectedOp, OplogBufferCollection::extractEmbeddedOplogDocument(originalOp));
}
Пример #11
0
TEST_F(KeyGeneratorUpdateTest, ShouldCreateAnotherKeyIfOnlyOneKeyExists) {
    KeyGenerator generator("dummy", catalogClient(), Seconds(5));

    LogicalClock::get(operationContext())
        ->setClusterTimeFromTrustedSource(LogicalTime(Timestamp(100, 2)));

    KeysCollectionDocument origKey1(
        1, "dummy", TimeProofService::generateRandomKey(), LogicalTime(Timestamp(105, 0)));
    ASSERT_OK(insertToConfigCollection(
        operationContext(), KeysCollectionDocument::ConfigNS, origKey1.toBSON()));

    {
        auto allKeys = getKeys(operationContext());

        ASSERT_EQ(1u, allKeys.size());

        const auto& key1 = allKeys.front();
        ASSERT_EQ(1, key1.getKeyId());
        ASSERT_EQ("dummy", key1.getPurpose());
        ASSERT_EQ(Timestamp(105, 0), key1.getExpiresAt().asTimestamp());
    }

    auto currentTime = LogicalClock::get(operationContext())->getClusterTime();

    auto generateStatus = generator.generateNewKeysIfNeeded(operationContext());
    ASSERT_OK(generateStatus);

    {
        auto allKeys = getKeys(operationContext());

        ASSERT_EQ(2u, allKeys.size());

        const auto& key1 = allKeys.front();
        ASSERT_EQ(1, key1.getKeyId());
        ASSERT_EQ("dummy", key1.getPurpose());
        ASSERT_EQ(origKey1.getKey(), key1.getKey());
        ASSERT_EQ(Timestamp(105, 0), key1.getExpiresAt().asTimestamp());

        const auto& key2 = allKeys.back();
        ASSERT_EQ(currentTime.asTimestamp().asLL(), key2.getKeyId());
        ASSERT_EQ("dummy", key2.getPurpose());
        ASSERT_EQ(Timestamp(110, 0), key2.getExpiresAt().asTimestamp());

        ASSERT_NE(key1.getKey(), key2.getKey());
    }
}
Пример #12
0
MetaAlertPtrNN makeNewMetaAlert(const char *name, const unsigned int id)
{
  return MetaAlertPtrNN( new MetaAlert( MetaAlert::Name(name),
                                        0.1, 0.2,
                                        makeNewReferenceURL().shared_ptr(),
                                        Timestamp(),
                                        id ) );
}
Пример #13
0
TEST_F(SyncTailTest, MultiSyncApplyGroupsInsertOperationByNamespaceBeforeApplying) {
    int seconds = 0;
    auto makeOp = [&seconds](const NamespaceString& nss) {
        return makeInsertDocumentOplogEntry(
            {Timestamp(Seconds(seconds), 0), 1LL}, nss, BSON("_id" << seconds++));
    };
    NamespaceString nss1("test." + _agent.getSuiteName() + "_" + _agent.getTestName() + "_1");
    NamespaceString nss2("test." + _agent.getSuiteName() + "_" + _agent.getTestName() + "_2");
    auto createOp1 = makeCreateCollectionOplogEntry({Timestamp(Seconds(seconds++), 0), 1LL}, nss1);
    auto createOp2 = makeCreateCollectionOplogEntry({Timestamp(Seconds(seconds++), 0), 1LL}, nss2);
    auto insertOp1a = makeOp(nss1);
    auto insertOp1b = makeOp(nss1);
    auto insertOp2a = makeOp(nss2);
    auto insertOp2b = makeOp(nss2);
    MultiApplier::Operations operationsApplied;
    auto syncApply = [&operationsApplied](OperationContext*, const BSONObj& op, bool) {
        operationsApplied.push_back(OplogEntry(op));
        return Status::OK();
    };

    MultiApplier::OperationPtrs ops = {
        &createOp1, &createOp2, &insertOp1a, &insertOp2a, &insertOp1b, &insertOp2b};
    ASSERT_OK(multiSyncApply_noAbort(_txn.get(), &ops, syncApply));

    ASSERT_EQUALS(4U, operationsApplied.size());
    ASSERT_EQUALS(createOp1, operationsApplied[0]);
    ASSERT_EQUALS(createOp2, operationsApplied[1]);

    // Check grouped insert operations in namespace "nss1".
    ASSERT_EQUALS(insertOp1a.getOpTime(), operationsApplied[2].getOpTime());
    ASSERT_EQUALS(insertOp1a.ns, operationsApplied[2].ns);
    ASSERT_EQUALS(BSONType::Array, operationsApplied[2].o.type());
    auto group1 = operationsApplied[2].o.Array();
    ASSERT_EQUALS(2U, group1.size());
    ASSERT_EQUALS(insertOp1a.o.Obj(), group1[0].Obj());
    ASSERT_EQUALS(insertOp1b.o.Obj(), group1[1].Obj());

    // Check grouped insert operations in namespace "nss2".
    ASSERT_EQUALS(insertOp2a.getOpTime(), operationsApplied[3].getOpTime());
    ASSERT_EQUALS(insertOp2a.ns, operationsApplied[3].ns);
    ASSERT_EQUALS(BSONType::Array, operationsApplied[3].o.type());
    auto group2 = operationsApplied[3].o.Array();
    ASSERT_EQUALS(2U, group2.size());
    ASSERT_EQUALS(insertOp2a.o.Obj(), group2[0].Obj());
    ASSERT_EQUALS(insertOp2b.o.Obj(), group2[1].Obj());
}
Пример #14
0
TEST_F(SyncTailTest, MultiApplyReturnsBadValueOnNullApplyOperation) {
    auto writerPool = SyncTail::makeWriterPool();
    MultiApplier::ApplyOperationFn nullApplyOperationFn;
    auto op = makeCreateCollectionOplogEntry({Timestamp(Seconds(1), 0), 1LL});
    auto status = multiApply(_txn.get(), writerPool.get(), {op}, nullApplyOperationFn).getStatus();
    ASSERT_EQUALS(ErrorCodes::BadValue, status);
    ASSERT_STRING_CONTAINS(status.reason(), "invalid apply operation function");
}
Пример #15
0
Timestamp getNextGlobalTimestamp() {
    stdx::lock_guard<stdx::mutex> lk(globalTimestampMutex);

    const unsigned now = (unsigned)time(0);
    const unsigned globalSecs = globalTimestamp.getSecs();
    if (globalSecs == now) {
        globalTimestamp = Timestamp(globalSecs, globalTimestamp.getInc() + 1);
    } else if (now < globalSecs) {
        globalTimestamp = Timestamp(globalSecs, globalTimestamp.getInc() + 1);
        // separate function to keep out of the hot code path
        fassert(17449, !skewed(globalTimestamp));
    } else {
        globalTimestamp = Timestamp(now, 1);
    }

    return globalTimestamp;
}
Пример #16
0
void WiredTigerSnapshotManager::beginTransactionOnOplog(WiredTigerOplogManager* oplogManager,
                                                        WT_SESSION* session) const {
    invariantWTOK(session->begin_transaction(session, nullptr));
    auto rollbacker =
        MakeGuard([&] { invariant(session->rollback_transaction(session, nullptr) == 0); });

    auto allCommittedTimestamp = oplogManager->getOplogReadTimestamp();
    invariant(Timestamp(static_cast<unsigned long long>(allCommittedTimestamp)).asULL() ==
              allCommittedTimestamp);
    auto status = setTransactionReadTimestamp(
        Timestamp(static_cast<unsigned long long>(allCommittedTimestamp)),
        session,
        true /* roundToOldest */);

    fassert(50771, status);
    rollbacker.Dismiss();
}
Пример #17
0
Timestamp Timestamp::now()
{
  struct timeval tv;
  gettimeofday(&tv, NULL);
  time_t seconds = tv.tv_sec;
  
  return Timestamp(seconds * kAccuracyPerSecond + tv.tv_usec);
}
TEST_F(KeysManagerShardedTest, GetKeyForValidationTimesOutIfRefresherIsNotRunning) {
    operationContext()->setDeadlineAfterNowBy(Microseconds(250 * 1000),
                                              ErrorCodes::ExceededTimeLimit);

    ASSERT_THROWS(
        keyManager()->getKeyForValidation(operationContext(), 1, LogicalTime(Timestamp(100, 0))),
        DBException);
}
Пример #19
0
// Test timestamp
TEST(FTDCCompressor, TestTimeStamp) {
    TestTie c;

    BSONObjBuilder builder1;
    BSONObj o = builder1.append("ts", Timestamp(0x55667788LL, 0x11223344LL)).obj();
    auto st = c.addSample(o);
    ASSERT_HAS_SPACE(st);
}
TEST_F(KeysManagerShardedTest, GetKeyWithSingleKey) {
    keyManager()->startMonitoring(getServiceContext());

    KeysCollectionDocument origKey1(
        1, "dummy", TimeProofService::generateRandomKey(), LogicalTime(Timestamp(105, 0)));
    ASSERT_OK(insertToConfigCollection(
        operationContext(), KeysCollectionDocument::ConfigNS, origKey1.toBSON()));

    auto keyStatus =
        keyManager()->getKeyForValidation(operationContext(), 1, LogicalTime(Timestamp(100, 0)));
    ASSERT_OK(keyStatus.getStatus());

    auto key = keyStatus.getValue();
    ASSERT_EQ(1, key.getKeyId());
    ASSERT_EQ(origKey1.getKey(), key.getKey());
    ASSERT_EQ(Timestamp(105, 0), key.getExpiresAt().asTimestamp());
}
Пример #21
0
void CMakeGifDoc::saveGif(const String &fileName) {
  if(m_gif == NULL) {
    return;
  }
  ::saveGif(ByteOutputFile(fileName), m_gif);
  setDocName(fileName);
  setSaveTime(Timestamp());
}
TEST_F(KeysManagerShardedTest, GetKeyForValidationTimesOutIfRefresherIsNotRunning) {
    operationContext()->setDeadlineAfterNowBy(Microseconds(250 * 1000));

    ASSERT_THROWS(keyManager()
                      ->getKeyForValidation(operationContext(), 1, LogicalTime(Timestamp(100, 0)))
                      .status_with_transitional_ignore(),
                  DBException);
}
TEST_F(CacheReaderTest, RefreshCanIncrementallyGetNewKeys) {
    auto catalogClient = Grid::get(operationContext())->catalogClient(operationContext());
    KeysCollectionCacheReader reader("test", catalogClient);

    KeysCollectionDocument origKey0(
        0, "test", TimeProofService::generateRandomKey(), LogicalTime(Timestamp(100, 0)));
    ASSERT_OK(insertToConfigCollection(
        operationContext(), NamespaceString(KeysCollectionDocument::ConfigNS), origKey0.toBSON()));

    {
        auto refreshStatus = reader.refresh(operationContext());
        ASSERT_OK(refreshStatus.getStatus());


        auto key = refreshStatus.getValue();
        ASSERT_EQ(0, key.getKeyId());
        ASSERT_EQ(origKey0.getKey(), key.getKey());
        ASSERT_EQ("test", key.getPurpose());
        ASSERT_EQ(Timestamp(100, 0), key.getExpiresAt().asTimestamp());

        auto keyStatus = reader.getKey(LogicalTime(Timestamp(112, 1)));
        ASSERT_EQ(ErrorCodes::KeyNotFound, keyStatus.getStatus());
    }

    KeysCollectionDocument origKey1(
        1, "test", TimeProofService::generateRandomKey(), LogicalTime(Timestamp(105, 0)));
    ASSERT_OK(insertToConfigCollection(
        operationContext(), NamespaceString(KeysCollectionDocument::ConfigNS), origKey1.toBSON()));

    KeysCollectionDocument origKey2(
        2, "test", TimeProofService::generateRandomKey(), LogicalTime(Timestamp(110, 0)));
    ASSERT_OK(insertToConfigCollection(
        operationContext(), NamespaceString(KeysCollectionDocument::ConfigNS), origKey2.toBSON()));

    {
        auto refreshStatus = reader.refresh(operationContext());
        ASSERT_OK(refreshStatus.getStatus());

        auto key = refreshStatus.getValue();
        ASSERT_EQ(2, key.getKeyId());
        ASSERT_EQ(origKey2.getKey(), key.getKey());
        ASSERT_EQ("test", key.getPurpose());
        ASSERT_EQ(Timestamp(110, 0), key.getExpiresAt().asTimestamp());
    }

    {
        auto keyStatus = reader.getKey(LogicalTime(Timestamp(108, 1)));

        auto key = keyStatus.getValue();
        ASSERT_EQ(2, key.getKeyId());
        ASSERT_EQ(origKey2.getKey(), key.getKey());
        ASSERT_EQ("test", key.getPurpose());
        ASSERT_EQ(Timestamp(110, 0), key.getExpiresAt().asTimestamp());
    }
}
Пример #24
0
Timestamp MixerImpl::getElapsedTime(SoundHandle handle) {
	Common::StackLock lock(_mutex);

	const int index = handle._val % NUM_CHANNELS;
	if (!_channels[index] || _channels[index]->getHandle()._val != handle._val)
		return Timestamp(0, _sampleRate);

	return _channels[index]->getElapsedTime();
}
Пример #25
0
Timestamp WiredTigerRecoveryUnit::_beginTransactionAtAllCommittedTimestamp(WT_SESSION* session) {
    WiredTigerBeginTxnBlock txnOpen(session, _ignorePrepared);
    Timestamp txnTimestamp = Timestamp(_oplogManager->fetchAllCommittedValue(session->connection));
    auto status =
        txnOpen.setTimestamp(txnTimestamp, WiredTigerBeginTxnBlock::RoundToOldest::kRound);
    fassert(50948, status);

    // Since this is not in a critical section, we might have rounded to oldest between
    // calling getAllCommitted and setTimestamp.  We need to get the actual read timestamp we
    // used.
    char buf[(2 * 8 /*bytes in hex*/) + 1 /*nul terminator*/];
    auto wtstatus = session->query_timestamp(session, buf, "get=read");
    invariantWTOK(wtstatus);
    uint64_t read_timestamp;
    fassert(50949, parseNumberFromStringWithBase(buf, 16, &read_timestamp));
    txnOpen.done();
    return Timestamp(read_timestamp);
}
Пример #26
0
void WiredTigerRecoveryUnit::_txnClose(bool commit) {
    invariant(_isActive(), toString(_state));
    WT_SESSION* s = _session->getSession();
    if (_timer) {
        const int transactionTime = _timer->millis();
        // `serverGlobalParams.slowMs` can be set to values <= 0. In those cases, give logging a
        // break.
        if (transactionTime >= std::max(1, serverGlobalParams.slowMS)) {
            LOG(kSlowTransactionSeverity) << "Slow WT transaction. Lifetime of SnapshotId "
                                          << _mySnapshotId << " was " << transactionTime << "ms";
        }
    }

    int wtRet;
    if (commit) {
        if (!_commitTimestamp.isNull()) {
            const std::string conf = "commit_timestamp=" + integerToHex(_commitTimestamp.asULL());
            invariantWTOK(s->timestamp_transaction(s, conf.c_str()));
            _isTimestamped = true;
        }

        wtRet = s->commit_transaction(s, nullptr);
        LOG(3) << "WT commit_transaction for snapshot id " << _mySnapshotId;
    } else {
        wtRet = s->rollback_transaction(s, nullptr);
        invariant(!wtRet);
        LOG(3) << "WT rollback_transaction for snapshot id " << _mySnapshotId;
    }

    if (_isTimestamped) {
        if (!_orderedCommit) {
            // We only need to update oplog visibility where commits can be out-of-order with
            // respect to their assigned optime and such commits might otherwise be visible.
            // This should happen only on primary nodes.
            _oplogManager->triggerJournalFlush();
        }
        _isTimestamped = false;
    }
    invariantWTOK(wtRet);

    invariant(!_lastTimestampSet || _commitTimestamp.isNull(),
              str::stream() << "Cannot have both a _lastTimestampSet and a "
                               "_commitTimestamp. _lastTimestampSet: "
                            << _lastTimestampSet->toString()
                            << ". _commitTimestamp: "
                            << _commitTimestamp.toString());

    // We reset the _lastTimestampSet between transactions. Since it is legal for one
    // transaction on a RecoveryUnit to call setTimestamp() and another to call
    // setCommitTimestamp().
    _lastTimestampSet = boost::none;

    _prepareTimestamp = Timestamp();
    _mySnapshotId = nextSnapshotId.fetchAndAdd(1);
    _isOplogReader = false;
    _orderedCommit = true;  // Default value is true; we assume all writes are ordered.
}
Пример #27
0
	RawStream(int rate, bool stereo, DisposeAfterUse::Flag disposeStream, Common::SeekableReadStream *stream)
		: _rate(rate), _isStereo(stereo), _playtime(0, rate), _stream(stream, disposeStream), _endOfData(false), _buffer(0) {
		// Setup our buffer for readBuffer
		_buffer = new byte[kSampleBufferLength * (is16Bit ? 2 : 1)];
		assert(_buffer);

		// Calculate the total playtime of the stream
		_playtime = Timestamp(0, _stream->size() / (_isStereo ? 2 : 1) / (is16Bit ? 2 : 1), rate);
	}
TEST_F(KeysManagerShardedTest, GetKeyForSigningShouldReturnRightKey) {
    keyManager()->startMonitoring(getServiceContext());

    KeysCollectionDocument origKey1(
        1, "dummy", TimeProofService::generateRandomKey(), LogicalTime(Timestamp(105, 0)));
    ASSERT_OK(insertToConfigCollection(
        operationContext(), NamespaceString(KeysCollectionDocument::ConfigNS), origKey1.toBSON()));

    keyManager()->refreshNow(operationContext());

    auto keyStatus = keyManager()->getKeyForSigning(nullptr, LogicalTime(Timestamp(100, 0)));
    ASSERT_OK(keyStatus.getStatus());

    auto key = keyStatus.getValue();
    ASSERT_EQ(1, key.getKeyId());
    ASSERT_EQ(origKey1.getKey(), key.getKey());
    ASSERT_EQ(Timestamp(105, 0), key.getExpiresAt().asTimestamp());
}
Пример #29
0
FvUInt64 MySqlThreadResPool::StopThreadTaskTiming( MySqlThreadData& threadData )
{
	FvUInt64	opDuration = Timestamp() - threadData.m_uiStartTimestamp;
	m_uiOPDurationTotal += opDuration;
	++m_uiOPCount;
	threadData.m_uiStartTimestamp = 0;

	return opDuration;
}
TEST_F(KeysManagerShardedTest, ShouldNotReturnKeysInFeatureCompatibilityVersion34) {
    serverGlobalParams.featureCompatibility.version.store(
        ServerGlobalParams::FeatureCompatibility::Version::k34);

    keyManager()->startMonitoring(getServiceContext());
    keyManager()->enableKeyGenerator(operationContext(), true);

    KeysCollectionDocument origKey(
        1, "dummy", TimeProofService::generateRandomKey(), LogicalTime(Timestamp(105, 0)));
    ASSERT_OK(insertToConfigCollection(
        operationContext(), NamespaceString(KeysCollectionDocument::ConfigNS), origKey.toBSON()));

    keyManager()->refreshNow(operationContext());

    auto keyStatus =
        keyManager()->getKeyForValidation(operationContext(), 1, LogicalTime(Timestamp(100, 0)));
    ASSERT_EQ(ErrorCodes::KeyNotFound, keyStatus.getStatus());
}