YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
manager.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-License-Identifier: BSD-3-Clause
4 */
5
6#include <cstring>
17#include <yarp/os/LogStream.h>
18#include <set>
19
21
22
23#define RUN_TIMEOUT 10 // Run timeout in seconds
24#define STOP_TIMEOUT 30 // Stop timeout in seconds
25#define KILL_TIMEOUT 10 // kill timeout in seconds
26
27#define BROKER_LOCAL "local"
28#define BROKER_YARPRUN "yarprun"
29#define BROKER_YARPDEV "yarpdev"
30
31
32using namespace yarp::manager;
33
34
39Manager::Manager(bool withWatchDog) : MEvent()
40{
41 logger = ErrorLogger::Instance();
42 bWithWatchDog = withWatchDog;
43 bAutoDependancy = false;
44 bAutoConnect = false;
45 bRestricted = false;
46 strDefBroker = BROKER_YARPRUN;
47 knowledge.createFrom(nullptr, nullptr, nullptr);
48 connector.init();
49}
50
51Manager::Manager(const char* szModPath, const char* szAppPath,
52 const char* szResPath, bool withWatchDog)
53{
54 logger = ErrorLogger::Instance();
55 bWithWatchDog = withWatchDog;
56 bAutoDependancy = false;
57 bAutoConnect = false;
58 bRestricted = false;
59 strDefBroker = BROKER_YARPRUN;
60
61 XmlModLoader modload(szModPath, nullptr);
62 XmlModLoader* pModLoad = &modload;
63 if (!modload.init()) {
64 pModLoad = nullptr;
65 }
66
67 XmlAppLoader appload(szAppPath, nullptr);
68 XmlAppLoader* pAppLoad = &appload;
69 if (!appload.init()) {
70 pAppLoad = nullptr;
71 }
72
73 XmlResLoader resload(szResPath, nullptr);
74 XmlResLoader* pResLoad = &resload;
75 if (!resload.init()) {
76 pResLoad = nullptr;
77 }
78
79 knowledge.createFrom(pModLoad, pAppLoad, pResLoad);
80 connector.init();
81}
82
83
85{
86 // untopic persistent connections
87 rmconnect();
88 clearExecutables();
89}
90
91bool Manager::addApplication(const char* szFileName, char** szAppName_, bool modifyName)
92{
93 if (find(listOfXml.begin(), listOfXml.end(), szFileName) == listOfXml.end()) {
94 listOfXml.emplace_back(szFileName);
95 } else {
96 return true; //it means that the app exist already so it is safe to return true
97 }
98 XmlAppLoader appload(szFileName);
99 if (!appload.init()) {
100 return false;
101 }
102 Application* application = appload.getNextApplication();
103 if (!application) {
104 return false;
105 }
106
107 return knowledge.addApplication(application, szAppName_, modifyName);
108}
109
110
111bool Manager::addApplications(const char* szPath)
112{
113 XmlAppLoader appload(szPath, nullptr);
114 if (!appload.init()) {
115 return false;
116 }
117 Application* application;
118 while((application = appload.getNextApplication()))
119 {
120 const char* currentFile = application->getXmlFile();
121 knowledge.addApplication(application);
122 listOfXml.emplace_back(currentFile);
123 }
124 return true;
125}
126
127
128bool Manager::addModule(const char* szFileName)
129{
130 XmlModLoader modload(szFileName);
131 if (!modload.init()) {
132 return false;
133 }
134 Module* themodule = modload.getNextModule();
135 if (!themodule) {
136 return false;
137 }
138 return knowledge.addModule(themodule);
139}
140
141
142bool Manager::addModules(const char* szPath)
143{
144 XmlModLoader modload(szPath, nullptr);
145 if (!modload.init()) {
146 return false;
147 }
148 Module* themodule;
149 while ((themodule = modload.getNextModule())) {
150 knowledge.addModule(themodule);
151 }
152 return true;
153}
154
155
156bool Manager::addResource(const char* szFileName)
157{
158 XmlResLoader resload(szFileName);
159 if (!resload.init()) {
160 return false;
161 }
162 GenericResource* resource;
163 bool bloaded = false;
164 while ((resource = resload.getNextResource())) {
165 bloaded |= knowledge.addResource(resource);
166 }
167 return bloaded;
168}
169
170
171bool Manager::addResources(const char* szPath)
172{
173 XmlResLoader resload(szPath, nullptr);
174 if (!resload.init()) {
175 return false;
176 }
177 GenericResource* resource;
178 while ((resource = resload.getNextResource())) {
179 knowledge.addResource(resource);
180 }
181 return true;
182}
183
184
185bool Manager::removeApplication(const char *szFileName, const char* szAppName)
186{
187 //Note: use it with care. it is better we first check that no application
188 //is loaded.
189 if(!runnables.empty())
190 {
191 logger->addError("Application cannot be removed if there is a loaded application");
192 return false;
193 }
194 listOfXml.erase(std::remove(listOfXml.begin(), listOfXml.end(), szFileName), listOfXml.end());
195 Application* app = knowledge.getApplication(szAppName);
196 if (!app) {
197 return false;
198 }
199 return knowledge.removeApplication(app);
200}
201
202
203bool Manager::removeModule(const char* szModName)
204{
205 //Note: use it with care. it is better we first check that no application
206 //is loaded.
207 if(!runnables.empty())
208 {
209 logger->addError("Module cannot be removed if there is a loaded application");
210 return false;
211 }
212
213 Module* mod = knowledge.getModule(szModName);
214 if (!mod) {
215 return false;
216 }
217
218 return knowledge.removeModule(mod);
219}
220
221bool Manager::removeResource(const char* szResName)
222{
223 //Note: use it with care. it is better we first check that no application
224 //is loaded.
225 if(!runnables.empty())
226 {
227 logger->addError("Resource cannot be removed if there is a loaded application");
228 return false;
229 }
230
231 GenericResource* res = knowledge.getResource(szResName);
232 if (!res) {
233 return false;
234 }
235
236 return knowledge.removeResource(res);
237}
238
239
240
241bool Manager::loadApplication(const char* szAppName)
242{
243 __CHECK_NULLPTR(szAppName);
244
245 if(!allStopped())
246 {
247 logger->addError("Please stop current running application first.");
248 return false;
249 }
250
251 strAppName = szAppName;
252
253 // set all resources as unavailable
254 ResourcePContainer allresources = knowledge.getResources();
255 for(auto& allresource : allresources)
256 {
257 auto* comp = dynamic_cast<Computer*>(allresource);
258 if (comp) {
259 comp->setAvailability(false);
260 }
261 }
262
263 return prepare(true);
264}
265
266
267bool Manager::saveApplication(const char* szAppName, const char* fileName)
268{
269 Application* pApp = knowledge.getApplication();
270 __CHECK_NULLPTR(pApp);
271
272 XmlAppSaver appsaver(fileName);
273 return knowledge.saveApplication(&appsaver, pApp);
274}
275
276
278{
280 bool ret = prepare(false);
281 return ret;
282}
283
285{
286 if (id < runnables.size())
287 {
288 return runnables[id];
289 }
290 else
291 {
292 return nullptr;
293 }
294}
295
297{
298 Executable* exe = getExecutableById(id);
299 if (removeBroker(exe))
300 {
301 modules[id]->setHost(exe->getHost());
302 Broker* broker = createBroker(modules[id]);
303 if ( broker == nullptr)
304 {
305 return false;
306 }
307 broker->setDisplay(modules[id]->getDisplay());
308 exe->setAndInitializeBroker(broker);
309 }
310 else
311 {
312 return false;
313 }
314 return true;
315}
316
317
318bool Manager::prepare(bool silent)
319{
320 knowledge.reasolveDependency(strAppName.c_str(), bAutoDependancy, silent);
321
322 clearExecutables();
323 connections.clear();
324 modules.clear();
325 resources.clear();
326 connections = knowledge.getSelConnection();
327 modules = knowledge.getSelModules();
328 resources = knowledge.getSelResources();
329
338 ModulePIterator itr;
339 int id = 0;
340 for(itr=modules.begin(); itr!=modules.end(); itr++)
341 {
342 Broker* broker = createBroker(*itr);
343 broker->setDisplay((*itr)->getDisplay());
344 auto* exe = new Executable(broker, (MEvent*)this, *itr, bWithWatchDog);
345 exe->setID(id++);
346 exe->setCommand((*itr)->getName());
347 exe->setParam((*itr)->getParam());
348 exe->setHost((*itr)->getHost());
349 exe->setStdio((*itr)->getStdio());
350 exe->setWorkDir((*itr)->getWorkDir());
351 exe->setPostExecWait((*itr)->getPostExecWait());
352 exe->setPostStopWait((*itr)->getPostStopWait());
353 exe->setOriginalPostExecWait((*itr)->getPostExecWait());
354 exe->setOriginalPostStopWait((*itr)->getPostStopWait());
355 std::string env;
356 if ((*itr)->getPrefix() && strlen((*itr)->getPrefix())) {
357 env = std::string("YARP_PORT_PREFIX=") + std::string((*itr)->getPrefix());
358 }
359 if ((*itr)->getEnvironment() && strlen((*itr)->getEnvironment())) {
360 env += (env.length()) ? (std::string(";") + (*itr)->getEnvironment()) : (*itr)->getEnvironment();
361 }
362 exe->setEnv(env.c_str());
363
369 //CnnIterator cnn;
370 //for(cnn=connections.begin(); cnn!=connections.end(); cnn++)
371 // if((*cnn).owner() == (*itr))
372 // exe->addConnection(*cnn);
373
377 for(auto& resource : resources)
378 {
379 auto* res = dynamic_cast<ResYarpPort*>(resource);
380 if (res && (res->owner() == (*itr))) {
381 exe->addResource(*res);
382 }
383 }
384
385 runnables.push_back(exe);
386 }
387
388 return true;
389}
390
391Broker* Manager::createBroker(Module* themodule)
392{
393 if(strlen(themodule->getBroker()) == 0)
394 {
395 if (compareString(themodule->getHost(), "localhost")) {
396 return (new LocalBroker());
397 } else {
398 return (new YarpBroker());
399 }
400 }
401 else if(compareString(themodule->getBroker(), BROKER_YARPDEV))
402 {
403 if (compareString(themodule->getHost(), "localhost")) {
404 return (new YarpdevLocalBroker());
405 } else {
406 return (new YarpdevYarprunBroker());
407 }
408 } else if (compareString(themodule->getHost(), "localhost")) {
409 return (new ScriptLocalBroker(themodule->getBroker()));
410 }
411
412 return (new ScriptYarprunBroker(themodule->getBroker()));
413}
414
415bool Manager::removeBroker(Executable* exe)
416{
417 if (exe == nullptr)
418 {
419 return false;
420 }
421 else if(exe->state() == RUNNING)
422 {
423 exe->stop();
424 exe->stopWatchDog();
425 }
426
427 exe->removeBroker(); //TODO possible race condition in case watchdog enabled.
428 return true;
429}
430
431bool Manager::updateExecutable(unsigned int id, const char* szparam,
432 const char* szhost, const char* szstdio,
433 const char* szworkdir, const char* szenv )
434{
435 if(runnables.empty())
436 {
437 logger->addError("Application is not loaded.");
438 return false;
439 }
440
441 if(id>=runnables.size())
442 {
443 logger->addError("Module id is out of range.");
444 return false;
445 }
446
447 Executable* exe = runnables[id];
448 exe->setParam(szparam);
449 exe->setHost(szhost);
450 exe->setStdio(szstdio);
451 exe->setWorkDir(szworkdir);
452 exe->setEnv(szenv);
453 return true;
454}
455
456
457bool Manager::updateConnection(unsigned int id, const char* from,
458 const char* to, const char* carrier)
459{
460 if(id>=connections.size())
461 {
462 logger->addError("Connection id is out of range.");
463 return false;
464 }
465
466 /*
467 if(connections[id].owner())
468 {
469 OSTRINGSTREAM msg;
470 msg<<"Connection ["<<connections[id].from()<<" -> ";
471 msg<<connections[id].to()<<"] cannot be updated.";
472 logger->addWarning(msg);
473 return false;
474 }
475 */
476
477 connections[id].setFrom(from);
478 connections[id].setTo(to);
479 connections[id].setCarrier(carrier);
480
481 return true;
482}
483
484Node* Manager::getNode(std::string appName)
485{
486 Node* node = knowledge.getNode(appName);
487 return node;
488}
489
490bool Manager::exist(unsigned int id)
491{
492 if(id>=resources.size())
493 {
494 logger->addError("Resource id is out of range.");
495 return false;
496 }
497
498 GenericResource* res = resources[id];
499 if (compareString(res->getName(), "localhost")) {
500 return true;
501 }
502
503 if(dynamic_cast<Computer*>(res) || dynamic_cast<ResYarpPort*>(res))
504 {
505 if(res->getName())
506 {
507 //YarpBroker broker;
508 //broker.init();
509 std::string strPort = res->getName();
510 if (strPort[0] != '/') {
511 strPort = std::string("/") + strPort;
512 }
513 if(dynamic_cast<ResYarpPort*>(res))
514 {
515 res->setAvailability(connector.exists(strPort.c_str()));
516 }
517 else //if it is a computer I have to be sure that the port has been opened through yarp runner
518 {
519 yarp::os::Bottle cmd, reply;
520 cmd.addString("get");
521 cmd.addString(strPort);
522 cmd.addString("yarprun");
523 bool ret = yarp::os::impl::NameClient::getNameClient().send(cmd, reply);
524 if(!ret)
525 {
526 yError()<<"Manager::Cannot contact the NameClient";
527 return false;
528 }
529 if(reply.size()==6)
530 {
531 if(reply.get(5).asBool())
532 {
533 res->setAvailability(true);
534 }
535 else
536 {
537 res->setAvailability(false);
538 }
539
540 }
541 else
542 {
543 res->setAvailability(false);
544 }
545
546 }
547
548 }
549 }
550 return res->getAvailability();
551}
552
553
555{
556 YarpBroker broker;
557 broker.init();
558
559 // finding all available yarp ports
560 std::vector<std::string> ports;
561 broker.getAllPorts(ports);
562
563 ResourcePContainer allresources = knowledge.getResources();
564 for(auto& allresource : allresources)
565 {
566 auto* comp = dynamic_cast<Computer*>(allresource);
567 if(comp && updateResource(comp))
568 {
569 //set all as unavailable
570 for(int i=0; i<comp->peripheralCount(); i++)
571 {
572 auto* res = dynamic_cast<ResYarpPort*>(&comp->getPeripheralAt(i));
573 if (res) {
574 res->setAvailability(false);
575 }
576 }
577
578 // adding all available yarp ports as peripherals
579 for(auto& port : ports)
580 {
581 ResYarpPort resport;
582 resport.setName(port.c_str());
583 resport.setPort(port.c_str());
584
585 bool bfound = false;
586 for(int i=0; i<comp->peripheralCount(); i++)
587 {
588 auto* res = dynamic_cast<ResYarpPort*>(&comp->getPeripheralAt(i));
589 if(res && (std::string(res->getName()) == std::string(resport.getName())))
590 {
591 res->setAvailability(true);
592 bfound = true;
593 break;
594 }
595 }
596 if (!bfound) {
597 comp->addPeripheral(resport);
598 }
599 }
600 }
601 } // end of for
602
603 return true;
604}
605
606
607bool Manager::updateResource(const char* szName)
608{
609 GenericResource* res = knowledge.getResource(szName);
610 if (!res) {
611 return false;
612 }
613 return updateResource(res);
614}
615
617{
618 YarpBroker broker;
619 broker.init();
620
621 auto* comp = dynamic_cast<Computer*>(resource);
622 if (!comp || !strlen(comp->getName())) {
623 return false;
624 }
625
626 if (compareString(comp->getName(), "localhost")) {
627 return false;
628 }
629
631 std::string strServer = comp->getName();
632 if (strServer[0] != '/') {
633 strServer = std::string("/") + strServer;
634 }
635 if(!broker.getSystemInfo(strServer.c_str(), info))
636 {
637 logger->addError(broker.error());
638 comp->setAvailability(false);
639 }
640 else
641 {
642 comp->setAvailability(true);
643
644 comp->getMemory().setTotalSpace(info.memory.totalSpace*1024);
645 comp->getMemory().setFreeSpace(info.memory.freeSpace*1024);
646
647 comp->getStorage().setTotalSpace(info.storage.totalSpace*1024);
648 comp->getStorage().setFreeSpace(info.storage.freeSpace*1024);
649
650 //comp->getNetwork().setIP4(info.network.ip4.c_str());
651 //comp->getNetwork().setIP6(info.network.ip6.c_str());
652 //comp->getNetwork().setMAC(info.network.mac.c_str());
653
654
655 comp->getProcessor().setArchitecture(info.processor.architecture.c_str());
656 comp->getProcessor().setCores(info.processor.cores);
657 comp->getProcessor().setSiblings(info.processor.siblings);
658 comp->getProcessor().setFrequency(info.processor.frequency);
659 comp->getProcessor().setModel(info.processor.model.c_str());
660 LoadAvg load;
661 load.loadAverageInstant = (double)info.load.cpuLoadInstant;
662 load.loadAverage1 = info.load.cpuLoad1;
663 load.loadAverage5 = info.load.cpuLoad5;
664 load.loadAverage15 = info.load.cpuLoad15;
665 comp->getProcessor().setCPULoad(load);
666
667 comp->getPlatform().setName(info.platform.name.c_str());
668 comp->getPlatform().setDistribution(info.platform.distribution.c_str());
669 comp->getPlatform().setRelease(info.platform.release.c_str());
670 }
671 return true;
672}
673
674bool Manager::waitingModuleRun(unsigned int id)
675{
676 double base = yarp::os::Time::now();
677 double wait = runnables[id]->getPostExecWait() + RUN_TIMEOUT;
678 while (!timeout(base, wait)) {
679 if (running(id)) {
680 return true;
681 }
682 }
683
684 OSTRINGSTREAM msg;
685 msg<<"Failed to run "<<runnables[id]->getCommand();
686 msg<<" on "<<runnables[id]->getHost();
687 msg<<". (State: "<<runnables[id]->state();
688 msg<<", parameter: "<<runnables[id]->getParam()<<")";
689 logger->addError(msg);
690 return false;
691
692}
693
694bool Manager::waitingModuleStop(unsigned int id)
695{
696 double base = yarp::os::Time::now();
697 while (!timeout(base, STOP_TIMEOUT)) {
698 if (!running(id)) {
699 return true;
700 }
701 }
702
703 OSTRINGSTREAM msg;
704 msg<<"Failed to stop "<<runnables[id]->getCommand();
705 msg<<" on "<<runnables[id]->getHost();
706 msg<<". (State: "<<runnables[id]->state();
707 msg<<", paramete: "<<runnables[id]->getParam()<<")";
708 logger->addError(msg);
709 return false;
710}
711
712bool Manager::waitingModuleKill(unsigned int id)
713{
714 double base = yarp::os::Time::now();
715 while (!timeout(base, KILL_TIMEOUT)) {
716 if (!running(id)) {
717 return true;
718 }
719 }
720
721 OSTRINGSTREAM msg;
722 msg<<"Failed to kill "<<runnables[id]->getCommand();
723 msg<<" on "<<runnables[id]->getHost();
724 msg<<". (State: "<<runnables[id]->state();
725 msg<<", paramete: "<<runnables[id]->getParam()<<")";
726 logger->addError(msg);
727 return false;
728
729}
730
731
732bool Manager::existPortFrom(unsigned int id)
733{
734 if(id>=connections.size())
735 {
736 logger->addError("Connection id is out of range.");
737 return false;
738 }
739 std::string portName(connections[id].from());
740 if(portName.find(' ') != std::string::npos)
741 {
742 std::string message = "Port name \"" + portName + "\" contains spaces.";
743 logger->addError(message.c_str());
744 return false;
745 }
746
747 bool exists = connector.exists(portName.c_str());
748 connections[id].setFromExists(exists);
749 return exists;
750}
751
752
753bool Manager::existPortTo(unsigned int id)
754{
755 if(id>=connections.size())
756 {
757 logger->addError("Connection id is out of range.");
758 return false;
759 }
760 std::string portName(connections[id].to());
761 if(portName.find(' ') != std::string::npos)
762 {
763 std::string message = "Port name \"" + portName + "\" contains spaces.";
764 logger->addError(message.c_str());
765 return false;
766 }
767
768 bool exists = connector.exists(portName.c_str());
769 connections[id].setToExists(exists);
770 return exists;
771}
772
773
775{
781 bool ret = true;
782 ResourcePIterator itrRes;
783 for(itrRes=resources.begin(); itrRes!=resources.end(); itrRes++)
784 {
785 if(!(*itrRes)->getAvailability())
786 {
787 ret = false;
788 OSTRINGSTREAM err;
789 err<<"Resource "<<(*itrRes)->getName()<<" is not available!";
790 logger->addError(err);
791 }
792 }
793
794 return ret;
795}
796
797
798
799bool Manager::run(unsigned int id, bool async)
800{
801 if(runnables.empty())
802 {
803 logger->addError("Application is not loaded.");
804 return false;
805 }
806
807 if(id>=runnables.size())
808 {
809 logger->addError("Module id is out of range.");
810 return false;
811 }
812
813 if (runnables[id]->shouldChangeBroker())
814 {
815 if (!switchBroker(id))
816 {
817 logger->addError("Failing to switch broker");
818 return false;
819 }
820 }
821
822 runnables[id]->disableAutoConnect();
823 runnables[id]->start();
824 if(bWithWatchDog) {
826 runnables[id]->startWatchDog();
827 }
828 if (async) {
829 return true;
830 }
831
832 // waiting for running
833 return waitingModuleRun(id);
834}
835
837{
838 if(runnables.empty())
839 {
840 logger->addError("Application is not loaded.");
841 return false;
842 }
843
844 if(!checkDependency())
845 {
846 if(bRestricted)
847 {
848 logger->addError("Some of external ports dependency are not satisfied.");
849 return false;
850 } else {
851 logger->addWarning("Some of external ports dependency are not satisfied.");
852 }
853 }
854
856 double wait = 0.0;
857 for(itr=runnables.begin(); itr!=runnables.end(); itr++)
858 {
859 if (bAutoConnect) {
860 (*itr)->enableAutoConnect();
861 } else {
862 (*itr)->disableAutoConnect();
863 }
864 (*itr)->start();
866 wait = (wait > (*itr)->getPostExecWait()) ? wait : (*itr)->getPostExecWait();
867 }
868
869 // waiting for running
870 double base = yarp::os::SystemClock::nowSystem();
871 while (!timeout(base, wait + RUN_TIMEOUT)) {
872 if (allRunning()) {
873 break;
874 }
875 }
876
877 // starting the watchdog if needed
878 if(bWithWatchDog) {
879 for (itr = runnables.begin(); itr != runnables.end(); itr++) {
880 (*itr)->startWatchDog();
881 }
882 }
883
884 if(!allRunning())
885 {
887 for (itr = runnables.begin(); itr != runnables.end(); itr++) {
888 if((*itr)->state() != RUNNING)
889 {
890 OSTRINGSTREAM msg;
891 msg<<"Failed to run "<<(*itr)->getCommand();
892 msg<<" on "<<(*itr)->getHost();
893 msg<<". (State: "<<(*itr)->state();
894 msg<<", parameter: "<<(*itr)->getParam()<<")";
895 logger->addError(msg);
896 }
897 }
898
899 if(bRestricted)
900 {
901 kill();
902 return false;
903 }
904 }
905
906 /* connecting extra ports*/
907 if (bAutoConnect) {
908 if(!connectExtraPorts())
909 {
910 logger->addError("Failed to stablish some of connections.");
911 if (bRestricted) {
912 return false;
913 }
914 }
915 }
916
917 return true;
918}
919
920bool Manager::stop(unsigned int id, bool async)
921{
922 if(runnables.empty())
923 {
924 logger->addError("Application is not loaded.");
925 return false;
926 }
927
928 if(id>=runnables.size())
929 {
930 logger->addError("Module id is out of range.");
931 return false;
932 }
933
934 runnables[id]->stop();
935
936 if (async) {
937 return true;
938 }
939
940 // waiting for stop
941 return waitingModuleStop(id);
942}
943
944
946{
947 if (runnables.empty()) {
948 return true;
949 }
950
952 for(itr=runnables.begin(); itr!=runnables.end(); itr++)
953 {
954 (*itr)->stop();
956 }
957
958 double base = yarp::os::SystemClock::nowSystem();
959 while (!timeout(base, STOP_TIMEOUT)) {
960 if (allStopped()) {
961 break;
962 }
963 }
964
965 if(!allStopped())
966 {
968 for (itr = runnables.begin(); itr != runnables.end(); itr++) {
969 if( ((*itr)->state() != SUSPENDED) &&
970 ((*itr)->state() != DEAD))
971 {
972 OSTRINGSTREAM msg;
973 msg<<"Failed to stop "<<(*itr)->getCommand();
974 msg<<" on "<<(*itr)->getHost();
975 msg<<". (State: "<<(*itr)->state();
976 msg<<", paramete: "<<(*itr)->getParam()<<")";
977 logger->addError(msg);
978 }
979 }
980 return false;
981 }
982
983 return true;
984}
985
986bool Manager::kill(unsigned int id, bool async)
987{
988 if(runnables.empty())
989 {
990 logger->addError("Application is not loaded.");
991 return false;
992 }
993
994 if(id>=runnables.size())
995 {
996 logger->addError("Module id is out of range.");
997 return false;
998 }
999
1000 runnables[id]->kill();
1001
1002 if (async) {
1003 return true;
1004 }
1005 return waitingModuleKill(id);
1006}
1007
1008
1010{
1011 if (runnables.empty()) {
1012 return true;
1013 }
1014
1016 for(itr=runnables.begin(); itr!=runnables.end(); itr++)
1017 {
1018 (*itr)->kill();
1020 }
1021
1022 double base = yarp::os::SystemClock::nowSystem();
1023 while (!timeout(base, KILL_TIMEOUT)) {
1024 if (allStopped()) {
1025 break;
1026 }
1027 }
1028
1029 if(!allStopped())
1030 {
1032 for (itr = runnables.begin(); itr != runnables.end(); itr++) {
1033 if( ((*itr)->state() != SUSPENDED) &&
1034 ((*itr)->state() != DEAD))
1035 {
1036 OSTRINGSTREAM msg;
1037 msg<<"Failed to kill "<<(*itr)->getCommand();
1038 msg<<" on "<<(*itr)->getHost();
1039 msg<<". (State: "<<(*itr)->state();
1040 msg<<", paramete: "<<(*itr)->getParam()<<")";
1041 logger->addError(msg);
1042 }
1043 }
1044 return false;
1045 }
1046
1047 return true;
1048}
1049
1050
1051void Manager::clearExecutables()
1052{
1054 for(itr=runnables.begin(); itr!=runnables.end(); itr++)
1055 {
1056 // broker will be deleted by Executable
1057 delete (*itr);
1058 }
1059 runnables.clear();
1060}
1061
1062
1063bool Manager::connect(unsigned int id)
1064{
1065 if(id>=connections.size())
1066 {
1067 logger->addError("Connection id is out of range.");
1068 return false;
1069 }
1070
1071 //YarpBroker connector;
1072 //connector.init();
1073
1074 if( !connector.connect(connections[id].from(),
1075 connections[id].to(),
1076 connections[id].carrier(),
1077 connections[id].isPersistent()) )
1078 {
1079 logger->addError(connector.error());
1080 //cout<<connector.error()<<endl;
1081 return false;
1082 }
1083
1084 // setting the connection Qos if specified
1085 return connector.setQos(connections[id].from(),
1086 connections[id].to(),
1087 connections[id].qosFrom(),
1088 connections[id].qosTo());
1089}
1090
1092{
1093 //YarpBroker connector;
1094 //connector.init();
1095 CnnIterator cnn;
1096 for(cnn=connections.begin(); cnn!=connections.end(); cnn++) {
1097 if( !(*cnn).getFromExists() ||
1098 !(*cnn).getToExists() ||
1099 !connector.connect((*cnn).from(), (*cnn).to(),
1100 (*cnn).carrier(), (*cnn).isPersistent()) )
1101 {
1102 logger->addError(connector.error());
1103 //cout<<connector.error()<<endl;
1104 if (bRestricted) {
1105 return false;
1106 }
1107 }
1108
1109 // setting the connection Qos if specified
1110 if(! connector.setQos((*cnn).from(), (*cnn).to(),
1111 (*cnn).qosFrom(), (*cnn).qosTo())) {
1112 if (bRestricted) {
1113 return false;
1114 }
1115 }
1116 }
1117 return true;
1118}
1119
1120bool Manager::disconnect(unsigned int id)
1121{
1122 if(id>=connections.size())
1123 {
1124 logger->addError("Connection id is out of range.");
1125 return false;
1126 }
1127
1128 //YarpBroker connector;
1129 //connector.init();
1130
1131 if( !connector.disconnect(connections[id].from(),
1132 connections[id].to(),
1133 connections[id].carrier()) )
1134 {
1135 logger->addError(connector.error());
1136 //cout<<connector.error()<<endl;
1137 return false;
1138 }
1139
1140 return true;
1141}
1142
1144{
1145 //YarpBroker connector;
1146 //connector.init();
1147 CnnIterator cnn;
1148 for (cnn = connections.begin(); cnn != connections.end(); cnn++) {
1149 if( !connector.disconnect((*cnn).from(), (*cnn).to(), (*cnn).carrier()) )
1150 {
1151 logger->addError(connector.error());
1152 //cout<<connector.error()<<endl;
1153 return false;
1154 }
1155 }
1156 return true;
1157}
1158
1159
1160bool Manager::rmconnect(unsigned int id)
1161{
1162 if(id>=connections.size())
1163 {
1164 logger->addError("Connection id is out of range.");
1165 return false;
1166 }
1167
1168 if(!connector.rmconnect(connections[id].from(),
1169 connections[id].to()) )
1170 {
1171 logger->addError(connector.error());
1172 return false;
1173 }
1174
1175 return true;
1176}
1177
1178
1180{
1181 CnnIterator cnn;
1182 for (cnn = connections.begin(); cnn != connections.end(); cnn++) {
1183 if( !connector.rmconnect((*cnn).from(), (*cnn).to()) )
1184 {
1185 logger->addError(connector.error());
1186 return false;
1187 }
1188 }
1189 return true;
1190}
1191
1192
1193bool Manager::connected(unsigned int id)
1194{
1195 if(id>=connections.size())
1196 {
1197 logger->addError("Connection id is out of range.");
1198 return false;
1199 }
1200
1201 return connections[id].getFromExists() &&
1202 connections[id].getToExists() &&
1203 connector.connected(connections[id].from(),
1204 connections[id].to(),
1205 connections[id].carrier());
1206}
1207
1208
1210{
1211 //YarpBroker connector;
1212 //connector.init();
1213 CnnIterator cnn;
1214 bool bConnected = true;
1215 for (cnn = connections.begin(); cnn != connections.end(); cnn++) {
1216 if (!(*cnn).getFromExists() || !(*cnn).getToExists() || !connector.connected((*cnn).from(), (*cnn).to(), (*cnn).carrier())) {
1217 bConnected = false;
1218 }
1219 }
1220 return bConnected;
1221}
1222
1223bool Manager::checkPortsAvailable(Broker* broker)
1224{
1225 CnnIterator itr;
1226 for(itr=connections.begin(); itr!=connections.end(); itr++)
1227 {
1228 //if(!(*itr).owner() )
1229 // {
1230 if (!broker->exists((*itr).to()) || !broker->exists((*itr).from())) {
1231 return false;
1232 }
1233 // }
1234 }
1235 return true;
1236}
1237
1238
1239bool Manager::connectExtraPorts()
1240{
1241 //YarpBroker connector;
1242 //connector.init();
1243
1244 double base = yarp::os::SystemClock::nowSystem();
1245 while (!timeout(base, 10.0)) {
1246 if (checkPortsAvailable(&connector)) {
1247 break;
1248 }
1249 }
1250
1251 CnnIterator cnn;
1252 for(cnn=connections.begin(); cnn!=connections.end(); cnn++)
1253 {
1254 //if(!(*cnn).owner() )
1255 //{
1256 if( !connector.connect((*cnn).from(), (*cnn).to(),
1257 (*cnn).carrier()) )
1258 {
1259 logger->addError(connector.error());
1260 //cout<<connector.error()<<endl;
1261 return false;
1262 }
1263 //}
1264 }
1265 return true;
1266}
1267
1268bool Manager::running(unsigned int id)
1269{
1270 if(id>=runnables.size())
1271 {
1272 logger->addError("Module id is out of range.");
1273 return false;
1274 }
1275
1276 RSTATE st = runnables[id]->state();
1277 if ((st == RUNNING) || (st == CONNECTING) || (st == DYING)) {
1278 return true;
1279 }
1280 return false;
1281}
1282
1283void Manager::collectYarprunProcessesByHost(std::map<std::string, ProcessContainer>& hostProcesses,
1284 std::map<std::string, bool>& hostQueryOk)
1285{
1286 hostProcesses.clear();
1287 hostQueryOk.clear();
1288
1289 std::set<std::string> yarprunHosts;
1290 for (auto* exe : runnables) {
1291 if (exe && exe->getBrokerType() == BrokerType::yarp) {
1292 yarprunHosts.insert(exe->getHost());
1293 }
1294 }
1295
1296 if (yarprunHosts.empty()) {
1297 return;
1298 }
1299
1300 YarpBroker queryBroker;
1301 if (!queryBroker.init()) {
1302 for (const auto& host : yarprunHosts) {
1303 hostQueryOk[host] = false;
1304 }
1305 return;
1306 }
1307
1308 for (const auto& host : yarprunHosts) {
1309 ProcessContainer processes;
1310 const bool ok = queryBroker.getAllProcesses(host, processes);
1311 hostQueryOk[host] = ok;
1312 if (ok) {
1313 hostProcesses[host] = processes;
1314 }
1315 }
1316}
1317
1318
1319bool Manager::allRunning()
1320{
1321 if (!runnables.size()) {
1322 return false;
1323 }
1325 for(itr=runnables.begin(); itr!=runnables.end(); itr++)
1326 {
1327 RSTATE st = (*itr)->state();
1328 if ((st != RUNNING) && (st != CONNECTING) && (st != DYING)) {
1329 return false;
1330 }
1331 }
1332 return true;
1333}
1334
1335
1336bool Manager::suspended(unsigned int id)
1337{
1338 if(id>=runnables.size())
1339 {
1340 logger->addError("Module id is out of range.");
1341 return false;
1342 }
1343 RSTATE st = runnables[id]->state();
1344 if ((st == SUSPENDED) || (st == DEAD)) {
1345 return true;
1346 }
1347 return false;
1348}
1349
1350
1351bool Manager::allStopped()
1352{
1353 if (!runnables.size()) {
1354 return true;
1355 }
1357 for(itr=runnables.begin(); itr!=runnables.end(); itr++)
1358 {
1359 RSTATE st = (*itr)->state();
1360 if ((st != SUSPENDED) && (st != DEAD)) {
1361 return false;
1362 }
1363 }
1364 return true;
1365}
1366
1367bool Manager::attachStdout(unsigned int id)
1368{
1369 if(id>=runnables.size())
1370 {
1371 logger->addError("Module id is out of range.");
1372 return false;
1373 }
1374
1375 if(!runnables[id]->getBroker()->attachStdout())
1376 {
1377 OSTRINGSTREAM msg;
1378 msg<<"Cannot attach to stdout of "<<runnables[id]->getCommand();
1379 msg<<" on "<<runnables[id]->getHost();
1380 msg<<". (State: "<<runnables[id]->state();
1381 msg<<", paramete: "<<runnables[id]->getParam()<<") ";
1382 msg<<"because "<<runnables[id]->getBroker()->error();
1383 logger->addError(msg);
1384 return false;
1385 }
1386 return true;
1387}
1388
1389bool Manager::detachStdout(unsigned int id)
1390{
1391 if(id>=runnables.size())
1392 {
1393 logger->addError("Module id is out of range.");
1394 return false;
1395 }
1396
1397 runnables[id]->getBroker()->detachStdout();
1398 return true;
1399}
1400
1401bool Manager::timeout(double base, double t)
1402{
1404 if ((yarp::os::SystemClock::nowSystem() - base) > t) {
1405 return true;
1406 }
1407 return false;
1408}
1409
1410
1411void Manager::onExecutableStart(void* which) {}
1412void Manager::onExecutableStop(void* which) {}
1413void Manager::onCnnStablished(void* which) {}
1414void Manager::onExecutableDied(void* which) {}
1416void Manager::onExecutableStdout(void* which, const char* msg) {}
1417void Manager::onCnnFailed(void* which) {}
1418void Manager::onError(void* which) {}
1419
1420
1421/*
1422bool Manager::loadModule(const char* szModule, const char* szHost)
1423{
1424 __CHECK_NULLPTR(szModule);
1425 strAppName = szModule;
1426
1427 SingleAppLoader appLoader(szModule, szHost);
1428 if(!appLoader.init())
1429 {
1430 logger->addError("Error initializing SingleAppLoader.");
1431 return false;
1432 }
1433
1434 if(!createKnowledgeBase(appLoader))
1435 {
1436 logger->addError("Cannot create knowledge base");
1437 return false;
1438 }
1439
1440 return prepare();
1441
1442}
1443*/
#define yError(...)
Definition Log.h:361
Class Application.
Class Broker.
Definition broker.h:30
void setDisplay(const char *szDisplay)
Definition broker.h:60
virtual bool exists(const std::string &port)=0
void addError(const char *szError)
Definition utility.cpp:126
void addWarning(const char *szWarning)
Definition utility.cpp:104
static ErrorLogger * Instance()
Singleton class ErrorLogger.
Definition utility.cpp:98
Class Executable.
Definition executable.h:71
void setParam(const char *val)
Definition executable.h:82
void setWorkDir(const char *val)
Definition executable.h:85
void setHost(const char *val)
Definition executable.h:83
void setStdio(const char *val)
Definition executable.h:84
void setEnv(const char *val)
Definition executable.h:86
void setAndInitializeBroker(Broker *_broker)
void setAvailability(bool flag)
Definition resource.h:22
void setName(const char *szName)
Definition resource.h:27
bool removeModule(Module *themodule)
Definition kbase.cpp:177
Module * getModule(const char *szName)
Definition kbase.h:81
const CnnContainer & getSelConnection()
Definition kbase.h:68
const ModulePContainer & getSelModules()
Definition kbase.h:67
GenericResource * getResource(const char *szName)
Definition kbase.h:89
bool removeResource(GenericResource *resource)
Definition kbase.cpp:182
const ResourcePContainer & getSelResources()
Definition kbase.h:69
bool reasolveDependency(const char *szName, bool bAutoDependancy=false, bool bSilent=false)
Definition kbase.cpp:894
bool addModule(Module *themodule)
Definition kbase.cpp:120
bool addResource(GenericResource *resource)
Definition kbase.cpp:144
Node * getNode(std::string appName)
Definition kbase.cpp:1664
Application * getApplication()
Definition kbase.h:84
bool removeApplication(Application *application)
Definition kbase.cpp:172
bool createFrom(ModuleLoader *_mloader, AppLoader *_apploader, ResourceLoader *_resloader)
Definition kbase.cpp:19
const ResourcePContainer & getResources(Application *parent=nullptr)
Definition kbase.cpp:261
bool addApplication(Application *application, char **szAppName_=nullptr, bool modifyName=false)
Definition kbase.cpp:76
bool saveApplication(AppSaver *appSaver, Application *application)
Definition kbase.cpp:1304
Class LocalBroker.
Definition localbroker.h:33
void onExecutableStdout(void *which, const char *msg) override
Definition manager.cpp:1416
void onExecutableDied(void *which) override
Definition manager.cpp:1414
void onExecutableStop(void *which) override
Definition manager.cpp:1412
Manager(bool withWatchDog=false)
Class Manager.
Definition manager.cpp:39
bool removeApplication(const char *szFileName, const char *szAppName)
Definition manager.cpp:185
bool updateResource(const char *szName)
Definition manager.cpp:607
bool detachStdout(unsigned int id)
Definition manager.cpp:1389
void onCnnFailed(void *which) override
Definition manager.cpp:1417
bool addModule(const char *szFileName)
Definition manager.cpp:128
bool updateConnection(unsigned int id, const char *from, const char *to, const char *carrier)
Definition manager.cpp:457
bool attachStdout(unsigned int id)
Definition manager.cpp:1367
bool removeModule(const char *szModName)
Definition manager.cpp:203
bool existPortFrom(unsigned int id)
Definition manager.cpp:732
bool addModules(const char *szPath)
Definition manager.cpp:142
bool addResources(const char *szPath)
Definition manager.cpp:171
Node * getNode(std::string appName)
Definition manager.cpp:484
bool addApplication(const char *szFileName, char **szAppName_=nullptr, bool modifyName=false)
Definition manager.cpp:91
bool exist(unsigned int id)
Definition manager.cpp:490
bool existPortTo(unsigned int id)
Definition manager.cpp:753
void onError(void *which) override
Definition manager.cpp:1418
bool switchBroker(size_t id)
Definition manager.cpp:296
bool addResource(const char *szFileName)
Definition manager.cpp:156
bool updateExecutable(unsigned int id, const char *szparam, const char *szhost, const char *szstdio, const char *szworkdir, const char *szenv)
Definition manager.cpp:431
void collectYarprunProcessesByHost(std::map< std::string, ProcessContainer > &hostProcesses, std::map< std::string, bool > &hostQueryOk)
Definition manager.cpp:1283
bool waitingModuleKill(unsigned int id)
Definition manager.cpp:712
bool waitingModuleStop(unsigned int id)
Definition manager.cpp:694
bool removeResource(const char *szResName)
Definition manager.cpp:221
bool addApplications(const char *szPath)
Definition manager.cpp:111
void onExecutableFailed(void *which) override
Definition manager.cpp:1415
bool loadApplication(const char *szAppName)
Definition manager.cpp:241
bool saveApplication(const char *szAppName, const char *fileName=nullptr)
Definition manager.cpp:267
void onCnnStablished(void *which) override
Definition manager.cpp:1413
bool waitingModuleRun(unsigned int id)
Definition manager.cpp:674
Executable * getExecutableById(size_t id)
Definition manager.cpp:284
void onExecutableStart(void *which) override
Definition manager.cpp:1411
Class Module.
Definition module.h:99
const char * getBroker()
Definition module.h:139
const char * getHost()
Definition module.h:131
a Node of a Graph
Definition node.h:64
void setPort(const char *szPort)
Class XmlAppLoader.
Application * getNextApplication() override
Class XmlAppSaver.
Definition xmlappsaver.h:19
Class XmlModLoader.
Module * getNextModule() override
Class XmlResLoader.
GenericResource * getNextResource() override
bool rmconnect(const std::string &from, const std::string &to)
bool getAllPorts(std::vector< std::string > &stingList)
bool connected(const std::string &from, const std::string &to, const std::string &carrier) override
bool setQos(const std::string &from, const std::string &to, const std::string &qosFrom, const std::string &qosTo)
bool connect(const std::string &from, const std::string &to, const std::string &carrier, bool persist=false) override
connection broker
bool getAllProcesses(const std::string &server, ProcessContainer &processes)
std::string error() override
bool disconnect(const std::string &from, const std::string &to, const std::string &carrier) override
bool exists(const std::string &port) override
bool getSystemInfo(const std::string &server, yarp::os::SystemInfo &info)
A simple collection of objects that can be described and transmitted in a portable way.
Definition Bottle.h:64
size_type size() const
Gets the number of elements in the bottle.
Definition Bottle.cpp:252
Value & get(size_type index) const
Reads a Value v from a certain part of the list.
Definition Bottle.cpp:247
void addString(const char *str)
Places a string in the bottle, at the end of the list.
Definition Bottle.cpp:176
static double nowSystem()
static void delaySystem(double seconds)
A class to get the system (platform) status such as available memory, storage, CPU load and etc.
Definition SystemInfo.h:25
virtual bool asBool() const
Get boolean value.
Definition Value.cpp:186
static NameClient & getNameClient()
Get an instance of the name client.
#define KILL_TIMEOUT
#define RUN_TIMEOUT
#define STOP_TIMEOUT
#define BROKER_YARPDEV
Definition manager.cpp:29
#define BROKER_YARPRUN
Definition manager.cpp:28
bool compareString(const char *szFirst, const char *szSecond)
Definition utility.cpp:326
std::vector< Executable * >::iterator ExecutablePIterator
Definition executable.h:167
enum yarp::manager::__RSTATE RSTATE
std::vector< GenericResource * >::iterator ResourcePIterator
Definition resource.h:59
std::vector< Connection >::iterator CnnIterator
std::stringstream OSTRINGSTREAM
Definition utility.h:50
std::vector< GenericResource * > ResourcePContainer
Definition resource.h:58
std::vector< Module * >::iterator ModulePIterator
Definition module.h:231
std::vector< Process > ProcessContainer
double now()
Return the current time in seconds, relative to an arbitrary starting point.
Definition Time.cpp:121
#define __CHECK_NULLPTR(_ptr)
Definition ymm-types.h:77