1 #include "otsdaq-core/GatewaySupervisor/GatewaySupervisor.h"
2 #include "otsdaq-core/MessageFacility/MessageFacility.h"
3 #include "otsdaq-core/Macros/CoutMacros.h"
4 #include "otsdaq-core/XmlUtilities/HttpXmlDocument.h"
5 #include "otsdaq-core/CgiDataUtilities/CgiDataUtilities.h"
6 #include "otsdaq-core/SOAPUtilities/SOAPUtilities.h"
7 #include "otsdaq-core/SOAPUtilities/SOAPCommand.h"
9 #include "otsdaq-core/WorkLoopManager/WorkLoopManager.h"
10 #include "otsdaq-core/ConfigurationInterface/ConfigurationManager.h"
11 #include "otsdaq-core/ConfigurationInterface/ConfigurationManagerRW.h"
12 #include "otsdaq-core/ConfigurationPluginDataFormats/XDAQContextConfiguration.h"
13 #include "otsdaq-core/ConfigurationPluginDataFormats/DesktopIconConfiguration.h"
14 #include "otsdaq-core/GatewaySupervisor/ARTDAQCommandable.h"
17 #include "otsdaq-core/NetworkUtilities/TransceiverSocket.h"
21 #include <cgicc/HTMLClasses.h>
22 #include <cgicc/HTTPCookie.h>
23 #include <cgicc/HTMLDoctype.h>
24 #include <cgicc/HTTPHeader.h>
25 #include <xgi/Utils.h>
27 #include <xoap/Method.h>
28 #include <xdaq/NamespaceURI.h>
29 #include <toolbox/task/WorkLoopFactory.h>
30 #include <toolbox/fsm/FailedEvent.h>
40 #define ICON_FILE_NAME std::string(getenv("SERVICE_DATA_PATH")) + "/OtsWizardData/iconList.dat"
41 #define RUN_NUMBER_PATH std::string(getenv("SERVICE_DATA_PATH")) + "/RunNumber/"
42 #define RUN_NUMBER_FILE_NAME "NextRunNumber.txt"
43 #define FSM_LAST_GROUP_ALIAS_PATH std::string(getenv("SERVICE_DATA_PATH")) + "/RunControlData/"
44 #define FSM_LAST_GROUP_ALIAS_FILE_START std::string("FSMLastGroupAlias-")
45 #define FSM_USERS_PREFERENCES_FILETYPE "pref"
47 #define CORE_TABLE_INFO_FILENAME ((getenv("SERVICE_DATA_PATH") == NULL)?(std::string(getenv("USER_DATA"))+"/ServiceData"):(std::string(getenv("SERVICE_DATA_PATH")))) + "/CoreTableInfoNames.dat"
50 #define __MF_SUBJECT__ "GatewaySupervisor"
64 , theArtdaqCommandable_ (this)
65 , stateMachineWorkLoopManager_ (toolbox::task::bind(this, &GatewaySupervisor::stateMachineThread, "StateMachine"))
66 , stateMachineSemaphore_ (toolbox::BSem::FULL)
67 , infoRequestWorkLoopManager_ (toolbox::task::bind(this, &GatewaySupervisor::infoRequestThread, "InfoRequest"))
68 , infoRequestSemaphore_ (toolbox::BSem::FULL)
69 , activeStateMachineName_ ("")
73 INIT_MF(
"GatewaySupervisor");
74 __SUP_COUT__ << std::endl;
77 mkdir((FSM_LAST_GROUP_ALIAS_PATH).c_str(), 0755);
78 mkdir((RUN_NUMBER_PATH).c_str(), 0755);
80 securityType_ = theWebUsers_.getSecurity();
82 __SUP_COUT__ <<
"Security: " << securityType_ << std::endl;
84 xgi::bind (
this, &GatewaySupervisor::Default,
"Default");
85 xgi::bind (
this, &GatewaySupervisor::loginRequest,
"LoginRequest");
86 xgi::bind (
this, &GatewaySupervisor::request,
"Request");
87 xgi::bind (
this, &GatewaySupervisor::stateMachineXgiHandler,
"StateMachineXgiHandler");
88 xgi::bind (
this, &GatewaySupervisor::infoRequestHandler,
"InfoRequestHandler");
89 xgi::bind (
this, &GatewaySupervisor::infoRequestResultHandler,
"InfoRequestResultHandler");
90 xgi::bind (
this, &GatewaySupervisor::tooltipRequest,
"TooltipRequest");
92 xoap::bind(
this, &GatewaySupervisor::supervisorCookieCheck,
"SupervisorCookieCheck", XDAQ_NS_URI);
93 xoap::bind(
this, &GatewaySupervisor::supervisorGetActiveUsers,
"SupervisorGetActiveUsers", XDAQ_NS_URI);
94 xoap::bind(
this, &GatewaySupervisor::supervisorSystemMessage,
"SupervisorSystemMessage", XDAQ_NS_URI);
96 xoap::bind(
this, &GatewaySupervisor::supervisorSystemLogbookEntry,
"SupervisorSystemLogbookEntry", XDAQ_NS_URI);
97 xoap::bind(
this, &GatewaySupervisor::supervisorLastConfigGroupRequest,
"SupervisorLastConfigGroupRequest", XDAQ_NS_URI);
111 GatewaySupervisor::~GatewaySupervisor(
void)
113 delete CorePropertySupervisorBase::theConfigurationManager_;
114 makeSystemLogbookEntry(
"ots halted.");
118 void GatewaySupervisor::init(
void)
120 supervisorGuiHasBeenLoaded_ =
false;
153 bool enableStateChanges =
false;
157 CorePropertySupervisorBase::getContextTreeNode().getNode(
"EnableStateChangesOverUDP").getValue<
bool>();
166 auto artdaqStateChangeEnabled = CorePropertySupervisorBase::getContextTreeNode().getNode(
"EnableARTDAQCommanderPlugin").getValue<
bool>();
167 if (artdaqStateChangeEnabled)
169 auto artdaqStateChangePort = CorePropertySupervisorBase::getContextTreeNode().getNode(
"ARTDAQCommanderID").getValue<
int>();
170 auto artdaqStateChangePluginType = CorePropertySupervisorBase::getContextTreeNode().getNode(
"ARTDAQCommanderType").getValue<std::string>();
171 theArtdaqCommandable_.init(artdaqStateChangePort, artdaqStateChangePluginType);
179 if (enableStateChanges)
181 __SUP_COUT__ <<
"Enabling state changes over UDP..." << __E__;
183 std::thread([](GatewaySupervisor *s) { GatewaySupervisor::StateChangerWorkLoop(s); },
this).detach();
186 __SUP_COUT__ <<
"State changes over UDP are disabled." << __E__;
194 const std::set<std::string>& contextMemberNames = CorePropertySupervisorBase::theConfigurationManager_->getContextMemberNames();
195 const std::set<std::string>& backboneMemberNames = CorePropertySupervisorBase::theConfigurationManager_->getBackboneMemberNames();
196 const std::set<std::string>& iterateMemberNames = CorePropertySupervisorBase::theConfigurationManager_->getIterateMemberNames();
198 FILE * fp = fopen((CORE_TABLE_INFO_FILENAME).c_str(),
"r");
200 __SUP_COUT__ <<
"Updating core tables table..." << __E__;
204 std::vector<unsigned int> foundVector;
206 for (
const auto &name : contextMemberNames)
208 foundVector.push_back(
false);
210 while (fgets(line, 100, fp))
212 if (strlen(line) < 1)
continue;
213 line[strlen(line) - 1] =
'\0';
214 if (strcmp(line, name.c_str()) == 0)
216 foundVector.back() =
true;
223 for (
const auto &name : backboneMemberNames)
225 foundVector.push_back(
false);
227 while (fgets(line, 100, fp))
229 if (strlen(line) < 1)
continue;
230 line[strlen(line) - 1] =
'\0';
231 if (strcmp(line, name.c_str()) == 0)
233 foundVector.back() =
true;
240 for (
const auto &name : iterateMemberNames)
242 foundVector.push_back(
false);
244 while (fgets(line, 100, fp))
246 if (strlen(line) < 1)
continue;
247 line[strlen(line) - 1] =
'\0';
248 if (strcmp(line, name.c_str()) == 0)
250 foundVector.back() =
true;
264 fp = fopen((CORE_TABLE_INFO_FILENAME).c_str(),
"a");
268 for (
const auto &name : contextMemberNames)
271 fprintf(fp,
"%s\n", name.c_str());
275 for (
const auto &name : backboneMemberNames)
278 fprintf(fp,
"%s\n", name.c_str());
282 for (
const auto &name : iterateMemberNames)
285 fprintf(fp,
"%s\n", name.c_str());
293 __SUP_SS__ <<
"Failed to open core table info file for appending: " << CORE_TABLE_INFO_FILENAME << std::endl;
300 fp = fopen((CORE_TABLE_INFO_FILENAME).c_str(),
"w");
303 for (
const auto &name : contextMemberNames)
304 fprintf(fp,
"%s\n", name.c_str());
305 for (
const auto &name : backboneMemberNames)
306 fprintf(fp,
"%s\n", name.c_str());
307 for (
const auto &name : iterateMemberNames)
308 fprintf(fp,
"%s\n", name.c_str());
313 __SUP_SS__ <<
"Failed to open core table info file: " << CORE_TABLE_INFO_FILENAME << std::endl;
326 void GatewaySupervisor::StateChangerWorkLoop(GatewaySupervisor *theSupervisor)
328 ConfigurationTree configLinkNode = theSupervisor->CorePropertySupervisorBase::theConfigurationManager_->getSupervisorConfigurationNode(
329 theSupervisor->supervisorContextUID_, theSupervisor->supervisorApplicationUID_);
332 std::string myip = configLinkNode.getNode(
"IPAddressForStateChangesOverUDP").getValue<std::string>();
333 int myport = configLinkNode.getNode(
"PortForStateChangesOverUDP").getValue<
int>();
334 bool ackEnabled = configLinkNode.getNode(
"EnableAckForStateChangesOverUDP").getValue<
bool>();
336 __COUT__ <<
"ip = " << myip << __E__;
337 __COUT__ <<
"port = " << myport << __E__;
338 __COUT__ <<
"ackEnabled = " << ackEnabled << __E__;
349 __SS__ <<
"FATAL Console error. Could not initialize socket at ip '" << myip <<
351 myport <<
". Perhaps it is already in use? Exiting State Changer receive loop." << std::endl;
352 __COUT__ << ss.str();
353 throw std::runtime_error(ss.str());
357 unsigned int i, firsti;
359 std::string errorStr;
360 std::string command, fsmName;
361 std::vector<std::string> parameters;
371 if (sock.receive(buffer, 0 , 1,
374 __COUT__ <<
"UDP State Changer received size = " << buffer.size() << __E__;
376 command =
"", fsmName =
"";
380 for (firsti = 0, i = 0; i < buffer.size(); ++i)
382 if (buffer[i] ==
',')
386 command = buffer.substr(firsti, i - firsti);
387 __COUT__ <<
"command = " << command << __E__;
389 else if (fsmName ==
"")
391 fsmName = buffer.substr(firsti, i - firsti);
392 __COUT__ <<
"fsmName = " << fsmName << __E__;
396 parameters.push_back(buffer.substr(firsti, i - firsti));
398 __COUT__ <<
"parameter[" << parameters.size() - 1 <<
399 "] = " << command << __E__;
410 if (theSupervisor->VERBOSE_MUTEX) __COUT__ <<
"Waiting for FSM access" << __E__;
411 std::lock_guard<std::mutex> lock(theSupervisor->stateMachineAccessMutex_);
412 if (theSupervisor->VERBOSE_MUTEX) __COUT__ <<
"Have FSM access" << __E__;
414 errorStr = theSupervisor->attemptStateMachineTransition(
417 WebUsers::DEFAULT_STATECHANGER_USERNAME ,
418 WebUsers::DEFAULT_STATECHANGER_USERNAME,
424 __SS__ <<
"UDP State Changer failed to execute command because of the following error: " << errorStr;
425 __COUT_ERR__ << ss.str();
426 __MOUT_ERR__ << ss.str();
427 if (ackEnabled) sock.acknowledge(errorStr,
true );
431 __SS__ <<
"Successfully executed state change command '" << command <<
".'" << __E__;
432 __COUT_INFO__ << ss.str();
433 __MOUT_INFO__ << ss.str();
434 if (ackEnabled) sock.acknowledge(
"Done",
true );
448 void GatewaySupervisor::makeSystemLogbookEntry(std::string entryText)
450 __SUP_COUT__ <<
"Making System Logbook Entry: " << entryText << std::endl;
452 SupervisorInfoMap logbookInfoMap = allSupervisorInfo_.getAllLogbookTypeSupervisorInfo();
454 if (logbookInfoMap.size() == 0)
456 __SUP_COUT__ <<
"No logbooks found! Here is entry: " << entryText << std::endl;
457 __MOUT__ <<
"No logbooks found! Here is entry: " << entryText << std::endl;
462 __SUP_COUT__ <<
"Making logbook entry: " << entryText << std::endl;
463 __MOUT__ <<
"Making logbook entry: " << entryText << std::endl;
469 std::string replace[] =
470 {
"\"",
"'",
"&",
"<",
">",
"\n",
" " };
472 {
"%22",
"%27",
"%26",
"%3C",
"%3E",
"%0A%0D",
"%20%20" };
477 for (
int i = 0; i < numOfKeys; ++i)
479 while ((f = entryText.find(replace[i])) != std::string::npos)
481 entryText = entryText.substr(0, f) + with[i] +
482 entryText.substr(f + replace[i].length());
493 for (
auto& logbookInfo : logbookInfoMap)
495 xoap::MessageReference retMsg = SOAPMessenger::sendWithSOAPReply(
496 logbookInfo.second.getDescriptor(),
497 "MakeSystemLogbookEntry", parameters);
502 receive(retMsg, retParameters);
504 __SUP_COUT__ <<
"Returned Status: " << retParameters.getValue(
"Status") << std::endl;
510 void GatewaySupervisor::Default(xgi::Input* in, xgi::Output* out)
514 if (!supervisorGuiHasBeenLoaded_ && (supervisorGuiHasBeenLoaded_ =
true))
515 makeSystemLogbookEntry(
"ots started.");
518 "<!DOCTYPE HTML><html lang='en'><head><title>ots</title>" <<
521 "<link rel='apple-touch-icon' sizes='57x57' href='/WebPath/images/otsdaqIcons/apple-icon-57x57.png'>\
522 <link rel='apple-touch-icon' sizes='60x60' href='/WebPath/images/otsdaqIcons/apple-icon-60x60.png'>\
523 <link rel='apple-touch-icon' sizes='72x72' href='/WebPath/images/otsdaqIcons/apple-icon-72x72.png'>\
524 <link rel='apple-touch-icon' sizes='76x76' href='/WebPath/images/otsdaqIcons/apple-icon-76x76.png'>\
525 <link rel='apple-touch-icon' sizes='114x114' href='/WebPath/images/otsdaqIcons/apple-icon-114x114.png'>\
526 <link rel='apple-touch-icon' sizes='120x120' href='/WebPath/images/otsdaqIcons/apple-icon-120x120.png'>\
527 <link rel='apple-touch-icon' sizes='144x144' href='/WebPath/images/otsdaqIcons/apple-icon-144x144.png'>\
528 <link rel='apple-touch-icon' sizes='152x152' href='/WebPath/images/otsdaqIcons/apple-icon-152x152.png'>\
529 <link rel='apple-touch-icon' sizes='180x180' href='/WebPath/images/otsdaqIcons/apple-icon-180x180.png'>\
530 <link rel='icon' type='image/png' sizes='192x192' href='/WebPath/images/otsdaqIcons/android-icon-192x192.png'>\
531 <link rel='icon' type='image/png' sizes='32x32' href='/WebPath/images/otsdaqIcons/favicon-32x32.png'>\
532 <link rel='icon' type='image/png' sizes='96x96' href='/WebPath/images/otsdaqIcons/favicon-96x96.png'>\
533 <link rel='icon' type='image/png' sizes='16x16' href='/WebPath/images/otsdaqIcons/favicon-16x16.png'>\
534 <link rel='manifest' href='/WebPath/images/otsdaqIcons/manifest.json'>\
535 <meta name='msapplication-TileColor' content='#ffffff'>\
536 <meta name='msapplication-TileImage' content='/ms-icon-144x144.png'>\
537 <meta name='theme-color' content='#ffffff'>" <<
540 "<frameset col='100%' row='100%'>" <<
541 "<frame src='/WebPath/html/Desktop.html?urn=" <<
542 this->getApplicationDescriptor()->getLocalId() <<
"=securityType=" <<
543 securityType_ <<
"'></frameset></html>";
547 void GatewaySupervisor::stateMachineXgiHandler(xgi::Input* in, xgi::Output* out)
550 if (VERBOSE_MUTEX) __SUP_COUT__ <<
"Waiting for FSM access" << std::endl;
551 std::lock_guard<std::mutex> lock(stateMachineAccessMutex_);
552 if (VERBOSE_MUTEX) __SUP_COUT__ <<
"Have FSM access" << std::endl;
554 cgicc::Cgicc cgiIn(in);
556 std::string command = CgiDataUtilities::getData(cgiIn,
"StateMachine");
557 std::string requestType =
"StateMachine" + command;
561 CgiDataUtilities::postData(cgiIn,
"CookieCode"));
563 CorePropertySupervisorBase::getRequestUserInfo(userInfo);
565 if(!theWebUsers_.xmlRequestOnGateway(
599 std::string fsmName = CgiDataUtilities::getData(cgiIn,
"fsmName");
600 std::string fsmWindowName = CgiDataUtilities::getData(cgiIn,
"fsmWindowName");
601 fsmWindowName = CgiDataUtilities::decodeURIComponent(fsmWindowName);
602 std::string currentState = theStateMachine_.getCurrentStateName();
604 __SUP_COUT__ <<
"Check for Handled by theIterator_" << std::endl;
607 if((activeStateMachineWindowName_ ==
"" ||
608 activeStateMachineWindowName_ ==
"iterator") &&
609 theIterator_.handleCommandRequest(xmlOut,command,fsmWindowName))
611 __SUP_COUT__ <<
"Handled by theIterator_" << std::endl;
612 xmlOut.outputXmlDocument((std::ostringstream*) out,
false);
617 if (theStateMachine_.isInTransition())
619 __SUP_SS__ <<
"Error - Can not accept request because the State Machine is already in transition!" << std::endl;
620 __SUP_COUT_ERR__ <<
"\n" << ss.str();
622 xmlOut.addTextElementToData(
"state_tranisition_attempted",
"0");
623 xmlOut.addTextElementToData(
"state_tranisition_attempted_err",
625 xmlOut.outputXmlDocument((std::ostringstream*) out,
false,
true);
637 if (activeStateMachineName_ !=
"" &&
638 activeStateMachineName_ != fsmName)
640 __SUP_COUT__ <<
"currentState = " <<
641 currentState << std::endl;
642 if (currentState !=
"Halted" &&
643 currentState !=
"Initial")
647 __SUP_SS__ <<
"Error - Can not accept request because the State Machine " <<
648 "with window name '" <<
649 activeStateMachineWindowName_ <<
"' (UID: " <<
650 activeStateMachineName_ <<
") "
652 "in control of State Machine progress. ";
653 ss <<
"\n\nIn order for this State Machine with window name '" <<
654 fsmWindowName <<
"' (UID: " << fsmName <<
") "
655 "to control progress, please transition to Halted using the active " <<
656 "State Machine '" << activeStateMachineWindowName_ <<
".'" << std::endl;
657 __SUP_COUT_ERR__ <<
"\n" << ss.str();
659 xmlOut.addTextElementToData(
"state_tranisition_attempted",
"0");
660 xmlOut.addTextElementToData(
"state_tranisition_attempted_err",
662 xmlOut.outputXmlDocument((std::ostringstream*) out,
false,
true);
667 activeStateMachineName_ =
"";
668 activeStateMachineWindowName_ =
"";
677 std::vector<std::string> parameters;
678 if(command ==
"Configure")
679 parameters.push_back(CgiDataUtilities::postData(cgiIn,
"ConfigurationAlias"));
680 attemptStateMachineTransition(&xmlOut,out,command,fsmName,fsmWindowName,
681 userInfo.username_,parameters);
684 std::string GatewaySupervisor::attemptStateMachineTransition(
686 const std::string& command,
687 const std::string& fsmName,
const std::string& fsmWindowName,
688 const std::string& username,
689 const std::vector<std::string>& commandParameters)
691 std::string errorStr =
"";
693 std::string currentState = theStateMachine_.getCurrentStateName();
694 __SUP_COUT__ <<
"State Machine command = " << command << std::endl;
695 __SUP_COUT__ <<
"fsmName = " << fsmName << std::endl;
696 __SUP_COUT__ <<
"fsmWindowName = " << fsmWindowName << std::endl;
697 __SUP_COUT__ <<
"activeStateMachineName_ = " << activeStateMachineName_ << std::endl;
700 if (command ==
"Configure")
702 if (currentState !=
"Halted")
704 __SUP_SS__ <<
"Error - Can only transition to Configured if the current " <<
705 "state is Halted. Perhaps your state machine is out of sync." <<
707 __SUP_COUT_ERR__ <<
"\n" << ss.str();
710 if (xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted",
"0");
711 if (xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted_err",
713 if (out) xmldoc->outputXmlDocument((std::ostringstream*) out,
false,
true);
720 if (!commandParameters.size())
722 __SUP_SS__ <<
"Error - Can only transition to Configured if a Configuration Alias parameter is provided." <<
724 __SUP_COUT_ERR__ <<
"\n" << ss.str();
727 if (xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted",
"0");
728 if (xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted_err",
730 if (out) xmldoc->outputXmlDocument((std::ostringstream*) out,
false,
true);
735 parameters.addParameter(
"ConfigurationAlias",
736 commandParameters[0]);
738 std::string configurationAlias = parameters.getValue(
"ConfigurationAlias");
739 __SUP_COUT__ <<
"Configure --> Name: ConfigurationAlias Value: " <<
740 configurationAlias << std::endl;
743 std::string fn = FSM_LAST_GROUP_ALIAS_PATH + FSM_LAST_GROUP_ALIAS_FILE_START +
744 username +
"." + FSM_USERS_PREFERENCES_FILETYPE;
746 __SUP_COUT__ <<
"Save FSM preferences: " << fn << std::endl;
747 FILE *fp = fopen(fn.c_str(),
"w");
750 __SUP_SS__ << (
"Could not open file: " + fn) << std::endl;
751 __SUP_COUT_ERR__ << ss.str();
752 throw std::runtime_error(ss.str());
754 fprintf(fp,
"FSM_last_configuration_alias %s", configurationAlias.c_str());
757 activeStateMachineName_ = fsmName;
758 activeStateMachineWindowName_ = fsmWindowName;
760 else if (command ==
"Start")
762 if (currentState !=
"Configured")
764 __SUP_SS__ <<
"Error - Can only transition to Configured if the current " <<
765 "state is Halted. Perhaps your state machine is out of sync. " <<
766 "(Likely the server was restarted or another user changed the state)" <<
768 __SUP_COUT_ERR__ <<
"\n" << ss.str();
771 if (xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted",
"0");
772 if (xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted_err",
774 if (out) xmldoc->outputXmlDocument((std::ostringstream*) out,
false,
true);
779 unsigned int runNumber = getNextRunNumber();
780 parameters.addParameter(
"RunNumber", runNumber);
781 setNextRunNumber(++runNumber);
784 xoap::MessageReference message = SOAPUtilities::makeSOAPMessageReference(
785 command, parameters);
787 xoap::MessageReference reply = stateMachineXoapHandler(message);
791 if (xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted",
"1");
792 if (out) xmldoc->outputXmlDocument((std::ostringstream*) out,
false);
793 __SUP_COUT__ <<
"FSM state transition launched!" << std::endl;
795 stateMachineLastCommandInput_ = command;
850 xoap::MessageReference GatewaySupervisor::stateMachineXoapHandler(xoap::MessageReference message)
853 __SUP_COUT__ <<
"Soap Handler!" << std::endl;
854 stateMachineWorkLoopManager_.removeProcessedRequests();
855 stateMachineWorkLoopManager_.processRequest(message);
856 __SUP_COUT__ <<
"Done - Soap Handler!" << std::endl;
861 xoap::MessageReference GatewaySupervisor::stateMachineResultXoapHandler(
862 xoap::MessageReference message)
865 __SUP_COUT__ <<
"Soap Handler!" << std::endl;
868 __SUP_COUT__ <<
"Done - Soap Handler!" << std::endl;
873 bool GatewaySupervisor::stateMachineThread(toolbox::task::WorkLoop* workLoop)
875 stateMachineSemaphore_.take();
876 __SUP_COUT__ <<
"Re-sending message..." << SOAPUtilities::translate(stateMachineWorkLoopManager_.getMessage(workLoop)).getCommand() << std::endl;
877 std::string reply = send(
878 allSupervisorInfo_.getGatewayDescriptor(),
879 stateMachineWorkLoopManager_.getMessage(workLoop));
880 stateMachineWorkLoopManager_.report(workLoop, reply, 100,
true);
882 __SUP_COUT__ <<
"Done with message. Reply = " << reply << std::endl;
883 stateMachineSemaphore_.give();
885 if (reply ==
"Fault")
887 __SUP_SS__ <<
"Failure to send Workloop transition command! Unrecognized transition name." << std::endl;
888 __SUP_COUT_ERR__ << ss.str();
889 __MOUT_ERR__ << ss.str();
900 void GatewaySupervisor::infoRequestHandler(xgi::Input* in, xgi::Output* out)
903 __SUP_COUT__ <<
"Starting to Request!" << std::endl;
906 cgicc::Cgicc cgiIn(in);
907 std::string requestType =
"infoRequestHandler";
911 CgiDataUtilities::postData(cgiIn,
"CookieCode"));
913 CorePropertySupervisorBase::getRequestUserInfo(userInfo);
915 if(!theWebUsers_.xmlRequestOnGateway(
941 HttpXmlDocument tmpDoc = infoRequestWorkLoopManager_.processRequest(cgiIn);
943 xmlOut.copyDataChildren(tmpDoc);
945 xmlOut.outputXmlDocument((std::ostringstream*) out,
false);
949 void GatewaySupervisor::infoRequestResultHandler(xgi::Input* in, xgi::Output* out)
952 __SUP_COUT__ <<
"Starting ask!" << std::endl;
953 cgicc::Cgicc cgi(in);
956 cgicc::Cgicc cgiIn(in);
957 std::string requestType =
"infoRequestResultHandler";
961 CgiDataUtilities::postData(cgiIn,
"CookieCode"));
963 CorePropertySupervisorBase::getRequestUserInfo(userInfo);
965 if(!theWebUsers_.xmlRequestOnGateway(
987 infoRequestWorkLoopManager_.getRequestResult(cgiIn, xmlOut);
990 xmlOut.outputXmlDocument((std::ostringstream*) out,
false);
992 __SUP_COUT__ <<
"Done asking!" << std::endl;
996 bool GatewaySupervisor::infoRequestThread(toolbox::task::WorkLoop* workLoop)
1001 infoRequestSemaphore_.take();
1003 vectorTest_.clear();
1005 for (
unsigned long long i = 0; i < 100000000; i++)
1008 vectorTest_.push_back(counterTest_);
1011 infoRequestWorkLoopManager_.report(workLoop,
1012 "RESULT: This is the best result ever", 50,
false);
1013 std::string workLoopName = workLoop->getName();
1014 __SUP_COUT__ << workLoopName <<
" test: " << counterTest_
1015 <<
" vector size: " << vectorTest_.size() << std::endl;
1016 wait(400,
"InfoRequestThread ----- locked");
1017 infoRequestSemaphore_.give();
1019 wait(200,
"InfoRequestThread");
1021 infoRequestSemaphore_.take();
1023 vectorTest_.clear();
1025 for (
unsigned long long i = 0; i < 100000000; i++)
1028 vectorTest_.push_back(counterTest_);
1031 wait(400,
"InfoRequestThread ----- locked");
1032 __SUP_COUT__ << workLoopName <<
" test: " << counterTest_ <<
" vector size: " << vectorTest_.size() << std::endl;
1033 infoRequestSemaphore_.give();
1036 infoRequestWorkLoopManager_.report(workLoop,
1037 theStateMachine_.getCurrentStateName(), 100,
true);
1044 void GatewaySupervisor::stateInitial(toolbox::fsm::FiniteStateMachine & fsm)
1047 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1053 void GatewaySupervisor::statePaused(toolbox::fsm::FiniteStateMachine & fsm)
1056 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1072 void GatewaySupervisor::stateRunning(toolbox::fsm::FiniteStateMachine & fsm)
1076 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1092 void GatewaySupervisor::stateHalted(toolbox::fsm::FiniteStateMachine& fsm)
1095 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1096 __SUP_COUT__ <<
"Fsm is in transition? " << (theStateMachine_.isInTransition() ?
"yes" :
"no") << std::endl;
1122 void GatewaySupervisor::stateConfigured(toolbox::fsm::FiniteStateMachine & fsm)
1191 void GatewaySupervisor::inError(toolbox::fsm::FiniteStateMachine & fsm)
1194 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1199 void GatewaySupervisor::enteringError(toolbox::Event::Reference e)
1202 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1205 toolbox::fsm::FailedEvent& failedEvent =
dynamic_cast<toolbox::fsm::FailedEvent&
> (*e);
1206 __SUP_SS__ <<
"\nFailure performing transition from " << failedEvent.getFromState() <<
"-" <<
1207 theStateMachine_.getStateName(failedEvent.getFromState()) <<
1208 " to " << failedEvent.getToState() <<
"-" <<
1209 theStateMachine_.getStateName(failedEvent.getToState()) <<
1210 ".\n\nException:\n" << failedEvent.getException().what() << std::endl;
1211 __SUP_COUT_ERR__ <<
"\n" << ss.str();
1213 theStateMachine_.setErrorMessage(ss.str());
1216 broadcastMessage(SOAPUtilities::makeSOAPMessageReference(
"Error"));
1225 void GatewaySupervisor::transitionConfiguring(toolbox::Event::Reference e)
1228 RunControlStateMachine::theProgressBar_.step();
1230 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1232 std::string systemAlias = SOAPUtilities::translate(
1233 theStateMachine_.getCurrentMessage()).getParameters().getValue(
"ConfigurationAlias");
1235 __SUP_COUT__ <<
"Transition parameter: " << systemAlias << std::endl;
1237 RunControlStateMachine::theProgressBar_.step();
1242 CorePropertySupervisorBase::theConfigurationManager_->init();
1246 __SUP_SS__ <<
"\nTransition to Configuring interrupted! " <<
1247 "The Configuration Manager could not be initialized." << std::endl;
1249 __SUP_COUT_ERR__ <<
"\n" << ss.str();
1250 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1254 RunControlStateMachine::theProgressBar_.step();
1259 theConfigurationGroup_ = CorePropertySupervisorBase::theConfigurationManager_->getConfigurationGroupFromAlias(systemAlias);
1263 __SUP_COUT_INFO__ <<
"Exception occurred" << std::endl;
1266 RunControlStateMachine::theProgressBar_.step();
1268 if (theConfigurationGroup_.second.isInvalid())
1270 __SUP_SS__ <<
"\nTransition to Configuring interrupted! System Alias " <<
1271 systemAlias <<
" could not be translated to a group name and key." << std::endl;
1273 __SUP_COUT_ERR__ <<
"\n" << ss.str();
1274 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1278 RunControlStateMachine::theProgressBar_.step();
1280 __SUP_COUT__ <<
"Configuration group name: " << theConfigurationGroup_.first <<
" key: " <<
1281 theConfigurationGroup_.second << std::endl;
1285 std::stringstream ss;
1286 ss <<
"Configuring '" << systemAlias <<
"' which translates to " <<
1287 theConfigurationGroup_.first <<
" (" << theConfigurationGroup_.second <<
").";
1288 makeSystemLogbookEntry(ss.str());
1291 RunControlStateMachine::theProgressBar_.step();
1296 CorePropertySupervisorBase::theConfigurationManager_->loadConfigurationGroup(theConfigurationGroup_.first, theConfigurationGroup_.second,
true);
1300 tmpCfgMgr.activateConfigurationGroup(theConfigurationGroup_.first, theConfigurationGroup_.second);
1304 __SUP_SS__ <<
"\nTransition to Configuring interrupted! System Alias " <<
1305 systemAlias <<
" was translated to " << theConfigurationGroup_.first <<
1306 " (" << theConfigurationGroup_.second <<
") but could not be loaded and initialized." << std::endl;
1307 ss <<
"\n\nTo debug this problem, try activating this group in the Configuration GUI " <<
1308 " and detailed errors will be shown." << std::endl;
1309 __SUP_COUT_ERR__ <<
"\n" << ss.str();
1310 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1316 ConfigurationTree configLinkNode = CorePropertySupervisorBase::theConfigurationManager_->getSupervisorConfigurationNode(
1317 supervisorContextUID_, supervisorApplicationUID_);
1318 if (!configLinkNode.isDisconnected())
1323 bool dumpConfiguration =
true;
1324 std::string dumpFilePath, dumpFileRadix, dumpFormat;
1327 ConfigurationTree fsmLinkNode = configLinkNode.getNode(
"LinkToStateMachineConfiguration").
1328 getNode(activeStateMachineName_);
1329 dumpConfiguration = fsmLinkNode.getNode(
"EnableConfigurationDumpOnConfigureTransition").
1331 dumpFilePath = fsmLinkNode.getNode(
"ConfigurationDumpOnConfigureFilePath").getValue<std::string>();
1332 dumpFileRadix = fsmLinkNode.getNode(
"ConfigurationDumpOnConfigureFileRadix").getValue<std::string>();
1333 dumpFormat = fsmLinkNode.getNode(
"ConfigurationDumpOnConfigureFormat").getValue<std::string>();
1336 catch (std::runtime_error &e)
1338 __SUP_COUT_INFO__ <<
"FSM configuration dump Link disconnected." << std::endl;
1339 dumpConfiguration =
false;
1342 if (dumpConfiguration)
1345 CorePropertySupervisorBase::theConfigurationManager_->dumpActiveConfiguration(
1350 std::to_string(time(0)) +
1357 catch (std::runtime_error &e)
1359 __SUP_SS__ <<
"\nTransition to Configuring interrupted! There was an error identified " <<
1360 "during the configuration dump attempt:\n\n " <<
1361 e.what() << std::endl;
1362 __SUP_COUT_ERR__ <<
"\n" << ss.str();
1363 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1368 __SUP_SS__ <<
"\nTransition to Configuring interrupted! There was an error identified " <<
1369 "during the configuration dump attempt.\n\n " <<
1371 __SUP_COUT_ERR__ <<
"\n" << ss.str();
1372 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1378 RunControlStateMachine::theProgressBar_.step();
1380 parameters.addParameter(
"ConfigurationGroupName", theConfigurationGroup_.first);
1381 parameters.addParameter(
"ConfigurationGroupKey", theConfigurationGroup_.second.toString());
1384 xoap::MessageReference message = theStateMachine_.getCurrentMessage();
1385 SOAPUtilities::addParameters(message, parameters);
1386 broadcastMessage(message);
1387 RunControlStateMachine::theProgressBar_.step();
1392 saveGroupNameAndKey(theConfigurationGroup_, FSM_LAST_CONFIGURED_GROUP_ALIAS_FILE);
1394 __SUP_COUT__ <<
"Done" << std::endl;
1395 RunControlStateMachine::theProgressBar_.complete();
1399 void GatewaySupervisor::transitionHalting(toolbox::Event::Reference e)
1402 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1404 makeSystemLogbookEntry(
"Run halting.");
1406 broadcastMessage(theStateMachine_.getCurrentMessage());
1410 void GatewaySupervisor::transitionShuttingDown(toolbox::Event::Reference e)
1413 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1415 RunControlStateMachine::theProgressBar_.step();
1416 makeSystemLogbookEntry(
"System shutting down.");
1417 RunControlStateMachine::theProgressBar_.step();
1420 launchStartOTSCommand(
"OTS_APP_SHUTDOWN");
1421 RunControlStateMachine::theProgressBar_.step();
1424 for (
int i = 0; i < 5; ++i)
1427 RunControlStateMachine::theProgressBar_.step();
1432 void GatewaySupervisor::transitionStartingUp(toolbox::Event::Reference e)
1435 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1437 RunControlStateMachine::theProgressBar_.step();
1438 makeSystemLogbookEntry(
"System starting up.");
1439 RunControlStateMachine::theProgressBar_.step();
1442 launchStartOTSCommand(
"OTS_APP_STARTUP");
1443 RunControlStateMachine::theProgressBar_.step();
1446 for (
int i = 0; i < 10; ++i)
1449 RunControlStateMachine::theProgressBar_.step();
1454 void GatewaySupervisor::transitionInitializing(toolbox::Event::Reference e)
1457 __SUP_COUT__ << theStateMachine_.getCurrentStateName() << std::endl;
1459 if (!broadcastMessage(theStateMachine_.getCurrentMessage()))
1461 __SUP_COUT_ERR__ <<
"I can't Initialize the supervisors!" << std::endl;
1464 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1465 __SUP_COUT__ <<
"Fsm current transition: " << theStateMachine_.getCurrentTransitionName(e->type()) << std::endl;
1466 __SUP_COUT__ <<
"Fsm final state: " << theStateMachine_.getTransitionFinalStateName(e->type()) << std::endl;
1470 void GatewaySupervisor::transitionPausing(toolbox::Event::Reference e)
1473 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1475 makeSystemLogbookEntry(
"Run pausing.");
1477 broadcastMessage(theStateMachine_.getCurrentMessage());
1481 void GatewaySupervisor::transitionResuming(toolbox::Event::Reference e)
1484 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1486 makeSystemLogbookEntry(
"Run resuming.");
1488 broadcastMessage(theStateMachine_.getCurrentMessage());
1492 void GatewaySupervisor::transitionStarting(toolbox::Event::Reference e)
1495 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1498 receive(theStateMachine_.getCurrentMessage(), parameters);
1500 std::string runNumber = parameters.getValue(
"RunNumber");
1501 __SUP_COUT__ << runNumber << std::endl;
1505 ConfigurationTree configLinkNode = CorePropertySupervisorBase::theConfigurationManager_->getSupervisorConfigurationNode(
1506 supervisorContextUID_, supervisorApplicationUID_);
1507 if (!configLinkNode.isDisconnected())
1511 bool dumpConfiguration =
true;
1512 std::string dumpFilePath, dumpFileRadix, dumpFormat;
1515 ConfigurationTree fsmLinkNode = configLinkNode.getNode(
"LinkToStateMachineConfiguration").
1516 getNode(activeStateMachineName_);
1517 dumpConfiguration = fsmLinkNode.getNode(
"EnableConfigurationDumpOnRunTransition").
1519 dumpFilePath = fsmLinkNode.getNode(
"ConfigurationDumpOnRunFilePath").getValue<std::string>();
1520 dumpFileRadix = fsmLinkNode.getNode(
"ConfigurationDumpOnRunFileRadix").getValue<std::string>();
1521 dumpFormat = fsmLinkNode.getNode(
"ConfigurationDumpOnRunFormat").getValue<std::string>();
1523 catch (std::runtime_error &e)
1525 __SUP_COUT_INFO__ <<
"FSM configuration dump Link disconnected." << std::endl;
1526 dumpConfiguration =
false;
1529 if (dumpConfiguration)
1532 CorePropertySupervisorBase::theConfigurationManager_->dumpActiveConfiguration(
1539 std::to_string(time(0)) +
1546 catch (std::runtime_error &e)
1548 __SUP_SS__ <<
"\nTransition to Running interrupted! There was an error identified " <<
1549 "during the configuration dump attempt:\n\n " <<
1550 e.what() << std::endl;
1551 __SUP_COUT_ERR__ <<
"\n" << ss.str();
1552 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1557 __SUP_SS__ <<
"\nTransition to Running interrupted! There was an error identified " <<
1558 "during the configuration dump attempt.\n\n " <<
1560 __SUP_COUT_ERR__ <<
"\n" << ss.str();
1561 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1568 makeSystemLogbookEntry(
"Run " + runNumber +
" starting.");
1570 broadcastMessage(theStateMachine_.getCurrentMessage());
1573 saveGroupNameAndKey(theConfigurationGroup_, FSM_LAST_STARTED_GROUP_ALIAS_FILE);
1577 void GatewaySupervisor::transitionStopping(toolbox::Event::Reference e)
1580 __SUP_COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1582 makeSystemLogbookEntry(
"Run stopping.");
1584 broadcastMessage(theStateMachine_.getCurrentMessage());
1596 bool GatewaySupervisor::broadcastMessage(xoap::MessageReference message)
1599 RunControlStateMachine::theProgressBar_.step();
1602 allSupervisorInfo_.setSupervisorStatus(
this,
1603 theStateMachine_.getCurrentStateName());
1605 std::string command = SOAPUtilities::translate(message).getCommand();
1606 bool proceed =
true;
1609 __SUP_COUT__ <<
"=========> Broadcasting state machine command = " << command << __E__;
1613 for (
auto& it : allSupervisorInfo_.getOrderedSupervisorDescriptors(command))
1617 RunControlStateMachine::theProgressBar_.step();
1619 __SUP_COUT__ <<
"Sending message to Supervisor " << appInfo.getName() <<
" [LID=" <<
1620 appInfo.getId() <<
"]: " << command << std::endl;
1621 __SUP_COUT__ <<
"Sending message to Supervisor " << appInfo.getName() <<
" [LID=" <<
1622 appInfo.getId() <<
"]: " << command << std::endl;
1623 __SUP_COUT__ <<
"Sending message to Supervisor " << appInfo.getName() <<
" [LID=" <<
1624 appInfo.getId() <<
"]: " << command << std::endl;
1625 __SUP_COUT__ <<
"Sending message to Supervisor " << appInfo.getName() <<
" [LID=" <<
1626 appInfo.getId() <<
"]: " << command << std::endl;
1630 reply = send(appInfo.getDescriptor(), message);
1632 catch (
const xdaq::exception::Exception &e)
1635 __SUP_SS__ <<
"Error! Gateway Supervisor can NOT " << command <<
" Supervisor instance = '" <<
1636 appInfo.getName() <<
"' [LID=" <<
1637 appInfo.getId() <<
"] in Context '" <<
1638 appInfo.getContextName() <<
"' [URL=" <<
1641 "Xoap message failure. Did the target Supervisor crash? Try re-initializing or restarting otsdaq." << std::endl;
1642 __SUP_COUT_ERR__ << ss.str();
1643 __MOUT_ERR__ << ss.str();
1647 __SUP_COUT__ <<
"Try again.." << __E__;
1648 reply = send(appInfo.getDescriptor(), message);
1650 catch (
const xdaq::exception::Exception &e)
1652 __SUP_COUT__ <<
"Failed.." << __E__;
1653 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1655 __SUP_COUT__ <<
"2nd passed.." << __E__;
1659 if (reply != command +
"Done")
1661 __SUP_SS__ <<
"Error! Gateway Supervisor can NOT " << command <<
" Supervisor instance = '" <<
1662 appInfo.getName() <<
"' [LID=" <<
1663 appInfo.getId() <<
"] in Context '" <<
1664 appInfo.getContextName() <<
"' [URL=" <<
1668 __SUP_COUT_ERR__ << ss.str() << std::endl;
1669 __MOUT_ERR__ << ss.str() << std::endl;
1671 __SUP_COUT__ <<
"Getting error message..." << std::endl;
1674 xoap::MessageReference errorMessage = sendWithSOAPReply(appInfo.getDescriptor(),
1675 SOAPUtilities::makeSOAPMessageReference(
"StateMachineErrorMessageRequest"));
1677 parameters.addParameter(
"ErrorMessage");
1678 SOAPMessenger::receive(errorMessage, parameters);
1680 std::string error = parameters.getValue(
"ErrorMessage");
1683 std::stringstream err;
1684 err <<
"Unknown error from Supervisor instance = '" <<
1685 appInfo.getName() <<
"' [LID=" <<
1686 appInfo.getId() <<
"] in Context '" <<
1687 appInfo.getContextName() <<
"' [URL=" <<
1689 "]. If the problem persists or is repeatable, please notify admins.\n\n";
1693 __SUP_SS__ <<
"Received error from Supervisor instance = '" <<
1694 appInfo.getName() <<
"' [LID=" <<
1695 appInfo.getId() <<
"] in Context '" <<
1696 appInfo.getContextName() <<
"' [URL=" <<
1698 "].\n\n Error Message = " << error << std::endl;
1700 __SUP_COUT_ERR__ << ss.str() << std::endl;
1701 __MOUT_ERR__ << ss.str() << std::endl;
1703 if (command ==
"Error")
continue;
1705 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1709 catch (
const xdaq::exception::Exception &e)
1712 __SUP_SS__ <<
"Error! Gateway Supervisor failed to read error message from Supervisor instance = '" <<
1713 appInfo.getName() <<
"' [LID=" <<
1714 appInfo.getId() <<
"] in Context '" <<
1715 appInfo.getContextName() <<
"' [URL=" <<
1718 "Xoap message failure. Did the target Supervisor crash? Try re-initializing or restarting otsdaq." << std::endl;
1719 __SUP_COUT_ERR__ << ss.str();
1720 __MOUT_ERR__ << ss.str();
1721 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1728 __SUP_COUT__ <<
"Supervisor instance = '" <<
1729 appInfo.getName() <<
"' [LID=" <<
1730 appInfo.getId() <<
"] in Context '" <<
1731 appInfo.getContextName() <<
"' [URL=" <<
1733 "] was " << command <<
"'d correctly!" << std::endl;
1738 __SUP_COUT__ <<
"Breaking out of loop." << __E__;
1743 RunControlStateMachine::theProgressBar_.step();
1749 void GatewaySupervisor::wait(
int milliseconds, std::string who)
const
1751 for (
int s = 1; s <= milliseconds; s++)
1756 __SUP_COUT__ << s <<
" msecs " << who << std::endl;
1765 void GatewaySupervisor::loginRequest(xgi::Input * in, xgi::Output * out)
1768 cgicc::Cgicc cgi(in);
1769 std::string Command = CgiDataUtilities::getData(cgi,
"RequestType");
1770 __SUP_COUT__ <<
"*** Login RequestType = " << Command << std::endl;
1779 std::vector<std::string> loggedOutUsernames;
1780 theWebUsers_.cleanupExpiredEntries(&loggedOutUsernames);
1781 for (
unsigned int i = 0; i < loggedOutUsernames.size(); ++i)
1782 makeSystemLogbookEntry(loggedOutUsernames[i] +
" login timed out.");
1784 if (Command ==
"sessionId")
1791 std::string uuid = CgiDataUtilities::postData(cgi,
"uuid");
1793 std::string sid = theWebUsers_.createNewLoginSession(uuid,
1794 cgi.getEnvironment().getRemoteAddr() );
1800 else if (Command ==
"checkCookie")
1804 std::string jumbledUser;
1805 std::string cookieCode;
1815 uuid = CgiDataUtilities::postData(cgi,
"uuid");
1816 jumbledUser = CgiDataUtilities::postData(cgi,
"ju");
1817 cookieCode = CgiDataUtilities::postData(cgi,
"cc");
1824 uid = theWebUsers_.isCookieCodeActiveForLogin(uuid, cookieCode,
1827 if (uid == theWebUsers_.NOT_FOUND_IN_DATABASE)
1829 __SUP_COUT__ <<
"cookieCode invalid" << std::endl;
1834 __SUP_COUT__ <<
"cookieCode is good." << std::endl;
1839 theWebUsers_.insertSettingsForUser(uid, &xmldoc);
1841 xmldoc.outputXmlDocument((std::ostringstream*) out);
1844 else if (Command ==
"login")
1855 std::string uuid = CgiDataUtilities::postData(cgi,
"uuid");
1856 std::string newAccountCode = CgiDataUtilities::postData(cgi,
"nac");
1857 std::string jumbledUser = CgiDataUtilities::postData(cgi,
"ju");
1858 std::string jumbledPw = CgiDataUtilities::postData(cgi,
"jp");
1865 uint64_t uid = theWebUsers_.attemptActiveSession(uuid, jumbledUser,
1866 jumbledPw, newAccountCode, cgi.getEnvironment().getRemoteAddr());
1869 if (uid == theWebUsers_.NOT_FOUND_IN_DATABASE)
1871 __SUP_COUT__ <<
"Login invalid." << std::endl;
1873 if (newAccountCode !=
"1")
1874 newAccountCode =
"0";
1877 makeSystemLogbookEntry(
1878 theWebUsers_.getUsersUsername(uid) +
" logged in.");
1884 theWebUsers_.insertSettingsForUser(uid, &xmldoc);
1888 if (uid != theWebUsers_.NOT_FOUND_IN_DATABASE)
1890 uint64_t asCnt = theWebUsers_.getActiveSessionCountForUser(uid) - 1;
1892 sprintf(asStr,
"%lu", asCnt);
1893 xmldoc.addTextElementToData(
"user_active_session_count", asStr);
1896 xmldoc.outputXmlDocument((std::ostringstream*) out);
1899 else if (Command ==
"cert")
1910 std::string uuid = CgiDataUtilities::postData(cgi,
"uuid");
1911 std::string jumbledEmail = cgicc::form_urldecode(CgiDataUtilities::getData(cgi,
"httpsUser"));
1912 std::string username =
"";
1913 std::string cookieCode =
"";
1919 uint64_t uid = theWebUsers_.attemptActiveSessionWithCert(uuid, jumbledEmail,
1920 cookieCode, username, cgi.getEnvironment().getRemoteAddr());
1923 if (uid == theWebUsers_.NOT_FOUND_IN_DATABASE)
1925 __SUP_COUT__ <<
"cookieCode invalid" << std::endl;
1927 if (cookieCode !=
"1")
1931 makeSystemLogbookEntry(
1932 theWebUsers_.getUsersUsername(uid) +
" logged in.");
1938 theWebUsers_.insertSettingsForUser(uid, &xmldoc);
1942 if (uid != theWebUsers_.NOT_FOUND_IN_DATABASE)
1944 uint64_t asCnt = theWebUsers_.getActiveSessionCountForUser(uid) - 1;
1946 sprintf(asStr,
"%lu", asCnt);
1947 xmldoc.addTextElementToData(
"user_active_session_count", asStr);
1950 xmldoc.outputXmlDocument((std::ostringstream*) out);
1952 else if (Command ==
"logout")
1954 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
1955 std::string logoutOthers = CgiDataUtilities::postData(cgi,
1962 if (theWebUsers_.cookieCodeLogout(cookieCode, logoutOthers ==
"1",
1963 &uid, cgi.getEnvironment().getRemoteAddr())
1964 != theWebUsers_.NOT_FOUND_IN_DATABASE)
1968 if (!theWebUsers_.isUserIdActive(uid))
1969 makeSystemLogbookEntry(
1970 theWebUsers_.getUsersUsername(uid) +
" logged out.");
1975 __SUP_COUT__ << __LINE__ <<
"\tInvalid Command" << std::endl;
1981 void GatewaySupervisor::tooltipRequest(xgi::Input * in, xgi::Output * out)
1984 cgicc::Cgicc cgi(in);
1986 std::string Command = CgiDataUtilities::getData(cgi,
"RequestType");
1987 __SUP_COUT__ <<
"Tooltip RequestType = " << Command << std::endl;
1993 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
1996 if (!theWebUsers_.cookieCodeIsActiveForRequest(cookieCode,
2010 if (Command ==
"check")
2012 WebUsers::tooltipCheckForUsername(
2013 theWebUsers_.getUsersUsername(uid),
2015 CgiDataUtilities::getData(cgi,
"srcFile"),
2016 CgiDataUtilities::getData(cgi,
"srcFunc"),
2017 CgiDataUtilities::getData(cgi,
"srcId"));
2019 else if (Command ==
"setNeverShow")
2021 WebUsers::tooltipSetNeverShowForUsername(
2022 theWebUsers_.getUsersUsername(uid),
2024 CgiDataUtilities::getData(cgi,
"srcFile"),
2025 CgiDataUtilities::getData(cgi,
"srcFunc"),
2026 CgiDataUtilities::getData(cgi,
"srcId"),
2027 CgiDataUtilities::getData(cgi,
"doNeverShow") ==
"1" ?
true :
false,
2028 CgiDataUtilities::getData(cgi,
"temporarySilence") ==
"1" ?
true :
false);
2032 __SUP_COUT__ <<
"Command Request, " << Command <<
", not recognized." << std::endl;
2034 xmldoc.outputXmlDocument((std::ostringstream*) out,
false,
true);
2040 void GatewaySupervisor::setSupervisorPropertyDefaults()
2042 CorePropertySupervisorBase::setSupervisorProperty(CorePropertySupervisorBase::SUPERVISOR_PROPERTIES.UserPermissionsThreshold, std::string() +
2043 "*=1 | gatewayLaunchOTS=-1 | gatewayLaunchWiz=-1");
2049 void GatewaySupervisor::forceSupervisorPropertyValues()
2055 CorePropertySupervisorBase::setSupervisorProperty(CorePropertySupervisorBase::SUPERVISOR_PROPERTIES.AutomatedRequestTypes,
2056 "getSystemMessages | getCurrentState | gatewayLaunchOTS | gatewayLaunchWiz");
2057 CorePropertySupervisorBase::setSupervisorProperty(CorePropertySupervisorBase::SUPERVISOR_PROPERTIES.RequireUserLockRequestTypes,
2058 "gatewayLaunchOTS | gatewayLaunchWiz");
2065 void GatewaySupervisor::request(xgi::Input * in, xgi::Output * out)
2069 if (VERBOSE_MUTEX) __SUP_COUT__ <<
"Waiting for FSM access" << std::endl;
2070 std::lock_guard<std::mutex> lock(stateMachineAccessMutex_);
2071 if (VERBOSE_MUTEX) __SUP_COUT__ <<
"Have FSM access" << std::endl;
2073 cgicc::Cgicc cgiIn(in);
2075 std::string requestType = CgiDataUtilities::getData(cgiIn,
"RequestType");
2080 CgiDataUtilities::postData(cgiIn,
"CookieCode"));
2082 CorePropertySupervisorBase::getRequestUserInfo(userInfo);
2085 if(!theWebUsers_.xmlRequestOnGateway(
2143 if (requestType ==
"getSettings")
2145 std::string accounts = CgiDataUtilities::getData(cgiIn,
"accounts");
2147 __SUP_COUT__ <<
"Get Settings Request" << std::endl;
2148 __SUP_COUT__ <<
"accounts = " << accounts << std::endl;
2149 theWebUsers_.insertSettingsForUser(userInfo.uid_, &xmlOut, accounts ==
"1");
2151 else if (requestType ==
"setSettings")
2153 std::string bgcolor = CgiDataUtilities::postData(cgiIn,
"bgcolor");
2154 std::string dbcolor = CgiDataUtilities::postData(cgiIn,
"dbcolor");
2155 std::string wincolor = CgiDataUtilities::postData(cgiIn,
"wincolor");
2156 std::string layout = CgiDataUtilities::postData(cgiIn,
"layout");
2157 std::string syslayout = CgiDataUtilities::postData(cgiIn,
"syslayout");
2159 __SUP_COUT__ <<
"Set Settings Request" << std::endl;
2160 __SUP_COUT__ <<
"bgcolor = " << bgcolor << std::endl;
2161 __SUP_COUT__ <<
"dbcolor = " << dbcolor << std::endl;
2162 __SUP_COUT__ <<
"wincolor = " << wincolor << std::endl;
2163 __SUP_COUT__ <<
"layout = " << layout << std::endl;
2164 __SUP_COUT__ <<
"syslayout = " << syslayout << std::endl;
2166 theWebUsers_.changeSettingsForUser(userInfo.uid_, bgcolor, dbcolor, wincolor,
2168 theWebUsers_.insertSettingsForUser(userInfo.uid_, &xmlOut,
true);
2170 else if (requestType ==
"accountSettings")
2172 std::string type = CgiDataUtilities::postData(cgiIn,
"type");
2175 if (type ==
"updateAccount")
2177 else if (type ==
"createAccount")
2179 else if (type ==
"deleteAccount")
2182 std::string username = CgiDataUtilities::postData(cgiIn,
"username");
2183 std::string displayname = CgiDataUtilities::postData(cgiIn,
2185 std::string email = CgiDataUtilities::postData(cgiIn,
"useremail");
2186 std::string permissions = CgiDataUtilities::postData(cgiIn,
2188 std::string accounts = CgiDataUtilities::getData(cgiIn,
"accounts");
2190 __SUP_COUT__ <<
"accountSettings Request" << std::endl;
2191 __SUP_COUT__ <<
"type = " << type <<
" - " << type_int << std::endl;
2192 __SUP_COUT__ <<
"username = " << username << std::endl;
2193 __SUP_COUT__ <<
"useremail = " << email << std::endl;
2194 __SUP_COUT__ <<
"displayname = " << displayname << std::endl;
2195 __SUP_COUT__ <<
"permissions = " << permissions << std::endl;
2197 theWebUsers_.modifyAccountSettings(userInfo.uid_, type_int, username, displayname,email,
2200 __SUP_COUT__ <<
"accounts = " << accounts << std::endl;
2202 theWebUsers_.insertSettingsForUser(userInfo.uid_, &xmlOut, accounts ==
"1");
2204 else if(requestType ==
"stateMatchinePreferences")
2206 std::string set = CgiDataUtilities::getData(cgiIn,
"set");
2207 const std::string DEFAULT_FSM_VIEW =
"Default_FSM_View";
2209 theWebUsers_.setGenericPreference(userInfo.uid_, DEFAULT_FSM_VIEW,
2210 CgiDataUtilities::getData(cgiIn, DEFAULT_FSM_VIEW));
2212 theWebUsers_.getGenericPreference(userInfo.uid_, DEFAULT_FSM_VIEW, &xmlOut);
2214 else if(requestType ==
"getAliasList")
2216 std::string username = theWebUsers_.getUsersUsername(userInfo.uid_);
2217 std::string fsmName = CgiDataUtilities::getData(cgiIn,
"fsmName");
2218 __SUP_COUT__ <<
"fsmName = " << fsmName << std::endl;
2220 std::string stateMachineAliasFilter =
"*";
2222 std::map<std::string ,
2224 CorePropertySupervisorBase::theConfigurationManager_->getGroupAliasesConfiguration();
2228 ConfigurationTree configLinkNode = CorePropertySupervisorBase::theConfigurationManager_->getSupervisorConfigurationNode(
2229 supervisorContextUID_, supervisorApplicationUID_);
2231 if (!configLinkNode.isDisconnected())
2235 ConfigurationTree fsmLinkNode = configLinkNode.getNode(
"LinkToStateMachineConfiguration");
2236 if (!fsmLinkNode.isDisconnected())
2237 stateMachineAliasFilter =
2238 fsmLinkNode.getNode(fsmName +
"/SystemAliasFilter").getValue<std::string>();
2240 __SUP_COUT_INFO__ <<
"FSM Link disconnected." << std::endl;
2242 catch (std::runtime_error &e) { __SUP_COUT_INFO__ << e.what() << std::endl; }
2243 catch (...) { __SUP_COUT_ERR__ <<
"Unknown error. Should never happen." << std::endl; }
2246 __SUP_COUT_INFO__ <<
"FSM Link disconnected." << std::endl;
2248 __SUP_COUT__ <<
"stateMachineAliasFilter = " << stateMachineAliasFilter << std::endl;
2255 bool invertFilter = stateMachineAliasFilter.size() && stateMachineAliasFilter[0] ==
'!';
2256 std::vector<std::string> filterArr;
2259 if (invertFilter) ++i;
2262 while ((f = stateMachineAliasFilter.find(
'*', i)) != std::string::npos)
2264 tmp = stateMachineAliasFilter.substr(i, f - i);
2266 filterArr.push_back(tmp);
2271 if (i <= stateMachineAliasFilter.size())
2273 tmp = stateMachineAliasFilter.substr(i);
2274 filterArr.push_back(tmp);
2282 for (
auto& aliasMapPair : aliasMap)
2288 if (filterArr.size() == 1)
2290 if (filterArr[0] !=
"" &&
2291 filterArr[0] !=
"*" &&
2292 aliasMapPair.first != filterArr[0])
2293 filterMatch =
false;
2298 for (f = 0; f < filterArr.size(); ++f)
2300 if (!filterArr[f].size())
continue;
2304 if ((i = aliasMapPair.first.find(filterArr[f])) != 0)
2306 filterMatch =
false;
2310 else if (f == filterArr.size() - 1)
2312 if (aliasMapPair.first.rfind(filterArr[f]) !=
2313 aliasMapPair.first.size() - filterArr[f].size())
2315 filterMatch =
false;
2319 else if ((i = aliasMapPair.first.find(filterArr[f])) ==
2322 filterMatch =
false;
2328 if (invertFilter) filterMatch = !filterMatch;
2332 if (!filterMatch)
continue;
2334 xmlOut.addTextElementToData(
"config_alias", aliasMapPair.first);
2335 xmlOut.addTextElementToData(
"config_key",
2336 ConfigurationGroupKey::getFullGroupString(aliasMapPair.second.first,
2337 aliasMapPair.second.second).c_str());
2339 std::string groupComment, groupAuthor, groupCreationTime;
2342 CorePropertySupervisorBase::theConfigurationManager_->loadConfigurationGroup(
2343 aliasMapPair.second.first, aliasMapPair.second.second,
2345 &groupComment, &groupAuthor, &groupCreationTime,
false );
2347 xmlOut.addTextElementToData(
"config_comment", groupComment);
2348 xmlOut.addTextElementToData(
"config_author", groupAuthor);
2349 xmlOut.addTextElementToData(
"config_create_time", groupCreationTime);
2353 __SUP_COUT_WARN__ <<
"Failed to load group metadata." << std::endl;
2359 std::string fn = FSM_LAST_GROUP_ALIAS_PATH + FSM_LAST_GROUP_ALIAS_FILE_START +
2360 username +
"." + FSM_USERS_PREFERENCES_FILETYPE;
2361 __SUP_COUT__ <<
"Load preferences: " << fn << std::endl;
2362 FILE *fp = fopen(fn.c_str(),
"r");
2365 char tmpLastAlias[500];
2366 fscanf(fp,
"%*s %s", tmpLastAlias);
2367 __SUP_COUT__ <<
"tmpLastAlias: " << tmpLastAlias << std::endl;
2369 xmlOut.addTextElementToData(
"UserLastConfigAlias",tmpLastAlias);
2373 else if (requestType ==
"getFecList")
2375 xmlOut.addTextElementToData(
"fec_list",
"");
2377 for (
auto it : allSupervisorInfo_.getAllFETypeSupervisorInfo())
2379 xmlOut.addTextElementToParent(
"fec_url",
2380 it.second.getURL(),
"fec_list");
2381 xmlOut.addTextElementToParent(
2383 std::to_string(it.second.getId()),
"fec_list");
2386 else if (requestType ==
"getSystemMessages")
2388 xmlOut.addTextElementToData(
"systemMessages",
2389 theSystemMessenger_.getSystemMessage(
2390 theWebUsers_.getUsersDisplayName(userInfo.uid_)));
2392 xmlOut.addTextElementToData(
"username_with_lock",
2393 theWebUsers_.getUserWithLock());
2397 else if (requestType ==
"setUserWithLock")
2399 std::string username = CgiDataUtilities::postData(cgiIn,
"username");
2400 std::string lock = CgiDataUtilities::postData(cgiIn,
"lock");
2401 std::string accounts = CgiDataUtilities::getData(cgiIn,
"accounts");
2403 __SUP_COUT__ << requestType << std::endl;
2404 __SUP_COUT__ <<
"username " << username << std::endl;
2405 __SUP_COUT__ <<
"lock " << lock << std::endl;
2406 __SUP_COUT__ <<
"accounts " << accounts << std::endl;
2407 __SUP_COUT__ <<
"userInfo.uid_ " << userInfo.uid_ << std::endl;
2409 std::string tmpUserWithLock = theWebUsers_.getUserWithLock();
2410 if(!theWebUsers_.setUserWithLock(userInfo.uid_, lock ==
"1", username))
2411 xmlOut.addTextElementToData(
"server_alert",
2412 std::string(
"Set user lock action failed. You must have valid permissions and ") +
2413 "locking user must be currently logged in.");
2415 theWebUsers_.insertSettingsForUser(userInfo.uid_, &xmlOut, accounts ==
"1");
2417 if (tmpUserWithLock != theWebUsers_.getUserWithLock())
2418 theSystemMessenger_.addSystemMessage(
"*", theWebUsers_.getUserWithLock()
2419 ==
"" ? tmpUserWithLock +
" has unlocked ots."
2420 : theWebUsers_.getUserWithLock()
2421 +
" has locked ots.");
2423 else if (requestType ==
"getStateMachine")
2426 std::vector<toolbox::fsm::State> states;
2427 states = theStateMachine_.getStates();
2430 std::string transName;
2431 std::string transParameter;
2434 for (
unsigned int i = 0; i < states.size(); ++i)
2436 stateStr[0] = states[i];
2437 DOMElement* stateParent = xmlOut.addTextElementToData(
"state", stateStr);
2439 xmlOut.addTextElementToParent(
"state_name", theStateMachine_.getStateName(states[i]), stateParent);
2444 std::map<std::string, toolbox::fsm::State, std::less<std::string> >
2445 trans = theStateMachine_.getTransitions(states[i]);
2446 std::set<std::string> actionNames = theStateMachine_.getInputs(states[i]);
2448 std::map<std::string, toolbox::fsm::State, std::less<std::string> >::iterator it =
2450 std::set<std::string>::iterator ait = actionNames.begin();
2458 for (; it != trans.end() && ait != actionNames.end(); ++it, ++ait)
2460 stateStr[0] = it->second;
2462 if (stateStr[0] ==
'R')
2465 xmlOut.addTextElementToParent(
"state_transition", stateStr, stateParent);
2469 xmlOut.addTextElementToParent(
"state_transition_action", *ait, stateParent);
2471 transName = theStateMachine_.getTransitionName(states[i], *ait);
2474 xmlOut.addTextElementToParent(
"state_transition_name",
2475 transName, stateParent);
2476 transParameter = theStateMachine_.getTransitionParameter(states[i], *ait);
2479 xmlOut.addTextElementToParent(
"state_transition_parameter", transParameter, stateParent);
2482 else if (stateStr[0] ==
'C')
2485 xmlOut.addTextElementToParent(
"state_transition", stateStr, stateParent);
2489 xmlOut.addTextElementToParent(
"state_transition_action", *ait, stateParent);
2491 transName = theStateMachine_.getTransitionName(states[i], *ait);
2494 xmlOut.addTextElementToParent(
"state_transition_name",
2495 transName, stateParent);
2496 transParameter = theStateMachine_.getTransitionParameter(states[i], *ait);
2499 xmlOut.addTextElementToParent(
"state_transition_parameter", transParameter, stateParent);
2506 ait = actionNames.begin();
2509 for (; it != trans.end() && ait != actionNames.end(); ++it, ++ait)
2513 stateStr[0] = it->second;
2515 if (stateStr[0] ==
'R')
2517 else if (stateStr[0] ==
'C')
2520 xmlOut.addTextElementToParent(
"state_transition", stateStr, stateParent);
2524 xmlOut.addTextElementToParent(
"state_transition_action", *ait, stateParent);
2526 transName = theStateMachine_.getTransitionName(states[i], *ait);
2529 xmlOut.addTextElementToParent(
"state_transition_name",
2530 transName, stateParent);
2531 transParameter = theStateMachine_.getTransitionParameter(states[i], *ait);
2534 xmlOut.addTextElementToParent(
"state_transition_parameter", transParameter, stateParent);
2539 else if (requestType ==
"getStateMachineNames")
2542 ConfigurationTree configLinkNode = CorePropertySupervisorBase::theConfigurationManager_->getSupervisorConfigurationNode(
2543 supervisorContextUID_, supervisorApplicationUID_);
2547 auto fsmNodes = configLinkNode.getNode(
2548 "LinkToStateMachineConfiguration").getChildren();
2549 for(
const auto& fsmNode:fsmNodes)
2550 xmlOut.addTextElementToData(
"stateMachineName", fsmNode.first);
2554 __SUP_COUT__ <<
"Caught exception, assuming no valid FSM names." << std::endl;
2555 xmlOut.addTextElementToData(
"stateMachineName",
"");
2558 else if (requestType ==
"getIterationPlanStatus")
2561 theIterator_.handleCommandRequest(xmlOut,requestType,
"");
2563 else if (requestType ==
"getCurrentState")
2565 xmlOut.addTextElementToData(
"current_state", theStateMachine_.getCurrentStateName());
2566 xmlOut.addTextElementToData(
"in_transition", theStateMachine_.isInTransition() ?
"1" :
"0");
2567 if (theStateMachine_.isInTransition())
2568 xmlOut.addTextElementToData(
"transition_progress", RunControlStateMachine::theProgressBar_.readPercentageString());
2570 xmlOut.addTextElementToData(
"transition_progress",
"100");
2574 sprintf(tmp,
"%lu",theStateMachine_.getTimeInState());
2575 xmlOut.addTextElementToData(
"time_in_state", tmp);
2584 std::string fsmName = CgiDataUtilities::getData(cgiIn,
"fsmName");
2592 if (!theStateMachine_.isInTransition())
2594 std::string stateMachineRunAlias =
"Run";
2597 ConfigurationTree configLinkNode = CorePropertySupervisorBase::theConfigurationManager_->getSupervisorConfigurationNode(
2598 supervisorContextUID_, supervisorApplicationUID_);
2600 if (!configLinkNode.isDisconnected())
2604 ConfigurationTree fsmLinkNode = configLinkNode.getNode(
"LinkToStateMachineConfiguration");
2605 if (!fsmLinkNode.isDisconnected())
2606 stateMachineRunAlias =
2607 fsmLinkNode.getNode(fsmName +
"/RunDisplayAlias").getValue<std::string>();
2611 catch (std::runtime_error &e)
2620 __SUP_COUT_ERR__ <<
"Unknown error. Should never happen." << std::endl;
2622 __SUP_COUT_INFO__ <<
"No state machine Run alias. Ignoring and assuming alias of '" <<
2623 stateMachineRunAlias <<
".'" << std::endl;
2631 xmlOut.addTextElementToData(
"stateMachineRunAlias", stateMachineRunAlias);
2637 if (theStateMachine_.getCurrentStateName() ==
"Running" ||
2638 theStateMachine_.getCurrentStateName() ==
"Paused")
2639 sprintf(tmp,
"Current %s Number: %u", stateMachineRunAlias.c_str(), getNextRunNumber(activeStateMachineName_) - 1);
2641 sprintf(tmp,
"Next %s Number: %u",stateMachineRunAlias.c_str(),getNextRunNumber(fsmName));
2642 xmlOut.addTextElementToData(
"run_number", tmp);
2645 else if(requestType ==
"getErrorInStateMatchine")
2647 xmlOut.addTextElementToData(
"FSM_Error", theStateMachine_.getErrorMessage());
2649 else if(requestType ==
"getDesktopIcons")
2658 std::vector<DesktopIconConfiguration::DesktopIcon> icons =
2659 iconConfiguration->getAllDesktopIcons();
2661 std::string iconString =
"";
2675 std::map<std::string,WebUsers::permissionLevel_t> userPermissionLevelsMap =
2676 theWebUsers_.getPermissionsForUser(userInfo.uid_);
2677 std::map<std::string,WebUsers::permissionLevel_t> iconPermissionThresholdsMap;
2680 bool firstIcon =
true;
2681 for(
const auto& icon: icons)
2683 __COUTV__(icon.caption_);
2684 __COUTV__(icon.permissionThresholdString_);
2686 CorePropertySupervisorBase::extractPermissionsMapFromString(
2687 icon.permissionThresholdString_,
2688 iconPermissionThresholdsMap);
2690 if(!CorePropertySupervisorBase::doPermissionsGrantAccess(
2691 userPermissionLevelsMap,
2692 iconPermissionThresholdsMap))
continue;
2697 if(firstIcon) firstIcon =
false;
2698 else iconString +=
",";
2700 iconString += icon.caption_;
2701 iconString +=
"," + icon.alternateText_;
2702 iconString +=
"," + std::string(icon.enforceOneWindowInstance_?
"1":
"0");
2703 iconString +=
"," + std::string(
"1");
2704 iconString +=
"," + icon.imageURL_;
2705 iconString +=
"," + icon.windowContentURL_;
2706 iconString +=
"," + icon.folderPath_;
2708 __COUTV__(iconString);
2710 xmlOut.addTextElementToData(
"iconList", iconString);
2712 else if(requestType ==
"gatewayLaunchOTS" || requestType ==
"gatewayLaunchWiz")
2716 __SUP_COUT_WARN__ << requestType <<
" requestType received! " << std::endl;
2717 __MOUT_WARN__ << requestType <<
" requestType received! " << std::endl;
2721 theWebUsers_.saveActiveSessions();
2725 if(requestType ==
"gatewayLaunchOTS")
2726 launchStartOTSCommand(
"LAUNCH_OTS");
2727 else if(requestType ==
"gatewayLaunchWiz")
2728 launchStartOTSCommand(
"LAUNCH_WIZ");
2781 else if(requestType ==
"resetUserTooltips")
2783 WebUsers::resetAllUserTooltips(theWebUsers_.getUsersUsername(userInfo.uid_));
2786 __SUP_COUT__ <<
"requestType Request, " << requestType <<
", not recognized." << std::endl;
2791 xmlOut.outputXmlDocument((std::ostringstream*) out,
false,
true);
2798 void GatewaySupervisor::launchStartOTSCommand(
const std::string& command)
2800 __SUP_COUT__ <<
"launch StartOTS Command = " << command << __E__;
2801 __SUP_COUT__ <<
"Extracting target context hostnames... " << std::endl;
2803 std::vector<std::string> hostnames;
2806 CorePropertySupervisorBase::theConfigurationManager_->init();
2810 auto contexts = contextConfiguration->getContexts();
2812 for (
const auto& context : contexts)
2814 if (!context.status_)
continue;
2818 for (i = 0; i < context.address_.size(); ++i)
2819 if (context.address_[i] ==
'/')
2821 hostnames.push_back(context.address_.substr(j));
2822 __SUP_COUT__ <<
"hostname = " << hostnames.back() << std::endl;
2827 __SUP_SS__ <<
"\nRelaunch of otsdaq interrupted! " <<
2828 "The Configuration Manager could not be initialized." << std::endl;
2833 for (
const auto& hostname : hostnames)
2835 std::string fn = (std::string(getenv(
"SERVICE_DATA_PATH")) +
2836 "/StartOTS_action_" + hostname +
".cmd");
2837 FILE* fp = fopen(fn.c_str(),
"w");
2840 fprintf(fp, command.c_str());
2845 __SUP_SS__ <<
"Unable to open command file: " << fn << std::endl;
2888 xoap::MessageReference GatewaySupervisor::supervisorCookieCheck(xoap::MessageReference message)
2895 parameters.addParameter(
"CookieCode");
2896 parameters.addParameter(
"RefreshOption");
2897 parameters.addParameter(
"IPAddress");
2898 receive(message, parameters);
2899 std::string cookieCode = parameters.getValue(
"CookieCode");
2900 std::string refreshOption = parameters.getValue(
"RefreshOption");
2901 std::string ipAddress = parameters.getValue(
"IPAddress");
2905 std::map<std::string ,WebUsers::permissionLevel_t> userGroupPermissionsMap;
2906 std::string userWithLock =
"";
2907 uint64_t activeSessionIndex, uid;
2908 theWebUsers_.cookieCodeIsActiveForRequest(
2910 &userGroupPermissionsMap,
2913 refreshOption ==
"1",
2915 &activeSessionIndex);
2921 retParameters.addParameter(
"CookieCode", cookieCode);
2922 retParameters.addParameter(
"Permissions", StringMacros::mapToString(userGroupPermissionsMap).c_str());
2923 retParameters.addParameter(
"UserWithLock", userWithLock);
2924 retParameters.addParameter(
"Username", theWebUsers_.getUsersUsername(uid));
2925 retParameters.addParameter(
"DisplayName", theWebUsers_.getUsersDisplayName(uid));
2926 sprintf(tmpStringForConversions_,
"%lu", activeSessionIndex);
2927 retParameters.addParameter(
"ActiveSessionIndex", tmpStringForConversions_);
2931 return SOAPUtilities::makeSOAPMessageReference(
"CookieResponse",
2938 xoap::MessageReference GatewaySupervisor::supervisorGetActiveUsers(
2939 xoap::MessageReference message)
2942 __SUP_COUT__ << std::endl;
2945 parameters(
"UserList", theWebUsers_.getActiveUsersString());
2946 return SOAPUtilities::makeSOAPMessageReference(
"ActiveUserResponse",
2954 xoap::MessageReference GatewaySupervisor::supervisorSystemMessage(
2955 xoap::MessageReference message)
2959 parameters.addParameter(
"ToUser");
2960 parameters.addParameter(
"Message");
2961 receive(message, parameters);
2963 __SUP_COUT__ <<
"toUser: " << parameters.getValue(
"ToUser").substr(
2964 0, 10) <<
", message: " << parameters.getValue(
"Message").substr(0,
2967 theSystemMessenger_.addSystemMessage(parameters.getValue(
"ToUser"),
2968 parameters.getValue(
"Message"));
2969 return SOAPUtilities::makeSOAPMessageReference(
"SystemMessageResponse");
2976 xoap::MessageReference GatewaySupervisor::supervisorSystemLogbookEntry(
2977 xoap::MessageReference message)
2981 parameters.addParameter(
"EntryText");
2982 receive(message, parameters);
2984 __SUP_COUT__ <<
"EntryText: " << parameters.getValue(
"EntryText").substr(
2985 0, 10) << std::endl;
2987 makeSystemLogbookEntry(parameters.getValue(
"EntryText"));
2989 return SOAPUtilities::makeSOAPMessageReference(
"SystemLogbookResponse");
2997 xoap::MessageReference GatewaySupervisor::supervisorLastConfigGroupRequest(
2998 xoap::MessageReference message)
3002 parameters.addParameter(
"ActionOfLastGroup");
3003 receive(message, parameters);
3005 return GatewaySupervisor::lastConfigGroupRequestHandler(parameters);
3014 xoap::MessageReference GatewaySupervisor::lastConfigGroupRequestHandler(
3017 std::string action = parameters.getValue(
"ActionOfLastGroup");
3018 __COUT__ <<
"ActionOfLastGroup: " << action.substr(
3019 0, 10) << std::endl;
3021 std::string fileName =
"";
3022 if (action ==
"Configured")
3023 fileName = FSM_LAST_CONFIGURED_GROUP_ALIAS_FILE;
3024 else if (action ==
"Started")
3025 fileName = FSM_LAST_STARTED_GROUP_ALIAS_FILE;
3028 __COUT_ERR__ <<
"Invalid last group action requested." << std::endl;
3029 return SOAPUtilities::makeSOAPMessageReference(
"LastConfigGroupResponseFailure");
3031 std::string timeString;
3033 loadGroupNameAndKey(fileName, timeString);
3037 retParameters.addParameter(
"GroupName", theGroup.first);
3038 retParameters.addParameter(
"GroupKey", theGroup.second.toString());
3039 retParameters.addParameter(
"GroupAction", action);
3040 retParameters.addParameter(
"GroupActionTime", timeString);
3043 return SOAPUtilities::makeSOAPMessageReference(
"LastConfigGroupResponse",
3054 unsigned int GatewaySupervisor::getNextRunNumber(
const std::string &fsmNameIn)
3056 std::string runNumberFileName = RUN_NUMBER_PATH +
"/";
3057 std::string fsmName = fsmNameIn ==
"" ? activeStateMachineName_ : fsmNameIn;
3059 for (
unsigned int i = 0; i < fsmName.size(); ++i)
3060 if ((fsmName[i] >=
'a' && fsmName[i] <=
'z') ||
3061 (fsmName[i] >=
'A' && fsmName[i] <=
'Z') ||
3062 (fsmName[i] >=
'0' && fsmName[i] <=
'9'))
3063 runNumberFileName += fsmName[i];
3064 runNumberFileName += RUN_NUMBER_FILE_NAME;
3067 std::ifstream runNumberFile(runNumberFileName.c_str());
3068 if (!runNumberFile.is_open())
3070 __SUP_COUT__ <<
"Can't open file: " << runNumberFileName << std::endl;
3072 __SUP_COUT__ <<
"Creating file and setting Run Number to 1: " << runNumberFileName << std::endl;
3073 FILE *fp = fopen(runNumberFileName.c_str(),
"w");
3077 runNumberFile.open(runNumberFileName.c_str());
3078 if (!runNumberFile.is_open())
3080 __SUP_SS__ <<
"Error. Can't create file: " << runNumberFileName << std::endl;
3081 __SUP_COUT_ERR__ << ss.str();
3082 throw std::runtime_error(ss.str());
3085 std::string runNumberString;
3086 runNumberFile >> runNumberString;
3087 runNumberFile.close();
3088 return atoi(runNumberString.c_str());
3092 bool GatewaySupervisor::setNextRunNumber(
unsigned int runNumber,
const std::string &fsmNameIn)
3094 std::string runNumberFileName = RUN_NUMBER_PATH +
"/";
3095 std::string fsmName = fsmNameIn ==
"" ? activeStateMachineName_ : fsmNameIn;
3097 for (
unsigned int i = 0; i < fsmName.size(); ++i)
3098 if ((fsmName[i] >=
'a' && fsmName[i] <=
'z') ||
3099 (fsmName[i] >=
'A' && fsmName[i] <=
'Z') ||
3100 (fsmName[i] >=
'0' && fsmName[i] <=
'9'))
3101 runNumberFileName += fsmName[i];
3102 runNumberFileName += RUN_NUMBER_FILE_NAME;
3103 __SUP_COUT__ <<
"runNumberFileName: " << runNumberFileName << std::endl;
3105 std::ofstream runNumberFile(runNumberFileName.c_str());
3106 if (!runNumberFile.is_open())
3108 __SUP_SS__ <<
"Can't open file: " << runNumberFileName << std::endl;
3109 __SUP_COUT__ << ss.str();
3110 throw std::runtime_error(ss.str());
3112 std::stringstream runNumberStream;
3113 runNumberStream << runNumber;
3114 runNumberFile << runNumberStream.str().c_str();
3115 runNumberFile.close();
3125 std::pair<std::string ,
3127 std::string &returnedTimeString)
3129 std::string fullPath = FSM_LAST_GROUP_ALIAS_PATH +
"/" + fileName;
3131 FILE *groupFile = fopen(fullPath.c_str(),
"r");
3134 __COUT__ <<
"Can't open file: " << fullPath << std::endl;
3136 __COUT__ <<
"Returning empty groupName and key -1" << std::endl;
3138 return std::pair<std::string ,
3144 std::pair<std::string ,
3147 fgets(line, 500, groupFile);
3148 theGroup.first = line;
3150 fgets(line, 500, groupFile);
3152 sscanf(line,
"%d", &key);
3153 theGroup.second = key;
3155 fgets(line, 500, groupFile);
3157 sscanf(line,
"%ld", ×tamp);
3159 ::localtime_r(×tamp, &tmstruct);
3160 ::strftime(line, 30,
"%c %Z", &tmstruct);
3161 returnedTimeString = line;
3165 __COUT__ <<
"theGroup.first= " << theGroup.first <<
3166 " theGroup.second= " << theGroup.second << std::endl;
3172 void GatewaySupervisor::saveGroupNameAndKey(
const std::pair<std::string ,
3174 const std::string &fileName)
3176 std::string fullPath = FSM_LAST_GROUP_ALIAS_PATH +
"/" + fileName;
3178 std::ofstream groupFile(fullPath.c_str());
3179 if (!groupFile.is_open())
3181 __SUP_SS__ <<
"Error. Can't open file: " << fullPath << std::endl;
3182 __SUP_COUT_ERR__ <<
"\n" << ss.str();
3183 throw std::runtime_error(ss.str());
3185 std::stringstream outss;
3186 outss << theGroup.first <<
"\n" << theGroup.second <<
"\n" << time(0);
3187 groupFile << outss.str().c_str();