void CUnitTest::Test(const char* description, bool test, const char* failureMessage, int32 testType /* = eTT_Stage */) { TRACE(TRACE_ENABLE); const char* none = "None"; uint32 logFlags = m_log.GetFlags(); m_log.SetFlags(logFlags & ~(engine::system::CLog::eBAI_NAME | engine::system::CLog::eBAI_TIMESTAMP)); if (test != true) { LOG_ALWAYS(m_log, COLOUR_PROGRESS "\n\t\t[%d:%d]" COLOUR_INFO "\t[%s]" COLOUR_PROGRESS ":" COLOUR_ERROR "[%s]", GetStage(), GetSubstage(), (description != NULL) ? description : none, (failureMessage != NULL) ? failureMessage : none); ++m_errors; } else { LOG_ALWAYS(m_log, COLOUR_SUCCESS "."); } switch (testType) { case eTT_Stage: ++m_stage; break; case eTT_SubStage: ++m_subStage; break; } ++m_totalTests; m_log.SetFlags(logFlags); }
nsFtpControlConnection::nsFtpControlConnection(const nsCSubstring& host, PRUint32 port) : mServerType(0), mSessionId(gFtpHandler->GetSessionId()), mHost(host) , mPort(port) { LOG_ALWAYS(("FTP:CC created @%p", this)); }
PsdStatus PsdFile::readHeader() { // read PSD file header const PsdFileHeader *header = (const PsdFileHeader *) mMapped.get().mAddress; if (!CHECK_FOUR_CHAR(header->mSignature, '8', 'B', 'P', 'S')) { LOG_ALWAYS("PSD file signature not found"); return PsdStatusFileMalformed; } // All PSD integers are stored in network byte order mVersion = ntohs(header->mVersion); mChannels = ntohs(header->mChannels); mHeight = ntohl(header->mHeight); mWidth = ntohl(header->mWidth); mDepth = ntohs(header->mDepth); mColorMode = (ColorMode) ntohs(header->mColorMode); mColorDataBlock.assign(mMapped.get().mAddress + sizeof(PsdFileHeader)); LOG_DEBUG("version: %u\nchannels: %u\n%d X %d %dbpp\nmode: %d", mVersion, mChannels, mWidth, mHeight, mDepth, mColorMode); if (mVersion != 1) return PsdStatusUnsupportedVersion; return PsdStatusOK; }
int subscribe_clearfi(const std::string &appDataPath, u64 userId, u64 &clearfiDatasetId) { LOG_INFO("start"); int rv = 0; int i; s32 numDatasets; LOG_INFO(">>>> CCDIListOwnedDatasets"); ccd::ListOwnedDatasetsInput ownedDatasetsInput; ccd::ListOwnedDatasetsOutput ownedDatasetsOutput; ownedDatasetsInput.set_user_id(userId); ownedDatasetsInput.set_only_use_cache(false); rv = CCDIListOwnedDatasets(ownedDatasetsInput, ownedDatasetsOutput); if (rv != CCD_OK) { LOG_ERROR("CCDIListOwnedDatasets fail: %d", rv); return -1; } else { LOG_INFO("CCDIListOwnedDatasets OK"); } LOG_INFO(" Num datasets %d", ownedDatasetsOutput.dataset_details_size()); numDatasets = ownedDatasetsOutput.dataset_details_size(); LOG_INFO(">>>> CCDIAddSyncSubscription"); for (i = 0; i < numDatasets; i++) { ccd::AddSyncSubscriptionInput addSyncSubInput; u64 datasetId = ownedDatasetsOutput.dataset_details(i).datasetid(); std::string datasetName = ownedDatasetsOutput.dataset_details(i).datasetname(); if (ownedDatasetsOutput.dataset_details(i).datasettype() == vplex::vsDirectory::CLEAR_FI) { char temp[17]; snprintf(temp, ARRAY_SIZE_IN_BYTES(temp), "%016"PRIx64, userId); std::string s_metadataSubscriptionPath = Util_CleanupPath(appDataPath + "/" + temp + "/clear.fi"); LOG_ALWAYS("Subscribing clearfi dataset: %s", s_metadataSubscriptionPath.c_str()); addSyncSubInput.set_user_id(userId); addSyncSubInput.set_device_root(s_metadataSubscriptionPath); addSyncSubInput.set_dataset_id(datasetId); addSyncSubInput.set_subscription_type(ccd::SUBSCRIPTION_TYPE_NORMAL); rv = CCDIAddSyncSubscription(addSyncSubInput); if (rv == DATASET_ALREADY_SUBSCRIBED) { LOG_ERROR("Old clearfi subscription found, please use command StopCloudPC/StopClient to unsubscribe"); return -1; } else if (rv != CCD_OK) { LOG_ERROR("CCDIAddSyncSubscription failed for dataset_id "FMTu64": %d", datasetId, rv); return -1; } else { LOG_INFO("CCDIAddSyncSubscription for clear.fi OK"); clearfiDatasetId = datasetId; } } } return 0; }
PsdStatus PsdLayer::readAdditionalInfo() { assert(mAdditionalInfoBlock.mAddress != NULL); if (mAdditionalInfoBlock.mLength == 0) return PsdStatusOK; const uint8_t *ptr = mAdditionalInfoBlock.mAddress, *end = mAdditionalInfoBlock.getEndAddress() - 4; const uint8_t *key; uint32_t length; while (ptr < end) { if (!CHECK_FOUR_CHAR(ptr, '8', 'B', 'I', 'M') && !CHECK_FOUR_CHAR(ptr, '8', 'B', '6', '4')) { LOG_ALWAYS("Layer addtional info signature is not found. (%u)", uint32_t(ptr - mFile->mMapped.get().mAddress)); return PsdStatusFileMalformed; } key = ptr + 4; length = PsdUtils::fetch32(ptr + 8); ptr += 12; if (CHECK_FOUR_CHAR(key, 'l', 's', 'c', 't')) { if (length >= 4) { switch (PsdUtils::fetch32(ptr)) { case 3: mIsEndOfGroup = true; case 1: case 2: mType = LayerTypeGroup; break; default: break; } } } // *Almost* all group layers has the value 'lset' for 'lnsr'. // However, there are some groups does not has this attribute and // some layers (not groups) has 'lset'. // It seems to be better to not handle 'lset' at all and use the above method to parse groups. // else if (mType != LayerTypeGroup && CHECK_FOUR_CHAR(key, 'l', 'n', 's', 'r')) { // assert(length == 4); // // if (CHECK_FOUR_CHAR(ptr, 'l', 's', 'e', 't')) // mType = LayerTypeGroup; // else if (CHECK_FOUR_CHAR(ptr, 'l', 'a', 'y', 'r')) // mType = LayerTypeNormal; // else // mType = LayerTypeUndefined; // } //LOG_DEBUG(" AddtionalInfo: %.4s %u\n", key, length); ptr += length; } return PsdStatusOK; }
PsdStatus PsdFile::openMemoryMap() { PsdStatus status = mMapped.open(mFilePath.c_str()); if (status != PsdStatusOK) return status; if (mMapped.get().mLength < MIN_PSD_SIZE) { LOG_ALWAYS("The input file is too small to be a PSD file."); mMapped.close(); return PsdStatusFileMalformed; } return PsdStatusOK; }
void TimerCallback(engine::time::CTimer* pTimer) { double elapsed = pTimer->GetElapsedTime().GetSeconds(); double frame = pTimer->GetFrameTime().GetSeconds(); const engine::time::CFPSCalculator* pEngineFPS = engine::base::CEngine::Get().GetFPS(); const engine::time::CFPSCalculator* pGLFWFPS = engine::base::CEngine::Get().GetGLFW()->GetFPS(); LOG_ALWAYS(GAME_LOGGER, "timer callback (elapsed %.2f, interval %.2f), engine fps (%.2f fps), display fps (%.2f fps)", elapsed, frame, pEngineFPS->GetAverageFPS(), pGLFWFPS->GetAverageFPS()); if (elapsed >= 10.0) { g_run = false; } }
CUnitTest::~CUnitTest(void) { TRACE(TRACE_ENABLE); CTimeValue elapsed = m_timeEnded-m_timeStarted; int32 days, hours, minutes; float seconds; elapsed.GetTime(days, hours, minutes, seconds); const char* errorColour = (m_errorTotal != 0) ? COLOUR_ERROR : COLOUR_DEFAULT; LOG_ALWAYS(m_log, COLOUR_TEST_INFO "[%s] " COLOUR_DEFAULT "%d tests completed in %s%d days, %02u:%02u:%06.3fs; " COLOUR_DEFAULT "%s%d errors\n\n" COLOUR_RESET, m_name, m_totalTests, (elapsed.GetTicks() < 0) ? "-" : "", days, hours, minutes, seconds, errorColour, m_errorTotal); }
int mem_rns_release() { #ifdef RNS_SYSFS SYSFS_REMOVE(&mem_kobj); #endif if(MEM_TOTAL != 0) { /* Print this regardless of the debugging level!! */ LOG_ALWAYS(KERN_ALERT, "ALER", "Memory use mismatch! Left: %d", MEM_TOTAL); } return SUCCESS; }
CUnitTest::eTestStatus CUnitTest::Update(void) { TRACE(TRACE_ENABLE); if (m_testStatus == eTS_RUNNING) { if (m_testIterator != m_tests.end()) { STest& test = *m_testIterator; if (GetStage() == 1) { LOG_ALWAYS(m_log, COLOUR_TEST_INFO "[%s:%s] " COLOUR_DEFAULT "started", m_name, test.m_name.c_str()); } uint32 status = test.m_function(this); ResetSubstage(); if (status & eSS_COMPLETE) { m_log.SetFlags(m_log.GetFlags() & ~(engine::system::CLog::eBAI_NAME | engine::system::CLog::eBAI_TIMESTAMP)); LOG_ALWAYS(m_log, COLOUR_DEFAULT "complete.\n"); m_log.SetFlags(m_log.GetFlags() | engine::system::CLog::eBAI_NAME | engine::system::CLog::eBAI_TIMESTAMP); m_errorTotal += m_errors; ResetStage(); ++m_testIterator; } } else { m_testStatus = eTS_FINISHED; } } return m_testStatus; }
bool isCloudpc(u64 userId, u64 deviceId) { LOG_INFO("start"); bool isPsn = false; int rv = 0; ccd::ListLinkedDevicesOutput listSnOut; ccd::ListLinkedDevicesInput request; request.set_user_id(userId); request.set_storage_nodes_only(true); // Try contacting infra for the most updated information first rv = CCDIListLinkedDevices(request, listSnOut); if (rv != 0) { LOG_ERROR("CCDIListLinkedDevice for user("FMTu64") failed %d", userId, rv); // Fall back to cache if cannot reach server LOG_ALWAYS("Retry with only_use_cache option"); request.set_only_use_cache(true); rv = CCDIListLinkedDevices(request, listSnOut); if (rv != 0) { LOG_ERROR("CCDIListLinkedDevice for user("FMTu64") failed %d", userId, rv); } } if (rv == 0) { for (int i = 0; i < listSnOut.devices_size(); i++) { LOG_ALWAYS("user("FMTu64") device("FMTu64") is cloudpc", userId, deviceId); if (listSnOut.devices(i).device_id() == deviceId) { isPsn = true; break; } } } return isPsn; }
static int subscribeDatasetHelper(u64 userId, u64 datasetId, bool useType, ccd::SyncSubscriptionType_t subType, const std::string& appDataPath, const std::string& dsetName, bool useAppDataPathOnly, u64 maxSizeBytes, bool useMaxBytes, u64 maxFiles, bool useMaxFiles) { int rv = 0; std::string subscriptionPath; if(useAppDataPathOnly) { subscriptionPath = Util_CleanupPath(appDataPath); }else{ char temp[17]; snprintf(temp, ARRAY_SIZE_IN_BYTES(temp), "%016"PRIx64, userId); subscriptionPath = Util_CleanupPath(appDataPath + "/" + temp + "/" + dsetName); } LOG_ALWAYS("Subscribing %s dataset: %s", dsetName.c_str(), subscriptionPath.c_str()); ccd::AddSyncSubscriptionInput addSyncSubInput; addSyncSubInput.set_user_id(userId); addSyncSubInput.set_dataset_id(datasetId); addSyncSubInput.set_device_root(subscriptionPath); if(useType) { addSyncSubInput.set_subscription_type(subType); } if(useMaxBytes) { addSyncSubInput.set_max_size(maxSizeBytes); } if(useMaxFiles) { addSyncSubInput.set_max_files(maxFiles); } rv = CCDIAddSyncSubscription(addSyncSubInput); if(rv == DATASET_ALREADY_SUBSCRIBED) { LOG_ERROR("Old %s subscription found, please use command StopCloudPC/StopClient " "to unsubscribe. Subscription variables may be different.", dsetName.c_str()); }else if (rv != CCD_OK) { LOG_ERROR("CCDIAddSyncSubscription failed for %s. userId:"FMTx64" dataset_id "FMTx64": %d", dsetName.c_str(), userId, datasetId, rv); } else { LOG_INFO("CCDIAddSyncSubscription for %s is OK.", dsetName.c_str()); } return rv; }
CUnitTest::CUnitTest(const char* name) : m_log(engine::system::GetMasterLog(), "UnitTest", engine::system::CLog::eB_ACTIVE | engine::system::CLog::eB_NO_STDERR | engine::system::CLog::eBT_CONSOLE | engine::system::CLog::eBT_DEBUGGER | engine::system::CLog::eBT_FILE) , m_testStatus(eTS_UNINITIALISED) , m_stageStatus(eSS_PASS) , m_name(name) , m_errors(0) , m_errorTotal(0) , m_totalTests(0) , m_stage(0) , m_subStage(0) { TRACE(TRACE_ENABLE); LOG_ALWAYS(m_log, COLOUR_DEFAULT); m_log.SetFlags(m_log.GetFlags() | engine::system::CLog::eBAI_NAME | engine::system::CLog::eBAI_TIMESTAMP); }
int checkRunningCcd() { LOG_ALWAYS("2014/05/29 PM6.15."); LOG_ALWAYS("Check ccd instance not present."); setDebugLevel(LOG_LEVEL_CRITICAL); // Avoid confusing log where it gives error if ccd is not detected yet LOG_ALWAYS("after set debug level."); ccd::GetSystemStateInput request; LOG_ALWAYS("after get system state input."); request.set_get_players(true); ccd::GetSystemStateOutput response; LOG_ALWAYS("after get system state ouput."); int rv; LOG_ALWAYS("before CCDI get system state"); rv = CCDIGetSystemState(request, response); LOG_ALWAYS("after CCDI get system state"); resetDebugLevel(); LOG_ALWAYS("after reset debug level"); if (rv == CCD_OK) { LOG_ALWAYS("CCD is already present!\n"); } return (rv == 0) ? -1 : 0; // Only a success if CCDIGetSystemState failed. }
nsresult nsFtpControlConnection::Disconnect(nsresult status) { if (!mSocket) return NS_OK; // already disconnected LOG_ALWAYS(("FTP:(%p) CC disconnecting (%x)", this, status)); if (NS_FAILED(status)) { // break cyclic reference! mSocket->Close(status); mSocket = 0; mSocketInput->AsyncWait(nullptr, 0, 0, nullptr); // clear any observer mSocketInput = nullptr; mSocketOutput = nullptr; } return NS_OK; }
/** load all dlls in dir and check for plugin factories */ void ComponentPluginManager::LoadPluginsInDir(const std::string& path) { std::string cleanedPath(path); if (path[path.size() - 1] == GetNativePathSeparator()) { // remove the trailing path separator as this causes issues... cleanedPath = path.substr(0, path.size() - 1); } if(!GetSystemInterface()->FileExists(cleanedPath)) { LOG_ALWAYS("Plugin folder not found! Path: " + cleanedPath); return; } std::string libExtension = GetLibExtension(); LOG_DEBUG("Looking for plugins with extension: " + libExtension); // get libs from directory SystemInterface::DirectoryContents files = GetSystemInterface()->GetDirectoryContents(cleanedPath); // for each library in dir SystemInterface::DirectoryContents::const_iterator i; for(i = files.begin(); i != files.end(); ++i) { std::string fileName = *i; if(fileName.size() <= libExtension.size()) continue; std::string ending = fileName.substr(fileName.size() - libExtension.size(), fileName.size()); if(ending.compare(libExtension) != 0) { continue; } std::ostringstream libpath; libpath << cleanedPath << GetNativePathSeparator() << fileName; AddPlugin(libpath.str()); LOG_DEBUG("Loaded plugin: " + libpath.str()); } }
PsdStatus PsdLayer::readMaskData() { if (mMaskInfoBlock.mLength == 0) return PsdStatusOK; if (mMaskInfoBlock.mLength == 20 || mMaskInfoBlock.mLength == 36) { const PsdMaskInfo *info = (const PsdMaskInfo *) mMaskInfoBlock.mAddress; mMask.reset(new PsdMaskInfo); PsdUtils::fetchRect(&mMask->mRect, &info->mRect); mMask->mDefaultColor = info->mDefaultColor; mMask->mFlags = info->mFlags; if (mMaskInfoBlock.mLength == 36) { mMask->mRealFlags = info->mRealFlags; mMask->mRealDefaultColor = info->mRealDefaultColor; PsdUtils::fetchRect(&mMask->mRealRect, &info->mRealRect); } return PsdStatusOK; } LOG_ALWAYS("Layer mask info size is wrong (%u)", mMaskInfoBlock.mLength); return PsdStatusFileMalformed; }
PsdStatus PsdFile::readAdditionalInfo() { assert(mAdditionalInfoBlock.mAddress != NULL); if (mAdditionalInfoBlock.mLength == 0) return PsdStatusOK; const uint8_t *ptr = mAdditionalInfoBlock.mAddress, *end = mAdditionalInfoBlock.getEndAddress() - 4; const uint8_t *key; uint32_t length; PsdStatus status; while (ptr < end) { if (!CHECK_FOUR_CHAR(ptr, '8', 'B', 'I', 'M') && !CHECK_FOUR_CHAR(ptr, '8', 'B', '6', '4')) { LOG_ALWAYS("Global addtional info signature is not found. (%u)", uint32_t(ptr - mMapped.get().mAddress)); return PsdStatusOK; } key = ptr + 4; length = PsdUtils::fetch32(ptr + 8); ptr += 12; if (CHECK_FOUR_CHAR(key, 'L', 'r', '1', '6')) { LOG_DEBUG("Layers are stored in global additional info."); readLayerCount(ptr); if (mLayersCount > 0) { const uint8_t *data = ptr + 2; status = readLayers(data, ptr + length); if (status != PsdStatusOK) return status; } } // XXX test shows it should be pad by 4, psdparse is not able to parse this though ptr += PAD4(length); } return PsdStatusOK; }
nsFtpControlConnection::~nsFtpControlConnection() { LOG_ALWAYS(("FTP:CC destroyed @%p", this)); }
Handle<Value> LogAlways(const Arguments& args) { LOG_ALWAYS(ToStdString(args[0])); return Undefined(); }
int main(int argc, char* argv[]) { /* enum eSyntaxID { eSID_LOG = engine::system::CConfiguration::eSID_FIRST_USERID, }; */ engine::system::CConfiguration config; config.Parse(argc, argv); config.Parse("system.cfg"); engine::base::CEngine& myEngine = engine::base::CEngine::Get(); myEngine.Initialise(config); LOG_ALWAYS(GAME_LOGGER, "Start..."); engine::glfw::SConfiguration glfwConfiguration; uint32 display_width = config.GetValue("display_width", DEFAULT_WINDOW_WIDTH); uint32 display_height = config.GetValue("display_height", DEFAULT_WINDOW_HEIGHT); bool display_fullScreen = config.GetValue("display_fullscreen", DEFAULT_FULL_SCREEN); glfwConfiguration.m_desiredFrameRate = config.GetValue("display_framerate", DEFAULT_FRAMERATE); glfwConfiguration.m_realtime = config.GetValue("application_realtime", DEFAULT_APPLICATION_REALTIME); glfwConfiguration.m_vsync = config.GetValue("display_vsync", DEFAULT_DISPLAY_VSYNC); engine::glfw::CGLFW* pGLFW = myEngine.GetGLFW(); pGLFW->Initialise(glfwConfiguration); engine::glfw::CDisplay::TDisplayID id = pGLFW->OpenDisplay(display_width, display_height, DEFAULT_WINDOW_TITLE, display_fullScreen); pGLFW->GetDisplayInfo(id); CGame* pGame = new CGame(); engine::base::CThread t("dummy"); t.Initialise(); bool done = false; while (g_run) { engine::time::CTimeValue tick = myEngine.Update(); engine::time::CTimeValue elapsed = myEngine.GetTime()->GetElapsedTime(); if (!done && (elapsed.GetSeconds() >= 5.0)) { t.Terminate(true); done = true; } g_run &= (tick != engine::time::INVALID_TIME); } delete pGame; /* engine::system::CConsole::TIVariablePtr plog_level = myEngine.GetConsole()->FindVariable("log_level"); if (plog_level != NULL) { LOG_ALWAYS(GAME_LOGGER, "log_level = %" PRId64, plog_level->GetInteger()); } */ LOG_ALWAYS(GAME_LOGGER, "All done."); myEngine.Uninitialise(); // Not strictly needed as will be called when engine destructed return 0; }
void Joined(const dtEntity::Message& m) { const dtEntityNet::JoinMessage& msg = static_cast<const dtEntityNet::JoinMessage&>(m); LOG_ALWAYS("JoinedMessage EntityType " << msg.GetEntityType() << " uid " << msg.GetUniqueId()); }
PsdStatus PsdLayer::readMeta(const uint8_t *data, const uint8_t *end) { assert(data != NULL); LOG_DEBUG("[Layer] %08X\n", uint32_t(data - mFile->mMapped.get().mAddress)); const uint8_t *dataSanity = data + sizeof(PsdLayerRecordMeta1) + sizeof(PsdLayerRecordMeta2) + 8; if (dataSanity > end) return PsdStatusFileOutOfRange; PsdStatus status; const PsdLayerRecordMeta1 *meta1 = (const PsdLayerRecordMeta1 *) data; PsdUtils::fetchRect(&mRect, &meta1->mRect); // The layer region may exceed the image size mAdjustedRect.mRight = mRect.mRight <= mFile->getWidth() ? mRect.mRight : mFile->getWidth(); mAdjustedRect.mBottom = mRect.mBottom <= mFile->getHeight() ? mRect.mBottom : mFile->getHeight(); mAdjustedRect.mLeft = mRect.mLeft >= 0 ? (mRect.mLeft <= mAdjustedRect.mRight ? mRect.mLeft : mAdjustedRect.mRight) : 0; mAdjustedRect.mTop = mRect.mTop >= 0 ? (mRect.mTop <= mAdjustedRect.mBottom ? mRect.mTop : mAdjustedRect.mBottom) : 0; mChannels = ntohs(meta1->mChannels); LOG_DEBUG("(%d, %d, %d, %d) (%d, %d, %d, %d) channels: %u\n", mRect.mLeft, mRect.mTop, mRect.mRight, mRect.mBottom, mAdjustedRect.mLeft, mAdjustedRect.mTop, mAdjustedRect.mRight, mAdjustedRect.mBottom, mChannels); data += sizeof(PsdLayerRecordMeta1); dataSanity += mChannels * sizeof(PsdChannelInfo); if (dataSanity > end) return PsdStatusFileOutOfRange; const PsdChannelInfo *channelsInfo = (const PsdChannelInfo *) data; mChannelsInfo.resize(mChannels); for (uint16_t i = 0; i < mChannels; i++) { mChannelsInfo[i].mId = ntohs(channelsInfo[i].mId); mChannelsInfo[i].mLength = ntohl(channelsInfo[i].mLength); mImageDataBlock.mLength += mChannelsInfo[i].mLength; LOG_DEBUG("channel %u: id: %d len: %u\n", i, mChannelsInfo[i].mId, mChannelsInfo[i].mLength); } LOG_DEBUG("image data length: %u\n", mImageDataBlock.mLength); data += sizeof(PsdChannelInfo) * mChannels; if (!CHECK_FOUR_CHAR(data, '8', 'B', 'I', 'M')) { LOG_ALWAYS("Blend mode signature not found"); return PsdStatusFileMalformed; } data += 4; const PsdLayerRecordMeta2 *meta2 = (const PsdLayerRecordMeta2 *) data; memcpy(mBlendMode, meta2->mBlendMode, sizeof(mBlendMode)); mOpacity = meta2->mOpacity; mClipping = meta2->mClipping; mFlags = meta2->mFlags; mFiller = meta2->mFiller; if (mFiller != 0) { LOG_DEBUG("Filler is not zero\n"); return PsdStatusFileMalformed; } mExtraDataBlock.assign((const uint8_t *)(meta2 + 1)); if (mExtraDataBlock.getEndAddress() > end || mExtraDataBlock.mLength < 4) return PsdStatusFileOutOfRange; mMaskInfoBlock.assign(mExtraDataBlock.mAddress); status = readMaskData(); if (status != PsdStatusOK) return status; if (mMaskInfoBlock.getEndAddress() + 4 > end) return PsdStatusFileOutOfRange; mBlendingRangesBlock.assign(mMaskInfoBlock.getEndAddress()); mName = PsdUtils::fetchPascalString(mBlendingRangesBlock.getEndAddress()); mAdditionalInfoBlock.mAddress = mBlendingRangesBlock.getEndAddress() + PAD4(mName.size() + 1); if (mExtraDataBlock.getEndAddress() < mAdditionalInfoBlock.mAddress) return PsdStatusFileOutOfRange; mAdditionalInfoBlock.mLength = (ptrdiff_t) mExtraDataBlock.getEndAddress() - (ptrdiff_t) mAdditionalInfoBlock.mAddress; LOG_DEBUG("layer addtional info: %u + %u\n", uint32_t(mAdditionalInfoBlock.mAddress - mFile->mMapped.get().mAddress), mAdditionalInfoBlock.mLength); if (mAdditionalInfoBlock.mLength > 0) { status = readAdditionalInfo(); if (status != PsdStatusOK) return status; } return PsdStatusOK; }
int dumpDatasetList(u64 userId) { int i; s32 numDatasets = 0; int rv; LOG_ALWAYS(">>>> CCDIListOwnedDatasets"); ccd::ListOwnedDatasetsInput ownedDatasetsInput; ccd::ListOwnedDatasetsOutput ownedDatasetsOutput; ownedDatasetsInput.set_user_id(userId); ownedDatasetsInput.set_only_use_cache(false); rv = CCDIListOwnedDatasets(ownedDatasetsInput, ownedDatasetsOutput); if (rv != CCD_OK) { LOG_ERROR("CCDIListOwnedDatasets fail: %d", rv); goto exit; } else { LOG_INFO("CCDIListOwnedDatasets OK"); } numDatasets = ownedDatasetsOutput.dataset_details_size(); for (i = 0; i < numDatasets; i++) { LOG_ALWAYS("["FMTu64"] Dataset name: %s [Content type(%s)]", ownedDatasetsOutput.dataset_details(i).datasetid(), ownedDatasetsOutput.dataset_details(i).datasetname().c_str(), ownedDatasetsOutput.dataset_details(i).contenttype().c_str()); if (ownedDatasetsOutput.dataset_details(i).has_datasettype()) { LOG_ALWAYS(" DatasetType(%d)", (int)ownedDatasetsOutput.dataset_details(i).datasettype()); } if (ownedDatasetsOutput.dataset_details(i).has_storageclustername()) { LOG_ALWAYS(" StorageClusterName(%s)", ownedDatasetsOutput.dataset_details(i).storageclustername().c_str()); } if (ownedDatasetsOutput.dataset_details(i).has_storageclusterhostname()) { LOG_ALWAYS(" StorageClusterHostName(%s)", ownedDatasetsOutput.dataset_details(i).storageclusterhostname().c_str()); } if (ownedDatasetsOutput.dataset_details(i).has_linkedto()) { LOG_ALWAYS(" LinkedTo("FMTu64")", ownedDatasetsOutput.dataset_details(i).linkedto()); } if (ownedDatasetsOutput.dataset_details(i).has_clusterid()) { LOG_ALWAYS(" ClusterId("FMTu64")", ownedDatasetsOutput.dataset_details(i).clusterid()); } if (ownedDatasetsOutput.dataset_details(i).has_userid()) { LOG_ALWAYS(" UserId("FMTu64")", ownedDatasetsOutput.dataset_details(i).userid()); } if (ownedDatasetsOutput.dataset_details(i).has_datasetlocation()) { LOG_ALWAYS(" DatasetLocation(%s)", ownedDatasetsOutput.dataset_details(i).datasetlocation().c_str()); } if (ownedDatasetsOutput.dataset_details(i).archivestoragedeviceid_size() > 0) { for (int j = 0; j < ownedDatasetsOutput.dataset_details(i).archivestoragedeviceid_size(); j++) { LOG_ALWAYS(" ArchiveStorageDeviceId("FMTu64")", ownedDatasetsOutput.dataset_details(i).archivestoragedeviceid(j)); } } if (ownedDatasetsOutput.dataset_details(i).has_displayname()) { LOG_ALWAYS(" displayName(%s)", ownedDatasetsOutput.dataset_details(i).displayname().c_str()); } } exit: return rv; }
PsdStatus PsdFile::readLayers(const uint8_t *&ptr, const uint8_t *end) { if (ptr > mMapped.get().getEndAddress()) return PsdStatusFileOutOfRange; PsdStatus status; deque<PsdLayerGroup *> groups; PsdLayerGroup *group = NULL; PsdLayers allLayers(new vector<shared_ptr<PsdLayer> >()); allLayers->reserve(mLayersCount); mLayers.reset(new vector<shared_ptr<PsdLayer> >); mLayers->reserve(mLayersCount / 2 + 1); // read the header of each layer and construct the layer group tree for (uint16_t i = 0; i < mLayersCount && ptr < end; i++) { shared_ptr<PsdLayer> layer(new PsdLayer(this)); status = layer->readMeta(ptr, end); if (status != PsdStatusOK) return status; allLayers->push_back(layer); LOG_DEBUG("layer: %s\n", layer->getName()); if (layer->getType() == PsdLayer::LayerTypeGroup) { if (layer->mIsEndOfGroup) { group = new PsdLayerGroup(this); groups.push_back(group); } else if (group) { group->mName = layer->mName; groups.pop_back(); if (groups.empty()) { // No group in the stack, push to the root group mLayers->push_back(shared_ptr<PsdLayer>(group)); group = NULL; } else { // Otherwise, push to the top group on the stack groups.back()->mLayers->push_back(shared_ptr<PsdLayer>(group)); group = groups.back(); } } else { LOG_ALWAYS("A group layer is found but no end-of-group layer exists. Ignoring this layer."); } } else { if (group) group->mLayers->push_back(layer); else mLayers->push_back(layer); } ptr = layer->mAdditionalInfoBlock.getEndAddress(); } if (!groups.empty()) return PsdStatusLayerGroupNotComplete; LOG_DEBUG("Layer image data start: %u\n", uint32_t(ptr - mMapped.get().mAddress)); // loop over all layers to obtain the address and length of per-layer image data vector<shared_ptr<PsdLayer> >::iterator iter = allLayers->begin(), layersEnd = allLayers->end(); for (; iter != layersEnd; iter++) { PsdLayer *layer = iter->get(); if (ptr + layer->mImageDataBlock.mLength > end) return PsdStatusFileOutOfRange; LOG_DEBUG("Layer image data: %u\n", uint32_t(ptr - mMapped.get().mAddress)); layer->mImageDataBlock.mAddress = ptr; ptr += layer->mImageDataBlock.mLength; } LOG_DEBUG("Layer image data end: %u\n", uint32_t(ptr - mMapped.get().mAddress)); return PsdStatusOK; }
void ShaderParamTextureCubeMap::LoadImage() { if( GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_X || GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_X || GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_Y || GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_Y || GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_Z || GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_Z ) { //Timer statsTickClock; //Timer_t frameTickStart = statsTickClock.Tick(); RefPtr<osgDB::ReaderWriter::Options> options = new osgDB::ReaderWriter::Options; options->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_ALL); std::string filePath = dtCore::FindFileInPathList(GetTexture()); osg::Image *image = osgDB::readImageFile(filePath, options.get()); if (image == NULL) { // we don't want to crash just because a shader couldnt find an image, but we need to let // the user know. image = new osg::Image(); // gotta have some sort of image placeholder LOG_ALWAYS("Could not find image for shader parameter [" + GetName() + "] at location [" + GetTexture() + "]."); //throw dtUtil::Exception(ShaderParameterException::INVALID_ATTRIBUTE,"Could not find image for texture at location: " + GetTexture()); } osg::TextureCubeMap *texCube = static_cast<osg::TextureCubeMap*>(GetTextureObject()); if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_X) { texCube->setImage(osg::TextureCubeMap::POSITIVE_X, image); } else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_X) { texCube->setImage(osg::TextureCubeMap::NEGATIVE_X, image); } else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_Y) { texCube->setImage(osg::TextureCubeMap::POSITIVE_Y, image); } else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_Y) { texCube->setImage(osg::TextureCubeMap::NEGATIVE_Y, image); } else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_Z) { texCube->setImage(osg::TextureCubeMap::POSITIVE_Z, image); } else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_Z) { texCube->setImage(osg::TextureCubeMap::NEGATIVE_Z, image); } // we aren't dirty anymore //Timer_t frameTickStop = statsTickClock.Tick(); //double processTime = statsTickClock.DeltaSec(frameTickStart, frameTickStop); //printf("Load Image time [%f]", processTime); } SetImageSourceDirty(false); }
int do_autotest_regression_streaming_transcode_negative(int argc, const char* argv[]) { int rv = VPL_OK; u32 retry = 0; u32 photoAlbumNum = 0; u32 photoNum = 0; u32 expectedPhotoNum = 0; std::string photosToStream = "-1"; // meaning no limit int cloudPCId = 1; int clientPCId = 2; std::string CloudPC_alias = "CloudPC"; std::string MD_alias = "MD"; std::string osVersion; const char* TEST_TRANSCODE2_STR = "SdkTranscodeStreamingPositive"; bool full = false; if (argc == 6 && (strcmp(argv[5], "-f") == 0 || strcmp(argv[5], "--fulltest") == 0) ) { full = true; } if (checkHelp(argc, argv) || (argc < 5) || (argc == 6 && !full)) { printf("AutoTest %s <username> <password> <expectedPhotoNum> [<fulltest>(-f/--fulltest)]\n", argv[0]); return 0; // No arguments needed } LOG_ALWAYS("AutoTest Transcode Streaming: Domain(%s) User(%s) Password(%s) ExpectedPhotoNum(%s)", argv[1], argv[2], argv[3], argv[4]); // Does a hard stop for all ccds { const char *testArg[] = { "StopCCD" }; stop_ccd_hard(ARRAY_ELEMENT_COUNT(testArg), testArg); } expectedPhotoNum = static_cast<u32>(atoi(argv[4])); VPLFile_Delete("dumpfile"); LOG_ALWAYS("\n\n==== Launching Cloud PC CCD (instanceId %d) ====", cloudPCId); SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), rv); if (rv < 0) { setCcdTestInstanceNum(cloudPCId); } CHECK_LINK_REMOTE_AGENT(CloudPC_alias, TEST_TRANSCODE2_STR, rv); START_CCD(TEST_TRANSCODE2_STR, rv); START_CLOUDPC(argv[2], argv[3], TEST_TRANSCODE2_STR, true, rv); VPLThread_Sleep(VPLTIME_FROM_MILLISEC(1000)); LOG_ALWAYS("\n\n==== Launching MD CCD (instanceId %d) ====", clientPCId); SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv); if (rv < 0) { setCcdTestInstanceNum(clientPCId); } CHECK_LINK_REMOTE_AGENT(MD_alias, TEST_TRANSCODE2_STR, rv); QUERY_TARGET_OSVERSION(osVersion, TEST_TRANSCODE2_STR, rv); START_CCD(TEST_TRANSCODE2_STR, rv); UPDATE_APP_STATE(TEST_TRANSCODE2_STR, rv); START_CLIENT(argv[2], argv[3], TEST_TRANSCODE2_STR, true, rv); VPLThread_Sleep(VPLTIME_FROM_MILLISEC(1000)); // make sure both cloudpc/client has the device linked info updated LOG_ALWAYS("\n\n== Checking cloudpc and Client device link status =="); { std::vector<u64> deviceIds; u64 userId = 0; u64 cloudPCDeviceId = 0; u64 MDDeviceId = 0; const char *testCloudStr = "CheckCloudPCDeviceLinkStatus"; const char *testMDStr = "CheckMDDeviceLinkStatus"; SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), rv); if (rv < 0) { setCcdTestInstanceNum(cloudPCId); } rv = getUserIdBasic(&userId); if (rv != 0) { LOG_ERROR("Fail to get user id:%d", rv); CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testCloudStr, rv); } rv = getDeviceId(&cloudPCDeviceId); if (rv != 0) { LOG_ERROR("Fail to get CloudPC device id:%d", rv); CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testCloudStr, rv); } SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv); if (rv < 0) { setCcdTestInstanceNum(cloudPCId); } rv = getDeviceId(&MDDeviceId); if (rv != 0) { LOG_ERROR("Fail to get MD device id:%d", rv); CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testMDStr, rv); } deviceIds.push_back(cloudPCDeviceId); LOG_ALWAYS("Add Device Id "FMTu64, cloudPCDeviceId); deviceIds.push_back(MDDeviceId); LOG_ALWAYS("Add Device Id "FMTu64, MDDeviceId); rv = wait_for_devices_to_be_online_by_alias(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), cloudPCId, userId, deviceIds, 20); CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testCloudStr, rv); rv = wait_for_devices_to_be_online_by_alias(TEST_TRANSCODE2_STR, MD_alias.c_str(), clientPCId, userId, deviceIds, 20); CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testMDStr, rv); SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv); if (rv < 0) { setCcdTestInstanceNum(clientPCId); } rv = wait_for_cloudpc_get_accesshandle(userId, cloudPCDeviceId, 20); CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "CheckCloudPCGetAccessHandle", rv); } LOG_ALWAYS("\n\n==== Testing ClearMetadata (CloudPC) ===="); SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), rv); if (rv < 0) { setCcdTestInstanceNum(cloudPCId); } { const char *testStr = "ClearMetadata"; const char *testArg[] = { testStr }; rv = msa_delete_catalog(ARRAY_ELEMENT_COUNT(testArg), testArg); if(rv != 0) { LOG_ERROR("RegressionStreaming_ClearMetadata failed!"); } CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, testStr, rv); } #if defined(CLOUDNODE) LOG_ALWAYS("\n\n==== Testing CloudMedia CloudnodeAddPhoto (ClientPC) ===="); SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv); if (rv < 0) { setCcdTestInstanceNum(clientPCId); } { std::string dxroot; std::string photoSetPath; rv = getDxRootPath(dxroot); if (rv != VPL_OK) { LOG_ERROR("Fail to set %s root path", argv[0]); goto exit; } photoSetPath.assign(dxroot.c_str()); const char *testStr1 = "CloudMedia"; const char *testStr2 = "CloudnodeAddPhoto"; photoSetPath.append("/GoldenTest/image_transcode_negative_test_1"); const char *testArg4[] = { testStr1, testStr2, photoSetPath.c_str() }; rv = cloudmedia_commands(3, testArg4); if (rv != VPL_OK) { LOG_ERROR("SdkTranscodeStreaming2_CloudMedia_CloudnodeAddPhoto failed!"); } CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "CloudMedia_CloudnodeAddPhoto", rv); } #endif // CLOUDNODE LOG_ALWAYS("\n\n==== Testing CloudMedia AddPhoto (CloudPC) ===="); SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, CloudPC_alias.c_str(), rv); if (rv < 0) { setCcdTestInstanceNum(cloudPCId); } { std::string dxroot; std::string photoSetPath; rv = getDxRootPath(dxroot); if (rv != VPL_OK) { LOG_ERROR("Fail to set %s root path", argv[0]); goto exit; } photoSetPath.assign(dxroot.c_str()); const char *testStr1 = "CloudMedia"; const char *testStr2 = "AddPhoto"; photoSetPath.append("/GoldenTest/image_transcode_negative_test_1"); const char *testArg4[] = { testStr1, testStr2, photoSetPath.c_str() }; rv = cloudmedia_commands(3, testArg4); if (rv != VPL_OK) { LOG_ERROR("SdkTranscodeStreaming2_CloudMedia_AddPhoto failed!"); } CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "CloudMedia_AddPhoto", rv); } // Verify if the metadata is synced retry = 0; SET_TARGET_MACHINE(TEST_TRANSCODE2_STR, MD_alias.c_str(), rv); if (rv < 0) { setCcdTestInstanceNum(clientPCId); } LOG_ALWAYS("\n\n==== List Metadata (ClientPC) ===="); { VPLTime_t startTime = VPLTime_GetTimeStamp(); while(1) { rv = mca_get_photo_object_num(photoAlbumNum, photoNum); if(rv != VPL_OK) { LOG_ERROR("Cannot get photo count from metadata"); } else if(photoNum == expectedPhotoNum) { u64 elapsedTime = VPLTIME_TO_SEC(VPLTime_GetTimeStamp() - startTime); LOG_ALWAYS("Retry (%d) times waited ("FMTu64") seconds for photo to be synced.", retry, elapsedTime); break; } if(retry++ > METADATA_SYNC_TIMEOUT) { u64 elapsedTime = VPLTIME_TO_SEC(VPLTime_GetTimeStamp() - startTime); LOG_ERROR("Timeout retry (%d) waiting for metadata to sync; waited for ("FMTu64") seconds.", retry, elapsedTime); rv = -1; break; } else { LOG_ALWAYS("Waiting (cnt %d) photoNum (%d) photoAlbumNum (%d)", retry, photoNum, photoAlbumNum); } VPLThread_Sleep(VPLTIME_FROM_SEC(1)); } LOG_ALWAYS("Photo added by CloudPC: %d; Expected photo: %d", photoNum, expectedPhotoNum); CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "Verify_Uploaded_Photo_Num1", rv); } LOG_ALWAYS("\n\n==== SetupStreamTest to generate dump file ===="); { const char *testStr = "SetupStreamTest"; const char *testArg[] = { testStr, "-d", "dumpfile", "-f", "2", "-M", photosToStream.c_str() }; rv = setup_stream_test(ARRAY_ELEMENT_COUNT(testArg), testArg); CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "SetupStreamTest_dumpfile", rv); } // Negative Test - Scale an invalid photo to 800x800 LOG_ALWAYS("\n\n==== Negative Test, scale an invalid photo to 800x800 ===="); { const char *testStr = "TimeStreamDownload"; const char *testArg[] = { testStr, "-d", "dumpfile", "-R", "800,800", "-f", "JPG" }; rv = time_stream_download(ARRAY_ELEMENT_COUNT(testArg), testArg); if (rv == -1) { rv = 0; } else if (rv == 0) { if(osVersion == OS_LINUX) { rv = -1; CHECK_AND_PRINT_EXPECTED_TO_FAIL(TEST_TRANSCODE2_STR, "NegativeTest_InvalidImage", rv, "13344"); rv = 0; goto exit; } } else { LOG_ERROR("Expected -1, but got %d", rv); rv = -1; } CHECK_AND_PRINT_RESULT(TEST_TRANSCODE2_STR, "NegativeTest_InvalidImage", rv); } exit: LOG_ALWAYS("\n\n== Freeing Client =="); if(set_target_machine(MD_alias.c_str()) < 0) setCcdTestInstanceNum(clientPCId); { const char *testArg[] = { "StopClient" }; stop_client(ARRAY_ELEMENT_COUNT(testArg), testArg); } if (isWindows(osVersion) || osVersion.compare(OS_LINUX) == 0) { const char *testArg[] = { "StopCCD" }; stop_ccd_soft(ARRAY_ELEMENT_COUNT(testArg), testArg); } LOG_ALWAYS("\n\n== Freeing Cloud PC =="); if(set_target_machine(CloudPC_alias.c_str()) < 0) setCcdTestInstanceNum(cloudPCId); { const char *testArg[] = { "StopCloudPC" }; stop_cloudpc(ARRAY_ELEMENT_COUNT(testArg), testArg); } { const char *testArg[] = { "StopCCD" }; stop_ccd_soft(ARRAY_ELEMENT_COUNT(testArg), testArg); } return rv; }
/************************************************************************************************** * @fn tiLogging_Init * @brief Initializes logging code. If never called, logging will still * work, but the process name won't be shown and only the default * log level will be possible. * * input parameters * * @param *configFileName: multi-purpose... * If 'configFileName' as an unsigned integer is >0 and <= LOG_LEVEL_MAX * it will use that as the logging level (Limitation: Using this method you cannot * disable LOG_FATAL logging, but that's probably not anything you would want off.) * Else if 'configFileName' is non-NULL, * it will try to read the logging level from 'configFileName'. * Else if 'configFileName' is NULL, then first looks for a file in the same base name as * the process but with DEFAULT_LOG_CFG_SUFFIX, and will look for it in * LOG_CONFIG_FILE_OVERRIDE_PATH1 and if not found then in LOG_CONFIG_FILE_OVERRIDE_PATH2. * If it doesn't exist there, it will look in the path of the process. If it's not there * it gives up and defaults to MAX_LOG_LEVEL_TO_STDIO (defined above). * If it finds a config file and the value is out of range, it ignores it and defaults to * MAX_LOG_LEVEL_TO_STDIO. * * @return FALSE if previously initialized OR no config was found, otherwise TRUE. ************************************************************************************************** */ bool tiLogging_Init(char const *configFileName) { static const char kDefaultCfgExtension[] = DEFAULT_LOG_CFG_SUFFIX; static const char kConfigFileOverridePath1[] = LOG_CONFIG_FILE_OVERRIDE_PATH1; static const char kConfigFileOverridePath2[] = LOG_CONFIG_FILE_OVERRIDE_PATH2; static bool alreadyInitialized = false; struct stat statData; auto int statResult = 0; auto bool foundConfig = false; if (!alreadyInitialized) { FILE *fp; char *allocatedPath = NULL; char *processName = NULL; char nameBuf[256] = {0}; alreadyInitialized = true; // IMPORTANT: This call to setvbuf() MUST BE DONE FIRST. // It changes the buffering of stdout to line-based, and // that works ONLY if the stream has not been used yet, so // we MUST NOT printf/log anything before calling it... // Set stdout buffering to line-based buffering. If // it is going to a terminal, it should be this by default, // but if it's being redirected to a file, files are block- // buffered by default and we want to be able to tail a // log file and see output in realtime, AND in the instance // of a crash, we don't want to lose a block that hadn't // been flushed yet. We are NOT disabling buffering // altogether because that has more of an impact on performance. setvbuf(stdout, NULL, _IOLBF, 0); // Leaves buffer, changes mode. // Find our process name to be used as part of the logging prefix... if (!(fp=fopen("/proc/self/cmdline", "r"))) LOG_ALWAYS("%s(): Can't open cmdline for reading to determine process name!\n", __FUNCTION__); else { if (!fgets(nameBuf, sizeof(nameBuf), fp)) LOG_ALWAYS("%s(): Can't read cmdline to determine process name!\n", __FUNCTION__); else { char *ptr; fgets(nameBuf, sizeof(nameBuf), fp); ptr = nameBuf; while (*ptr && !isspace(*ptr)) // Find first whitespace (or EOL) ++ptr; if (ptr) *ptr = 0; // Terminate string at first whitepace if (!(processName=strrchr(nameBuf, '/'))) // Get base name (no path) of process; processName = nameBuf; else ++processName; // Skip past '/' if (processName && *processName) { int len = strlen(processName) + 4; // +4 is for brackets, space, and null terminator. ptr = malloc(len); if (ptr) // Shouldn't fail malloc, but playing it safe so processLogPrefix can't become NULL { snprintf(ptr, len, "[%s] ", processName); processLogPrefix = ptr; } } } fclose(fp); } if (configFileName && (((intptr_t)configFileName) <= LOG_LEVEL_MAX)) { __APP_LOG_LEVEL = ((intptr_t)configFileName); LOG_ALWAYS("%s(): Called with hard-coded level. Logging threshold set to level %s.\n\n", __FUNCTION__, levelToName(__APP_LOG_LEVEL)); configFileName = NULL; foundConfig = true; } else if ((!configFileName || !*configFileName) && processName && *processName) { // By now, if we were successful getting the process name from the cmdline, // it's stored in processLogPrefix, and the full path to it is still in nameBuf. int maxLen = strlen(nameBuf) + SIZEMAX(kConfigFileOverridePath1,kConfigFileOverridePath2) + sizeof(kDefaultCfgExtension) + 1; // Allocate space for the longest path/name of the locations we'll try. if ((allocatedPath = malloc(maxLen))) { snprintf(allocatedPath, maxLen, "%s%s%s", kConfigFileOverridePath1, processName, kDefaultCfgExtension); if ((statResult = stat(allocatedPath, &statData)) == 0) configFileName = allocatedPath; else { snprintf(allocatedPath, maxLen, "%s%s%s", kConfigFileOverridePath2, processName, kDefaultCfgExtension); if ((statResult = stat(allocatedPath, &statData)) == 0) configFileName = allocatedPath; else { snprintf(allocatedPath, maxLen, "%s%s", nameBuf, kDefaultCfgExtension); if ((statResult = stat(allocatedPath, &statData)) == 0) configFileName = allocatedPath; } } } } // Note that we're implementing our own log filter if file exists. // This should get set to a positive value. (See tiLogging.h) if (!foundConfig && configFileName && *configFileName) { if ((fp = fopen(configFileName, "r")) == NULL) LOG_ALWAYS("%s(): File %s exists, but unable to open it for reading.\n", __FUNCTION__, configFileName); else { char valBuf[10]; bool skipNext = false; bool gotValueFromFile = false; while (fgets(valBuf, sizeof(valBuf), fp) && !gotValueFromFile) { if (!skipNext && ((gotValueFromFile = isdigit(*valBuf)))) // Allow ANY non-digit as first character to be taken as a comment line. { int tmp=atoi(valBuf); if (tmp <= 0 || tmp > LOG_LEVEL_MAX) LOG_ALWAYS("%s(): Invalid value found (%d) in %s.\n", __FUNCTION__, tmp, configFileName); else { __APP_LOG_LEVEL = tmp; LOG_ALWAYS("%s(): Found %s. Logging threshold set to level %s.\n\n", __FUNCTION__, configFileName, levelToName(__APP_LOG_LEVEL)); foundConfig = true; } } // If fgets terminated due to length, not newline, skip reads until we hit a newline (or end of file). skipNext = valBuf[strlen(valBuf)-1] != '\n'; } fclose(fp); if (!gotValueFromFile) LOG_ALWAYS("%s(): %s exists but has no numeric line.\n", __FUNCTION__, configFileName); } } if (configFileName == allocatedPath) configFileName = NULL; if (!foundConfig) { if (configFileName) LOG_ALWAYS("%s(): Could not find specified logging config file %s\n", __FUNCTION__, configFileName); else if (processName && *processName) LOG_DEBUG("%s(): No default logging config file %s%s in %s nor in %s nor in process directory.\n", __FUNCTION__, processName, kDefaultCfgExtension, kConfigFileOverridePath1, kConfigFileOverridePath2); else LOG_ALWAYS("%s(): Could not determine process name to extrapolate into logging config file name!\n", __FUNCTION__); __APP_LOG_LEVEL = MAX_LOG_LEVEL_TO_STDIO; LOG_ALWAYS("%s(): Defaulting logging threshold to %s.\n\n", __FUNCTION__, levelToName(__APP_LOG_LEVEL)); } if (allocatedPath) free(allocatedPath); } return foundConfig; }
int VcsShare_share(const VcsSession& vcsSession, VPLHttp2& httpHandle, const VcsDataset& dataset, const std::string& componentName, u64 compId, const std::vector<std::string>& recipientEmail, bool printLog) { int rv = 0; rv = httpHandle.SetDebug(printLog); if(rv != 0) { LOG_WARN("SetDebug failed(%d), Not critical. Continuing.", rv); } std::string componentNameLeadingOrTrailingSlash; Util_trimSlashes(componentName, componentNameLeadingOrTrailingSlash); std::stringstream ss; ss.str(""); ss << vcsSession.urlPrefix << "/vcs/sbm/share/"; ss << dataset.id << "/" << VPLHttp_UrlEncoding(componentNameLeadingOrTrailingSlash, "/"); ss << "?compId=" << compId; std::string url = ss.str(); rv = httpHandle.SetUri(url); if(rv != 0) { LOG_ERROR("SetUri:%d, %s", rv, url.c_str()); return rv; } rv = addSessionHeaders(vcsSession, httpHandle); if(rv != 0) { LOG_ERROR("Error adding session headers:%d", rv); return rv; } ss.str(""); ss << "{" << "\"recipients\":" << "["; bool notFirst = false; for (std::vector<std::string>::const_iterator emailIter = recipientEmail.begin(); emailIter != recipientEmail.end(); ++emailIter) { if (notFirst) { ss << ","; } ss << "\"" << *emailIter << "\""; notFirst = true; } ss << "]" << "}"; std::string jsonBody = ss.str(); if(printLog){ LOG_ALWAYS("jsonBody:%s", jsonBody.c_str()); } std::string httpPostResponse; rv = httpHandle.Post(jsonBody, httpPostResponse); if(rv != 0) { LOG_ERROR("http Post:%d", rv); return rv; } // Http error code, should be 200 unless server can't be reached. rv = vcs_translate_http_status_code(httpHandle.GetStatusCode()); if(rv != 0) { LOG_ERROR("vcs_translate_http_status_code:%d, dset:"FMTu64",path:%s," "compId:"FMTu64, rv, dataset.id, componentName.c_str(), compId); goto exit_with_server_response; } // Parse VCS error code, if any. if(isVcsErrorTemplate(httpPostResponse.c_str(), rv)) { LOG_WARN("VCS_ERRCODE(%d)", rv); goto exit_with_server_response; } // On success, there is nothing returned. exit_with_server_response: if (rv != 0) { LOG_WARN("rv=%d, url=\"%s\", response: %s", rv, url.c_str(), httpPostResponse.c_str()); } return rv; }
/************************************************************************************************** * @fn HalGpioResetInit * * * @brief Initialise RESET GPIO. * * @param gpioCfg - Reset pin configuration parameters * * @return STATUS **************************************************************************************************/ int HalGpioResetInit(halGpioCfg_t *gpioCfg) { memcpy(resetGpioCfg.gpio.value, gpioCfg->gpio.value, strlen(gpioCfg->gpio.value)); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] resetGpioCfg.gpio.value = '%s'\n", __FUNCTION__, resetGpioCfg.gpio.value); } memcpy(resetGpioCfg.gpio.direction, gpioCfg->gpio.direction, strlen(gpioCfg->gpio.direction)); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] resetGpioCfg.gpio.direction = '%s'\n", __FUNCTION__, resetGpioCfg.gpio.direction); } resetGpioCfg.gpio.active_high_low = gpioCfg->gpio.active_high_low; if ( ( gpioCfg->levelshifter.value) && ( gpioCfg->levelshifter.active_high_low) && ( gpioCfg->levelshifter.direction)) { memcpy(resetGpioCfg.levelshifter.value, gpioCfg->levelshifter.value, strlen(gpioCfg->levelshifter.value)); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] resetGpioCfg.levelshifter.value = '%s'\n", __FUNCTION__, resetGpioCfg.levelshifter.value); } memcpy(resetGpioCfg.levelshifter.direction, gpioCfg->levelshifter.direction, strlen(gpioCfg->levelshifter.direction)); resetGpioCfg.levelshifter.active_high_low = gpioCfg->levelshifter.active_high_low; if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] resetGpioCfg.levelshifter.direction = '%s'\n", __FUNCTION__, resetGpioCfg.levelshifter.direction); } //open the GPIO DIR file for the level shifter direction signal gpioResetFd = open(resetGpioCfg.levelshifter.direction, O_RDWR); if(gpioResetFd == 0) { perror(resetGpioCfg.levelshifter.direction); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] %s open failed\n", __FUNCTION__, resetGpioCfg.levelshifter.direction); } npi_ipc_errno = NPI_LNX_ERROR_HAL_GPIO_RESET_LVLSHFT_DIR_OPEN; return NPI_LNX_FAILURE; } //Set the direction of the GPIO to output if (ERROR == write(gpioResetFd, "out", 3)) { perror(resetGpioCfg.levelshifter.direction); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] can't write in %s \n", __FUNCTION__, resetGpioCfg.levelshifter.direction); } npi_ipc_errno = NPI_LNX_ERROR_HAL_GPIO_RESET_LVLSHFT_DIR_WRITE; return NPI_LNX_FAILURE; } //close the DIR file close(gpioResetFd); //open the GPIO VALUE file for the level shifter direction signal gpioResetFd = open(resetGpioCfg.levelshifter.value, O_RDWR); if(gpioResetFd == 0) { perror(resetGpioCfg.levelshifter.value); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] %s open failed\n", __FUNCTION__, resetGpioCfg.levelshifter.value); } npi_ipc_errno = NPI_LNX_ERROR_HAL_GPIO_RESET_LVLSHFT_VAL_OPEN; return NPI_LNX_FAILURE; } //Set the value of the GPIO to 0 (level shifter direction from Host to CC2531) if(ERROR == write(gpioResetFd, "1", 1)) { perror(resetGpioCfg.levelshifter.value); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] can't write in %s\n", __FUNCTION__, resetGpioCfg.levelshifter.value); } npi_ipc_errno = NPI_LNX_ERROR_HAL_GPIO_RESET_LVLSHFT_VAL_WRITE; return NPI_LNX_FAILURE; } //close the DIR file close(gpioResetFd); } else { if (__BIG_DEBUG_ACTIVE == TRUE) { LOG_ALWAYS("[%s] Wrong Configuration File, one of the following Key value are missing for MRDY.Level Shifter definition: '\n", __FUNCTION__); LOG_ALWAYS("value: \t\t%s\n", resetGpioCfg.gpio.value); LOG_ALWAYS("direction: \t%s\n", resetGpioCfg.gpio.direction); LOG_ALWAYS("active_high_low: %d\n", resetGpioCfg.gpio.active_high_low); LOG_ALWAYS("Level Shifter is optional, please check if you need it or not before continuing...\n"); } } //open the RESET GPIO DIR file gpioResetFd = open(resetGpioCfg.gpio.direction, O_RDWR); if(gpioResetFd == 0) { perror(resetGpioCfg.gpio.direction); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] %s open failed\n", __FUNCTION__, resetGpioCfg.gpio.direction); } npi_ipc_errno = NPI_LNX_ERROR_HAL_GPIO_RESET_GPIO_DIR_OPEN; return NPI_LNX_FAILURE; } //Set RESET GPIO as output if(ERROR == write(gpioResetFd, "out", 3)) { perror(resetGpioCfg.gpio.direction); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] can't write in %s\n", __FUNCTION__, resetGpioCfg.gpio.direction); } npi_ipc_errno = NPI_LNX_ERROR_HAL_GPIO_RESET_GPIO_DIR_WRITE; return NPI_LNX_FAILURE; } //close RESET DIR file close(gpioResetFd); //open the RESET GPIO VALUE file so it can be written to using the file handle later gpioResetFd = open(resetGpioCfg.gpio.value, O_RDWR); if(gpioResetFd == 0) { perror(resetGpioCfg.gpio.value); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] %s open failed\n", __FUNCTION__, resetGpioCfg.gpio.value); } npi_ipc_errno = NPI_LNX_ERROR_HAL_GPIO_RESET_GPIO_VAL_OPEN; return NPI_LNX_FAILURE; } //Set RESET GPIO to 1 as default if(ERROR == write(gpioResetFd, "1", 3)) { perror(resetGpioCfg.gpio.value); if (__BIG_DEBUG_ACTIVE == TRUE) { time_printf("[%s] can't write in %s\n", __FUNCTION__, resetGpioCfg.gpio.value); } npi_ipc_errno = NPI_LNX_ERROR_HAL_GPIO_RESET_GPIO_VAL_WRITE; return NPI_LNX_FAILURE; } return NPI_LNX_SUCCESS; }