void ProcessesList::produzirListaProcessos(){ this->listaProcessos.clear(); QDir *directory; QFile *arquivo; QString *S; QStringList files; std::string data; QDir aDir("/proc"); aDir.setFilter(QDir::Dirs); QStringList entries = aDir.entryList(); this->numThreads = 0; for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry) { S = new QString("/proc/" + QString(*entry)); if((S->compare("/proc/.") == 0) || (S->compare("/proc/..") == 0)){ continue; } directory = new QDir(*S); if(!directory->exists()){ continue; } else if(!((S->toStdString()[6] >= '0') && (S->toStdString()[6] <= '9'))){ continue; } directory->setFilter(QDir::Files); arquivo = new QFile(*S + "/status"); if((!arquivo)){ qDebug() << "ERRO 1! (" << *S << ")"; continue; } else if(!arquivo->open(QIODevice::ReadOnly | QIODevice::Text)){ qDebug() << arquivo->errorString(); qDebug() << "ERRO 2! (" << *S << ")"; continue; } process P; QTextStream buffer(arquivo); QStringList fileContent = buffer.readAll().split("\n"); QString buf; P.nome = processName(fileContent.at(0)); P.status = processStatus(fileContent.at(1)); P.pid = processPid(fileContent.at(3)); P.ppid = processPPid(fileContent.at(4)); P.user = processUser(fileContent.at(6)); for (int var = 7; var < fileContent.size(); ++var) { buf = fileContent.at(var); if(buf.startsWith("Threads")){ break; } } P.threads = processThreadsNumber(buf); this->numThreads += P.threads; P.trocas_contexto = processTrocasContexto(fileContent.at(fileContent.size()-3),fileContent.at(fileContent.size()-2)); this->listaProcessos.push_back(P); arquivo->close(); } delete arquivo; delete directory; delete S; }
int readSingleFile(char theNames[NUM_NAME_BUFFER][NAME_LENGTH_BUFFER], int nameNumberRep[NUM_NAME_BUFFER][10], int yearIndex, char fileName[],int totalNames) { int i, j, powerIndex, namesAdded; char ch; FILE *theFile = fopen(fileName, "r"); i = 0; j = 0; powerIndex = 0; namesAdded = 0; char lineBuffer[LINE_BUFFER_SIZE]; while (j < 100 && theFile != NULL) { ch = fgetc(theFile); if (ch <= 57 && ch >= 48) //we found an ascii number powerIndex++; if (ch == '\n') { j++; //controls the number of names we found. ch = fgetc(theFile); // need to do one more read for the new tab namesAdded += processName(lineBuffer, theNames, nameNumberRep, namesAdded+totalNames, powerIndex, yearIndex); powerIndex = 0; //reset vars i = 0; //reset vars memset(lineBuffer, 0, sizeof(lineBuffer)); //reset Array } lineBuffer[i] = ch; i++; } return namesAdded; }
//______________________________________________________________________________ // RConsoleProxy static TInt StartServer(const TDesC& aServerName, const TDesC& aServerArgs) { TPtrC processName(aServerName); if (processName.Length() && processName[0] == '!') { processName.Set(processName.Mid(1)); } RProcess server; TInt r = server.Create(processName, aServerArgs); if (r!=KErrNone) return r; TRequestStatus stat; server.Rendezvous(stat); if (stat != KRequestPending) { server.Kill(0); } else { server.Resume(); } User::WaitForRequest(stat); // wait for start or death r = (server.ExitType() == EExitPanic) ? KErrGeneral : stat.Int(); server.Close(); return r; }
bool CWsPackageProcessEx::onAddPackage(IEspContext &context, IEspAddPackageRequest &req, IEspAddPackageResponse &resp) { resp.updateStatus().setCode(0); StringAttr target(req.getTarget()); StringAttr name(req.getPackageMap()); if (target.isEmpty()) throw MakeStringExceptionDirect(PKG_MISSING_PARAM, "Target cluster parameter required"); if (name.isEmpty()) throw MakeStringExceptionDirect(PKG_MISSING_PARAM, "PackageMap name parameter required"); DBGLOG("%s adding packagemap %s to target %s", context.queryUserId(), name.str(), target.str()); StringBuffer pmid; if (!req.getGlobalScope()) pmid.append(target).append("::"); pmid.append(name.get()); bool activate = req.getActivate(); unsigned updateFlags = 0; if (req.getOverWrite()) updateFlags |= (DALI_UPDATEF_PACKAGEMAP | DALI_UPDATEF_REPLACE_FILE | DALI_UPDATEF_CLONE_FROM | DALI_UPDATEF_SUPERFILES); if (req.getReplacePackageMap()) updateFlags |= DALI_UPDATEF_PACKAGEMAP; if (req.getUpdateCloneFrom()) updateFlags |= DALI_UPDATEF_CLONE_FROM; if (req.getUpdateSuperFiles()) updateFlags |= DALI_UPDATEF_SUPERFILES; if (req.getAppendCluster()) updateFlags |= DALI_UPDATEF_APPEND_CLUSTER; StringAttr processName(req.getProcess()); Owned<IUserDescriptor> userdesc; const char *user = context.queryUserId(); const char *password = context.queryPassword(); if (user && *user && *password && *password) { userdesc.setown(createUserDescriptor()); userdesc->set(user, password); } StringBuffer srcCluster; StringBuffer daliip; StringBuffer prefix; splitDerivedDfsLocation(req.getDaliIp(), srcCluster, daliip, prefix, req.getSourceProcess(), req.getSourceProcess(), NULL, NULL); StringBuffer pkgSetId; buildPkgSetId(pkgSetId, processName.get()); StringArray filesNotFound; addPackageMapInfo(updateFlags, req.getInfo(), filesNotFound, processName, target, pmid, pkgSetId, daliip, srcCluster, prefix, activate, userdesc, req.getAllowForeignFiles(), req.getPreloadAllPackages()); resp.setFilesNotFound(filesNotFound); StringBuffer msg; msg.append("Successfully loaded ").append(name.get()); resp.updateStatus().setDescription(msg.str()); return true; }
void NaughtyProcessMonitor::_process(ulong pid, uint load) { if(!d->loadMap_.contains(pid)) { d->loadMap_.insert(pid, load); return; } uint oldLoad = d->loadMap_[pid]; bool misbehaving = (load - oldLoad) > 40 * (d->interval_ / 1000); bool wasMisbehaving = d->scoreMap_.contains(pid); if(misbehaving) if(wasMisbehaving) { d->scoreMap_.replace(pid, d->scoreMap_[pid] + 1); if(canKill(pid)) emit(runawayProcess(pid, processName(pid))); } else d->scoreMap_.insert(pid, 1); else if(wasMisbehaving) d->scoreMap_.remove(pid); d->loadMap_.replace(pid, load); }
bool PlatformBinding::OpenApplicationImpl(const std::string& name) { std::vector<std::string> args; args.push_back(name); std::string processName("xdg-open"); Poco::Process::launch(processName, args); return true; }
void WebMemorySampler::initializeTimers(double interval) { m_sampleTimer.startRepeating(1); printf("Started memory sampler for process %s", processName().utf8().data()); if (interval > 0) { m_stopTimer.startOneShot(interval); printf(" for a interval of %g seconds", interval); } printf("; Sampler log file stored at: %s\n", m_sampleLogFilePath.utf8().data()); m_runningTime = interval; m_isRunning = true; }
void LLAvatarNameCache::legacyNameCallback(const LLUUID& id, const std::string& first, const std::string& last, BOOL is_group, void* data) { std::string full_name = first + " " +last; // Construct a dummy record for this name. By convention, SLID is blank // Never expires, but not written to disk, so lasts until end of session. LLAvatarName av_name; buildLegacyName(full_name, &av_name); // Don't add to cache, the data already exists in the legacy name system // cache and we don't want or need duplicate storage, because keeping the // two copies in sync is complex. processName(id, av_name, false); }
//a function that will read in 1 input file (partly by calling ...) void readFile(const char fileName[], int year, char myName[MAX_NAME_TOTAL][MAX_NAME_LENGTH], int myRank[MAX_NAME_TOTAL][MAX_RANK_LENGTH]) { int i; FILE *infile; infile = fopen(&fileName[0], "r"); char name[MAX_NAME_LENGTH]; for(i = 0; i < MAX_NAME; i++) { fscanf(infile, " %[^,]%*s", name); processName(name, i + 1, year, myName, myRank); } fclose(infile); }
bool Util::caesariaIsRunning() { DWORD processes[1024]; DWORD num; bool haveInfoAboutProcesses = EnumProcesses(processes, sizeof(processes), &num); if( !haveInfoAboutProcesses ) { return false; } // Iterate over the processes for (int i = 0; i < int(num/sizeof(DWORD)); i++) { char szProcessName[MAX_PATH] = "unknown"; // Get the handle for this process HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, processes[i]); if( hProcess ) { HMODULE hMod; DWORD countBytes; bool haveInfoAboutProcess = EnumProcessModules(hProcess, &hMod, sizeof(hMod), &countBytes); if( haveInfoAboutProcess ) { GetModuleBaseNameA(hProcess, hMod, szProcessName, sizeof(szProcessName)); std::string processName(szProcessName); // grayman - This was checking for "Doom3.exe". Starting with 1.08, the D3 // executable is no longer needed to run TDM, so we'll check for TheDarkMod.exe // instead. if (processName == "caesaria.exe") { // At this point, we know we need to quit. There's no longer a need CloseHandle(hProcess); // close the handle, we're terminating return true; } } } CloseHandle(hProcess); } return false; }
void LLAvatarNameCache::legacyNameFetch(const LLUUID& agent_id, const std::string& full_name, bool is_group) { LL_DEBUGS("AvNameCache") << "LLAvatarNameCache agent " << agent_id << " " << "full name '" << full_name << "'" << ( is_group ? " [group]" : "" ) << LL_ENDL; // Construct an av_name record from this name. LLAvatarName av_name; av_name.fromString(full_name); // Add to cache: we're still using the new cache even if we're using the old (legacy) protocol. processName(agent_id, av_name); }
bool CWsPackageProcessEx::onAddPackage(IEspContext &context, IEspAddPackageRequest &req, IEspAddPackageResponse &resp) { resp.updateStatus().setCode(0); StringAttr target(req.getTarget()); StringAttr name(req.getPackageMap()); if (target.isEmpty()) throw MakeStringExceptionDirect(PKG_MISSING_PARAM, "Target cluster parameter required"); if (name.isEmpty()) throw MakeStringExceptionDirect(PKG_MISSING_PARAM, "PackageMap name parameter required"); StringBuffer pmid; if (!req.getGlobalScope()) pmid.append(target).append("::"); pmid.append(name.get()); bool activate = req.getActivate(); bool overWrite = req.getOverWrite(); StringAttr processName(req.getProcess()); Owned<IUserDescriptor> userdesc; const char *user = context.queryUserId(); const char *password = context.queryPassword(); if (user && *user && *password && *password) { userdesc.setown(createUserDescriptor()); userdesc->set(user, password); } StringBuffer srcCluster; StringBuffer daliip; StringBuffer prefix; splitDerivedDfsLocation(req.getDaliIp(), srcCluster, daliip, prefix, req.getSourceProcess(), req.getSourceProcess(), NULL, NULL); StringBuffer pkgSetId; buildPkgSetId(pkgSetId, processName.get()); StringArray filesNotFound; addPackageMapInfo(req.getInfo(), filesNotFound, processName, target, pmid, pkgSetId, daliip, srcCluster, prefix, activate, overWrite, userdesc, req.getAllowForeignFiles(), req.getPreloadAllPackages()); resp.setFilesNotFound(filesNotFound); StringBuffer msg; msg.append("Successfully loaded ").append(name.get()); resp.updateStatus().setDescription(msg.str()); return true; }
void WebMemorySampler::writeHeaders() { String processDetails = String("Process: "); processDetails.append(processName()); processDetails.append(String("\n")); writeToFile(m_sampleLogFile, processDetails.utf8().data(), processDetails.utf8().length()); String header; WebMemoryStatistics stats = sampleWebKit(); if (!stats.keys.isEmpty()) { for (size_t i = 0; i < stats.keys.size(); ++i) { header.append(m_separator); header.append(stats.keys[i].utf8().data()); } } header.append(String("\n")); writeToFile(m_sampleLogFile, header.utf8().data(), header.utf8().length()); }
void logException( e_xbt_log_priority_t prio, const char* context, std::exception const& exception) { try { auto name = simgrid::xbt::demangle(typeid(exception).name()); auto with_context = dynamic_cast<const simgrid::xbt::WithContextException*>(&exception); if (with_context != nullptr) XBT_LOG(prio, "%s %s by %s/%d: %s", context, name.get(), with_context->processName().c_str(), with_context->pid(), exception.what()); else XBT_LOG(prio, "%s %s: %s", context, name.get(), exception.what()); // Do we have a backtrace? if (with_context != nullptr) { auto backtrace = simgrid::xbt::resolveBacktrace( with_context->backtrace().data(), with_context->backtrace().size()); for (std::string const& s : backtrace) XBT_LOG(prio, " -> %s", s.c_str()); } // Do we have a nested exception? auto with_nested = dynamic_cast<const std::nested_exception*>(&exception); if (with_nested == nullptr || with_nested->nested_ptr() == nullptr) return; try { with_nested->rethrow_nested(); } catch (std::exception& nested_exception) { logException(prio, "Caused by", nested_exception); } // We could catch nested_exception or WithContextException but we don't bother: catch (...) { XBT_LOG(prio, "Caused by an unknown exception"); } } catch (...) { // Don't log exceptions we got when trying to log exception } }
void LLAvatarNameCache::legacyNameCallback(const LLUUID& agent_id, const std::string& full_name, bool is_group) { // Construct a dummy record for this name. By convention, SLID is blank // Never expires, but not written to disk, so lasts until end of session. LLAvatarName av_name; LL_DEBUGS("AvNameCache") << "LLAvatarNameCache::legacyNameCallback " << "agent " << agent_id << " " << "full name '" << full_name << "'" << ( is_group ? " [group]" : "" ) << LL_ENDL; buildLegacyName(full_name, &av_name); // Don't add to cache, the data already exists in the legacy name system // cache and we don't want or need duplicate storage, because keeping the // two copies in sync is complex. processName(agent_id, av_name, false); }
void WebMemorySampler::stop() { if (!m_isRunning) return; m_sampleTimer.stop(); m_sampleLogFile = 0; printf("Stopped memory sampler for process %s\n", processName().utf8().data()); // Flush stdout buffer so python script can be guaranteed to read up to this point. fflush(stdout); m_isRunning = false; if(m_stopTimer.isActive()) m_stopTimer.stop(); if (m_sampleLogSandboxExtension) { m_sampleLogSandboxExtension->invalidate(); m_sampleLogSandboxExtension = 0; } }
void WebMemorySampler::writeHeaders() { String processDetails = String::format("Process: %s Pid: %d\n", processName().utf8().data(), getpid()); CString utf8String = processDetails.utf8(); writeToFile(m_sampleLogFile, utf8String.data(), utf8String.length()); StringBuilder header; WebMemoryStatistics stats = sampleWebKit(); if (!stats.keys.isEmpty()) { for (size_t i = 0; i < stats.keys.size(); ++i) { header.append(separator); header.append(stats.keys[i]); } } header.append('\n'); utf8String = header.toString().utf8(); writeToFile(m_sampleLogFile, utf8String.data(), utf8String.length()); }
bool Util::DarkRadiantIsRunning() { DWORD processes[1024]; DWORD num; if (!EnumProcesses(processes, sizeof(processes), &num)) { return false; } // Iterate over the processes for (int i = 0; i < int(num/sizeof(DWORD)); i++) { char szProcessName[MAX_PATH] = "unknown"; // Get the handle for this process HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, processes[i]); if (hProcess) { HMODULE hMod; DWORD countBytes; if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &countBytes)) { GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName)); std::string processName(szProcessName); boost::algorithm::to_lower(processName); if (processName == "darkradiant.exe") { CloseHandle(hProcess); // close the handle, we're terminating return true; } } } CloseHandle(hProcess); } return false; }
void LLAvatarNameCache::legacyNameCallback(const LLUUID& agent_id, const std::string& full_name, bool is_group) { // Construct a dummy record for this name. By convention, SLID is blank // Never expires, but not written to disk, so lasts until end of session. LLAvatarName av_name; LL_DEBUGS("AvNameCache") << "LLAvatarNameCache::legacyNameCallback " << "agent " << agent_id << " " << "full name '" << full_name << "'" << ( is_group ? " [group]" : "" ) << LL_ENDL; buildLegacyName(full_name, &av_name); // Add to cache, because if we don't we'll keep rerequesting the // same record forever. buildLegacyName should always guarantee // that these records expire reasonably soon // (in TEMP_CACHE_ENTRY_LIFETIME seconds), so if the failure was due // to something temporary we will eventually request and get the right data. processName(agent_id, av_name, true); }
void MemoryPressureHandler::pollMemoryPressure(void*) { ASSERT(!isMainThread()); bool critical; String processName(getProcessName()); do { if (s_pollMaximumProcessMemoryCriticalLimit) { size_t vmRSS = readToken(s_processStatus, "VmRSS:", KB); if (!vmRSS) return; if (vmRSS > s_pollMaximumProcessMemoryNonCriticalLimit) { critical = vmRSS > s_pollMaximumProcessMemoryCriticalLimit; break; } } else { size_t memFree = readToken(s_memInfo, "MemFree:", KB); if (!memFree) return; if (memFree < s_memNonCriticalLimit) { critical = memFree < s_memCriticalLimit; break; } } sleep(s_pollTimeSec); } while (true); if (ReliefLogger::loggingEnabled()) LOG(MemoryPressure, "Polled memory pressure (%s)", critical ? "critical" : "non-critical"); MemoryPressureHandler::singleton().setUnderMemoryPressure(critical); callOnMainThread([critical] { MemoryPressureHandler::singleton().respondToMemoryPressure(critical ? Critical::Yes : Critical::No); }); }
static bool defaultPollMaximumProcessMemory(size_t &criticalLimit, size_t &nonCriticalLimit) { // Syntax: Case insensitive, process name, wildcard (*), unit multipliers (M=Mb, K=Kb, <empty>=bytes). // Example: WPE_POLL_MAX_MEMORY='WPEWebProcess:500M,*Process:150M' String processName(getProcessName().convertToLowercaseWithoutLocale()); String s(getenv("WPE_POLL_MAX_MEMORY")); if (!s.isEmpty()) { Vector<String> entries; s.split(',', false, entries); for (const String& entry : entries) { Vector<String> keyvalue; entry.split(':', false, keyvalue); if (keyvalue.size() != 2) continue; String key = "*"+keyvalue[0].stripWhiteSpace().convertToLowercaseWithoutLocale(); String value = keyvalue[1].stripWhiteSpace().convertToLowercaseWithoutLocale(); size_t units = 1; if (value.endsWith('k')) units = 1024; else if (value.endsWith('m')) units = 1024 * 1024; if (units != 1) value = value.substring(0, value.length()-1); bool ok = false; size_t size = size_t(value.toUInt64(&ok)); if (!ok) continue; if (!fnmatch(key.utf8().data(), processName.utf8().data(), 0)) { criticalLimit = size * units; nonCriticalLimit = criticalLimit * 0.75; return true; } } } return false; }
/* Constructor for action parameter. */ CoinParam::CoinParam (std::string name, std::string help, bool display) : type_(coinParamAct), name_(name), lengthName_(0), lengthMatch_(0), lowerDblValue_(0.0), upperDblValue_(0.0), dblValue_(0.0), lowerIntValue_(0), upperIntValue_(0), intValue_(0), strValue_(), definedKwds_(), currentKwd_(0), pushFunc_(0), pullFunc_(0), shortHelp_(help), longHelp_(), display_(display) { processName() ; }
bool Util::TDMIsRunning() { DWORD processes[1024]; DWORD num; if (!EnumProcesses(processes, sizeof(processes), &num)) { return false; } // Iterate over the processes for (int i = 0; i < int(num/sizeof(DWORD)); i++) { char szProcessName[MAX_PATH] = "unknown"; // Get the handle for this process HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, processes[i]); if (hProcess) { HMODULE hMod; DWORD countBytes; if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &countBytes)) { GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName)); std::string processName(szProcessName); // grayman - This was checking for "Doom3.exe". Starting with 1.08, the D3 // executable is no longer needed to run TDM, so we'll check for TheDarkMod.exe // instead. if (processName == "TheDarkMod.exe") { // At this point, we know we need to quit. There's no longer a need // to check for "gamex86.dll". /* HMODULE hModules[1024]; DWORD cbNeeded; if (EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbNeeded)) { for (unsigned int m = 0; m < (cbNeeded / sizeof(HMODULE)); m++) { TCHAR szModName[MAX_PATH]; // Get the full path to the module's file. if (GetModuleBaseName(hProcess, hModules[m], szModName, sizeof(szModName)/sizeof(TCHAR))) { // Print the module name and handle value. if (std::string(szModName) == "gamex86.dll") { CloseHandle(hProcess); // close the handle, we're terminating return true; } } } } */ // instead, quit CloseHandle(hProcess); // close the handle, we're terminating return true; } } } CloseHandle(hProcess); } return false; }
inline void setName(std::string name) { name_ = name ; processName() ; }
DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpackage::DropPartitionStatement& dropPartitionStmt) { SUMMARY_INFO("DropPartitionProcessor::processPackage"); DDLResult result; result.result = NO_ERROR; std::string err; VERBOSE_INFO(dropPartitionStmt); // Commit current transaction. // all DDL statements cause an implicit commit VERBOSE_INFO("Getting current txnID"); int rc = 0; rc = fDbrm->isReadWrite(); BRM::TxnID txnID; txnID.id= fTxnid.id; txnID.valid= fTxnid.valid; if (rc != 0 ) { logging::Message::Args args; logging::Message message(9); args.add("Unable to execute the statement due to DBRM is read only"); message.format(args); result.result = DROP_ERROR; result.message = message; fSessionManager.rolledback(txnID); return result; } std::vector <CalpontSystemCatalog::OID> oidList; CalpontSystemCatalog::RIDList tableColRidList; CalpontSystemCatalog::DictOIDList dictOIDList; execplan::CalpontSystemCatalog::ROPair roPair; uint32_t processID = 0; u_int64_t uniqueID = 0; uint32_t sessionID = dropPartitionStmt.fSessionID; std::string processName("DDLProc"); u_int64_t uniqueId = 0; //Bug 5070. Added exception handling try { uniqueId = fDbrm->getUnique64(); } catch (std::exception& ex) { logging::Message::Args args; logging::Message message(9); args.add(ex.what()); message.format(args); result.result = ALTER_ERROR; result.message = message; fSessionManager.rolledback(txnID); return result; } catch ( ... ) { logging::Message::Args args; logging::Message message(9); args.add("Unknown error occured while getting unique number."); message.format(args); result.result = ALTER_ERROR; result.message = message; fSessionManager.rolledback(txnID); return result; } string stmt = dropPartitionStmt.fSql + "|" + dropPartitionStmt.fTableName->fSchema +"|"; SQLLogger logger(stmt, fDDLLoggingId, sessionID, txnID.id); try { //check table lock CalpontSystemCatalog *systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(dropPartitionStmt.fSessionID); systemCatalogPtr->identity(CalpontSystemCatalog::EC); systemCatalogPtr->sessionID(dropPartitionStmt.fSessionID); CalpontSystemCatalog::TableName tableName; tableName.schema = dropPartitionStmt.fTableName->fSchema; tableName.table = dropPartitionStmt.fTableName->fName; roPair = systemCatalogPtr->tableRID( tableName ); //@Bug 3054 check for system catalog if ( roPair.objnum < 3000 ) { throw std::runtime_error("Drop partition cannot be operated on Calpont system catalog."); } int i = 0; processID = ::getpid(); oam::OamCache * oamcache = OamCache::makeOamCache(); std::vector<int> pmList = oamcache->getModuleIds(); std::vector<uint> pms; for (unsigned i=0; i < pmList.size(); i++) { pms.push_back((uint)pmList[i]); } try { uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); } catch (std::exception&) { result.result = DROP_ERROR; result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE); // no need to release lock. dbrm un-hold the lock fSessionManager.rolledback(txnID); return result; } if ( uniqueID == 0 ) { int waitPeriod = 10; int sleepTime = 100; // sleep 100 milliseconds between checks int numTries = 10; // try 10 times per second waitPeriod = Config::getWaitPeriod(); numTries = waitPeriod * 10; struct timespec rm_ts; rm_ts.tv_sec = sleepTime/1000; rm_ts.tv_nsec = sleepTime%1000 *1000000; for (; i < numTries; i++) { #ifdef _MSC_VER Sleep(rm_ts.tv_sec * 1000); #else struct timespec abs_ts; do { abs_ts.tv_sec = rm_ts.tv_sec; abs_ts.tv_nsec = rm_ts.tv_nsec; } while(nanosleep(&abs_ts,&rm_ts) < 0); #endif // reset sessionID = dropPartitionStmt.fSessionID; txnID.id= fTxnid.id; txnID.valid= fTxnid.valid; processID = ::getpid(); processName = "DDLProc"; try { uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); } catch (std::exception&) { result.result = DROP_ERROR; result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE); fSessionManager.rolledback(txnID); return result; } if (uniqueID > 0) break; } if (i >= numTries) //error out { result.result = DROP_ERROR; logging::Message::Args args; args.add(processName); args.add((uint64_t)processID); args.add((uint64_t)sessionID); result.message = Message(IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED,args)); fSessionManager.rolledback(txnID); return result; } } // 1. Get the OIDs for the columns // 2. Get the OIDs for the dictionaries // 3. Save the OIDs to a log file // 4. Disable the extents from extentmap for the partition // 5. Remove the column and dictionary files for the partition // 6. Flush PrimProc Cache // 7. Remove the extents from extentmap for the partition CalpontSystemCatalog::TableName userTableName; userTableName.schema = dropPartitionStmt.fTableName->fSchema; userTableName.table = dropPartitionStmt.fTableName->fName; tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); //Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format for ( unsigned i=0; i < tableColRidList.size(); i++ ) { if ( tableColRidList[i].objnum > 3000 ) oidList.push_back( tableColRidList[i].objnum ); } for ( unsigned i=0; i < dictOIDList.size(); i++ ) { if ( dictOIDList[i].dictOID > 3000 ) oidList.push_back( dictOIDList[i].dictOID ); } //Mark the partition disabled from extent map string emsg; rc = fDbrm->markPartitionForDeletion( oidList, dropPartitionStmt.fPartitions, emsg); if (rc != 0 && rc !=BRM::ERR_PARTITION_DISABLED && rc != BRM::ERR_INVALID_OP_LAST_PARTITION && rc != BRM::ERR_NOT_EXIST_PARTITION) { throw std::runtime_error(emsg); } set<BRM::LogicalPartition> markedPartitions; set<BRM::LogicalPartition> outOfServicePartitions; // only log partitions that are successfully marked disabled. rc = fDbrm->getOutOfServicePartitions(oidList[0], outOfServicePartitions); if (rc != 0) { string errorMsg; BRM::errString(rc, errorMsg); ostringstream oss; oss << "getOutOfServicePartitions failed due to " << errorMsg; throw std::runtime_error(oss.str()); } set<BRM::LogicalPartition>::iterator it; for (it = dropPartitionStmt.fPartitions.begin(); it != dropPartitionStmt.fPartitions.end(); ++it) { if (outOfServicePartitions.find(*it) != outOfServicePartitions.end()) markedPartitions.insert(*it); } //Save the oids to a file createWritePartitionLogFile( roPair.objnum, markedPartitions, oidList, uniqueId); VERBOSE_INFO("Removing files"); removePartitionFiles( oidList, markedPartitions, uniqueId ); //Flush PrimProc cache for those lbids rc = cacheutils::flushPartition( oidList, markedPartitions ); //Remove the partition from extent map emsg.clear(); rc = fDbrm->deletePartition( oidList, dropPartitionStmt.fPartitions, emsg); if ( rc != 0 ) throw std::runtime_error(emsg); } catch (exception& ex) { cerr << "DropPartitionProcessor::processPackage: " << ex.what() << endl; logging::Message::Args args; logging::Message message(ex.what()); if (rc == BRM::ERR_TABLE_NOT_LOCKED) result.result = USER_ERROR; else if (rc == BRM::ERR_NOT_EXIST_PARTITION || rc == BRM::ERR_INVALID_OP_LAST_PARTITION) result.result = PARTITION_WARNING; else if (rc == BRM::ERR_NO_PARTITION_PERFORMED) result.result = WARN_NO_PARTITION; else result.result = DROP_ERROR; result.message = message; try { fDbrm->releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE); } fSessionManager.rolledback(txnID); return result; } catch (...) { cerr << "DropPartitionProcessor::processPackage: caught unknown exception!" << endl; logging::Message::Args args; logging::Message message(1); args.add("Drop partition failed: "); args.add( "encountered unkown exception" ); args.add(""); args.add(""); message.format( args ); result.result = DROP_ERROR; result.message = message; try { fDbrm->releaseTableLock(uniqueID); } catch (std::exception&) { result.result = DROP_ERROR; result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE); } fSessionManager.rolledback(txnID); return result; } // Log the DDL statement logging::logDDL(dropPartitionStmt.fSessionID, txnID.id, dropPartitionStmt.fSql, dropPartitionStmt.fOwner); //Remove the log file //release the transaction try { fDbrm->releaseTableLock(uniqueID); deleteLogFile(DROPPART_LOG, roPair.objnum, uniqueId); } catch (std::exception&) { result.result = DROP_ERROR; result.message = IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE); fSessionManager.rolledback(txnID); return result; } fSessionManager.committed(txnID); return result; }
void WebMemorySampler::initializeTempLogFile() { m_sampleLogFilePath = openTemporaryFile(processName(), m_sampleLogFile); writeHeaders(); }