BasicWorldState::BasicWorldState (DisseminationService *pDisService) : PeerState (PeerState::NEIGHBOR_STATES), _remoteNodes (true, true, true, true), _neighborStates(true, true, true, true) { _pDisService = pDisService; ConfigFileReader cfgReader (pDisService->_pCfgMgr); _bDataCacheStateSeqId = cfgReader.isDataCacheStateEnabled(); _bTopologyStateSeqId = cfgReader.isTopologyStateEnabled(); _bSubscriptionStateSeqId = cfgReader.isSubscriptionStateEnabled(); _ui32DataCacheStateSeqId = _ui32TopologyStateSeqId = _ui32SubscriptionStateSeqId = 1; _ui32DeadPeerInterval = DisseminationService::DEFAULT_DEAD_PEER_INTERVAL; }
void TestExecutor::handle(ConfigFileReader& testSettings) { auto testCases = testSettings.getSettings(); for(auto testCase: testCases) { shared_ptr<TestBase> currentTestCase; if(testCase.second.find("disabled") != testCase.second.end()) continue; if(endsWith(testCase.first,"TransportTest")) currentTestCase.reset(new ClientTransportTest<BasicTransportTask<char*>>(testCase.first)); else if(endsWith(testCase.first, "CreateStoreTest-AllTypes")) currentTestCase.reset(new CreateStoreTestAllTypes<BasicTaskExecution<shared_ptr< ::google::protobuf::Message>>>(testCase.first)); else if(endsWith(testCase.first, "DropStoreTest-AllTypes")) currentTestCase.reset(new DropStoreTestAllTypes<BasicTaskExecution<shared_ptr< ::google::protobuf::Message>>>(testCase.first)); else if(endsWith(testCase.first, "SetTest-Simple")) currentTestCase.reset(new SetTestSimple<BasicTaskExecution<shared_ptr< ::google::protobuf::Message>>>(testCase.first)); else if(endsWith(testCase.first, "DeleteTest-Simple")) currentTestCase.reset(new DeleteTestSimple<BasicTaskExecution<shared_ptr< ::google::protobuf::Message>>>(testCase.first)); else if(endsWith(testCase.first, "GetTest-Simple")) currentTestCase.reset(new GetTestSimple<BasicTaskExecution<shared_ptr< ::google::protobuf::Message>>>(testCase.first)); else if(endsWith(testCase.first, "PruneIndexScan")) currentTestCase.reset(new PruneIndexScan<BasicTaskExecution<shared_ptr< ::google::protobuf::Message>>>(testCase.first)); if(currentTestCase.get()) currentTestCase->run(testCase.second); } FILE_LOG(logINFO)<<"Finished Tests"; }
bool ConfigParamsHomog::initParamsFromConfigFile(std::string &configFilePath) { // initialize the config file reader with the input config file ConfigFileReader cfr; try { cfr.readFile(configFilePath.c_str()); } catch(const libconfig::FileIOException) { std::cerr << "I/O error while reading file." << std::endl; return false; } catch(const libconfig::ParseException &pex) { std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine() << " - " << pex.getError() << std::endl; return false; } // now read in parameters try { // usac parameters if (!initUSACParamsFromConfigFile(cfr)) { std::cerr << "Error reading USAC parameters from config file." << std::endl; return false; } // homog parameters if ( !cfr.getTopLevelParameterValue("problem_specific", "input_file_path", homog.inputFilePath) ) { return false; } } catch(...) { return false; } return true; }
vector<queuedFile> ReadConfiguration(wstring const& filename) { vector<queuedFile> retv; // Read each line // if the line begins with a ';' discard it // strip out the whitespace at the beginning FileHandle hFile = CreateFile(filename.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { return retv; } // We will assume the config file is less than 4GB long. If you have one that big, the error is yours string buffer; buffer.resize(GetFileSize(hFile, NULL) + 1); buffer[buffer.size()-1] = 0; DWORD readLen = 0; ReadFile(hFile, &buffer[0], buffer.size()-1, &readLen, NULL); vector<string> validLines = ConvertBufferToLines(buffer); return ProcessConfig(validLines); }
int _tmain(int argc, _TCHAR* argv[]) { // Initialize GUIDs CLSIDFromString(GUID_IOTechDeviceString, &GUID_IOTechDevice); CLSIDFromString(GUID_InternalTimerString, &GUID_InternalTimer); // Start by reading the config file into the dicitonary InterpretConfigurationResourceFields(L"devicesConfiguration", DeviceHolder::DictionaryBuilder(g_devices)); InterpretConfigFields icf; ReadConfigurationFields(argc, argv, icf); internalTime boundary = GetTimeBoundary(secondsBoundary); FindNextTimeInTheFuture(*boundary.UINT64Ptr(), secondsBoundary * oneSecond); internalTime dummy = boundary;// - (internalTime)internalTime::SystemTimeMinusLocalTime(); SYSTEMTIME systemTime; FileTimeToSystemTime(dummy.FileTimePtr(), &systemTime); wstring filename; UCSBUtility::CreateDirectoryGetFilename(rootDirectory, L".spaceball", filename); g_hFile = CreateFile(filename.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL); g_devices.CreateFileHeader(g_hFile); EncoderWrapper encoder(g_hFile, boardName, readRate); HANDLE hThreads[] = { Periodic::CreateTimedThreadRef(encoder, 100) }; printf("press any key to stop data collection\n"); while (!g_quit) { if (_kbhit()) { _getch(); g_quit = true; break; } // If we need a new file, open it and write the header to it // Once that is done, transfer all the data to collect to that one if (internalTime::Now() > boundary) { wstring filename; UCSBUtility::CreateDirectoryGetFilename(rootDirectory, L".spaceball", filename); HANDLE hFile = CreateFile(filename.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL); g_devices.CreateFileHeader(hFile); HANDLE hTemp = g_hFile; g_hFile = hFile; CloseHandle(hTemp); FindNextTimeInTheFuture(*boundary.UINT64Ptr(), secondsBoundary * oneSecond); } Sleep (50); } WaitForMultipleObjects(_countof(hThreads), hThreads, true, INFINITE); return 0; }
int main(int argc, char **argv) { int ret= 0; int ok= parseCommandLine(argc, argv); #if defined(DEBUG_MEM) atexit(_CheckMemLeaks); #endif #if defined(__FreeBSD__) //set_terminate( term_exception ); setlocale(LC_TIME, "fr_FR.ISO8859-1"); //signal(SIGINT, sigINT); signal(SIGPIPE, SIG_IGN); #elif defined(WIN32) setlocale(LC_TIME, "French"); WSAData wsaData; main_thread= GetCurrentThread(); console.run(); sleep(1); # if defined(_DEBUG) && defined(_MSC_VER) // add breakpoint when memory block n is allocated // _crtBreakAlloc //_CrtSetBreakAlloc(n); //_CrtSetBreakAlloc(10193); //_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF | // _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_CHECK_CRT_DF | _CRTDBG_DELAY_FREE_MEM_DF); # endif if( WSAStartup(MAKEWORD(1,1), &wsaData) != 0) { Error("Unable to initialise network: %d\n", WSAGetLastError()); } else { #endif Output("Dryon v" BOT_VERSION " compiled on " __DATE__ "\n"); Output("Embedded AMX: v" SMALL_VERSION "\n"); Output("Embedded Ruby: v" RUBY_VERSION "\n"); if( ok != 0 ) { usleep(10000); return 1; } if( help_mode ) { Output("Usage: %s [option(s)]\n", basename(argv[0])); Output("--test enable test mode\n"); Output("--help display help\n"); Output("--hidden start hidden (windows)\n"); Output("--config xxx set dryon.cfg file\n"); Output("--servers xxx set servers.txt file\n"); Output("--userfile xxx set userfile.txt file\n"); usleep(10000); return 0; } cfg.setFile( configfile_path.c_str() ); /* some checks on required folders/files */ if( makeSanityChecks() == 0 ) { bool err= false; cfg.readFile(); #define CHECK_CFG_VAR(X) if( !cfg.isDefined(#X) ){ Error("variable '" #X "' undefined\n"); err= true; } // check if required config directives are set CHECK_CFG_VAR( botname ); CHECK_CFG_VAR( alt_nick ); CHECK_CFG_VAR( realname ); CHECK_CFG_VAR( useauth ); CHECK_CFG_VAR( script_01); // if one or more vars are undefined then exit now // exit also if the compilation of scripts fails if( !err && (PMgr.loadScriptsFromCfg(cfg) == 0) ) { //// compile/test the scripts ///// if( test_mode ) { Output("** TEST MODE **\n"); PMgr.callEvent("event_onTest"); } /////////// else { string last_srv= "", srv= ""; cfg.readFile(); userfile.readUserFile( userfile_path.c_str() ); servers.loadFromFile( serverlist_path.c_str() ); while(1) { int ret; if( cfg.isDefined("debugmode") ) bot.setIntOption(OPTION_INT_DEBUGMODE, cfg.readIntKey("debugmode")); else bot.setIntOption(OPTION_INT_DEBUGMODE, 0); bot.setIntOption(OPTION_INT_USEAUTH, cfg.readBoolKey("useauth")?1:0); bot.setStrOption(OPTION_STR_REALNAME, cfg.readStringKey("realname")); bot.setStrOption(OPTION_STR_ALTNICK, cfg.readStringKey("alt_nick")); srv= servers.getNextServer(); // if the server is the same than the last one we tried, wait 2min // before trying to reconnect to be nice with the server :) if( srv == "" ) { Error("No servers in servers.txt, exiting...\n"); break; } else if( srv == last_srv ) { Debug("Waiting 2min before reconnect attempt...\n"); sleep(120); } // if exceptions occur then they came from the STL since // i don't use them try { ret= bot.mainLoop(srv, cfg.readStringKey("botname")); } catch( exception &e ) { Error("exception: %s\n", e.what()); } last_srv= srv; if( ret!=0 ) { Debug("Exiting...\n"); break; } PMgr.callEvent("event_onBotDisconnected"); } } } else { Output("Errors during loading/compilation\n"); ret= 1; } } else { ret= 1; } #if defined(WIN32) } #endif // i had problems when the bot exited immediatly from an error // the thread didn't had time to initialiase before exiting and this resulted // in a seg fault, with a small delay it works fine :) usleep(10000); #if defined(WIN32) WSACleanup(); Output("%sBot exited successfully, you can now close the window.%s\n", COLOR_GREEN, COLOR_RESET); // console.requestEnd(); // console.waitEnd(); #endif return ret; }
void DryonBot::onPrivMsg(const string &sender, const string &dest, const string &msg) { vector<string> msg_parts; Tokenize(msg, msg_parts, " "); user_Info *usr; GET_USR(usr, sender); const string &command= msg_parts[0].substr(1); // load user flags from userfile.txt checkUserFlags(usr, dest); if( command=="reload" ) { /* if user has owner flag then reload all config files */ if( usr->hasFlag(USRLVL_OWNER) ) { // force update of user flags for(userDataTypeIter it= userData.begin(); it!= userData.end(); it++) (*it).second.flags_set= false; servers.loadFromFile("servers.txt"); userfile.saveFile(); userfile.readUserFile(); cfg.readFile(); PMgr.loadScriptsFromCfg(cfg); } return; } // user list else if( command=="userlist" ) { if( usr->hasAccount() && usr->hasFlag(USRLVL_OWNER) ) { map<string, UsersData> &ulist= userfile.getAccessList(); notice(sender, "User list: %d entries", ulist.size()); notice(sender, "-------- Start (Show accounts and global flags) --------"); for(map<string, UsersData>::iterator it= ulist.begin(); it!=ulist.end(); it++) { string what= it->first; if( (what[0]=='a') && (what[1]=='/') ) { what= '#' + what.substr(2); } notice(sender, "%15s %35s %5s", it->second.name.c_str(), what.c_str(), it->second.flags.c_str()); } notice(sender, "-------- End --------"); } return; } else if( command == "showflags" ) { if( usr->hasAccount() && usr->hasFlag(USRLVL_MASTER) ) { map<string, UsersData> &ulist= userfile.getAccessList(); string &chan= msg_parts[1]; notice(sender, "User list for %s", chan.c_str()); for(map<string, UsersData>::iterator it= ulist.begin(); it!=ulist.end(); it++) { string what= it->first; UsersData &tmp= it->second; for(map<string,string>::iterator it2= tmp.channel_flags.begin(); it2 != tmp.channel_flags.end(); it2++) { if( it2->first == chan ) notice(sender, "%15s %5s", it->second.name.c_str(), it2->second.c_str()); } } notice(sender, "-------- End --------"); } } // return a list of loaded plugins else if( command=="scripts" ) { uint count= PMgr.getPluginCount(); for(int i= count-1; i>= 0; i--) { notice(sender, "%2d ) %s\n", i, PMgr.getPlugin(i)->getPath()); } } else if( command=="quit" ) { if( usr->hasFlag(USRLVL_OWNER) ) { quit("exit requested"); } return; } else if( command=="help" ) { if( usr->hasAccount() ) { notice(sender, "Core commands:"); if( usr->hasFlag(USRLVL_OWNER) ) { notice(sender, ":reload - reload all plugins and config file"); notice(sender, ":userlist - display user list"); } notice(sender, ":help - display this :<"); notice(sender, ":scripts - display list of currently loaded scripts"); notice(sender, "---"); PMgr.sendCommandsList(sender, dest, usr); //return; } } else if( command=="nfo" ) { if( msg_parts.size() == 1 ) { Output("Nick: '%s'\n", bot_data.nick.c_str()); Output("Host: '%s'\n", bot_data.full_host.c_str()); Output("Auth: '%s'\n", bot_data.auth.c_str()); } else if( msg_parts.size() >= 2 ) { user_Info *u= getUserData(msg_parts[1]); if( u!=NULL ) { Output("Nick: '%s'\n", u->nick.c_str()); Output("Host: '%s'\n", u->full_host.c_str()); Output("Auth: '%s'\n", u->auth.c_str()); } else { notice(sender, "Nick unknown: %s", msg_parts[1].c_str()); } } } else { chan_Info *chan; if( isChannelName(dest) ) { GET_CHAN(chan, dest); PMgr.callEvent("event_onPrivMsg", "ucv", usr, chan, &msg_parts); PMgr.callCommand(usr, (dummy_Info*)chan, msg_parts); } else { PMgr.callEvent("event_onPrivMsg", "uuv", usr, &bot_data, &msg_parts); PMgr.callCommand(usr, (dummy_Info*)&bot_data, msg_parts); } } }
bool ConfigManager::init() { char * confDir = getenv("CALVR_CONFIG_DIR"); if(confDir) { _configDir = confDir; } else { _configDir = CalVR::instance()->getConfigDir(); } std::string file; char * confFile = getenv("CALVR_CONFIG_FILE"); if(confFile) { file = confFile; } else { std::cerr << "Warning: CALVR_CONFIG_FILE not set, using config.xml." << std::endl; file = "config.xml"; } if(file.empty()) { std::cerr << "Error: CALVR_CONFIG_FILE is empty." << std::endl; return false; } std::vector<std::string> fileList; size_t pos = 0; while((pos = file.find_first_of(':')) != std::string::npos) { if(pos) { fileList.push_back(file.substr(0,pos)); } if(pos + 1 < file.size()) { file = file.substr(pos + 1,file.size() - (pos + 1)); } else { break; } } if(file.size()) { fileList.push_back(file); } if(!fileList.size()) { std::cerr << "Error: no valid config file in CALVR_CONFIG_FILE" << std::endl; return false; } for(int i = 0; i < fileList.size(); i++) { size_t pos = fileList[i].find_last_of('.'); if(pos == std::string::npos || pos + 1 == fileList[i].size()) { std::cerr << "ConfigManager: Error: Unable to find extension for file: " << fileList[i] << std::endl; return false; } std::string extension = fileList[i].substr(pos + 1, fileList[i].size() - (pos + 1)); std::transform(extension.begin(),extension.end(),extension.begin(), ::tolower); ConfigFileReader * cfr = NULL; if(extension == "xml") { cfr = new XMLReader(); } else { std::cerr << "ConfigManager: Error: No reader could be identified for file: " << fileList[i] << std::endl; return false; } if(cfr) { cfr->setDebugOutput(true); if(cfr->loadFile(fileList[i])) { _configFileList.push_back(cfr); } else { std::cerr << "ConfigManager: Error loading config files." << std::endl; delete cfr; return false; } cfr->setDebugOutput(false); } else { std::cerr << "ConfigManager: Error: ConfigFileReader pointer is NULL. file: " << fileList[i] << std::endl; return false; } } _debugOutput = getBool("ConfigDebug",false); for(int i = 0; i < _configFileList.size(); i++) { _configFileList[i]->setDebugOutput(_debugOutput); } return true; }
//// Sets the input value to a time in the future //int FindNextTimeInTheFuture(UINT64& nextTime, UINT64 interval) //{ // int skipped = 0; // // UINT64 now = internalTime::Now() + oneSecond / 100; // // if (nextTime <= now) // { // UINT64 diff = now - nextTime; // skipped = static_cast<int>((diff / interval) + 1); // nextTime += skipped * interval; // } // // return skipped; //} // // Interpret the configuration file // all lines that start with ';' are comments // valid lines have the format // [url] [dest] [hh:mm:ss] [hh:mm:ss] // where the first [hh:mm:ss] is the time of day to start downloading // and the second is the amount of time between downloads vector<queuedFile> ProcessConfig(vector<string> const& validLines) { vector<queuedFile> retv; for(vector<string>::const_iterator cit = validLines.begin(); cit < validLines.end(); ++cit) { queuedFile qf; vector<string> fields = ConvertLineToFields(*cit); if (fields.size() < 4) { // Malformed line found UCSBUtility::LogError(__FUNCTION__, __FILE__, __LINE__, "skipping malformed line:\n%s\n", cit->c_str()); continue; } // Check to see if the first field is FLIR if (fields[0] == "FLIR") { qf.isFLIR = true; } else { // Now just extract the data wstring source = StupidConvertToWString(fields[0]); URL_COMPONENTS urlParts = { sizeof(URL_COMPONENTS) }; urlParts.dwHostNameLength = source.length(); urlParts.dwUrlPathLength = source.length(); InternetCrackUrl(source.c_str(), 0, 0, &urlParts); qf.sourceServer = wstring(urlParts.lpszHostName, urlParts.lpszHostName + urlParts.dwHostNameLength); qf.sourceResource = wstring (urlParts.lpszUrlPath, urlParts.lpszUrlPath + urlParts.dwUrlPathLength); } qf.destinationRootName = StupidConvertToWString(fields[1]); qf.startTime = ConvertStringToInt64Time(fields[2]); qf.downloadInterval = ConvertStringToInt64Time(fields[3]); UINT64 now = internalTime::Now(); // If we have a don't care state, for start time use now if (qf.startTime == 0) { qf.startTime = now; } else { qf.startTime = ConvertStringToInt64TimeToday(fields[2]); FindNextTimeInTheFuture(qf.startTime, qf.downloadInterval); } if (qf.isFLIR) { if (fields.size() <= 4) { UCSBUtility::LogError(__FUNCTION__, __FILE__, __LINE__, "skipping malformed line:\n%s\n", cit->c_str()); continue; } qf.flatFieldFrameInterval = atoi(fields[4].c_str()); } else if (fields.size() > 4) { qf.username = StupidConvertToWString(fields[4]); } if (fields.size() > 5) { qf.password = StupidConvertToWString(fields[5]); } retv.push_back(qf); } return retv; }
Configuration::Configuration() { ConfigFileReader reader; reader.ReadFile(CONFIG_PATH, this); }