void Dying::refresh() { ErrorLogger* logger = ErrorLogger::Instance(); int ret = executable->getBroker()->running(); if(ret == 0) Dying::moduleFailed(); else if(ret == -1) logger->addError(executable->getBroker()->error()); }
bool XmlModLoader::init() { module.clear(); fileNames.clear(); ErrorLogger* logger = ErrorLogger::Instance(); /** * loading single module indicated by its xml file name */ if(!strFileName.empty()) { fileNames.push_back(strFileName); return true; } if(strPath.empty()) { logger->addError("No module path is introduced."); return false; } DIR *dir; struct dirent *entry; if ((dir = opendir(strPath.c_str())) == nullptr) { OSTRINGSTREAM err; err<<"Cannot access "<<strPath; logger->addError(err); return false; } /* we need to load all xml modules */ while((entry = readdir(dir))) { string name = entry->d_name; if(name.size() > 3) { string ext = name.substr(name.size()-3,3); if(compareString(ext.c_str(), "xml")) fileNames.push_back(strPath+name); } } closedir(dir); /* if(fileNames.empty()) { OSTRINGSTREAM err; err<<"No xml module file found in "<<strPath; logger->addWarning(err); //return true; } */ return true; }
// refresh() from Suspended can be used for recovering from // unexptected termination of manager. void Suspended::refresh(void) { ErrorLogger* logger = ErrorLogger::Instance(); int ret = executable->getBroker()->running(); if(ret == 1) { executable->getEvent()->onExecutableStart(executable); castEvent(EventFactory::recoverEvent); } else if(ret == -1) logger->addError(executable->getBroker()->error()); }
bool Arbitrator::trainWeights(const char* opnd) { __CHECK_NULLPTR(opnd); ErrorLogger* logger = ErrorLogger::Instance(); string rule = getRule(opnd); if(!rule.length()) { std::map<std::string, double> w; alphas[opnd] = w; biases[opnd] = 1.0; return true; } BinaryExpParser parser; std::map<string, string>::iterator itr; for(itr=rules.begin(); itr!=rules.end(); itr++) parser.addRestrictedOperand((itr->first).c_str()); // parsing the compact logic rule = string(opnd) + " : " + rule; if(!parser.parse(rule.c_str())) return false; // trining the weights LinkTrainer trainer; if(trainer.train(parser.getTruthTable())) { biases[opnd] = trainer.getBias(); std::vector<double> alf = trainer.getAlphas(); std::map<std::string, double> w; std::map<std::string, bool>::iterator itr; std::map<std::string, bool> operands = parser.getOperands(); int i=0; for(itr=operands.begin(); itr!=operands.end(); itr++) { w[itr->first] = alf[i]; i++; } alphas[opnd] = w; } else { logger->addError("Maximum number of iterations is reached without finding any solution. Check for the correctness of the expression logic."); return false; } return true; }
void YConsoleManager::reportErrors(void) { ErrorLogger* logger = ErrorLogger::Instance(); if(logger->errorCount() || logger->warningCount()) { const char* msg; while((msg=logger->getLastError())) cout<<FAIL<<"ERROR: "<<INFO<<msg<<ENDC<<endl; while((msg=logger->getLastWarning())) cout<<WARNING<<"WARNING: "<<INFO<<msg<<ENDC<<endl; } }
bool SingleAppLoader::init(void) { ErrorLogger* logger = ErrorLogger::Instance(); app.clear(); if(strModule.empty()) { logger->addError("Empty module name."); return false; } app.setName(strModule.c_str()); ModuleInterface module(strModule.c_str()); module.setHost(strHost.c_str()); app.addImodule(module); return true; }
void Dying::killModule(void) { ErrorLogger* logger = ErrorLogger::Instance(); if(!executable->getBroker()->kill()) { OSTRINGSTREAM msg; msg<<"cannot kill "<<executable->getCommand()<<" on "<<executable->getHost(); if(executable->getBroker()->error()) msg<<" : "<<executable->getBroker()->error(); logger->addError(msg); executable->getEvent()->onError(executable); castEvent(EventFactory::killModuleEventFailed); } else { castEvent(EventFactory::killModuleEventOk); executable->getEvent()->onExecutableDied(executable); } }
void Dying::disconnectAllPorts(void) { ErrorLogger* logger = ErrorLogger::Instance(); if(executable->autoConnect()) { CnnIterator itr; for(itr=executable->getConnections().begin(); itr!=executable->getConnections().end(); itr++) { if( !executable->getBroker()->disconnect((*itr).from(), (*itr).to()) ) { OSTRINGSTREAM msg; msg<<"cannot disconnect "<<(*itr).from() <<" to "<<(*itr).to(); if(executable->getBroker()->error()) msg<<" : "<<executable->getBroker()->error(); logger->addError(msg); } else executable->getEvent()->onCnnReleased(&(*itr)); } } // We do not need to handle event disconnectAllPortsEventOk }
void SafeManager::onExecutableFailed(void* which) { WAIT_SEMAPHOR(); ErrorLogger* logger = ErrorLogger::Instance(); Executable* exe = static_cast<Executable*>(which); if(exe) { if(m_pConfig->find("module_failure").asString() == "prompt") { OSTRINGSTREAM err; err<<exe->getCommand()<<" from "<<exe->getHost()<<" is failed! [id:"<<exe->getID()<<"]"; logger->addError(err); if(eventReceiver && exe) eventReceiver->onModStop(exe->getID()); } if(m_pConfig->find("module_failure").asString() == "recover") { OSTRINGSTREAM err; err<<exe->getCommand()<<" from "<<exe->getHost()<<" is failed! [id:"<<exe->getID()<<"] (restarting...)"; logger->addError(err); exe->start(); } if(m_pConfig->find("module_failure").asString() == "terminate") { OSTRINGSTREAM err; err<<exe->getCommand()<<" from "<<exe->getHost()<<" is failed! [id:"<<exe->getID()<<"] (terminating...)"; logger->addError(err); Manager::stop(); } } if(eventReceiver) eventReceiver->onError(); POST_SEMAPHOR(); }
void Dying::stopModule() { ErrorLogger* logger = ErrorLogger::Instance(); if (executable->getPostStopWait() > 0) { yarp::os::SystemClock::delaySystem(executable->getPostStopWait()); } executable->restoreOriginalPostStopWait(); if(!executable->getBroker()->stop()) { OSTRINGSTREAM msg; msg<<"cannot stop "<<executable->getCommand()<<" on "<<executable->getHost(); if(executable->getBroker()->error()) msg<<" : "<<executable->getBroker()->error(); logger->addError(msg); executable->getEvent()->onError(executable); castEvent(EventFactory::stopModuleEventFailed); } else { castEvent(EventFactory::stopModuleEventOk); executable->getEvent()->onExecutableStop(executable); } }
bool CheckNullPointer::analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) { if (!ctu) return false; bool foundErrors = false; (void)settings; // This argument is unused const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> callsMap = ctu->getCallsMap(); for (Check::FileInfo *fi1 : fileInfo) { const MyFileInfo *fi = dynamic_cast<MyFileInfo*>(fi1); if (!fi) continue; for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafeUsage) { for (int warning = 0; warning <= 1; warning++) { if (warning == 1 && !settings.isEnabled(Settings::WARNING)) break; const std::list<ErrorLogger::ErrorMessage::FileLocation> &locationList = ctu->getErrorPath(CTU::FileInfo::InvalidValueType::null, unsafeUsage, callsMap, "Dereferencing argument ARG that is null", nullptr, warning); if (locationList.empty()) continue; const ErrorLogger::ErrorMessage errmsg(locationList, emptyString, warning ? Severity::warning : Severity::error, "Null pointer dereference: " + unsafeUsage.myArgumentName, "ctunullpointer", CWE476, false); errorLogger.reportErr(errmsg); foundErrors = true; break; } } } return foundErrors; }
bool compile(const std::string& file) { std::ifstream fin(file.c_str()); if (!fin.is_open()) { reporter_->fileNotFound(file); return false; } if (boost::optional<cst::Module> module = parseFile(file, fin, logger_)) { ast::Module parsed = parseModule(*module, logger_); if (!logger_.errors().empty()) return true; FunctionAddrMap fam; generateBytecode(parsed, fam).swap(bytecode_); } return true; }
Module* XmlModLoader::parsXml(const char* szFile) { module.clear(); ErrorLogger* logger = ErrorLogger::Instance(); TiXmlDocument doc(szFile); if(!doc.LoadFile()) { OSTRINGSTREAM err; err<<"Syntax error while loading "<<szFile<<" at line "\ <<doc.ErrorRow()<<": "; err<<doc.ErrorDesc(); logger->addError(err); return nullptr; } /* retrieving root module */ TiXmlElement *root = doc.RootElement(); if(!root) { OSTRINGSTREAM err; err<<"Syntax error while loading "<<szFile<<" . "; err<<"No root element."; logger->addError(err); return nullptr; } if(!compareString(root->Value(), "module")) { /* OSTRINGSTREAM msg; msg<<szFile<<" is not a module descriptor file."; logger->addWarning(msg); */ return nullptr; } /* retrieving name */ auto* name = (TiXmlElement*) root->FirstChild("name"); if(!name || !name->GetText()) { OSTRINGSTREAM err; err<<"Module from "<<szFile<<" has no name."; logger->addError(err); //return NULL; } for(TiXmlElement* var = root->FirstChildElement("var"); var; var = var->NextSiblingElement()) { if(var->Attribute("name") && var->GetText()) { parser->addVariable(var->Attribute("name"), var->GetText()); } } module.setXmlFile(szFile); if(name) module.setName(parser->parseText(name->GetText()).c_str()); /* retrieving description */ TiXmlElement* desc; if((desc = (TiXmlElement*) root->FirstChild("description"))) module.setDescription(parser->parseText(desc->GetText()).c_str()); /* retrieving version */ TiXmlElement* ver; if((ver = (TiXmlElement*) root->FirstChild("version"))) module.setVersion(parser->parseText(ver->GetText()).c_str()); /* retrieving parameter */ TiXmlElement* arguments; if((arguments = (TiXmlElement*) root->FirstChild("arguments"))) for(TiXmlElement* param = arguments->FirstChildElement(); param; param = param->NextSiblingElement()) { if(compareString(param->Value(), "param")) { if(param->GetText()) { bool brequired = false; if(compareString(param->Attribute("required"), "yes")) brequired = true; Argument arg(parser->parseText(param->GetText()).c_str(), brequired, param->Attribute("desc")); arg.setDefault(param->Attribute("default")); module.addArgument(arg); } } else if(compareString(param->Value(), "switch")) { if(param->GetText()) { bool brequired = false; if(compareString(param->Attribute("required"), "yes")) brequired = true; Argument arg(parser->parseText(param->GetText()).c_str(), brequired, param->Attribute("desc"), true); arg.setDefault(param->Attribute("default")); module.addArgument(arg); } } else { OSTRINGSTREAM war; war<<"Unrecognized tag from "<<szFile<<" at line "\ <<param->Row()<<"."; logger->addWarning(war); } } /* retrieving rank */ TiXmlElement* rank; if((rank = (TiXmlElement*) root->FirstChild("rank")) && rank->GetText()) module.setRank(atoi(parser->parseText(rank->GetText()).c_str())); /* retrieving authors information*/ TiXmlElement* authors; if((authors = (TiXmlElement*) root->FirstChild("authors"))) for(TiXmlElement* ath = authors->FirstChildElement(); ath; ath = ath->NextSiblingElement()) { if(compareString(ath->Value(), "author")) { Author author; if(ath->GetText()) author.setName(parser->parseText(ath->GetText()).c_str()); if(ath->Attribute("email")) author.setEmail(ath->Attribute("email")); module.addAuthor(author); } else { OSTRINGSTREAM war; war<<"Unrecognized tag from "<<szFile<<" at line "\ <<ath->Row()<<"."; logger->addWarning(war); } } /* retrieving data */ if(root->FirstChild("data")) for(TiXmlElement* data = root->FirstChild("data")->FirstChildElement(); data; data = data->NextSiblingElement()) { /* output data */ if(compareString(data->Value(), "output")) { OutputData output; if(compareString(data->Attribute("port_type"), "stream") || !data->Attribute("port_type")) output.setPortType(STREAM_PORT); else if(compareString(data->Attribute("port_type"), "event")) output.setPortType(EVENT_PORT); else if(compareString(data->Attribute("port_type"), "service")) output.setPortType(SERVICE_PORT); else { OSTRINGSTREAM war; war<<"Unknown port type \'"<<data->Attribute("port_type")<<"\' from "<<szFile<<" at line "\ <<data->Row()<<". Available types : stream, event, service"; logger->addWarning(war); } TiXmlElement* element; if(output.getPortType() != SERVICE_PORT ) { if((element = (TiXmlElement*) data->FirstChild("type"))) output.setName(parser->parseText(element->GetText()).c_str()); else { OSTRINGSTREAM war; war<<"Output data from "<<szFile<<" at line "\ <<data->Row()<<" has no type."; logger->addWarning(war); } } else output.setName("*"); if((element = (TiXmlElement*) data->FirstChild("port"))) { output.setPort(parser->parseText(element->GetText()).c_str()); output.setCarrier(element->Attribute("carrier")); } else { OSTRINGSTREAM war; war<<"Output data from "<<szFile<<" at line "\ <<data->Row()<<" has no port."; logger->addWarning(war); } if((element = (TiXmlElement*) data->FirstChild("description"))) output.setDescription(parser->parseText(element->GetText()).c_str()); module.addOutput(output); } // end of output data /* input data */ if(compareString(data->Value(), "input")) { InputData input; if(compareString(data->Attribute("port_type"), "stream") || !data->Attribute("port_type")) input.setPortType(STREAM_PORT); else if(compareString(data->Attribute("port_type"), "event")) input.setPortType(EVENT_PORT); else if(compareString(data->Attribute("port_type"), "service")) input.setPortType(SERVICE_PORT); else { OSTRINGSTREAM war; war<<"Unknown port type \'"<<data->Attribute("port_type")<<"\' from "<<szFile<<" at line "\ <<data->Row()<<". Available types : stream, event, service"; logger->addWarning(war); } TiXmlElement* element; if(input.getPortType() != SERVICE_PORT ) { if((element = (TiXmlElement*) data->FirstChild("type"))) input.setName(parser->parseText(element->GetText()).c_str()); else { OSTRINGSTREAM war; war<<"Input data from "<<szFile<<" at line "\ <<data->Row()<<" has no type."; logger->addWarning(war); } } else input.setName("rpc"); if((element = (TiXmlElement*) data->FirstChild("port"))) { input.setPort(parser->parseText(element->GetText()).c_str()); input.setCarrier(element->Attribute("carrier")); } else { OSTRINGSTREAM war; war<<"Input data from "<<szFile<<" at line "\ <<data->Row()<<" has no port."; logger->addWarning(war); } if((element = (TiXmlElement*) data->FirstChild("description"))) input.setDescription(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) data->FirstChild("required"))) if(compareString(parser->parseText(element->GetText()).c_str(), "yes")) input.setRequired(true); if((element = (TiXmlElement*) data->FirstChild("priority"))) if(compareString(parser->parseText(element->GetText()).c_str(), "yes")) input.setPriority(true); module.addInput(input); } // end of input data } if(root->FirstChild("services")) { for(TiXmlElement* services = root->FirstChild("services")->FirstChildElement(); services; services = services->NextSiblingElement()) { /* server */ if(compareString(services->Value(), "server")) { InputData input; input.setPortType(SERVICE_PORT); TiXmlElement* element; if((element = (TiXmlElement*) services->FirstChild("port"))) { input.setPort(parser->parseText(element->GetText()).c_str()); input.setCarrier("tcp"); } if((element = (TiXmlElement*) services->FirstChild("description"))) input.setDescription(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) services->FirstChild("type"))) input.setName(parser->parseText(element->GetText()).c_str()); else input.setName("rpc"); module.addInput(input); } /* client */ if(compareString(services->Value(), "client")) { OutputData output; output.setPortType(SERVICE_PORT); TiXmlElement* element; if((element = (TiXmlElement*) services->FirstChild("port"))) { output.setPort(parser->parseText(element->GetText()).c_str()); output.setCarrier("tcp"); } if((element = (TiXmlElement*) services->FirstChild("description"))) output.setDescription(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) services->FirstChild("type"))) output.setName(parser->parseText(element->GetText()).c_str()); else output.setName("rpc"); module.addOutput(output); } } } /* retrieving broker*/ TiXmlElement* element; if((element = (TiXmlElement*) root->FirstChild("deployer"))) { module.setBroker(parser->parseText(element->GetText()).c_str()); module.setNeedDeployer(true); } /* retrieving dependencies*/ if(root->FirstChild("dependencies")) for(TiXmlElement* restag = root->FirstChild("dependencies")->FirstChildElement(); restag; restag = restag->NextSiblingElement()) { Computer computer; if(compareString(restag->Value(), "computer")) { Computer computer; computer.setXmlFile(szFile); for(TiXmlElement* comptag = restag->FirstChildElement(); comptag; comptag = comptag->NextSiblingElement()) { /* retrieving name */ if(compareString(comptag->Value(), "name")) computer.setName(parser->parseText(comptag->GetText()).c_str()); /* retrieving description */ if(compareString(comptag->Value(), "description")) computer.setDescription(parser->parseText(comptag->GetText()).c_str()); // platform if(compareString(comptag->Value(), "platform")) { Platform os; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("name"))) os.setName(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) comptag->FirstChild("distribution"))) os.setDistribution(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) comptag->FirstChild("release"))) os.setRelease(parser->parseText(element->GetText()).c_str()); computer.setPlatform(os); } // end of platform tag /* //multiplatform if(compareString(comptag->Value(), "multiplatform")) { MultiPlatform mltPlatform; for(TiXmlElement* mptag = comptag->FirstChild("multiplatform")->FirstChildElement(); mptag; mptag = mptag->NextSiblingElement()) { // platform if(compareString(mptag->Value(), "platform")) { Platform os; TiXmlElement* element; if((element = (TiXmlElement*) mptag->FirstChild("name"))) os.setName(element->GetText()); if((element = (TiXmlElement*) mptag->FirstChild("distribution"))) os.setDistribution(element->GetText()); if((element = (TiXmlElement*) mptag->FirstChild("release"))) os.setDistribution(element->GetText()); mltPlatform.addPlatform(os); } } module.addResource(mltPlatform); } // end of multiplatform tag */ // memory if(compareString(comptag->Value(), "memory")) { Memory mem; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("total_space"))) mem.setTotalSpace((Capacity)atol(parser->parseText(element->GetText()).c_str())); if((element = (TiXmlElement*) comptag->FirstChild("free_space"))) mem.setFreeSpace((Capacity)atol(parser->parseText(element->GetText()).c_str())); computer.setMemory(mem); } // end of memory tag // storage if(compareString(comptag->Value(), "storage")) { Storage stg; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("total_space"))) stg.setTotalSpace((Capacity)atol(parser->parseText(element->GetText()).c_str())); if((element = (TiXmlElement*) comptag->FirstChild("free_space"))) stg.setFreeSpace((Capacity)atol(parser->parseText(element->GetText()).c_str())); computer.setStorage(stg); } // end of storage tag // processor if(compareString(comptag->Value(), "processor")) { Processor proc; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("architecture"))) proc.setArchitecture(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) comptag->FirstChild("model"))) proc.setModel(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) comptag->FirstChild("cores"))) proc.setCores((size_t)atoi(parser->parseText(element->GetText()).c_str())); if((element = (TiXmlElement*) comptag->FirstChild("siblings"))) proc.setSiblings((size_t)atoi(parser->parseText(element->GetText()).c_str())); if((element = (TiXmlElement*) comptag->FirstChild("frequency"))) proc.setFrequency(atof(parser->parseText(element->GetText()).c_str())); computer.setProcessor(proc); } // end of processor tag // network if(compareString(comptag->Value(), "network")) { Network net; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("ip4"))) net.setIP4(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) comptag->FirstChild("ip6"))) net.setIP6(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) comptag->FirstChild("mac"))) net.setMAC(parser->parseText(element->GetText()).c_str()); module.addResource(net); computer.setNetwork(net); } // end of network tag // yarp_port if(compareString(comptag->Value(), "yarp_port")) { ResYarpPort yport; auto* element = (TiXmlElement*) comptag->FirstChild("name"); if(element && element->GetText()) { yport.setName(parser->parseText(element->GetText()).c_str()); yport.setPort(parser->parseText(element->GetText()).c_str()); computer.addPeripheral(yport); } else { OSTRINGSTREAM war; war<<"yarp_port from "<<szFile<<" at line " <<comptag->Row()<<" has no name."; logger->addWarning(war); } } // gpu if(compareString(comptag->Value(), "gpu")) { GPU gpu; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("name"))) gpu.setName(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) comptag->FirstChild("capability"))) gpu.setCompCompatibility(parser->parseText(element->GetText()).c_str()); if((element = (TiXmlElement*) comptag->FirstChild("cores"))) gpu.setCores((size_t)atoi(parser->parseText(element->GetText()).c_str())); if((element = (TiXmlElement*) comptag->FirstChild("frequency"))) gpu.setFrequency(atof(parser->parseText(element->GetText()).c_str())); if((element = (TiXmlElement*) comptag->FirstChild("register_block"))) gpu.setResgisterPerBlock((size_t)atoi(parser->parseText(element->GetText()).c_str())); if((element = (TiXmlElement*) comptag->FirstChild("thread_block"))) gpu.setThreadPerBlock((size_t)atoi(parser->parseText(element->GetText()).c_str())); if((element = (TiXmlElement*) comptag->FirstChild("overlap"))) { if(compareString(parser->parseText(element->GetText()).c_str(), "yes")) gpu.setOverlap(true); else gpu.setOverlap(false); } // global memory if(comptag->FirstChild("global_memory")) { TiXmlElement* element; element = (TiXmlElement*) comptag->FirstChild("global_memory"); if((element = (TiXmlElement*) element->FirstChild("total_space"))) gpu.setGlobalMemory((Capacity)atol(parser->parseText(element->GetText()).c_str())); } // end of global memory tag // shared memory if(comptag->FirstChild("shared_memory")) { TiXmlElement* element; element = (TiXmlElement*) comptag->FirstChild("shared_memory"); if((element = (TiXmlElement*) element->FirstChild("total_space"))) gpu.setSharedMemory((Capacity)atol(parser->parseText(element->GetText()).c_str())); } // end of shared memory tag // constant memory if(comptag->FirstChild("constant_memory")) { TiXmlElement* element; element = (TiXmlElement*) comptag->FirstChild("constant_memory"); if((element = (TiXmlElement*) element->FirstChild("total_space"))) gpu.setConstantMemory((Capacity)atol(parser->parseText(element->GetText()).c_str())); } // end of shared memory tag computer.addPeripheral(gpu); } // end of gpu tag } // end of computer tag loop module.addResource(computer); } //end of if computer tag }// end of dependecnies tag return &module; }
bool XmlAppSaver::serialXml(Application* app, const char* szFile) { // updating application xml file name app->setXmlFile(szFile); ErrorLogger* logger = ErrorLogger::Instance(); TiXmlDocument doc; //(szFile); TiXmlElement * root = new TiXmlElement("application"); doc.LinkEndChild( root ); TiXmlElement * appName = new TiXmlElement("name"); //are all these NEW ok? appName->LinkEndChild(new TiXmlText(app->getName())); root->LinkEndChild(appName); if (strcmp(app->getDescription(), "")) { TiXmlElement * desc= new TiXmlElement( "description"); desc->LinkEndChild(new TiXmlText( app->getDescription())); root->LinkEndChild(desc); } if(strcmp (app->getVersion(), "")) { TiXmlElement * vers= new TiXmlElement( "version"); vers->LinkEndChild(new TiXmlText( app->getVersion())); root->LinkEndChild(vers); } /* * TODO: setting prefix of the main application is inactivated. * Check this should be supported in future or not! */ /* if(strcmp (app->getPrefix(), "")) { TiXmlElement * prefix= new TiXmlElement( "prefix"); prefix->LinkEndChild(new TiXmlText( app->getPrefix())); root->LinkEndChild(prefix); } */ if(app->authorCount()>0) { TiXmlElement *auths=new TiXmlElement("authors"); for (int i=0; i<app->authorCount(); i++) { //app->getAuthorAt(i); TiXmlElement *auth=new TiXmlElement("author"); auth->SetAttribute("email", app->getAuthorAt(i).getEmail()); auth->LinkEndChild(new TiXmlText(app->getAuthorAt(i).getName())); auths->LinkEndChild(auth); } root->LinkEndChild(auths); } // iterate over modules { int nModules=app->imoduleCount(); for (int modCt=0; modCt<nModules; ++modCt) { TiXmlElement * newMod = new TiXmlElement("module"); root->LinkEndChild(newMod); //add module element ModuleInterface curMod=app->getImoduleAt(modCt); TiXmlElement *name = new TiXmlElement("name"); name->LinkEndChild(new TiXmlText(curMod.getName())); newMod->LinkEndChild(name); TiXmlElement *parameters=new TiXmlElement("parameters"); parameters->LinkEndChild(new TiXmlText(curMod.getParam())); newMod->LinkEndChild(parameters); TiXmlElement *node = new TiXmlElement("node"); node->LinkEndChild(new TiXmlText(curMod.getHost())); //is host the same as node? newMod->LinkEndChild(node); TiXmlElement *prefix=new TiXmlElement("prefix"); prefix->LinkEndChild(new TiXmlText(curMod.getPrefix())); newMod->LinkEndChild(prefix); if(strcmp(curMod.getStdio(), "")) { TiXmlElement *stdio=new TiXmlElement("stdio"); stdio->LinkEndChild(new TiXmlText(curMod.getStdio())); newMod->LinkEndChild(stdio); } if(strcmp(curMod.getWorkDir(), "")) { TiXmlElement *workdir=new TiXmlElement("workdir"); workdir->LinkEndChild(new TiXmlText(curMod.getWorkDir())); newMod->LinkEndChild(workdir); } if(strcmp(curMod.getBroker(), "")) { TiXmlElement *broker=new TiXmlElement("deployer"); broker->LinkEndChild(new TiXmlText(curMod.getBroker())); newMod->LinkEndChild(broker); } /* if(curMod.getRank()>0) //TODO check here how is rank handled { TiXmlElement *rank=new TiXmlElement("rank"); char str[256]; sprintf(str,"%d", curMod.getRank()); rank->LinkEndChild(new TiXmlText(str)); newMod->LinkEndChild(rank); } */ GraphicModel model = curMod.getModelBase(); OSTRINGSTREAM txt; if(model.points.size()>0) { txt<<"(Pos (x "<<model.points[0].x<<") "<<"(y "<<model.points[0].y<<"))"; TiXmlElement *geometry=new TiXmlElement("geometry"); geometry->LinkEndChild(new TiXmlText(txt.str().c_str())); newMod->LinkEndChild(geometry); } } } // iterate over embedded applications { int nApps=app->iapplicationCount(); for (int appCt=0; appCt<nApps; ++appCt) { TiXmlElement *newApp = new TiXmlElement("application"); root->LinkEndChild(newApp); //add application element ApplicationInterface curApp=app->getIapplicationAt(appCt); TiXmlElement *name = new TiXmlElement("name"); name->LinkEndChild(new TiXmlText(curApp.getName())); newApp->LinkEndChild(name); TiXmlElement *prefix=new TiXmlElement("prefix"); prefix->LinkEndChild(new TiXmlText(curApp.getPrefix())); newApp->LinkEndChild(prefix); GraphicModel model = curApp.getModelBase(); OSTRINGSTREAM txt; if(model.points.size()>0) { txt<<"(Pos (x "<<model.points[0].x<<") "<<"(y "<<model.points[0].y<<"))"; TiXmlElement *geometry=new TiXmlElement("geometry"); geometry->LinkEndChild(new TiXmlText(txt.str().c_str())); newApp->LinkEndChild(geometry); } } } // iterate over connections { int nConns=app->connectionCount(); for (int connCt=0; connCt<nConns; ++connCt) { TiXmlElement *newConn=new TiXmlElement("connection"); Connection curConn=app->getConnectionAt(connCt); if(strlen(curConn.getId())) newConn->SetAttribute("id", curConn.getId()); if(curConn.isPersistent()) newConn->SetAttribute("persist", "true"); TiXmlElement *from = new TiXmlElement("from"); if (curConn.isExternalFrom()) from->SetAttribute("external", "true"); from->LinkEndChild(new TiXmlText(curConn.from())); newConn->LinkEndChild(from); TiXmlElement *to = new TiXmlElement("to"); if (curConn.isExternalTo()) to->SetAttribute("external", "true"); to->LinkEndChild(new TiXmlText(curConn.to())); newConn->LinkEndChild(to); TiXmlElement *protocol = new TiXmlElement("protocol"); protocol->LinkEndChild(new TiXmlText(curConn.carrier())); newConn->LinkEndChild(protocol); GraphicModel model = curConn.getModelBase(); OSTRINGSTREAM txt; if(model.points.size()>0) { txt<<"(Pos "; for(unsigned int i=0; i<model.points.size(); i++) txt<<"((x "<<model.points[i].x<<") "<<"(y "<<model.points[i].y<<")) "; txt<<" )"; TiXmlElement *geometry=new TiXmlElement("geometry"); geometry->LinkEndChild(new TiXmlText(txt.str().c_str())); newConn->LinkEndChild(geometry); } root->LinkEndChild(newConn); } } // iterate over arbitrators for(int i=0; i<app->arbitratorCount(); i++) { Arbitrator& arb = app->getArbitratorAt(i); TiXmlElement *newArb = new TiXmlElement("arbitrator"); TiXmlElement *port = new TiXmlElement("port"); port->LinkEndChild(new TiXmlText(arb.getPort())); newArb->LinkEndChild(port); std::map<string, string> &rules = arb.getRuleMap(); for(std::map<string, string>::iterator it=rules.begin(); it!=rules.end(); ++it) { TiXmlElement *rule = new TiXmlElement("rule"); rule->SetAttribute("connection", it->first.c_str()); rule->LinkEndChild(new TiXmlText(it->second.c_str())); newArb->LinkEndChild(rule); } GraphicModel model = arb.getModelBase(); OSTRINGSTREAM txt; if(model.points.size()>0) { txt<<"(Pos "; for(unsigned int i=0; i<model.points.size(); i++) txt<<"((x "<<model.points[i].x<<") "<<"(y "<<model.points[i].y<<")) "; txt<<" )"; TiXmlElement *geometry=new TiXmlElement("geometry"); geometry->LinkEndChild(new TiXmlText(txt.str().c_str())); newArb->LinkEndChild(geometry); } root->LinkEndChild(newArb); } bool ok=doc.SaveFile(app->getXmlFile()); if (!ok) { OSTRINGSTREAM err; err<<"tinyXml error for file " << app->getXmlFile(); if (doc.Error()) err <<" at line " << doc.ErrorRow() << ", column " << doc.ErrorCol() << ": " << doc.ErrorDesc(); logger->addError(err); err <<"\n"; return false; } else return true; }
YConsoleManager::YConsoleManager(int argc, char* argv[]) : Manager() { #if defined(WIN32) __pManager = (Manager*) this; #endif bShouldRun = false; // Setup resource finder yarp::os::ResourceFinder rf; rf.setVerbose(false); rf.setDefaultContext("yarpmanager"); rf.setDefaultConfigFile(DEF_CONFIG_FILE); rf.configure(argc, argv); yarp::os::Property config; config.fromString(rf.toString()); if(config.check("help")) { cout<<HELP_MESSAGE<<endl; return; } if(config.check("version")) { cout<<VERSION_MESSAGE<<endl; return; } /** * preparing default options */ std::string inifile=rf.findFile("from").c_str(); std::string inipath=""; size_t lastSlash=inifile.rfind("/"); if (lastSlash!=std::string::npos) inipath=inifile.substr(0, lastSlash+1); else { lastSlash=inifile.rfind("\\"); if (lastSlash!=std::string::npos) inipath=inifile.substr(0, lastSlash+1); } // if(!config.check("ymanagerini_dir")) // config.put("ymanagerini_dir", inipath.c_str()); if(!config.check("apppath")) config.put("apppath", "./"); if(!config.check("modpath")) config.put("modpath", "./"); if(!config.check("respath")) config.put("respath", "./"); if(!config.check("load_subfolders")) config.put("load_subfolders", "no"); if(!config.check("watchdog")) config.put("watchdog", "no"); if(!config.check("module_failure")) config.put("module_failure", "prompt"); if(!config.check("connection_failure")) config.put("connection_failure", "prompt"); if(!config.check("auto_connect")) config.put("auto_connect", "no"); if(!config.check("auto_dependency")) config.put("auto_dependency", "no"); if(!config.check("color_theme")) config.put("color_theme", "light"); /** * Set configuration */ if(config.find("color_theme").asString() == "dark") setColorTheme(THEME_DARK); else if(config.find("color_theme").asString() == "light") setColorTheme(THEME_LIGHT); else setColorTheme(THEME_NONE); if(config.find("watchdog").asString() == "yes") enableWatchDog(); else disableWatchod(); if(config.find("auto_dependency").asString() == "yes") enableAutoDependency(); else disableAutoDependency(); if(config.find("auto_connect").asString() == "yes") enableAutoConnect(); else disableAutoConnect(); if(!config.check("silent")) { cout<<endl<<OKGREEN<<LOGO_MESSAGE<<ENDC<<endl; cout<<endl<<WELCOME_MESSAGE<<endl<<endl; } if(config.check("modpath")) { string strPath; stringstream modPaths(config.find("modpath").asString().c_str()); while (getline(modPaths, strPath, ';')) { trimString(strPath); if (!isAbsolute(strPath.c_str())) strPath=inipath+strPath; addModules(strPath.c_str()); } } if(config.check("respath")) { string strPath; stringstream resPaths(config.find("respath").asString().c_str()); while (getline(resPaths, strPath, ';')) { trimString(strPath); if (!isAbsolute(strPath.c_str())) strPath=inipath+strPath; addResources(strPath.c_str()); } } ErrorLogger* logger = ErrorLogger::Instance(); if(config.check("apppath")) { string strPath; stringstream appPaths(config.find("apppath").asString().c_str()); while (getline(appPaths, strPath, ';')) { trimString(strPath); if (!isAbsolute(strPath.c_str())) strPath=inipath+strPath; if(config.find("load_subfolders").asString() == "yes") { if(!loadRecursiveApplications(strPath.c_str())) logger->addError("Cannot load the applications from " + strPath); } else addApplications(strPath.c_str()); } } reportErrors(); #ifdef WITH_READLINE updateAppNames(&appnames); #endif #if defined(WIN32) ACE_OS::signal(SIGINT, (ACE_SignalHandler) YConsoleManager::onSignal); ACE_OS::signal(SIGBREAK, (ACE_SignalHandler) YConsoleManager::onSignal); ACE_OS::signal(SIGTERM, (ACE_SignalHandler) YConsoleManager::onSignal); #else struct sigaction new_action, old_action; /* Set up the structure to specify the new action. */ new_action.sa_handler = YConsoleManager::onSignal; sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; sigaction (SIGINT, NULL, &old_action); if (old_action.sa_handler != SIG_IGN) sigaction (SIGINT, &new_action, NULL); sigaction (SIGHUP, NULL, &old_action); if (old_action.sa_handler != SIG_IGN) sigaction (SIGHUP, &new_action, NULL); sigaction (SIGTERM, NULL, &old_action); if (old_action.sa_handler != SIG_IGN) sigaction (SIGTERM, &new_action, NULL); #endif if(config.check("application")) { XmlAppLoader appload(config.find("application").asString().c_str()); if(appload.init()) { Application* application = appload.getNextApplication(); if(application) { // add this application to the manager if does not exist if(!getKnowledgeBase()->getApplication(application->getName())) getKnowledgeBase()->addApplication(application); #ifdef WITH_READLINE updateAppNames(&appnames); #endif if(loadApplication(application->getName())) { if(!config.check("silent")) which(); if(config.check("assign_hosts")) loadBalance(); if(config.check("run")) { if(config.check("connect")) enableAutoConnect(); bShouldRun = run(); } else if(config.check("connect")) connect(); if(config.check("disconnect")) disconnect(); if(config.check("stop")) { ExecutablePContainer modules = getExecutables(); ExecutablePIterator moditr; unsigned int id = 0; bShouldRun = false; for(moditr=modules.begin(); moditr<modules.end(); moditr++) { if(running(id)) stop(id); id++; } bShouldRun = !suspended(); } if(config.check("kill")) { bShouldRun = false; kill(); } if(config.check("check_con")) checkConnections(); if(config.check("check_state")) checkStates(); if(config.check("check_dep")) if(checkDependency()) cout<<INFO<<"All of resource dependencies are satisfied."<<ENDC<<endl; } } } if(!config.check("silent")) reportErrors(); } if(!config.check("exit")) YConsoleManager::myMain(); }
bool BinaryExpParser::checkExpression(std::string& strexp) { ErrorLogger* logger = ErrorLogger::Instance(); if(std::count(strexp.begin(), strexp.end(), '(') != std::count(strexp.begin(), strexp.end(), ')')) { logger->addError("Incorrect expression format! (parentheses do not match)"); return false; } if(std::count(strexp.begin(), strexp.end(), IMPLY) != 1 ) { logger->addError("Incorrect expression format! (no implication ':' found)"); return false; } // erassing all the sapces strexp.erase(std::remove_if(strexp.begin(), strexp.end(), ::isspace), strexp.end()); if(!strexp.size()) { logger->addError("Empty expression!"); return false; } // making a copy of strexp and checking more string dummy = strexp; // removing all pranteses dummy.erase(std::remove_if(dummy.begin(), dummy.end(), isParentheses), dummy.end()); leftOpr = dummy.substr(0, dummy.find(IMPLY)); if(!leftOpr.size()) { logger->addError("Missing operand before ':'"); return false; } if(dummy.find(IMPLY) == (dummy.size()-1)) { logger->addError("Missing operands after ':'"); return false; } dummy.erase(0, dummy.find(IMPLY)+1); if(dummy.find(leftOpr) != string::npos) { std::string msg; msg = "recursive assignment of operand '" + leftOpr + "'"; logger->addError(msg.c_str()); return false; } // checking '~' size_t n = dummy.find(EXPNOT); while(n != string::npos) { OSTRINGSTREAM msg; bool bError = ((n+1) == dummy.length()); // empty operand after ~ if((n+1) < dummy.length()) { bError |= (dummy[n+1] == EXPAND); // operator & after ~ bError |= (dummy[n+1] == EXPOR); // operand | after ~ } if(n != 0) bError |= (dummy[n-1] != EXPAND) && (dummy[n-1] != EXPOR); // an operand before ~ if(bError) { msg<<"Incorrect expression format of '~' at "<<(int)n; logger->addError(msg.str().c_str()); return false; } n = dummy.find(EXPNOT, n+1); } // checking '| &' n = dummy.find_first_of("&|"); while(n != string::npos) { OSTRINGSTREAM msg; bool bError = ((n+1) == dummy.length()); // empty operand after & or | if((n+1) < dummy.length()) { bError |= (dummy[n+1] == EXPAND); // operator & after & or | bError |= (dummy[n+1] == EXPOR); // operand | after & or | } bError |= (n == 0); // empty operand before & or | if(n != 0) { bError |= (dummy[n-1] == EXPAND); // operator & before & or | bError |= (dummy[n-1] == EXPOR); // operand | before & or | bError |= (dummy[n-1] == EXPOR); // operand ~ before & or | } if(bError) { msg<<"Incorrect expression format of '&' or '|' at "<<(int)n; logger->addError(msg.str().c_str()); return false; } n = dummy.find_first_of("&|", n+1); } // at the end strexp.erase(0, strexp.find(IMPLY)+1); return true; }
bool XmlResLoader::parsXml(const char* szFile) { computers.clear(); ErrorLogger* logger = ErrorLogger::Instance(); TiXmlDocument doc(szFile); if(!doc.LoadFile()) { OSTRINGSTREAM err; err<<"Syntax error while loading "<<szFile<<" at line "\ <<doc.ErrorRow()<<": "; err<<doc.ErrorDesc(); logger->addError(err); return false; } /* retrieving root module */ TiXmlElement *root = doc.RootElement(); if(!root) { OSTRINGSTREAM err; err<<"Syntax error while loading "<<szFile<<" . "; err<<"No root element."; logger->addError(err); return false; } if(!compareString(root->Value(), "resources")) { /* OSTRINGSTREAM msg; msg<<szFile<<" is not a resource descriptor file."; logger->addWarning(msg); */ return false; } /* retrieving all computers descriptions */ for(TiXmlElement* restag = root->FirstChildElement(); restag; restag = restag->NextSiblingElement()) { /* retrieving a computer resource */ if(compareString(restag->Value(), "computer")) { Computer computer; computer.setXmlFile(szFile); for(TiXmlElement* comptag = restag->FirstChildElement(); comptag; comptag = comptag->NextSiblingElement()) { /* retrieving name */ if(compareString(comptag->Value(), "name")) computer.setName(comptag->GetText()); /* retrieving description */ if(compareString(comptag->Value(), "description")) computer.setDescription(comptag->GetText()); /* retrieving disablility */ if(compareString(comptag->Value(), "disable")) { if(compareString(comptag->GetText(), "yes")) computer.setDisable(true); } // platform if(compareString(comptag->Value(), "platform")) { Platform os; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("name"))) os.setName(element->GetText()); else { OSTRINGSTREAM war; war<<"Platform from "<<szFile<<" at line "\ <<comptag->Row()<<" has no name."; logger->addWarning(war); } if((element = (TiXmlElement*) comptag->FirstChild("distribution"))) os.setDistribution(element->GetText()); if((element = (TiXmlElement*) comptag->FirstChild("release"))) os.setRelease(element->GetText()); computer.setPlatform(os); } // end of platform tag // memory if(compareString(comptag->Value(), "memory")) { Memory mem; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("total_space"))) mem.setTotalSpace((Capacity)atol(element->GetText())); computer.setMemory(mem); } // end of memory tag // storage if(compareString(comptag->Value(), "storage")) { Storage stg; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("total_space"))) stg.setTotalSpace((Capacity)atol(element->GetText())); computer.setStorage(stg); } // end of storage tag // processor if(compareString(comptag->Value(), "processor")) { Processor proc; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("architecture"))) proc.setArchitecture(element->GetText()); if((element = (TiXmlElement*) comptag->FirstChild("model"))) proc.setModel(element->GetText()); if((element = (TiXmlElement*) comptag->FirstChild("cores"))) proc.setCores((size_t)atoi(element->GetText())); if((element = (TiXmlElement*) comptag->FirstChild("frequency"))) proc.setFrequency(atof(element->GetText())); computer.setProcessor(proc); } // end of processor tag // network if(compareString(comptag->Value(), "network")) { Network net; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("ip4"))) net.setIP4(element->GetText()); if((element = (TiXmlElement*) comptag->FirstChild("ip6"))) net.setIP6(element->GetText()); if((element = (TiXmlElement*) comptag->FirstChild("mac"))) net.setMAC(element->GetText()); computer.setNetwork(net); } // end of network tag // gpu if(compareString(comptag->Value(), "gpu")) { GPU gpu; TiXmlElement* element; if((element = (TiXmlElement*) comptag->FirstChild("name"))) gpu.setName(element->GetText()); if((element = (TiXmlElement*) comptag->FirstChild("capability"))) gpu.setCompCompatibility(element->GetText()); if((element = (TiXmlElement*) comptag->FirstChild("cores"))) gpu.setCores((size_t)atoi(element->GetText())); if((element = (TiXmlElement*) comptag->FirstChild("frequency"))) gpu.setFrequency(atof(element->GetText())); if((element = (TiXmlElement*) comptag->FirstChild("register_block"))) gpu.setResgisterPerBlock((size_t)atoi(element->GetText())); if((element = (TiXmlElement*) comptag->FirstChild("thread_block"))) gpu.setThreadPerBlock((size_t)atoi(element->GetText())); if((element = (TiXmlElement*) comptag->FirstChild("overlap"))) { if(compareString(element->GetText(), "yes")) gpu.setOverlap(true); else gpu.setOverlap(false); } // global memory if(comptag->FirstChild("global_memory")) { TiXmlElement* element; element = (TiXmlElement*) comptag->FirstChild("global_memory"); if((element = (TiXmlElement*) element->FirstChild("total_space"))) gpu.setGlobalMemory((Capacity)atol(element->GetText())); } // end of global memory tag // shared memory if(comptag->FirstChild("shared_memory")) { TiXmlElement* element; element = (TiXmlElement*) comptag->FirstChild("shared_memory"); if((element = (TiXmlElement*) element->FirstChild("total_space"))) gpu.setSharedMemory((Capacity)atol(element->GetText())); } // end of shared memory tag // constant memory if(comptag->FirstChild("constant_memory")) { TiXmlElement* element; element = (TiXmlElement*) comptag->FirstChild("constant_memory"); if((element = (TiXmlElement*) element->FirstChild("total_space"))) gpu.setConstantMemory((Capacity)atol(element->GetText())); } // end of shared memory tag computer.addPeripheral(gpu); } // end of gpu tag } // end of computer loop computers.push_back(computer); } // end of if computer } // end of resources return true; }
void Ready::startModule(void) { ErrorLogger* logger = ErrorLogger::Instance(); // wait for priority ports if auto connecte is enabled if(executable->autoConnect()) { bAborted = false; while(!checkPriorityPorts()) { yarp::os::Time::delay(1.0); if(bAborted) return; } } // finding maximum resource-waiting timeout ResourceIterator itr; double maxTimeout = 0; for(itr=executable->getResources().begin(); itr!=executable->getResources().end(); itr++) { if((*itr).getTimeout() > maxTimeout) maxTimeout = (*itr).getTimeout(); } // waiting for resources double base = yarp::os::Time::now(); while(!checkResources()) { if(bAborted) return; if(timeout(base, maxTimeout)) { OSTRINGSTREAM msg; msg<<"cannot run "<<executable->getCommand()<<" on "<<executable->getHost(); msg<<" : Timeout while waiting for some resources."; logger->addError(msg); castEvent(EventFactory::startModuleEventFailed); executable->getEvent()->onExecutableDied(executable); return; } } if(!executable->getBroker()->start()) { OSTRINGSTREAM msg; msg<<"cannot run "<<executable->getCommand()<<" on "<<executable->getHost(); if(executable->getBroker()->error()) msg<<" : "<<executable->getBroker()->error(); logger->addError(msg); castEvent(EventFactory::startModuleEventFailed); executable->getEvent()->onExecutableDied(executable); } else { castEvent(EventFactory::startModuleEventOk); executable->getEvent()->onExecutableStart(executable); } }
Application* XmlAppLoader::parsXml(const char* szFile) { app.clear(); ErrorLogger* logger = ErrorLogger::Instance(); TiXmlDocument doc(szFile); if(!doc.LoadFile()) { OSTRINGSTREAM err; err<<"Syntax error while loading "<<szFile<<" at line "\ <<doc.ErrorRow()<<": "; err<<doc.ErrorDesc(); logger->addError(err); return NULL; } /* retrieving root element */ TiXmlElement *root = doc.RootElement(); if(!root) { OSTRINGSTREAM err; err<<"Syntax error while loading "<<szFile<<" . "; err<<"No root element."; logger->addError(err); return NULL; } if(!compareString(root->Value(), "application")) { //OSTRINGSTREAM err; //err<<"File "<<szFile<<" has no tag <application>."; //logger->addError(err); return NULL; } /* retrieving name */ TiXmlElement* name = (TiXmlElement*) root->FirstChild("name"); if(!name || !name->GetText()) { OSTRINGSTREAM err; err<<"Module from "<<szFile<<" has no name."; logger->addError(err); //return NULL; } app.setXmlFile(szFile); if(name) { string strname = name->GetText(); for(unsigned int i=0; i<strname.size(); i++) if(strname[i] == ' ') strname[i] = '_'; app.setName(strname.c_str()); } /* retrieving description */ TiXmlElement* desc; if((desc = (TiXmlElement*) root->FirstChild("description"))) app.setDescription(desc->GetText()); /* retrieving version */ TiXmlElement* ver; if((ver = (TiXmlElement*) root->FirstChild("version"))) app.setVersion(ver->GetText()); /* * TODO: setting prefix of the main application is inactivated. * Check this should be supported in future or not! */ /* //retrieving application prefix TiXmlElement* pref; if((pref = (TiXmlElement*) root->FirstChild("prefix"))) app.setPrefix(pref->GetText()); */ /* retrieving authors information*/ TiXmlElement* authors; if((authors = (TiXmlElement*) root->FirstChild("authors"))) for(TiXmlElement* ath = authors->FirstChildElement(); ath; ath = ath->NextSiblingElement()) { if(compareString(ath->Value(), "author")) { Author author; if(ath->GetText()) author.setName(ath->GetText()); if(ath->Attribute("email")) author.setEmail(ath->Attribute("email")); app.addAuthor(author); } else { OSTRINGSTREAM war; war<<"Unrecognized tag from "<<szFile<<" at line "\ <<ath->Row()<<"."; logger->addWarning(war); } } /* retrieving resources information*/ TiXmlElement* resources; if((resources = (TiXmlElement*) root->FirstChild("dependencies"))) for(TiXmlElement* res = resources->FirstChildElement(); res; res = res->NextSiblingElement()) { if(compareString(res->Value(), "port")) { if(res->GetText()) { ResYarpPort resource(res->GetText()); resource.setPort(res->GetText()); app.addResource(resource); } } else { OSTRINGSTREAM war; war<<"Unrecognized tag from "<<szFile<<" at line "\ <<res->Row()<<"."; logger->addWarning(war); } } /* retrieving modules information*/ for(TiXmlElement* mod = root->FirstChildElement(); mod; mod = mod->NextSiblingElement()) { if(compareString(mod->Value(), "module")) { TiXmlElement* element; if((element = (TiXmlElement*) mod->FirstChild("name"))) { ModuleInterface module(element->GetText()); if((element = (TiXmlElement*) mod->FirstChild("node"))) module.setHost(element->GetText()); if((element = (TiXmlElement*) mod->FirstChild("parameters"))) module.setParam(element->GetText()); if((element = (TiXmlElement*) mod->FirstChild("stdio"))) module.setStdio(element->GetText()); if((element = (TiXmlElement*) mod->FirstChild("workdir"))) module.setWorkDir(element->GetText()); if((element = (TiXmlElement*) mod->FirstChild("deployer"))) module.setBroker(element->GetText()); if((element = (TiXmlElement*) mod->FirstChild("prefix"))) module.setPrefix(element->GetText()); if((element = (TiXmlElement*) mod->FirstChild("rank"))) module.setRank(atoi(element->GetText())); #ifdef WITH_GEOMETRY element = (TiXmlElement*) mod->FirstChild("geometry"); if(element && element->GetText()) { yarp::os::Property prop(element->GetText()); GraphicModel model; GyPoint pt; if(prop.check("Pos")) { pt.x = prop.findGroup("Pos").find("x").asDouble(); pt.y = prop.findGroup("Pos").find("y").asDouble(); model.points.push_back(pt); module.setModelBase(model); } } #endif /* retrieving resources information*/ TiXmlElement* resources; if((resources = (TiXmlElement*) mod->FirstChild("dependencies"))) { for(TiXmlElement* res = resources->FirstChildElement(); res; res = res->NextSiblingElement()) { if(compareString(res->Value(), "port")) { if(res->GetText()) { ResYarpPort resource(res->GetText()); resource.setPort(res->GetText()); if(res->Attribute("timeout")) resource.setTimeout(atof(res->Attribute("timeout"))); if(res->Attribute("request")) resource.setRequest(res->Attribute("request")); if(res->Attribute("reply")) resource.setReply(res->Attribute("reply")); module.addResource(resource); } } else { OSTRINGSTREAM war; war<<"Unrecognized tag from "<<szFile<<" at line "\ <<res->Row()<<"."; logger->addWarning(war); } } } /* retrieving portmaps */ for(TiXmlElement* map = mod->FirstChildElement(); map; map = map->NextSiblingElement()) if(compareString(map->Value(), "portmap")) { TiXmlElement* first; TiXmlElement* second; if((first=(TiXmlElement*) map->FirstChild("old")) && (second=(TiXmlElement*) map->FirstChild("new")) ) { Portmap portmap(first->GetText(), second->GetText()); module.addPortmap(portmap); } } app.addImodule(module); } else { OSTRINGSTREAM war; war<<"Module from "<<szFile<<" at line "\ <<mod->Row()<<" has not name tag."; logger->addWarning(war); } } } /* retrieving embedded application information*/ for(TiXmlElement* embApp = root->FirstChildElement(); embApp; embApp = embApp->NextSiblingElement()) { if(compareString(embApp->Value(), "application")) { TiXmlElement* name; TiXmlElement* prefix; if((name=(TiXmlElement*) embApp->FirstChild("name"))) { ApplicationInterface IApp(name->GetText()); if((prefix=(TiXmlElement*) embApp->FirstChild("prefix"))) IApp.setPrefix(prefix->GetText()); #ifdef WITH_GEOMETRY TiXmlElement* element = (TiXmlElement*) embApp->FirstChild("geometry"); if(element && element->GetText()) { yarp::os::Property prop(element->GetText()); GraphicModel model; GyPoint pt; if(prop.check("Pos")) { pt.x = prop.findGroup("Pos").find("x").asDouble(); pt.y = prop.findGroup("Pos").find("y").asDouble(); model.points.push_back(pt); IApp.setModelBase(model); } } #endif app.addIapplication(IApp); } else { OSTRINGSTREAM war; war<<"Incomplete application tag from "<<szFile<<" at line "\ <<embApp->Row()<<". (no name)"; logger->addWarning(war); } } } /* retrieving arbitrator information*/ for(TiXmlElement* arb = root->FirstChildElement(); arb; arb = arb->NextSiblingElement()) { if(compareString(arb->Value(), "arbitrator")) { TiXmlElement* port = (TiXmlElement*) arb->FirstChild("port"); if(port && port->GetText()) { Arbitrator arbitrator(port->GetText()); // retrieving rules for(TiXmlElement* rule = arb->FirstChildElement(); rule; rule = rule->NextSiblingElement()) { if(compareString(rule->Value(), "rule")) { if(rule->Attribute("connection")) arbitrator.addRule(rule->Attribute("connection"), rule->GetText()); } } #ifdef WITH_GEOMETRY TiXmlElement* geometry = (TiXmlElement*) arb->FirstChild("geometry"); if(geometry && geometry->GetText()) { yarp::os::Property prop(geometry->GetText()); GraphicModel model; if(prop.check("Pos")) { yarp::os::Bottle pos = prop.findGroup("Pos"); for(int i=1; i<pos.size(); i++) { GyPoint pt; pt.x = pos.get(i).find("x").asDouble(); pt.y = pos.get(i).find("y").asDouble(); model.points.push_back(pt); } arbitrator.setModelBase(model); } } #endif app.addArbitrator(arbitrator); } else { OSTRINGSTREAM war; war<<"Incomplete arbitrator tag from "<<szFile<<" at line "\ <<arb->Row()<<"."; logger->addWarning(war); } } } /* retrieving connections information*/ for(TiXmlElement* cnn = root->FirstChildElement(); cnn; cnn = cnn->NextSiblingElement()) { if(compareString(cnn->Value(), "connection")) { TiXmlElement* from = (TiXmlElement*) cnn->FirstChild("from"); TiXmlElement* to = (TiXmlElement*) cnn->FirstChild("to"); if(!from) from = (TiXmlElement*) cnn->FirstChild("output"); if(!to) to = (TiXmlElement*) cnn->FirstChild("input"); TiXmlElement* protocol; if(from && to) { string strCarrier; if((protocol=(TiXmlElement*) cnn->FirstChild("protocol")) && protocol->GetText()) strCarrier = protocol->GetText(); Connection connection(from->GetText(), to->GetText(), strCarrier.c_str()); if(from->Attribute("external") && compareString(from->Attribute("external"), "true")) { connection.setFromExternal(true); if(from->GetText()) { ResYarpPort resource(from->GetText()); resource.setPort(from->GetText()); app.addResource(resource); } } if(to->Attribute("external") && compareString(to->Attribute("external"), "true")) { if(to->GetText()) { connection.setToExternal(true); ResYarpPort resource(to->GetText()); resource.setPort(to->GetText()); app.addResource(resource); } } //Connections which have the same port name in Port Resources // should also be set as external for(int i=0; i<app.resourcesCount(); i++) { ResYarpPort res = app.getResourceAt(i); if(compareString(res.getPort(), connection.from())) connection.setFromExternal(true); if(compareString(res.getPort(), connection.to())) connection.setToExternal(true); } if(cnn->Attribute("id")) connection.setId(cnn->Attribute("id")); if(cnn->Attribute("persist") && compareString(cnn->Attribute("persist"), "true")) connection.setPersistent(true); #ifdef WITH_GEOMETRY TiXmlElement* geometry = (TiXmlElement*) cnn->FirstChild("geometry"); if(geometry && geometry->GetText()) { yarp::os::Property prop(geometry->GetText()); GraphicModel model; if(prop.check("Pos")) { yarp::os::Bottle pos = prop.findGroup("Pos"); for(int i=1; i<pos.size(); i++) { GyPoint pt; pt.x = pos.get(i).find("x").asDouble(); pt.y = pos.get(i).find("y").asDouble(); model.points.push_back(pt); } connection.setModelBase(model); } } #endif app.addConnection(connection); } else { OSTRINGSTREAM war; war<<"Incomplete connection tag from "<<szFile<<" at line "\ <<cnn->Row()<<"."; logger->addWarning(war); } } } return &app; }
bool TemplateSimplifier::simplifyTemplateInstantiations( TokenList& tokenlist, ErrorLogger& errorlogger, const Settings *_settings, const Token *tok, std::list<Token *> &templateInstantiations, std::set<std::string> &expandedtemplates) { // this variable is not used at the moment. The intention was to // allow continuous instantiations until all templates has been expanded //bool done = false; // Contains tokens such as "T" std::vector<const Token *> typeParametersInDeclaration; for (tok = tok->tokAt(2); tok && tok->str() != ">"; tok = tok->next()) { if (Token::Match(tok, "%var% ,|>")) typeParametersInDeclaration.push_back(tok); } // bail out if the end of the file was reached if (!tok) return false; // get the position of the template name int namepos = TemplateSimplifier::getTemplateNamePosition(tok); if (namepos == -1) { // debug message that we bail out.. if (_settings->debugwarnings) { std::list<const Token *> callstack(1, tok); errorlogger.reportErr(ErrorLogger::ErrorMessage(callstack, &tokenlist, Severity::debug, "debug", "simplifyTemplates: bailing out", false)); } return false; } // name of template function/class.. const std::string name(tok->strAt(namepos)); const bool isfunc(tok->strAt(namepos + 1) == "("); // locate template usage.. std::string::size_type amountOftemplateInstantiations = templateInstantiations.size(); unsigned int recursiveCount = 0; bool instantiated = false; for (std::list<Token *>::const_iterator iter2 = templateInstantiations.begin(); iter2 != templateInstantiations.end(); ++iter2) { if (amountOftemplateInstantiations != templateInstantiations.size()) { amountOftemplateInstantiations = templateInstantiations.size(); simplifyCalculations(tokenlist.front()); ++recursiveCount; if (recursiveCount > 100) { // bail out.. break; } } Token * const tok2 = *iter2; if (tok2->str() != name) continue; if (Token::Match(tok2->previous(), "[;{}=]") && !TemplateSimplifier::instantiateMatch(*iter2, name, typeParametersInDeclaration.size(), isfunc ? "(" : "*| %var%")) continue; // New type.. std::vector<const Token *> typesUsedInTemplateInstantiation; std::string typeForNewNameStr; std::string templateMatchPattern(name + " < "); unsigned int indentlevel = 0; for (const Token *tok3 = tok2->tokAt(2); tok3 && (indentlevel > 0 || tok3->str() != ">"); tok3 = tok3->next()) { // #2648 - unhandled parentheses => bail out // #2721 - unhandled [ => bail out if (tok3->str() == "(" || tok3->str() == "[") { typeForNewNameStr.clear(); break; } if (!tok3->next()) { typeForNewNameStr.clear(); break; } if (Token::Match(tok3->tokAt(-2), "[<,] %var% <") && templateParameters(tok3) > 0) ++indentlevel; else if (indentlevel > 0 && Token::Match(tok3, "> [,>]")) --indentlevel; else if (indentlevel > 0 && tok3->str() == ">>") { if (indentlevel == 1) { templateMatchPattern += '>'; typeForNewNameStr += '>'; break; } indentlevel -= 2; } templateMatchPattern += (tok3->str() == ">>") ? std::string("> >") : tok3->str(); templateMatchPattern += ' '; if (indentlevel == 0 && Token::Match(tok3->previous(), "[<,]")) typesUsedInTemplateInstantiation.push_back(tok3); // add additional type information if (tok3->str() != "class") { if (tok3->isUnsigned()) typeForNewNameStr += "unsigned"; else if (tok3->isSigned()) typeForNewNameStr += "signed"; if (tok3->isLong()) typeForNewNameStr += "long"; typeForNewNameStr += tok3->str(); } } templateMatchPattern += ">"; const std::string typeForNewName(typeForNewNameStr); if (typeForNewName.empty() || typeParametersInDeclaration.size() != typesUsedInTemplateInstantiation.size()) { if (_settings->debugwarnings) { std::list<const Token *> callstack(1, tok); errorlogger.reportErr(ErrorLogger::ErrorMessage(callstack, &tokenlist, Severity::debug, "debug", "Failed to instantiate template. The checking continues anyway.", false)); } if (typeForNewName.empty()) continue; break; } // New classname/funcname.. const std::string newName(name + "<" + typeForNewName + ">"); if (expandedtemplates.find(newName) == expandedtemplates.end()) { expandedtemplates.insert(newName); TemplateSimplifier::expandTemplate(tokenlist, tok,name,typeParametersInDeclaration,newName,typesUsedInTemplateInstantiation,templateInstantiations); instantiated = true; } // Replace all these template usages.. std::list< std::pair<Token *, Token *> > removeTokens; for (Token *tok4 = tok2; tok4; tok4 = tok4->next()) { if (Token::simpleMatch(tok4, templateMatchPattern.c_str())) { Token * tok5 = tok4->tokAt(2); unsigned int typeCountInInstantiation = 1U; // There is always at least one type const Token *typetok = (!typesUsedInTemplateInstantiation.empty()) ? typesUsedInTemplateInstantiation[0] : 0; unsigned int indentlevel5 = 0; // indentlevel for tok5 while (tok5 && (indentlevel5 > 0 || tok5->str() != ">")) { if (tok5->str() == "<" && templateParameters(tok5) > 0) ++indentlevel5; else if (indentlevel5 > 0 && Token::Match(tok5, "> [,>]")) --indentlevel5; else if (indentlevel5 == 0) { if (tok5->str() != ",") { if (!typetok || tok5->isUnsigned() != typetok->isUnsigned() || tok5->isSigned() != typetok->isSigned() || tok5->isLong() != typetok->isLong()) { break; } typetok = typetok ? typetok->next() : 0; } else { typetok = (typeCountInInstantiation < typesUsedInTemplateInstantiation.size()) ? typesUsedInTemplateInstantiation[typeCountInInstantiation] : 0; ++typeCountInInstantiation; } } tok5 = tok5->next(); } // matching template usage => replace tokens.. // Foo < int > => Foo<int> if (tok5 && tok5->str() == ">" && typeCountInInstantiation == typesUsedInTemplateInstantiation.size()) { tok4->str(newName); for (Token *tok6 = tok4->next(); tok6 != tok5; tok6 = tok6->next()) { if (tok6->isName()) templateInstantiations.remove(tok6); } removeTokens.push_back(std::pair<Token*,Token*>(tok4, tok5->next())); } tok4 = tok5; if (!tok4) break; } } while (!removeTokens.empty()) { Token::eraseTokens(removeTokens.back().first, removeTokens.back().second); removeTokens.pop_back(); } } // Template has been instantiated .. then remove the template declaration return instantiated; }
bool Arbitrator::validate(void) { ErrorLogger* logger = ErrorLogger::Instance(); if(!trainWeights()) return false; #ifdef WITH_YARPMATH //#if (GSL_MAJOR_VERSION >= 1 && GSL_MINOR_VERSION >= 14) int n = alphas.size(); if(n == 0) return true; yarp::sig::Matrix A(n, n); std::map<std::string, std::map<std::string, double> >::iterator itr; // iterating over rows std::map<std::string, std::map<std::string, double> >::iterator jtr; // iterating over cols int row = 0; for(itr=alphas.begin(); itr!=alphas.end(); itr++) { std::map<std::string, double>& w = itr->second; int col = 0; for(jtr=alphas.begin(); jtr!=alphas.end(); jtr++) { std::string opnd = jtr->first; if(w.find(opnd) != w.end()) A(row,col) = w[opnd]; else A(row,col) = 0.0; col++; } row++; } //printf("%s\n\n", A.toString(1).c_str()); yarp::sig::Vector real; yarp::sig::Vector img; yarp::math::eingenValues(A, real, img); bool bStable = true; for(size_t i=0; i<real.size(); i++) { if((float)fabs(real[i]) >= 1.0) { bStable = false; logger->addError("Inconsistency in logical expressions. This will result an unstable arbitration system!"); break; } } return bStable; /* gsl_vector_complex *eval = gsl_vector_complex_alloc(n); gsl_matrix_complex *evec = gsl_matrix_complex_alloc(n, n); gsl_eigen_nonsymmv_workspace * w = gsl_eigen_nonsymmv_alloc(n); gsl_eigen_nonsymmv ((gsl_matrix *)A.getGslMatrix(), eval, evec, w); bool bStable = true; for(int i=0; i<n; i++) { gsl_complex eval_i = gsl_vector_complex_get (eval, i); if((float)fabs(GSL_REAL(eval_i)) >= 1.0) { bStable = false; logger->addError("Inconsistency in logical expressions. This will result an unstable arbitration system!"); break; } //printf ("eigenvalue = %.2f + %.2fi\n", GSL_REAL(eval_i), GSL_IMAG(eval_i)); } gsl_eigen_nonsymmv_free(w); gsl_vector_complex_free(eval); gsl_matrix_complex_free(evec); return bStable; */ //#else //GSL_VERSION // logger->addWarning("The version of GNU Scientific Library (GSL) used in libYarpMath is insufficient (GSL_VERSION < 1.14). Your compact logical expression might result an unstable arbitration system!"); // return true; //#endif //GSL_VERSION #else //WITH_YARPMATH logger->addWarning("Yarpmanager is compiled without libYarpMath. Your compact logical expression might result an unstable arbitration system!"); return true; #endif //WITH_YARPMATH }