YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
ymanager.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6#include "ymanager.h"
7
11#include <dirent.h>
14
15/*
16 * TODO: using stringstream should be avoided to keep
17 * the compatibility with GUI
18 */
19#include <sstream>
20
21#include <cstring>
22#include <csignal>
23#include <map>
24#include <set>
25
26using namespace yarp::os;
27using namespace yarp::manager;
28
29#if defined(_WIN32)
30# define HEADER ""
31# define OKBLUE ""
32# define OKGREEN ""
33# define WARNING ""
34# define FAIL ""
35# define INFO ""
36# define ENDC ""
37#else
38# include <unistd.h>
39# include <cerrno>
40# if defined(YARP_HAS_SYS_TYPES_H)
41# include <sys/types.h>
42# endif
43# if defined(YARP_HAS_SYS_WAIT_H)
44# include <sys/wait.h>
45# endif
46# if defined(YARP_HAS_SYS_PRCTL_H)
47# include <sys/prctl.h>
48# endif
49 std::string HEADER;
50 std::string OKBLUE;
51 std::string OKGREEN;
52 std::string WARNING;
53 std::string FAIL;
54 std::string INFO;
55 std::string ENDC;
56#endif
57
58
59#define CMD_COUNTS 24
60#ifdef YARP_HAS_Libedit
61 #include <editline/readline.h>
62 const char* commands[CMD_COUNTS] = {"help", "exit","list mod", "list app", "list res", "add mod",
63 "add app", "add res", "load app", "run", "stop", "kill",
64 "connect", "disconnect", "which", "check state",
65 "check con", "check dep", "set", "get", "export",
66 "show mod", "assign hosts", " "};
67 char* command_generator (const char* text, int state);
68 char* appname_generator (const char* text, int state);
69 char ** my_completion (const char* text, int start, int end);
70 std::vector<std::string> appnames;
71#endif
72
73#define DEF_CONFIG_FILE "ymanager.ini"
74
75#define LOGO_MESSAGE "\
76__ __\n\
77\\ \\ / / __ ___ __ _ _ __ __ _ __ _ ___ _ __ \n\
78 \\ V / '_ ` _ \\ / _` | '_ \\ / _` |/ _` |/ _ \\ '__|\n\
79 | || | | | | | (_| | | | | (_| | (_| | __/ |\n\
80 |_||_| |_| |_|\\__,_|_| |_|\\__,_|\\__, |\\___|_|\n\
81 |___/"
82
83#define WELCOME_MESSAGE "type \"help\" for more information."
84#define VERSION_MESSAGE "Version 1.1"
85
86#define HELP_MESSAGE "\
87Usage:\n\
88 yarpmanager-console [option...]\n\n\
89Options:\n\
90 --application <app> Load a specific application identified by its xml file\n\
91 --run Run the current application (should be used with --application)\n\
92 --stop Stop the current application (should be used with --application)\n\
93 --kill Kill the current application (should be used with --application)\n\
94 --connect Connect all connections from the current application (should be used with --application)\n\
95 --disconnect Disconnect all connections from the current application (should be used with --application)\n\
96 --assign_hosts Automatically assign modules to proper nodes using load balancer. (should be used with --application)\n\
97 --check_dep Check for all resource dependencies of the current application (should be used with --application)\n\
98 --check_state Check for running state of modules of the current application (should be used with --application) \n\
99 --check_con Check the connections states of the of the current application (should be used with --application)\n\
100 --silent Do not print the status messages (should be used with --application)\n\
101 --exit Immediately exit after executing the commands (should be used with --application)\n\
102 --from <conf> Configuration file name\n\
103 --elapsed_time if present the time stamp for log messages will be relative to the GUI start time\n\
104 --version Show current version\n\
105 --help Show help\n"
106
107
108#if defined(_WIN32)
109static Manager* __pManager = NULL;
110#endif
111
112 bool isAbsolute(const char *path) { //copied from yarp_OS ResourceFinder.cpp
113 if (path[0]=='/'||path[0]=='\\') {
114 return true;
115 }
116 std::string str(path);
117 if (str.length()>1) {
118 if (str[1]==':') {
119 return true;
120 }
121 }
122 return false;
123 }
124
129YConsoleManager::YConsoleManager(int argc, char* argv[]) : Manager()
130{
131
132#if defined(_WIN32)
133 __pManager = (Manager*) this;
134#endif
135
136 bShouldRun = false;
137
138 // Setup resource finder
140 rf.setDefaultContext("yarpmanager");
142 rf.configure(argc, argv);
143
144 yarp::os::Property config;
145 config.fromString(rf.toString());
146
147 if(config.check("help"))
148 {
149 std::cout<<HELP_MESSAGE<<'\n';
150 return;
151 }
152
153 if(config.check("version"))
154 {
155 std::cout<<VERSION_MESSAGE<<'\n';
156 return;
157 }
158
159 // I the option elapsed_time is not set, set the start time to 00:00:00 (For error and warning logging)
160 if(!config.check("elapsed_time"))
161 {
163 clock.setStartTime("00:00:00");
164 }
165
170 std::string inifile=rf.findFile("from");
171 std::string inipath;
172 size_t lastSlash=inifile.rfind('/');
173 if (lastSlash != std::string::npos) {
174 inipath=inifile.substr(0, lastSlash+1);
175 } else {
176 lastSlash=inifile.rfind('\\');
177 if (lastSlash != std::string::npos) {
178 inipath = inifile.substr(0, lastSlash + 1);
179 }
180 }
181
182// if(!config.check("ymanagerini_dir"))
183// config.put("ymanagerini_dir", inipath.c_str());
184
185 if (!config.check("apppath")) {
186 config.put("apppath", "./");
187 }
188
189 if (!config.check("modpath")) {
190 config.put("modpath", "./");
191 }
192
193 if (!config.check("respath")) {
194 config.put("respath", "./");
195 }
196
197 if (!config.check("load_subfolders")) {
198 config.put("load_subfolders", "no");
199 }
200
201 if (!config.check("watchdog")) {
202 config.put("watchdog", "no");
203 }
204
205 if (!config.check("module_failure")) {
206 config.put("module_failure", "prompt");
207 }
208
209 if (!config.check("connection_failure")) {
210 config.put("connection_failure", "prompt");
211 }
212
213 if (!config.check("auto_connect")) {
214 config.put("auto_connect", "no");
215 }
216
217 if (!config.check("auto_dependency")) {
218 config.put("auto_dependency", "no");
219 }
220
221 if (!config.check("color_theme")) {
222 config.put("color_theme", "light");
223 }
224
225
229 if (config.find("color_theme").asString() == "dark") {
230 setColorTheme(THEME_DARK);
231 } else if (config.find("color_theme").asString() == "light") {
232 setColorTheme(THEME_LIGHT);
233 } else {
234 setColorTheme(THEME_NONE);
235 }
236
237 if (config.find("watchdog").asString() == "yes") {
239 } else {
241 }
242
243 if (config.find("auto_dependency").asString() == "yes") {
245 } else {
247 }
248
249 if (config.find("auto_connect").asString() == "yes") {
251 } else {
253 }
254
255 if(!config.check("silent"))
256 {
257 std::cout<<'\n'<<OKGREEN<<LOGO_MESSAGE<<ENDC<<'\n';
258 std::cout<<'\n'<<WELCOME_MESSAGE<<'\n'<<'\n';
259 }
260
261 if(config.check("modpath"))
262 {
263 std::string strPath;
264 std::stringstream modPaths(config.find("modpath").asString());
265 while (getline(modPaths, strPath, ';'))
266 {
267 trimString(strPath);
268 if (!isAbsolute(strPath.c_str())) {
269 strPath = std::string(inipath).append(strPath);
270 }
271 addModules(strPath.c_str());
272 }
273 }
274
275 if(config.check("respath"))
276 {
277 std::string strPath;
278 std::stringstream resPaths(config.find("respath").asString());
279 while (getline(resPaths, strPath, ';'))
280 {
281 trimString(strPath);
282 if (!isAbsolute(strPath.c_str())) {
283 strPath = std::string(inipath).append(strPath);
284 }
285 addResources(strPath.c_str());
286 }
287 }
288
290 if(config.check("apppath"))
291 {
292 std::string strPath;
293 std::stringstream appPaths(config.find("apppath").asString());
294 while (getline(appPaths, strPath, ';'))
295 {
296 trimString(strPath);
297 if (!isAbsolute(strPath.c_str())) {
298 strPath = std::string(inipath).append(strPath);
299 }
300 if(config.find("load_subfolders").asString() == "yes")
301 {
302 if (!loadRecursiveApplications(strPath.c_str())) {
303 logger->addError("Cannot load the applications from " + strPath);
304 }
305 } else {
306 addApplications(strPath.c_str());
307 }
308 }
309 }
310
311 reportErrors();
312
313#ifdef YARP_HAS_Libedit
314 updateAppNames(&appnames);
315#endif
316
317
318#if defined(_WIN32)
319 ::signal(SIGINT, YConsoleManager::onSignal);
320 ::signal(SIGBREAK, YConsoleManager::onSignal);
321 ::signal(SIGTERM, YConsoleManager::onSignal);
322#else
323 struct sigaction new_action, old_action;
324
325 /* Set up the structure to specify the new action. */
326 new_action.sa_handler = YConsoleManager::onSignal;
327 sigemptyset (&new_action.sa_mask);
328 new_action.sa_flags = 0;
329
330 sigaction (SIGINT, nullptr, &old_action);
331 if (old_action.sa_handler != SIG_IGN) {
332 sigaction(SIGINT, &new_action, nullptr);
333 }
334 sigaction (SIGHUP, nullptr, &old_action);
335 if (old_action.sa_handler != SIG_IGN) {
336 sigaction(SIGHUP, &new_action, nullptr);
337 }
338 sigaction (SIGTERM, nullptr, &old_action);
339 if (old_action.sa_handler != SIG_IGN) {
340 sigaction(SIGTERM, &new_action, nullptr);
341 }
342#endif
343
344 if(config.check("application"))
345 {
346 XmlAppLoader appload(config.find("application").asString().c_str());
347 if(appload.init())
348 {
349 Application* application = appload.getNextApplication();
350 if(application)
351 {
352 // add this application to the manager if does not exist
353 if (!getKnowledgeBase()->getApplication(application->getName())) {
354 getKnowledgeBase()->addApplication(application);
355 }
356
357#ifdef YARP_HAS_Libedit
358 updateAppNames(&appnames);
359 #endif
360
361 if(loadApplication(application->getName()))
362 {
363 if (!config.check("silent")) {
364 which();
365 }
366
367 if (config.check("assign_hosts")) {
368 loadBalance();
369 }
370
371 if(config.check("run"))
372 {
373 if (config.check("connect")) {
375 }
376 bShouldRun = run();
377 } else if (config.check("connect")) {
378 connect();
379 }
380
381 if (config.check("disconnect")) {
382 disconnect();
383 }
384
385 if(config.check("stop"))
386 {
389 unsigned int id = 0;
390 bShouldRun = false;
391 for(moditr=modules.begin(); moditr<modules.end(); moditr++)
392 {
393 if (running(id)) {
394 stop(id);
395 }
396 id++;
397 }
398 bShouldRun = !suspended();
399 }
400
401 if(config.check("kill"))
402 {
403 bShouldRun = false;
404 kill();
405 }
406
407 if (config.check("check_con")) {
408 checkConnections();
409 }
410
411 if (config.check("check_state")) {
412 checkStates();
413 }
414
415 if (config.check("check_dep")) {
416 if (checkDependency()) {
417 std::cout << INFO << "All of resource dependencies are satisfied." << ENDC << '\n';
418 }
419 }
420 }
421 }
422 }
423 if (!config.check("silent")) {
424 reportErrors();
425 }
426 }
427
428 if (!config.check("exit")) {
429 YConsoleManager::myMain();
430 }
431}
432
434
435
436
437void YConsoleManager::onSignal(int signum)
438{
439#if defined(_WIN32)
440 std::cout<<INFO<<"[force exit] yarpmanager will terminate all of the running modules on exit.";
441 if( __pManager)
442 __pManager->kill();
443#else
444 std::cout<<'\n'<<INFO<<"use"<<OKGREEN<<" 'exit' "<<INFO<<"to quit!"<<ENDC<<'\n';
445#endif
446}
447
448
449void YConsoleManager::myMain()
450{
451
452
453#ifdef YARP_HAS_Libedit
455#endif
456
457 while(!std::cin.eof())
458 {
459 std::string temp;
460
461#ifdef YARP_HAS_Libedit
462 static char* szLine = (char*)nullptr;
463 if(szLine)
464 {
465 free(szLine);
466 szLine = (char*)nullptr;
467 }
468
469 szLine = readline(">>");
470 if(szLine && *szLine)
471 {
472 temp = szLine;
474 } else {
475 temp = "";
476 }
477#else
478 std::cout << ">> ";
479 getline(std::cin, temp);
480#endif
481
482 //Break string into separate strings on whitespace
483 std::vector<std::string> cmdList;
484 std::stringstream foo(temp);
485 std::string s;
486 while (foo >> s)
487 {
488 if (s[0] == '~') {
489 s = getenv("HOME") + s.substr(1);
490 }
491 cmdList.push_back(s);
492 }
493 if(!process(cmdList))
494 {
495 if(cmdList[0] == "exit")
496 {
497 if (YConsoleManager::exit()) {
498 break;
499 }
500 }
501 else
502 {
503 std::cout<<"'"<<cmdList[0]<<"'"<<INFO<<" is not correct. ";
504 std::cout<<"type \"help\" for more information."<<ENDC<<'\n';
505 }
506 }
507 }
508
509#if defined(_WIN32)
510 if(bShouldRun)
511 {
512 kill();
513 reportErrors();
514 }
515#endif
516 std::cout<<"bye."<<'\n';
517
518}
519
520bool YConsoleManager::exit()
521{
522 if (!bShouldRun) {
523 return true;
524 }
525
526 std::string ans;
527 std::cout<<WARNING<<"WARNING: ";
528 std::cout<<INFO<<"You have some running modules. You might not be able to recover them later. Are you sure? [No/yes] "<<ENDC;
529 getline(std::cin, ans);
530 if(compareString(ans.c_str(),"yes"))
531 {
532 bShouldRun = false;
533 //kill();
534 //reportErrors();
535 return true;
536 }
537 return false;
538}
539
540
541bool YConsoleManager::process(const std::vector<std::string> &cmdList)
542{
543 if (!cmdList.size() || cmdList[0] == "") {
544 return true;
545 }
546
550 if((cmdList.size() == 1) &&
551 (cmdList[0] == "help"))
552 {
553 help();
554 return true;
555 }
556
557
561 if((cmdList.size() == 3) &&
562 (cmdList[0] == "add") && (cmdList[1] == "app"))
563 {
564 if (addApplication(cmdList[2].c_str())) {
565 std::cout << INFO << cmdList[2] << " is successfully added." << ENDC << '\n';
566 }
567 reportErrors();
568 #ifdef YARP_HAS_Libedit
569 updateAppNames(&appnames);
570 #endif
571 return true;
572 }
573
577 if((cmdList.size() == 3) &&
578 (cmdList[0] == "add") && (cmdList[1] == "mod"))
579 {
580 if (addModule(cmdList[2].c_str())) {
581 std::cout << INFO << cmdList[2] << " is successfully added." << ENDC << '\n';
582 }
583 reportErrors();
584 return true;
585 }
586
590 if((cmdList.size() == 3) &&
591 (cmdList[0] == "add") && (cmdList[1] == "res"))
592 {
593 if (addResource(cmdList[2].c_str())) {
594 std::cout << INFO << cmdList[2] << " is successfully added." << ENDC << '\n';
595 }
596 reportErrors();
597 return true;
598 }
599
600
604 if((cmdList.size() == 3) &&
605 (cmdList[0] == "load") && (cmdList[1] == "app"))
606 {
607 if(loadApplication(cmdList[2].c_str()))
608 {
609 //std::cout<<cmdList[2]<<" is successfully loaded."<<'\n';
610 which();
611 }
612 reportErrors();
613 return true;
614 }
615
619 /*
620 if((cmdList.size() >= 3) &&
621 (cmdList[0] == "load") && (cmdList[1] == "mod"))
622 {
623 if(cmdList.size() > 3)
624 {
625 if(manager.loadModule(cmdList[2].c_str(), cmdList[3].c_str()))
626 std::cout<<cmdList[2]<<" is successfully loaded."<<'\n';
627 }
628 else
629 if(manager.loadModule(cmdList[2].c_str()))
630 std::cout<<cmdList[2]<<" is successfully loaded."<<'\n';
631 reportErrors();
632 return true;
633 }
634 */
635
639 if((cmdList.size() == 1) &&
640 (cmdList[0] == "run"))
641 {
642 bShouldRun = run();
643 reportErrors();
644 return true;
645 }
646 if((cmdList.size() >= 2) &&
647 (cmdList[0] == "run"))
648 {
649 bShouldRun = false;
650 for (unsigned int i = 1; i < cmdList.size(); i++) {
651 bShouldRun |= run(atoi(cmdList[i].c_str()));
652 }
653 reportErrors();
654 return true;
655 }
656
660 if((cmdList.size() == 1) &&
661 (cmdList[0] == "stop"))
662 {
663 bShouldRun = false;
664 stop();
665 reportErrors();
666 return true;
667 }
668 if((cmdList.size() >= 2) &&
669 (cmdList[0] == "stop"))
670 {
671 //bShouldRun = false;
672 for (unsigned int i = 1; i < cmdList.size(); i++) {
673 stop(atoi(cmdList[i].c_str()));
674 }
675 bShouldRun = !suspended();
676 reportErrors();
677 return true;
678 }
679
683 if((cmdList.size() == 1) &&
684 (cmdList[0] == "kill"))
685 {
686 bShouldRun = false;
687 kill();
688 reportErrors();
689 return true;
690 }
691 if((cmdList.size() >= 2) &&
692 (cmdList[0] == "kill"))
693 {
694 //bShouldRun = false;
695 for (unsigned int i = 1; i < cmdList.size(); i++) {
696 kill(atoi(cmdList[i].c_str()));
697 }
698 bShouldRun = !suspended();
699 reportErrors();
700 return true;
701 }
702
706 if((cmdList.size() == 1) &&
707 (cmdList[0] == "connect"))
708 {
709 connect();
710 reportErrors();
711 return true;
712 }
713 if((cmdList.size() >= 2) &&
714 (cmdList[0] == "connect"))
715 {
716 for (unsigned int i = 1; i < cmdList.size(); i++) {
717 connect(atoi(cmdList[i].c_str()));
718 }
719 reportErrors();
720 return true;
721 }
722
723
727 if((cmdList.size() == 1) &&
728 (cmdList[0] == "disconnect"))
729 {
730 disconnect();
731 reportErrors();
732 return true;
733 }
734 if((cmdList.size() >= 2) &&
735 (cmdList[0] == "disconnect"))
736 {
737 for (unsigned int i = 1; i < cmdList.size(); i++) {
738 disconnect(atoi(cmdList[i].c_str()));
739 }
740 reportErrors();
741 return true;
742 }
743
744
748 if((cmdList.size() == 1) &&
749 (cmdList[0] == "which"))
750 {
751 which();
752 return true;
753 }
754
758 if((cmdList.size() == 2) &&
759 (cmdList[0] == "check") && (cmdList[1] == "dep"))
760 {
761 if (checkDependency()) {
762 std::cout << INFO << "All of resource dependencies are satisfied." << ENDC << '\n';
763 }
764 reportErrors();
765 return true;
766 }
767
768
772 if((cmdList.size() == 3) &&
773 (cmdList[0] == "check") && (cmdList[1] == "state"))
774 {
776 auto id = (unsigned int)atoi(cmdList[2].c_str());
777 if(id>=modules.size())
778 {
779 std::cout<<FAIL<<"ERROR: "<<INFO<<"Module id is out of range."<<ENDC<<'\n';
780 return true;
781 }
782
783 if (running(id)) {
784 std::cout<<OKGREEN<<"<RUNNING> ";
785 } else {
786 std::cout << FAIL << "<STOPPED> ";
787 }
788 std::cout<<INFO<<"("<<id<<") ";
789 std::cout<<modules[id]->getCommand();
790 std::cout<<" ["<<modules[id]->getHost()<<"]"<<ENDC<<'\n';
791 reportErrors();
792 return true;
793 }
794 if((cmdList.size() == 2) &&
795 (cmdList[0] == "check") && (cmdList[1] == "state"))
796 {
797 checkStates();
798 reportErrors();
799 return true;
800 }
801
802
806 if((cmdList.size() == 3) &&
807 (cmdList[0] == "check") && (cmdList[1] == "con"))
808 {
809
810 CnnContainer connections = getConnections();
811 auto id = (unsigned int)atoi(cmdList[2].c_str());
812 if(id>=connections.size())
813 {
814 std::cout<<FAIL<<"ERROR: "<<INFO<<"Connection id is out of range."<<ENDC<<'\n';
815 return true;
816 }
817
818 if (connected(id)) {
819 std::cout<<OKGREEN<<"<CONNECTED> ";
820 } else {
821 std::cout << FAIL << "<DISCONNECTED> ";
822 }
823
824 std::cout<<INFO<<"("<<id<<") ";
825 std::cout<<connections[id].from()<<" - "<<connections[id].to();
826 std::cout<<" ["<<connections[id].carrier()<<"]"<<ENDC<<'\n';
827 reportErrors();
828 return true;
829 }
830 if((cmdList.size() == 2) &&
831 (cmdList[0] == "check") && (cmdList[1] == "con"))
832 {
833 checkConnections();
834 return true;
835 }
836
838
842 if((cmdList.size() == 2) &&
843 (cmdList[0] == "list") && (cmdList[1] == "mod"))
844 {
846 ModulePContainer mods = kb->getModules();
847 int id = 0;
848 for(auto& mod : mods)
849 {
850 std::string fname;
851 std::string fpath = mod->getXmlFile();
852
853 size_t pos = fpath.rfind(directorySeparator);
854 if (pos != std::string::npos) {
855 fname = fpath.substr(pos);
856 } else {
857 fname = fpath;
858 }
859 std::cout<<INFO<<"("<<id++<<") ";
860 std::cout<<OKBLUE<<mod->getName()<<ENDC;
861 std::cout<<INFO<<" ["<<fname<<"]"<<ENDC<<'\n';
862 }
863 return true;
864 }
865
866
870 if((cmdList.size() == 2) &&
871 (cmdList[0] == "list") && (cmdList[1] == "app"))
872 {
874 ApplicaitonPContainer apps = kb->getApplications();
875 int id = 0;
876 for(auto& app : apps)
877 {
878 std::string fname;
879 std::string fpath = app->getXmlFile();
880
881 size_t pos = fpath.rfind(directorySeparator);
882 if (pos != std::string::npos) {
883 fname = fpath.substr(pos);
884 } else {
885 fname = fpath;
886 }
887 std::cout<<INFO<<"("<<id++<<") ";
888 std::cout<<OKBLUE<<app->getName()<<ENDC;
889 std::cout<<INFO<<" ["<<fname<<"]"<<ENDC<<'\n';
890 }
891 return true;
892 }
893
897 if((cmdList.size() == 2) &&
898 (cmdList[0] == "list") && (cmdList[1] == "res"))
899 {
901 ResourcePContainer resources = kb->getResources();
902 int id = 0;
903 for(auto& resource : resources)
904 {
905 auto* comp = dynamic_cast<Computer*>(resource);
906 if(comp)
907 {
908 std::string fname;
909 std::string fpath = comp->getXmlFile();
910 size_t pos = fpath.rfind(directorySeparator);
911 if (pos != std::string::npos) {
912 fname = fpath.substr(pos);
913 } else {
914 fname = fpath;
915 }
916 std::cout<<INFO<<"("<<id++<<") ";
917 if (comp->getDisable()) {
918 std::cout<<WARNING<<comp->getName()<<ENDC;
919 } else {
920 std::cout << OKBLUE << comp->getName() << ENDC;
921 }
922 std::cout<<INFO<<" ["<<fname<<"]"<<ENDC<<'\n';
923 }
924 }
925 return true;
926 }
927
928
932 if((cmdList.size() == 2) &&
933 (cmdList[0] == "export") )
934 {
935 if (!exportDependencyGraph(cmdList[1].c_str())) {
936 std::cout << FAIL << "ERROR: " << INFO << "Cannot export graph to " << cmdList[1] << "." << ENDC << '\n';
937 }
938 return true;
939 }
940
941
945 if((cmdList.size() == 3) &&
946 (cmdList[0] == "show") && (cmdList[1] == "mod"))
947 {
949 if(!kb->getModule(cmdList[2].c_str()))
950 {
951 std::cout<<FAIL<<"ERROR: "<<INFO<<"'"<<cmdList[2].c_str()<<"' not found."<<ENDC<<'\n';
952 return true;
953 }
954 std::cout<<INFO;
955 PRINT_MODULE(kb->getModule(cmdList[2].c_str()));
956 std::cout<<ENDC;
957 return true;
958 }
959
963 if((cmdList.size() == 3) &&
964 (cmdList[0] == "set"))
965 {
966 config.unput(cmdList[1]);
967 config.put(cmdList[1], cmdList[2]);
968
969 if(cmdList[1] == std::string("watchdog"))
970 {
971 if (cmdList[2] == std::string("yes")) {
973 } else {
975 }
976 }
977
978 if(cmdList[1] == std::string("auto_dependency"))
979 {
980 if (cmdList[2] == std::string("yes")) {
982 } else {
984 }
985 }
986
987 if(cmdList[1] == std::string("auto_connect"))
988 {
989 if (cmdList[2] == std::string("yes")) {
991 } else {
993 }
994 }
995
996 if(cmdList[1] == std::string("color_theme"))
997 {
998 if (cmdList[2] == std::string("dark")) {
999 setColorTheme(THEME_DARK);
1000 } else if (cmdList[2] == std::string("light")) {
1001 setColorTheme(THEME_LIGHT);
1002 } else {
1003 setColorTheme(THEME_NONE);
1004 }
1005 }
1006
1007 return true;
1008 }
1009
1010
1014 if((cmdList.size() == 2) &&
1015 (cmdList[0] == "get"))
1016 {
1017 if(config.check(cmdList[1]))
1018 {
1019 std::cout<<OKBLUE<<cmdList[1]<<INFO<<" = ";
1020 std::cout<<OKGREEN<<config.find(cmdList[1]).asString()<<ENDC<<'\n';
1021 } else {
1022 std::cout << FAIL << "ERROR: " << INFO << "'" << cmdList[1].c_str() << "' not found." << ENDC << '\n';
1023 }
1024 return true;
1025 }
1026
1030 if((cmdList.size() == 2) &&
1031 (cmdList[0] == "assign") && (cmdList[1] == "hosts"))
1032 {
1033 loadBalance();
1034 reportErrors();
1035 return true;
1036 }
1037
1038 return false;
1039}
1040
1041
1042void YConsoleManager::help()
1043{
1044 std::cout<<"Here is a list of YARP manager keywords.\n"<<'\n';
1045 std::cout<<OKGREEN<<"help"<<INFO<<" : show help."<<ENDC<<'\n';
1046 std::cout<<OKGREEN<<"exit"<<INFO<<" : exit yarp manager."<<ENDC<<'\n';
1047 std::cout<<OKGREEN<<"list mod"<<INFO<<" : list available modules."<<ENDC<<'\n';
1048 std::cout<<OKGREEN<<"list app"<<INFO<<" : list available applications."<<ENDC<<'\n';
1049 std::cout<<OKGREEN<<"list res"<<INFO<<" : list available resources. (i.e. nodes in a cluster)"<<ENDC<<'\n';
1050 std::cout<<OKGREEN<<"add mod <filename>"<<INFO<<" : add a module from its description file."<<ENDC<<'\n';
1051 std::cout<<OKGREEN<<"add app <filename>"<<INFO<<" : add an application from its description file."<<ENDC<<'\n';
1052 std::cout<<OKGREEN<<"add res <filename>"<<INFO<<" : add resources from a description file."<<ENDC<<'\n';
1053 std::cout<<OKGREEN<<"load app <application>"<<INFO<<" : load an application to run."<<'\n';
1054// std::cout<<"load mod <module> <host>: load a module to run on an optional host."<<'\n';
1055 std::cout<<OKGREEN<<"run [IDs]"<<INFO<<" : run application or a modules indicated by IDs."<<ENDC<<'\n';
1056 std::cout<<OKGREEN<<"stop [IDs]"<<INFO<<" : stop running application or modules indicated by IDs."<<ENDC<<'\n';
1057 std::cout<<OKGREEN<<"kill [IDs]"<<INFO<<" : kill running application or modules indicated by IDs."<<ENDC<<'\n';
1058 std::cout<<OKGREEN<<"connect [IDs]"<<INFO<<" : stablish all connections or just one connection indicated by IDs."<<ENDC<<'\n';
1059 std::cout<<OKGREEN<<"disconnect [IDs]"<<INFO<<" : remove all connections or just one connection indicated by IDs."<<ENDC<<'\n';
1060 std::cout<<OKGREEN<<"which"<<INFO<<" : list loaded modules, connections and resource dependencies."<<ENDC<<'\n';
1061 std::cout<<OKGREEN<<"check dep"<<INFO<<" : check for all resource dependencies."<<ENDC<<'\n';
1062 std::cout<<OKGREEN<<"check state [id]"<<INFO<<" : check for running state of application or a module indicated by id."<<ENDC<<'\n';
1063 std::cout<<OKGREEN<<"check con [id]"<<INFO<<" : check for all connections state or just one connection indicated by id."<<ENDC<<'\n';
1064 std::cout<<OKGREEN<<"set <option> <value>"<<INFO<<" : set value to an option."<<ENDC<<'\n';
1065 std::cout<<OKGREEN<<"get <option>"<<INFO<<" : show value of an option."<<ENDC<<'\n';
1066 std::cout<<OKGREEN<<"export <filename>"<<INFO<<" : export application's graph as Graphviz dot format."<<ENDC<<'\n';
1067// std::cout<<"edit mod <modname> : open module relevant xml file to edit."<<'\n';
1068// std::cout<<"edit app <appname> : open application relevant xml file to edit."<<'\n';
1069 std::cout<<OKGREEN<<"show mod <modname>"<<INFO<<" : display module information (description, input, output,...)."<<ENDC<<'\n';
1070 std::cout<<OKGREEN<<"assign hosts"<<INFO<<" : automatically assign modules to proper nodes using load balancer."<<ENDC<<'\n';
1071
1072 std::cout<<'\n';
1073}
1074
1075
1076void YConsoleManager::which()
1077{
1079 CnnContainer connections = getConnections();
1082
1083 std::cout<<'\n'<<HEADER<<"Application: "<<ENDC<<'\n';
1084 std::cout<<OKBLUE<<getApplicationName()<<ENDC<<'\n';
1085
1086 std::cout<<'\n'<<HEADER<<"Modules: "<<ENDC<<'\n';
1087 int id = 0;
1088 for(moditr=modules.begin(); moditr<modules.end(); moditr++)
1089 {
1090 std::cout<<INFO<<"("<<id++<<") ";
1091 std::cout<<OKBLUE<<(*moditr)->getCommand()<<INFO;
1092 std::cout<<" ["<<(*moditr)->getHost()<<"] ["<<(*moditr)->getParam()<<"]";
1093 std::cout<<" ["<<(*moditr)->getEnv()<<"]"<<ENDC<<'\n';
1094 }
1095 std::cout<<'\n'<<HEADER<<"Connections: "<<ENDC<<'\n';
1096 id = 0;
1097 for(cnnitr=connections.begin(); cnnitr<connections.end(); cnnitr++)
1098 {
1099 std::cout<<INFO<<"("<<id++<<") ";
1100 std::cout<<OKBLUE<<(*cnnitr).from()<<" - "<<(*cnnitr).to()<<INFO;
1101 std::cout<<" ["<<(*cnnitr).carrier()<<"]";
1102 std::cout<<ENDC<<'\n';
1103 }
1104
1105 std::cout<<'\n'<<HEADER<<"Resources:"<<ENDC<<'\n';
1106 id = 0;
1108 for(itrS=getResources().begin(); itrS!=getResources().end(); itrS++)
1109 {
1110 std::cout<<INFO<<"("<<id++<<") ";
1111 std::cout<<OKBLUE<<(*itrS)->getName()<<INFO<<" ["<<(*itrS)->getTypeName()<<"]"<<ENDC<<'\n';
1112 }
1113 std::cout<<'\n';
1114}
1115
1116void YConsoleManager::checkStates()
1117{
1120 unsigned int id = 0;
1121 bShouldRun = false;
1122 std::map<std::string, ProcessContainer> hostProcesses;
1123 std::map<std::string, bool> hostQueryOk;
1125
1126 for(moditr=modules.begin(); moditr<modules.end(); moditr++)
1127 {
1128 bool isRunning = false;
1129 Executable* exe = *moditr;
1130 if (exe && exe->getBrokerType() == BrokerType::yarp) {
1131 const std::string host = exe->getHost();
1132 const auto hostOkIt = hostQueryOk.find(host);
1133 if (hostOkIt != hostQueryOk.end() && hostOkIt->second) {
1134 const auto procIt = hostProcesses.find(host);
1135 if (procIt != hostProcesses.end()) {
1136 const std::string exeCmd = exe->getCommand();
1137 const std::string exeParam = exe->getParam();
1138 for (const auto& proc : procIt->second) {
1139 const bool statusRunning = proc.status.empty() || proc.status == "running";
1140 const bool cmdMatches = proc.command.find(exeCmd) != std::string::npos;
1141 const bool paramMatches = exeParam.empty() || (proc.command.find(exeParam) != std::string::npos);
1143 isRunning = true;
1144 break;
1145 }
1146 }
1147 }
1148 } else {
1149 // Fallback to the old per-module check if the remote ps query failed.
1150 isRunning = running(id);
1151 }
1152 } else {
1153 // Local and other brokers: keep previous behavior.
1154 isRunning = running(id);
1155 }
1156
1157 if(isRunning)
1158 {
1159 bShouldRun = true;
1160 std::cout<<OKGREEN<<"<RUNNING> ";
1161 } else {
1162 std::cout << FAIL << "<STOPPED> ";
1163 }
1164 std::cout<<INFO<<"("<<id<<") ";
1165 std::cout<<(*moditr)->getCommand();
1166 std::cout<<" ["<<(*moditr)->getHost()<<"]"<<ENDC<<'\n';
1167 id++;
1168 }
1169}
1170
1171void YConsoleManager::checkConnections()
1172{
1173 CnnContainer connections = getConnections();
1175 int id = 0;
1176 for(cnnitr=connections.begin(); cnnitr<connections.end(); cnnitr++)
1177 {
1178 if (connected(id)) {
1179 std::cout<<OKGREEN<<"<CONNECTED> ";
1180 } else {
1181 std::cout << FAIL << "<DISCONNECTED> ";
1182 }
1183
1184 std::cout<<INFO<<"("<<id<<") ";
1185 std::cout<<(*cnnitr).from()<<" - "<<(*cnnitr).to();
1186 std::cout<<" ["<<(*cnnitr).carrier()<<"]"<<ENDC<<'\n';
1187 id++;
1188 }
1189}
1190
1191void YConsoleManager::reportErrors()
1192{
1194 if(logger->errorCount() || logger->warningCount())
1195 {
1196 const char* msg;
1197 while ((msg = logger->getLastError())) {
1198 std::cout << FAIL << "ERROR: " << INFO << msg << ENDC << '\n';
1199 }
1200
1201 while ((msg = logger->getLastWarning())) {
1202 std::cout << WARNING << "WARNING: " << INFO << msg << ENDC << '\n';
1203 }
1204 }
1205}
1206
1207
1209
1211
1213
1215{
1216 auto* exe = (Executable*) which;
1217 if (config.find("module_failure").asString() == "prompt") {
1218 std::cout << exe->getCommand() << " from " << exe->getHost() << " is failed!" << '\n';
1219 }
1220
1221 if(config.find("module_failure").asString() == "recover")
1222 {
1223 std::cout<<'\n'<<exe->getCommand()<<" from "<<exe->getHost()<<" is failed! (restarting...)"<<'\n';
1224 exe->start();
1225 }
1226
1227 if(config.find("module_failure").asString() == "terminate")
1228 {
1229 std::cout<<'\n'<<exe->getCommand()<<" from "<<exe->getHost()<<" is failed! (terminating application...)"<<'\n';
1230 bShouldRun = false;
1231 stop();
1232 reportErrors();
1233 }
1234}
1235
1237
1239{
1240 auto* cnn = (Connection*) which;
1241 if (config.check("connection_failure") && config.find("connection_failure").asString() == "prompt") {
1242 std::cout << '\n'
1243 << "connection failed between " << cnn->from() << " and " << cnn->to() << '\n';
1244 }
1245
1246 if(bShouldRun && config.check("connection_failure") &&
1247 config.find("connection_failure").asString() == "terminate")
1248 {
1249 std::cout<<'\n'<<"connection failed between "<<cnn->from()<<" and "<<cnn->to()<<"(terminating application...)"<<'\n';
1250 bShouldRun = false;
1251 stop();
1252 reportErrors();
1253 }
1254}
1255
1256
1257bool YConsoleManager::loadRecursiveApplications(const char* szPath)
1258{
1260 std::string strPath = szPath;
1261 if ((strPath.rfind(directorySeparator) == std::string::npos) || (strPath.rfind(directorySeparator) != strPath.size() - 1)) {
1262 strPath = strPath + std::string(directorySeparator);
1263 }
1264
1265 DIR *dir;
1266 struct dirent *entry;
1267 if ((dir = opendir(strPath.c_str())) == nullptr) {
1268 return false;
1269 }
1270
1271 addApplications(strPath.c_str());
1272
1273 while((entry = readdir(dir)))
1274 {
1275 if((std::string(entry->d_name) != std::string("."))
1276 && (std::string(entry->d_name) != std::string("..")))
1277 {
1278 std::string name = strPath + std::string(entry->d_name);
1279 loadRecursiveApplications(name.c_str());
1280 }
1281 }
1282 closedir(dir);
1283 return true;
1284}
1285
1286
1287
1288void YConsoleManager::updateAppNames(std::vector<std::string>* names)
1289{
1290 names->clear();
1292 ApplicaitonPContainer apps = kb->getApplications();
1293 for (auto& app : apps) {
1294 names->push_back(app->getName());
1295 }
1296}
1297
1298
1299
1300void YConsoleManager::setColorTheme(ColorTheme theme)
1301{
1302
1303#if defined(_WIN32)
1304 // do nothing here
1305#else
1306 switch(theme) {
1307 case THEME_DARK : {
1308 HEADER = "\033[01;95m";
1309 OKBLUE = "\033[94m";
1310 OKGREEN = "\033[92m";
1311 WARNING = "\033[93m";
1312 FAIL = "\033[91m";
1313 INFO = "\033[37m";
1314 ENDC = "\033[0m";
1315 break;
1316 }
1317 case THEME_LIGHT: {
1318 HEADER = "\033[01;35m";
1319 OKBLUE = "\033[34m";
1320 OKGREEN = "\033[32m";
1321 WARNING = "\033[33m";
1322 FAIL = "\033[31m";
1323 INFO = "\033[0m";
1324 ENDC = "\033[0m";
1325 break;
1326 }
1327 default: {
1328 HEADER = "";
1329 OKBLUE = "";
1330 OKGREEN = "";
1331 WARNING = "";
1332 FAIL = "";
1333 INFO = "";
1334 ENDC = "";
1335 break;
1336 }
1337 };
1338#endif
1339
1340}
1341
1342
1343
1344#ifdef YARP_HAS_Libedit
1345
1346char* dupstr(char* s)
1347{
1348 char *r;
1349 r = (char*) malloc ((strlen (s) + 1));
1350 strcpy (r, s);
1351 return (r);
1352}
1353
1354/* Attempt to complete on the contents of TEXT. START and END show the
1355 region of TEXT that contains the word to complete. We can use the
1356 entire line in case we want to do some simple parsing. Return the
1357 array of matches, or NULL if there aren't any. */
1358char ** my_completion (const char* text, int start, int end)
1359{
1360 char **matches;
1361
1362 matches = (char **)nullptr;
1363
1364 /* If this word is at the start of the line, then it is a command
1365 to complete. Otherwise it is the name of a file in the current
1366 directory. */
1367 if (start == 0) {
1369 } else {
1371 }
1372
1373 return (matches);
1374}
1375
1376
1377/* Generator function for command completion. STATE lets us know whether
1378 to start from scratch; without any state (i.e. STATE == 0), then we
1379 start at the top of the list. */
1380char* command_generator (const char* text, int state)
1381{
1382 //printf("commmand_genrator\n");
1383
1384 static int list_index, len;
1385 char *name;
1386
1387 /* if this is a new word to complete, initialize now. this includes
1388 saving the length of text for efficiency, and initializing the index
1389 variable to 0. */
1390 if (!state)
1391 {
1392 list_index = 0;
1393 len = strlen (text);
1394 }
1395
1396 while ((list_index<CMD_COUNTS) && (name = (char*)commands[list_index]))
1397 {
1398 list_index++;
1399 if (strncmp(name, text, len) == 0) {
1400 return (dupstr(name));
1401 }
1402 }
1403
1404 /* if no names matched, then return null. */
1405 return ((char *)nullptr);
1406}
1407
1408
1409char* appname_generator (const char* text, int state)
1410{
1411
1412 static unsigned int list_index, len;
1413 char *name;
1414
1415 if (!state)
1416 {
1417 list_index = 0;
1418 len = strlen (text);
1419 }
1420
1421 while ((list_index<appnames.size()) && (name = (char*)appnames[list_index].c_str()))
1422 {
1423 list_index++;
1424 if (strncmp(name, text, len) == 0) {
1425 return (dupstr(name));
1426 }
1427 }
1428
1429 return ((char *)nullptr);
1430}
1431
1432#endif
void onCnnFailed(void *which) override
void onExecutableStop(void *which) override
~YConsoleManager() override
void onExecutableFailed(void *which) override
void onCnnStablished(void *which) override
void onExecutableStart(void *which) override
YConsoleManager(int argc, char *argv[])
Class YConsoleManager.
Definition ymanager.cpp:129
void onExecutableDied(void *which) override
Class Application.
Singleton class For storing execution start time.
Definition utility.h:86
static ClockStart & getInstance()
Definition utility.h:88
Singleton class ErrorLogger.
Definition utility.h:58
const char * getLastError()
Definition utility.cpp:148
void addError(const char *szError)
Definition utility.cpp:126
static ErrorLogger * Instance()
Singleton class ErrorLogger.
Definition utility.cpp:98
const char * getLastWarning()
Definition utility.cpp:167
Class Executable.
Definition executable.h:71
Class KnowledgeBase.
Definition kbase.h:32
bool addApplication(Application *application, char **szAppName_=nullptr, bool modifyName=false)
Definition kbase.cpp:76
Class Manager.
Definition manager.h:21
ExecutablePContainer & getExecutables()
Definition manager.h:85
bool addModule(const char *szFileName)
Definition manager.cpp:128
CnnContainer & getConnections()
Definition manager.h:88
ResourcePContainer & getResources()
Definition manager.h:89
bool addModules(const char *szPath)
Definition manager.cpp:142
const char * getApplicationName()
Definition manager.h:90
bool addResources(const char *szPath)
Definition manager.cpp:171
bool addApplication(const char *szFileName, char **szAppName_=nullptr, bool modifyName=false)
Definition manager.cpp:91
void disableAutoDependency()
Definition manager.h:99
bool addResource(const char *szFileName)
Definition manager.cpp:156
void collectYarprunProcessesByHost(std::map< std::string, ProcessContainer > &hostProcesses, std::map< std::string, bool > &hostQueryOk)
Definition manager.cpp:1283
void enableAutoDependency()
Definition manager.h:98
bool addApplications(const char *szPath)
Definition manager.cpp:111
bool loadApplication(const char *szAppName)
Definition manager.cpp:241
bool exportDependencyGraph(const char *szFileName)
Definition manager.h:102
KnowledgeBase * getKnowledgeBase()
Definition manager.h:106
void disableAutoConnect()
Definition manager.h:97
Class XmlAppLoader.
A mini-server for performing network communication in the background.
std::string getName() const override
Get name of port.
A controller for an individual connection.
Definition Connection.h:26
A class for storing options and configuration information.
Definition Property.h:33
Value & find(const std::string &key) const override
Gets a value corresponding to a given keyword.
void fromString(const std::string &txt, bool wipe=true)
Interprets a string as a list of properties.
void put(const std::string &key, const std::string &value)
Associate the given key with the given string.
Definition Property.cpp:987
bool check(const std::string &key) const override
Check if there exists a property of the given name.
void unput(const std::string &key)
Remove the association from the given key to a value, if present.
Helper class for finding config files and other external resources.
bool setDefaultContext(const std::string &contextName)
Sets the context for the current ResourceFinder object.
bool configure(int argc, char *argv[], bool skipFirstArgument=true)
Sets up the ResourceFinder.
std::string toString() const override
Return a standard text representation of the content of the object.
std::string findFile(const std::string &name)
Find the full path to a file.
bool setDefaultConfigFile(const std::string &fname)
Provide a default value for the configuration file (can be overridden from command line with the –fro...
virtual std::string asString() const
Get string value.
Definition Value.cpp:246
#define LOGO_MESSAGE
Definition main.cpp:21
#define HELP_MESSAGE
Definition main.cpp:18
#define DEF_CONFIG_FILE
Definition main.cpp:41
#define PRINT_MODULE(m)
Definition module.h:234
static constexpr value_type preferred_separator
Definition filesystem.h:21
bool compareString(const char *szFirst, const char *szSecond)
Definition utility.cpp:326
std::vector< Executable * >::iterator ExecutablePIterator
Definition executable.h:167
void trimString(std::string &str)
Definition utility.cpp:403
std::vector< GenericResource * >::iterator ResourcePIterator
Definition resource.h:59
std::vector< Connection >::iterator CnnIterator
std::vector< Executable * > ExecutablePContainer
Definition executable.h:166
std::vector< Module * > ModulePContainer
Definition module.h:230
std::vector< GenericResource * > ResourcePContainer
Definition resource.h:58
std::vector< Application * > ApplicaitonPContainer
std::vector< Connection > CnnContainer
An interface to the operating system, including Port based communication.
Definition OSTestMsg.cpp:13
const char * getenv(const char *var)
Portable wrapper for the getenv() function.
bool isAbsolute(const char *path)
std::string ENDC
Definition ymanager.cpp:55
bool isAbsolute(const char *path)
Definition ymanager.cpp:112
std::string OKGREEN
Definition ymanager.cpp:51
#define WELCOME_MESSAGE
Definition ymanager.cpp:83
std::string INFO
Definition ymanager.cpp:54
#define CMD_COUNTS
Definition ymanager.cpp:59
#define VERSION_MESSAGE
Definition ymanager.cpp:84
std::string WARNING
Definition ymanager.cpp:52
std::string HEADER
Definition ymanager.cpp:49
std::string FAIL
Definition ymanager.cpp:53
std::string OKBLUE
Definition ymanager.cpp:50
@ THEME_LIGHT
Definition ymanager.h:20
@ THEME_NONE
Definition ymanager.h:21
@ THEME_DARK
Definition ymanager.h:19