1 #include "otsdaq/GatewaySupervisor/GatewaySupervisor.h"
2 #include "otsdaq/CgiDataUtilities/CgiDataUtilities.h"
3 #include "otsdaq/Macros/CoutMacros.h"
4 #include "otsdaq/MessageFacility/MessageFacility.h"
5 #include "otsdaq/SOAPUtilities/SOAPCommand.h"
6 #include "otsdaq/SOAPUtilities/SOAPUtilities.h"
7 #include "otsdaq/XmlUtilities/HttpXmlDocument.h"
9 #include "otsdaq/ConfigurationInterface/ConfigurationManager.h"
10 #include "otsdaq/ConfigurationInterface/ConfigurationManagerRW.h"
11 #include "otsdaq/TablePlugins/DesktopIconTable.h"
12 #include "otsdaq/TablePlugins/XDAQContextTable.h"
13 #include "otsdaq/WorkLoopManager/WorkLoopManager.h"
15 #include "otsdaq/NetworkUtilities/TransceiverSocket.h"
17 #include <cgicc/HTMLClasses.h>
18 #include <cgicc/HTMLDoctype.h>
19 #include <cgicc/HTTPCookie.h>
20 #include <cgicc/HTTPHeader.h>
21 #include <xgi/Utils.h>
23 #include <toolbox/fsm/FailedEvent.h>
24 #include <toolbox/task/WorkLoopFactory.h>
25 #include <xdaq/NamespaceURI.h>
26 #include <xoap/Method.h>
35 #define RUN_NUMBER_PATH std::string(__ENV__("SERVICE_DATA_PATH")) + "/RunNumber/"
36 #define RUN_NUMBER_FILE_NAME "NextRunNumber.txt"
37 #define FSM_LAST_GROUP_ALIAS_PATH \
38 std::string(__ENV__("SERVICE_DATA_PATH")) + "/RunControlData/"
39 #define FSM_LAST_GROUP_ALIAS_FILE_START std::string("FSMLastGroupAlias-")
40 #define FSM_USERS_PREFERENCES_FILETYPE "pref"
43 #define __MF_SUBJECT__ "GatewaySupervisor"
49 : xdaq::Application(s)
53 , stateMachineWorkLoopManager_(toolbox::task::bind(
54 this, &GatewaySupervisor::stateMachineThread, "StateMachine"))
55 , stateMachineSemaphore_(toolbox::BSem::FULL)
56 , infoRequestWorkLoopManager_(
57 toolbox::task::bind(this, &GatewaySupervisor::infoRequestThread, "InfoRequest"))
58 , infoRequestSemaphore_(toolbox::BSem::FULL)
59 , activeStateMachineName_("")
61 , broadcastCommandMessageIndex_(0)
62 , broadcastIterationBreakpoint_(
66 INIT_MF(
"GatewaySupervisor");
70 mkdir((std::string(__ENV__(
"SERVICE_DATA_PATH"))).c_str(), 0755);
71 mkdir((FSM_LAST_GROUP_ALIAS_PATH).c_str(), 0755);
72 mkdir((RUN_NUMBER_PATH).c_str(), 0755);
74 securityType_ = theWebUsers_.getSecurity();
76 __COUT__ <<
"Security: " << securityType_ << __E__;
78 xgi::bind(
this, &GatewaySupervisor::Default,
"Default");
79 xgi::bind(
this, &GatewaySupervisor::loginRequest,
"LoginRequest");
80 xgi::bind(
this, &GatewaySupervisor::request,
"Request");
81 xgi::bind(
this, &GatewaySupervisor::stateMachineXgiHandler,
"StateMachineXgiHandler");
83 &GatewaySupervisor::stateMachineIterationBreakpoint,
84 "StateMachineIterationBreakpoint");
86 xgi::bind(
this, &GatewaySupervisor::statusRequest,
"StatusRequest");
87 xgi::bind(
this, &GatewaySupervisor::tooltipRequest,
"TooltipRequest");
90 &GatewaySupervisor::supervisorCookieCheck,
91 "SupervisorCookieCheck",
94 &GatewaySupervisor::supervisorGetActiveUsers,
95 "SupervisorGetActiveUsers",
98 &GatewaySupervisor::supervisorSystemMessage,
99 "SupervisorSystemMessage",
102 &GatewaySupervisor::supervisorSystemLogbookEntry,
103 "SupervisorSystemLogbookEntry",
106 &GatewaySupervisor::supervisorLastConfigGroupRequest,
107 "SupervisorLastConfigGroupRequest",
119 GatewaySupervisor::~GatewaySupervisor(
void)
121 delete CorePropertySupervisorBase::theConfigurationManager_;
122 makeSystemLogbookEntry(
"ots halted.");
128 CorePropertySupervisorBase::indicateOtsAlive(properties);
132 void GatewaySupervisor::init(
void)
134 supervisorGuiHasBeenLoaded_ =
false;
166 bool enableStateChanges =
false;
169 enableStateChanges = CorePropertySupervisorBase::getSupervisorTableNode()
170 .getNode(
"EnableStateChangesOverUDP")
178 if(enableStateChanges)
180 __COUT__ <<
"Enabling state changes over UDP..." << __E__;
183 [](GatewaySupervisor* s) { GatewaySupervisor::StateChangerWorkLoop(s); },
188 __COUT__ <<
"State changes over UDP are disabled." << __E__;
193 bool checkAppStatus =
false;
196 checkAppStatus = CorePropertySupervisorBase::getSupervisorTableNode()
197 .getNode(
"EnableApplicationStatusMonitoring")
207 __COUT__ <<
"Enabling App Status checking..." << __E__;
210 [](GatewaySupervisor* s) { GatewaySupervisor::AppStatusWorkLoop(s); },
215 __COUT__ <<
"App Status checking is disabled." << __E__;
247 void GatewaySupervisor::AppStatusWorkLoop(GatewaySupervisor* theSupervisor)
250 std::string status, progress, appName;
258 for(
const auto& it : theSupervisor->allSupervisorInfo_.getAllSupervisorInfo())
260 auto appInfo = it.second;
261 appName = appInfo.getName();
269 if(appName ==
"Supervisor")
272 status = theSupervisor->theStateMachine_.getCurrentStateName();
273 progress = theSupervisor->theProgressBar_.readPercentageString();
275 if(theSupervisor->theStateMachine_.isInTransition())
278 status = theSupervisor->theStateMachine_.getProvenanceStateName();
282 status = theSupervisor->theStateMachine_.getCurrentStateName();
289 appPointer.addParameter(
"ApplicationPointer");
291 xoap::MessageReference tempMessage =
292 SOAPUtilities::makeSOAPMessageReference(
"ApplicationStatusRequest");
300 xoap::MessageReference statusMessage =
301 theSupervisor->sendWithSOAPReply(appInfo.getDescriptor(),
310 parameters.addParameter(
"Status");
311 parameters.addParameter(
"Progress");
312 SOAPUtilities::receive(statusMessage, parameters);
314 status = parameters.getValue(
"Status");
320 progress = parameters.getValue(
"Progress");
328 catch(
const xdaq::exception::Exception& e)
330 __COUT__ <<
"Failed to send SOAP Message... " << std::endl;
337 theSupervisor->allSupervisorInfo_.setSupervisorStatus(appInfo, status);
340 std::istringstream ssProgress(progress);
341 ssProgress >> progressInteger;
342 theSupervisor->allSupervisorInfo_.setSupervisorProgress(appInfo,
354 void GatewaySupervisor::StateChangerWorkLoop(GatewaySupervisor* theSupervisor)
357 theSupervisor->CorePropertySupervisorBase::getSupervisorTableNode();
359 std::string ipAddressForStateChangesOverUDP =
360 configLinkNode.getNode(
"IPAddressForStateChangesOverUDP").getValue<std::string>();
361 int portForStateChangesOverUDP =
362 configLinkNode.getNode(
"PortForStateChangesOverUDP").getValue<
int>();
363 bool acknowledgementEnabled =
364 configLinkNode.getNode(
"EnableAckForStateChangesOverUDP").getValue<
bool>();
373 portForStateChangesOverUDP);
381 __SS__ <<
"FATAL Console error. Could not initialize socket at ip '"
382 << ipAddressForStateChangesOverUDP <<
"' and port "
383 << portForStateChangesOverUDP
384 <<
". Perhaps it is already in use? Exiting State Changer "
385 "SOAPUtilities::receive loop."
387 __COUT__ << ss.str();
392 std::size_t commaPosition;
393 unsigned int commaCounter = 0;
394 std::size_t begin = 0;
396 std::string errorStr;
399 std::vector<std::string> parameters;
409 buffer, 0 , 1 ,
false ) !=
412 __COUT__ <<
"UDP State Changer packet received of size = " << buffer.size()
415 size_t nCommas = std::count(buffer.begin(), buffer.end(),
',');
418 __SS__ <<
"Unrecognized State Machine command :-" << buffer
419 <<
"-. Format is FiniteStateMachineName,Command,Parameter(s). "
420 "Where Parameter(s) is/are optional."
422 __COUT_INFO__ << ss.str();
423 __MOUT_INFO__ << ss.str();
428 while((commaPosition = buffer.find(
',', begin)) != std::string::npos ||
429 commaCounter == nCommas)
431 if(commaCounter == nCommas)
432 commaPosition = buffer.size();
433 if(commaCounter == 0)
434 fsmName = buffer.substr(begin, commaPosition - begin);
435 else if(commaCounter == 1)
436 command = buffer.substr(begin, commaPosition - begin);
438 parameters.push_back(buffer.substr(begin, commaPosition - begin));
439 __COUT__ <<
"Word: " << buffer.substr(begin, commaPosition - begin)
442 begin = commaPosition + 1;
452 if(theSupervisor->VERBOSE_MUTEX)
453 __COUT__ <<
"Waiting for FSM access" << __E__;
454 std::lock_guard<std::mutex> lock(theSupervisor->stateMachineAccessMutex_);
455 if(theSupervisor->VERBOSE_MUTEX)
456 __COUT__ <<
"Have FSM access" << __E__;
458 errorStr = theSupervisor->attemptStateMachineTransition(
463 WebUsers::DEFAULT_STATECHANGER_USERNAME ,
464 WebUsers::DEFAULT_STATECHANGER_USERNAME,
470 __SS__ <<
"UDP State Changer failed to execute command because of the "
473 __COUT_ERR__ << ss.str();
474 __MOUT_ERR__ << ss.str();
475 if(acknowledgementEnabled)
476 sock.acknowledge(errorStr,
true );
480 __SS__ <<
"Successfully executed state change command '" << command
482 __COUT_INFO__ << ss.str();
483 __MOUT_INFO__ << ss.str();
484 if(acknowledgementEnabled)
485 sock.acknowledge(
"Done",
true );
499 void GatewaySupervisor::makeSystemLogbookEntry(std::string entryText)
501 __COUT__ <<
"Making System Logbook Entry: " << entryText << __E__;
503 SupervisorInfoMap logbookInfoMap =
504 allSupervisorInfo_.getAllLogbookTypeSupervisorInfo();
506 if(logbookInfoMap.size() == 0)
508 __COUT__ <<
"No logbooks found! Here is entry: " << entryText << __E__;
509 __MOUT__ <<
"No logbooks found! Here is entry: " << entryText << __E__;
514 __COUT__ <<
"Making logbook entry: " << entryText << __E__;
515 __MOUT__ <<
"Making logbook entry: " << entryText << __E__;
520 std::string replace[] = {
"\"",
"'",
"&",
"<",
">",
"\n",
" "};
521 std::string with[] = {
"%22",
"%27",
"%26",
"%3C",
"%3E",
"%0A%0D",
"%20%20"};
526 for(
int i = 0; i < numOfKeys; ++i)
528 while((f = entryText.find(replace[i])) != std::string::npos)
530 entryText = entryText.substr(0, f) + with[i] +
531 entryText.substr(f + replace[i].length());
542 for(
auto& logbookInfo : logbookInfoMap)
544 xoap::MessageReference retMsg = SOAPMessenger::sendWithSOAPReply(
545 logbookInfo.second.getDescriptor(),
"MakeSystemLogbookEntry", parameters);
550 SOAPUtilities::receive(retMsg, retParameters);
552 __COUT__ <<
"Returned Status: " << retParameters.getValue(
"Status")
558 void GatewaySupervisor::Default(xgi::Input* in, xgi::Output* out)
562 if(!supervisorGuiHasBeenLoaded_ &&
563 (supervisorGuiHasBeenLoaded_ =
565 makeSystemLogbookEntry(
"ots started.");
567 *out <<
"<!DOCTYPE HTML><html lang='en'><head><title>ots</title>" <<
570 "<link rel='apple-touch-icon' sizes='57x57' href='/WebPath/images/otsdaqIcons/apple-icon-57x57.png'>\
571 <link rel='apple-touch-icon' sizes='60x60' href='/WebPath/images/otsdaqIcons/apple-icon-60x60.png'>\
572 <link rel='apple-touch-icon' sizes='72x72' href='/WebPath/images/otsdaqIcons/apple-icon-72x72.png'>\
573 <link rel='apple-touch-icon' sizes='76x76' href='/WebPath/images/otsdaqIcons/apple-icon-76x76.png'>\
574 <link rel='apple-touch-icon' sizes='114x114' href='/WebPath/images/otsdaqIcons/apple-icon-114x114.png'>\
575 <link rel='apple-touch-icon' sizes='120x120' href='/WebPath/images/otsdaqIcons/apple-icon-120x120.png'>\
576 <link rel='apple-touch-icon' sizes='144x144' href='/WebPath/images/otsdaqIcons/apple-icon-144x144.png'>\
577 <link rel='apple-touch-icon' sizes='152x152' href='/WebPath/images/otsdaqIcons/apple-icon-152x152.png'>\
578 <link rel='apple-touch-icon' sizes='180x180' href='/WebPath/images/otsdaqIcons/apple-icon-180x180.png'>\
579 <link rel='icon' type='image/png' sizes='192x192' href='/WebPath/images/otsdaqIcons/android-icon-192x192.png'>\
580 <link rel='icon' type='image/png' sizes='32x32' href='/WebPath/images/otsdaqIcons/favicon-32x32.png'>\
581 <link rel='icon' type='image/png' sizes='96x96' href='/WebPath/images/otsdaqIcons/favicon-96x96.png'>\
582 <link rel='icon' type='image/png' sizes='16x16' href='/WebPath/images/otsdaqIcons/favicon-16x16.png'>\
583 <link rel='manifest' href='/WebPath/images/otsdaqIcons/manifest.json'>\
584 <meta name='msapplication-TileColor' content='#ffffff'>\
585 <meta name='msapplication-TileImage' content='/ms-icon-144x144.png'>\
586 <meta name='theme-color' content='#ffffff'>"
590 <<
"<frameset col='100%' row='100%'>"
591 <<
"<frame src='/WebPath/html/Desktop.html?urn="
592 << this->getApplicationDescriptor()->getLocalId()
593 <<
"&securityType=" << securityType_ <<
"'></frameset></html>";
600 void GatewaySupervisor::stateMachineIterationBreakpoint(xgi::Input* in,
601 xgi::Output* out)
try
603 cgicc::Cgicc cgiIn(in);
605 std::string requestType = CgiDataUtilities::getData(cgiIn,
"Request");
609 CgiDataUtilities::postData(cgiIn,
"CookieCode"));
611 CorePropertySupervisorBase::getRequestUserInfo(userInfo);
613 if(!theWebUsers_.xmlRequestOnGateway(cgiIn, out, &xmlOut, userInfo))
616 __COUTV__(requestType);
620 if(requestType ==
"get")
624 std::lock_guard<std::mutex> lock(broadcastIterationBreakpointMutex_);
625 v << broadcastIterationBreakpoint_;
628 xmlOut.addTextElementToData(
"iterationBreakpoint", v.str());
630 else if(requestType ==
"set")
632 unsigned int breakpointSetValue =
633 CgiDataUtilities::getDataAsInt(cgiIn,
"breakpointSetValue");
634 __COUTV__(breakpointSetValue);
637 std::lock_guard<std::mutex> lock(broadcastIterationBreakpointMutex_);
638 broadcastIterationBreakpoint_ = breakpointSetValue;
643 v << breakpointSetValue;
644 xmlOut.addTextElementToData(
"iterationBreakpoint", v.str());
648 __SS__ <<
"Unknown iteration breakpoint request type = " << requestType
653 catch(
const std::runtime_error& e)
655 __SS__ <<
"Error caught handling iteration breakpoint command: " << e.what()
657 __COUT_ERR__ << ss.str();
658 xmlOut.addTextElementToData(
"Error", ss.str());
662 __SS__ <<
"Unknown error caught handling iteration breakpoint command." << __E__;
663 __COUT_ERR__ << ss.str();
664 xmlOut.addTextElementToData(
"Error", ss.str());
667 xmlOut.outputXmlDocument((std::ostringstream*)out,
false,
true);
670 catch(
const std::runtime_error& e)
672 __SS__ <<
"Error caught handling iteration breakpoint command: " << e.what() << __E__;
673 __COUT_ERR__ << ss.str();
677 __SS__ <<
"Unknown error caught handling iteration breakpoint command." << __E__;
678 __COUT_ERR__ << ss.str();
682 void GatewaySupervisor::stateMachineXgiHandler(xgi::Input* in, xgi::Output* out)
688 __COUT__ <<
"Waiting for FSM access" << __E__;
689 std::lock_guard<std::mutex> lock(stateMachineAccessMutex_);
691 __COUT__ <<
"Have FSM access" << __E__;
693 cgicc::Cgicc cgiIn(in);
695 std::string command = CgiDataUtilities::getData(cgiIn,
"StateMachine");
696 std::string requestType =
697 "StateMachine" + command;
701 CgiDataUtilities::postData(cgiIn,
"CookieCode"));
703 CorePropertySupervisorBase::getRequestUserInfo(userInfo);
705 if(!theWebUsers_.xmlRequestOnGateway(cgiIn, out, &xmlOut, userInfo))
708 std::string fsmName = CgiDataUtilities::getData(cgiIn,
"fsmName");
709 std::string fsmWindowName = CgiDataUtilities::getData(cgiIn,
"fsmWindowName");
710 fsmWindowName = StringMacros::decodeURIComponent(fsmWindowName);
711 std::string currentState = theStateMachine_.getCurrentStateName();
713 __COUT__ <<
"Check for Handled by theIterator_" << __E__;
716 if((activeStateMachineWindowName_ ==
"" ||
717 activeStateMachineWindowName_ ==
"iterator") &&
718 theIterator_.handleCommandRequest(xmlOut, command, fsmWindowName))
720 __COUT__ <<
"Handled by theIterator_" << __E__;
721 xmlOut.outputXmlDocument((std::ostringstream*)out,
false);
726 if(theStateMachine_.isInTransition())
728 __SS__ <<
"Error - Can not accept request because the State Machine is already "
731 __COUT_ERR__ <<
"\n" << ss.str();
733 xmlOut.addTextElementToData(
"state_tranisition_attempted",
735 xmlOut.addTextElementToData(
736 "state_tranisition_attempted_err",
738 xmlOut.outputXmlDocument((std::ostringstream*)out,
false,
true);
748 if(activeStateMachineName_ !=
"" && activeStateMachineName_ != fsmName)
750 __COUT__ <<
"currentState = " << currentState << __E__;
751 if(currentState !=
"Halted" && currentState !=
"Initial")
755 __SS__ <<
"Error - Can not accept request because the State Machine "
756 <<
"with window name '" << activeStateMachineWindowName_
757 <<
"' (UID: " << activeStateMachineName_
760 <<
"in control of State Machine progress. ";
761 ss <<
"\n\nIn order for this State Machine with window name '"
762 << fsmWindowName <<
"' (UID: " << fsmName
764 "to control progress, please transition to Halted using the active "
765 <<
"State Machine '" << activeStateMachineWindowName_ <<
".'" << __E__;
766 __COUT_ERR__ <<
"\n" << ss.str();
768 xmlOut.addTextElementToData(
"state_tranisition_attempted",
770 xmlOut.addTextElementToData(
771 "state_tranisition_attempted_err",
773 xmlOut.outputXmlDocument((std::ostringstream*)out,
false,
true);
778 activeStateMachineName_ =
"";
779 activeStateMachineWindowName_ =
"";
785 std::vector<std::string> parameters;
787 if(command ==
"Configure")
788 parameters.push_back(CgiDataUtilities::postData(cgiIn,
"ConfigurationAlias"));
790 attemptStateMachineTransition(
791 &xmlOut, out, command, fsmName, fsmWindowName, userInfo.username_, parameters);
796 std::string GatewaySupervisor::attemptStateMachineTransition(
798 std::ostringstream* out,
799 const std::string& command,
800 const std::string& fsmName,
801 const std::string& fsmWindowName,
802 const std::string& username,
803 const std::vector<std::string>& commandParameters)
805 std::string errorStr =
"";
807 std::string currentState = theStateMachine_.getCurrentStateName();
808 __COUT__ <<
"State Machine command = " << command << __E__;
809 __COUT__ <<
"fsmName = " << fsmName << __E__;
810 __COUT__ <<
"fsmWindowName = " << fsmWindowName << __E__;
811 __COUT__ <<
"activeStateMachineName_ = " << activeStateMachineName_ << __E__;
812 __COUT__ <<
"command = " << command << __E__;
813 __COUT__ <<
"commandParameters.size = " << commandParameters.size() << __E__;
816 if(command ==
"Configure")
818 if(currentState !=
"Halted")
820 __SS__ <<
"Error - Can only transition to Configured if the current "
821 <<
"state is Halted. Perhaps your state machine is out of sync."
823 __COUT_ERR__ <<
"\n" << ss.str();
827 xmldoc->addTextElementToData(
828 "state_tranisition_attempted",
831 xmldoc->addTextElementToData(
832 "state_tranisition_attempted_err",
835 xmldoc->outputXmlDocument((std::ostringstream*)out,
844 if(commandParameters.size() == 0)
846 __SS__ <<
"Error - Can only transition to Configured if a Configuration "
847 "Alias parameter is provided."
849 __COUT_ERR__ <<
"\n" << ss.str();
853 xmldoc->addTextElementToData(
854 "state_tranisition_attempted",
857 xmldoc->addTextElementToData(
858 "state_tranisition_attempted_err",
861 xmldoc->outputXmlDocument((std::ostringstream*)out,
868 parameters.addParameter(
"ConfigurationAlias", commandParameters[0]);
870 std::string configurationAlias = parameters.getValue(
"ConfigurationAlias");
871 __COUT__ <<
"Configure --> Name: ConfigurationAlias Value: " << configurationAlias
875 std::string fn = FSM_LAST_GROUP_ALIAS_PATH + FSM_LAST_GROUP_ALIAS_FILE_START +
876 username +
"." + FSM_USERS_PREFERENCES_FILETYPE;
878 __COUT__ <<
"Save FSM preferences: " << fn << __E__;
879 FILE* fp = fopen(fn.c_str(),
"w");
882 __SS__ << (
"Could not open file: " + fn) << __E__;
883 __COUT_ERR__ << ss.str();
886 fprintf(fp,
"FSM_last_configuration_alias %s", configurationAlias.c_str());
889 activeStateMachineName_ = fsmName;
890 activeStateMachineWindowName_ = fsmWindowName;
892 else if(command ==
"Start")
894 if(currentState !=
"Configured")
897 <<
"Error - Can only transition to Configured if the current "
898 <<
"state is Halted. Perhaps your state machine is out of sync. "
899 <<
"(Likely the server was restarted or another user changed the state)"
901 __COUT_ERR__ <<
"\n" << ss.str();
905 xmldoc->addTextElementToData(
906 "state_tranisition_attempted",
909 xmldoc->addTextElementToData(
910 "state_tranisition_attempted_err",
913 xmldoc->outputXmlDocument((std::ostringstream*)out,
919 unsigned int runNumber;
920 if(commandParameters.size() == 0)
922 runNumber = getNextRunNumber();
923 setNextRunNumber(runNumber + 1);
927 runNumber = std::atoi(commandParameters[0].c_str());
929 parameters.addParameter(
"RunNumber", runNumber);
932 xoap::MessageReference message =
933 SOAPUtilities::makeSOAPMessageReference(command, parameters);
935 xoap::MessageReference reply = stateMachineXoapHandler(message);
940 xmldoc->addTextElementToData(
"state_tranisition_attempted",
943 xmldoc->outputXmlDocument((std::ostringstream*)out,
false);
944 __COUT__ <<
"FSM state transition launched!" << __E__;
946 stateMachineLastCommandInput_ = command;
1003 xoap::MessageReference GatewaySupervisor::stateMachineXoapHandler(
1004 xoap::MessageReference message)
1007 __COUT__ <<
"Soap Handler!" << __E__;
1008 stateMachineWorkLoopManager_.removeProcessedRequests();
1009 stateMachineWorkLoopManager_.processRequest(message);
1010 __COUT__ <<
"Done - Soap Handler!" << __E__;
1032 bool GatewaySupervisor::stateMachineThread(toolbox::task::WorkLoop* workLoop)
1034 stateMachineSemaphore_.take();
1035 std::string command =
1036 SOAPUtilities::translate(stateMachineWorkLoopManager_.getMessage(workLoop))
1039 __COUT__ <<
"Propagating command '" << command <<
"'..." << __E__;
1041 std::string reply = send(allSupervisorInfo_.getGatewayDescriptor(),
1042 stateMachineWorkLoopManager_.getMessage(workLoop));
1043 stateMachineWorkLoopManager_.report(workLoop, reply, 100,
true);
1045 __COUT__ <<
"Done with command '" << command <<
".' Reply = " << reply << __E__;
1046 stateMachineSemaphore_.give();
1048 if(reply ==
"Fault")
1050 __SS__ <<
"Failure to send Workloop transition command '" << command
1051 <<
"!' An error response '" << reply <<
"' was received." << __E__;
1052 __COUT_ERR__ << ss.str();
1053 __MOUT_ERR__ << ss.str();
1066 void GatewaySupervisor::statusRequest(xgi::Input* in, xgi::Output* out)
1069 __COUT__ <<
"Starting to Request!" << __E__;
1071 cgicc::Cgicc cgiIn(in);
1072 std::string requestType =
"statusRequest";
1076 CgiDataUtilities::postData(cgiIn,
"CookieCode"));
1078 CorePropertySupervisorBase::getRequestUserInfo(userInfo);
1080 if(!theWebUsers_.xmlRequestOnGateway(cgiIn, out, &xmlOut, userInfo))
1083 __COUT__ <<
"Starting to Request!" << __E__;
1094 xmlOut.outputXmlDocument((std::ostringstream*)out,
false);
1098 void GatewaySupervisor::infoRequestResultHandler(xgi::Input* in, xgi::Output* out)
1101 __COUT__ <<
"Starting ask!" << __E__;
1102 cgicc::Cgicc cgi(in);
1104 cgicc::Cgicc cgiIn(in);
1105 std::string requestType =
1106 "infoRequestResultHandler";
1110 CgiDataUtilities::postData(cgiIn,
"CookieCode"));
1112 CorePropertySupervisorBase::getRequestUserInfo(userInfo);
1114 if(!theWebUsers_.xmlRequestOnGateway(cgiIn, out, &xmlOut, userInfo))
1132 infoRequestWorkLoopManager_.getRequestResult(cgiIn, xmlOut);
1135 xmlOut.outputXmlDocument((std::ostringstream*)out,
false);
1137 __COUT__ <<
"Done asking!" << __E__;
1141 bool GatewaySupervisor::infoRequestThread(toolbox::task::WorkLoop* workLoop)
1146 infoRequestSemaphore_.take();
1148 vectorTest_.clear();
1150 for(
unsigned long long i = 0; i < 100000000; i++)
1153 vectorTest_.push_back(counterTest_);
1156 infoRequestWorkLoopManager_.report(
1157 workLoop,
"RESULT: This is the best result ever", 50,
false);
1158 std::string workLoopName = workLoop->getName();
1159 __COUT__ << workLoopName <<
" test: " << counterTest_
1160 <<
" vector size: " << vectorTest_.size() << __E__;
1161 wait(400,
"InfoRequestThread ----- locked");
1162 infoRequestSemaphore_.give();
1164 wait(200,
"InfoRequestThread");
1166 infoRequestSemaphore_.take();
1168 vectorTest_.clear();
1170 for(
unsigned long long i = 0; i < 100000000; i++)
1173 vectorTest_.push_back(counterTest_);
1176 wait(400,
"InfoRequestThread ----- locked");
1177 __COUT__ << workLoopName <<
" test: " << counterTest_
1178 <<
" vector size: " << vectorTest_.size() << __E__;
1179 infoRequestSemaphore_.give();
1183 infoRequestWorkLoopManager_.report(
1184 workLoop, theStateMachine_.getCurrentStateName(), 100,
true);
1193 void GatewaySupervisor::stateInitial(toolbox::fsm::FiniteStateMachine& fsm)
1196 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1204 void GatewaySupervisor::statePaused(toolbox::fsm::FiniteStateMachine& fsm)
1207 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1226 void GatewaySupervisor::stateRunning(toolbox::fsm::FiniteStateMachine& fsm)
1229 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1248 void GatewaySupervisor::stateHalted(toolbox::fsm::FiniteStateMachine& fsm)
1251 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1252 __COUT__ <<
"Fsm is in transition? "
1253 << (theStateMachine_.isInTransition() ?
"yes" :
"no") << __E__;
1282 void GatewaySupervisor::stateConfigured(toolbox::fsm::FiniteStateMachine& fsm)
1356 void GatewaySupervisor::inError(toolbox::fsm::FiniteStateMachine& fsm)
1360 <<
"Fsm current state: "
1369 void GatewaySupervisor::enteringError(toolbox::Event::Reference e)
1371 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1374 toolbox::fsm::FailedEvent& failedEvent =
dynamic_cast<toolbox::fsm::FailedEvent&
>(*e);
1379 if(RunControlStateMachine::asyncFailureReceived_)
1381 ss <<
"\nAn asynchronous failure was encountered."
1382 <<
".\n\nException:\n"
1383 << failedEvent.getException().what() << __E__;
1384 RunControlStateMachine::asyncFailureReceived_ =
false;
1388 ss <<
"\nFailure performing transition from " << failedEvent.getFromState() <<
"-"
1389 << theStateMachine_.getStateName(failedEvent.getFromState()) <<
" to "
1390 << failedEvent.getToState() <<
"-"
1391 << theStateMachine_.getStateName(failedEvent.getToState())
1392 <<
".\n\nException:\n"
1393 << failedEvent.getException().what() << __E__;
1396 __COUT_ERR__ <<
"\n" << ss.str();
1397 theStateMachine_.setErrorMessage(ss.str());
1400 broadcastMessage(SOAPUtilities::makeSOAPMessageReference(
"Error"));
1404 void GatewaySupervisor::checkForAsyncError()
1406 if(RunControlStateMachine::asyncFailureReceived_)
1408 __COUTV__(RunControlStateMachine::asyncFailureReceived_);
1410 XCEPT_RAISE(toolbox::fsm::exception::Exception,
1411 RunControlStateMachine::getErrorMessage());
1421 void GatewaySupervisor::transitionConfiguring(toolbox::Event::Reference e)
1423 checkForAsyncError();
1425 RunControlStateMachine::theProgressBar_.step();
1427 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1429 std::string systemAlias =
1430 SOAPUtilities::translate(theStateMachine_.getCurrentMessage())
1432 .getValue(
"ConfigurationAlias");
1434 __COUT__ <<
"Transition parameter: " << systemAlias << __E__;
1436 RunControlStateMachine::theProgressBar_.step();
1440 CorePropertySupervisorBase::theConfigurationManager_
1445 __SS__ <<
"\nTransition to Configuring interrupted! "
1446 <<
"The Configuration Manager could not be initialized." << __E__;
1448 __COUT_ERR__ <<
"\n" << ss.str();
1449 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1453 RunControlStateMachine::theProgressBar_.step();
1458 theConfigurationTableGroup_ =
1459 CorePropertySupervisorBase::theConfigurationManager_->getTableGroupFromAlias(
1464 __COUT_INFO__ <<
"Exception occurred" << __E__;
1467 RunControlStateMachine::theProgressBar_.step();
1469 if(theConfigurationTableGroup_.second.isInvalid())
1471 __SS__ <<
"\nTransition to Configuring interrupted! System Alias " << systemAlias
1472 <<
" could not be translated to a group name and key." << __E__;
1474 __COUT_ERR__ <<
"\n" << ss.str();
1475 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1479 RunControlStateMachine::theProgressBar_.step();
1481 __COUT__ <<
"Configuration table group name: " << theConfigurationTableGroup_.first
1482 <<
" key: " << theConfigurationTableGroup_.second << __E__;
1486 std::stringstream ss;
1487 ss <<
"Configuring '" << systemAlias <<
"' which translates to "
1488 << theConfigurationTableGroup_.first <<
" ("
1489 << theConfigurationTableGroup_.second <<
").";
1490 makeSystemLogbookEntry(ss.str());
1493 RunControlStateMachine::theProgressBar_.step();
1498 CorePropertySupervisorBase::theConfigurationManager_->loadTableGroup(
1499 theConfigurationTableGroup_.first,
1500 theConfigurationTableGroup_.second,
1503 __COUT__ <<
"Done loading Configuration Alias." << __E__;
1507 tmpCfgMgr.activateTableGroup(theConfigurationTableGroup_.first,
1508 theConfigurationTableGroup_.second);
1510 __COUT__ <<
"Done activating Configuration Alias." << __E__;
1514 __SS__ <<
"\nTransition to Configuring interrupted! System Alias " << systemAlias
1515 <<
" was translated to " << theConfigurationTableGroup_.first <<
" ("
1516 << theConfigurationTableGroup_.second
1517 <<
") but could not be loaded and initialized." << __E__;
1518 ss <<
"\n\nTo debug this problem, try activating this group in the Configuration "
1520 <<
" and detailed errors will be shown." << __E__;
1521 __COUT_ERR__ <<
"\n" << ss.str();
1522 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1530 CorePropertySupervisorBase::theConfigurationManager_
1531 ->dumpMacroMakerModeFhicl();
1535 __COUT_ERR__ <<
"Failed to dump MacroMaker mode fhicl." << __E__;
1539 CorePropertySupervisorBase::theConfigurationManager_->getSupervisorTableNode(
1540 supervisorContextUID_, supervisorApplicationUID_);
1541 if(!configLinkNode.isDisconnected())
1545 bool dumpConfiguration =
true;
1546 std::string dumpFilePath, dumpFileRadix, dumpFormat;
1550 configLinkNode.getNode(
"LinkToStateMachineTable")
1551 .getNode(activeStateMachineName_);
1554 .getNode(
"EnableConfigurationDumpOnConfigureTransition")
1557 fsmLinkNode.getNode(
"ConfigurationDumpOnConfigureFilePath")
1558 .getValue<std::string>();
1560 fsmLinkNode.getNode(
"ConfigurationDumpOnConfigureFileRadix")
1561 .getValue<std::string>();
1562 dumpFormat = fsmLinkNode.getNode(
"ConfigurationDumpOnConfigureFormat")
1563 .getValue<std::string>();
1565 catch(std::runtime_error& e)
1567 __COUT_INFO__ <<
"FSM configuration dump Link disconnected." << __E__;
1568 dumpConfiguration =
false;
1571 if(dumpConfiguration)
1574 CorePropertySupervisorBase::theConfigurationManager_
1575 ->dumpActiveConfiguration(dumpFilePath +
"/" + dumpFileRadix +
1576 "_" + std::to_string(time(0)) +
1580 CorePropertySupervisorBase::theConfigurationManager_
1581 ->dumpMacroMakerModeFhicl();
1584 catch(std::runtime_error& e)
1586 __SS__ <<
"\nTransition to Configuring interrupted! There was an error "
1588 <<
"during the configuration dump attempt:\n\n " << e.what()
1590 __COUT_ERR__ <<
"\n" << ss.str();
1591 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1596 __SS__ <<
"\nTransition to Configuring interrupted! There was an error "
1598 <<
"during the configuration dump attempt.\n\n " << __E__;
1599 __COUT_ERR__ <<
"\n" << ss.str();
1600 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1606 RunControlStateMachine::theProgressBar_.step();
1608 parameters.addParameter(
"ConfigurationTableGroupName",
1609 theConfigurationTableGroup_.first);
1610 parameters.addParameter(
"ConfigurationTableGroupKey",
1611 theConfigurationTableGroup_.second.toString());
1615 __COUT__ <<
"Initializing Macro Maker." << __E__;
1616 xoap::MessageReference message =
1617 SOAPUtilities::makeSOAPMessageReference(
"FECommunication");
1620 parameters.addParameter(
"type",
"initFElist");
1621 parameters.addParameter(
"groupName", theConfigurationTableGroup_.first);
1622 parameters.addParameter(
"groupKey",
1623 theConfigurationTableGroup_.second.toString());
1624 SOAPUtilities::addParameters(message, parameters);
1626 __COUT__ <<
"Sending FE communication: " << SOAPUtilities::translate(message)
1630 SOAPMessenger::send(CorePropertySupervisorBase::allSupervisorInfo_
1631 .getAllMacroMakerTypeSupervisorInfo()
1633 ->second.getDescriptor(),
1636 __COUT__ <<
"Macro Maker init reply: " << reply << __E__;
1637 if(reply ==
"Error")
1639 __SS__ <<
"\nTransition to Configuring interrupted! There was an error "
1640 "identified initializing Macro Maker.\n\n "
1642 __COUT_ERR__ <<
"\n" << ss.str();
1643 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1651 xoap::MessageReference message = theStateMachine_.getCurrentMessage();
1652 SOAPUtilities::addParameters(message, parameters);
1653 broadcastMessage(message);
1654 RunControlStateMachine::theProgressBar_.step();
1659 saveGroupNameAndKey(theConfigurationTableGroup_,
1660 FSM_LAST_CONFIGURED_GROUP_ALIAS_FILE);
1662 __COUT__ <<
"Done configuring." << __E__;
1663 RunControlStateMachine::theProgressBar_.complete();
1667 void GatewaySupervisor::transitionHalting(toolbox::Event::Reference e)
1669 checkForAsyncError();
1671 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1673 makeSystemLogbookEntry(
"Run halting.");
1675 broadcastMessage(theStateMachine_.getCurrentMessage());
1679 void GatewaySupervisor::transitionShuttingDown(toolbox::Event::Reference e)
1682 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1684 RunControlStateMachine::theProgressBar_.step();
1685 makeSystemLogbookEntry(
"System shutting down.");
1686 RunControlStateMachine::theProgressBar_.step();
1689 GatewaySupervisor::launchStartOTSCommand(
1690 "OTS_APP_SHUTDOWN", CorePropertySupervisorBase::theConfigurationManager_);
1691 RunControlStateMachine::theProgressBar_.step();
1695 for(
int i = 0; i < 5; ++i)
1698 RunControlStateMachine::theProgressBar_.step();
1703 void GatewaySupervisor::transitionStartingUp(toolbox::Event::Reference e)
1706 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1708 RunControlStateMachine::theProgressBar_.step();
1709 makeSystemLogbookEntry(
"System starting up.");
1710 RunControlStateMachine::theProgressBar_.step();
1713 GatewaySupervisor::launchStartOTSCommand(
1714 "OTS_APP_STARTUP", CorePropertySupervisorBase::theConfigurationManager_);
1715 RunControlStateMachine::theProgressBar_.step();
1719 for(
int i = 0; i < 10; ++i)
1722 RunControlStateMachine::theProgressBar_.step();
1727 void GatewaySupervisor::transitionInitializing(toolbox::Event::Reference e)
1730 __COUT__ << theStateMachine_.getCurrentStateName() << __E__;
1732 broadcastMessage(theStateMachine_.getCurrentMessage());
1734 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1735 __COUT__ <<
"Fsm current transition: "
1736 << theStateMachine_.getCurrentTransitionName(e->type()) << __E__;
1737 __COUT__ <<
"Fsm final state: "
1738 << theStateMachine_.getTransitionFinalStateName(e->type()) << __E__;
1742 void GatewaySupervisor::transitionPausing(toolbox::Event::Reference e)
1744 checkForAsyncError();
1746 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1748 makeSystemLogbookEntry(
"Run pausing.");
1751 if(RunControlStateMachine::asyncSoftFailureReceived_)
1753 __COUT_ERR__ <<
"Broadcasting pause for async SOFT error!" << __E__;
1754 broadcastMessage(SOAPUtilities::makeSOAPMessageReference(
"Pause"));
1757 broadcastMessage(theStateMachine_.getCurrentMessage());
1761 void GatewaySupervisor::transitionResuming(toolbox::Event::Reference e)
1763 if(RunControlStateMachine::asyncSoftFailureReceived_)
1766 __COUT_INFO__ <<
"Clearing async SOFT error!" << __E__;
1767 RunControlStateMachine::asyncSoftFailureReceived_ =
false;
1770 checkForAsyncError();
1772 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1774 makeSystemLogbookEntry(
"Run resuming.");
1776 broadcastMessage(theStateMachine_.getCurrentMessage());
1780 void GatewaySupervisor::transitionStarting(toolbox::Event::Reference e)
1782 if(RunControlStateMachine::asyncSoftFailureReceived_)
1785 __COUT_INFO__ <<
"Clearing async SOFT error!" << __E__;
1786 RunControlStateMachine::asyncSoftFailureReceived_ =
false;
1789 checkForAsyncError();
1791 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1794 SOAPUtilities::receive(theStateMachine_.getCurrentMessage(), parameters);
1796 std::string runNumber = parameters.getValue(
"RunNumber");
1797 __COUTV__(runNumber);
1802 CorePropertySupervisorBase::theConfigurationManager_->getSupervisorTableNode(
1803 supervisorContextUID_, supervisorApplicationUID_);
1804 if(!configLinkNode.isDisconnected())
1808 bool dumpConfiguration =
true;
1809 std::string dumpFilePath, dumpFileRadix, dumpFormat;
1813 configLinkNode.getNode(
"LinkToStateMachineTable")
1814 .getNode(activeStateMachineName_);
1816 fsmLinkNode.getNode(
"EnableConfigurationDumpOnRunTransition")
1818 dumpFilePath = fsmLinkNode.getNode(
"ConfigurationDumpOnRunFilePath")
1819 .getValue<std::string>();
1820 dumpFileRadix = fsmLinkNode.getNode(
"ConfigurationDumpOnRunFileRadix")
1821 .getValue<std::string>();
1822 dumpFormat = fsmLinkNode.getNode(
"ConfigurationDumpOnRunFormat")
1823 .getValue<std::string>();
1825 catch(std::runtime_error& e)
1827 __COUT_INFO__ <<
"FSM configuration dump Link disconnected." << __E__;
1828 dumpConfiguration =
false;
1831 if(dumpConfiguration)
1834 CorePropertySupervisorBase::theConfigurationManager_
1835 ->dumpActiveConfiguration(dumpFilePath +
"/" + dumpFileRadix +
1836 "_Run" + runNumber +
"_" +
1837 std::to_string(time(0)) +
".dump",
1841 catch(std::runtime_error& e)
1843 __SS__ <<
"\nTransition to Running interrupted! There was an error "
1845 <<
"during the configuration dump attempt:\n\n " << e.what()
1847 __COUT_ERR__ <<
"\n" << ss.str();
1848 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1853 __SS__ <<
"\nTransition to Running interrupted! There was an error "
1855 <<
"during the configuration dump attempt.\n\n " << __E__;
1856 __COUT_ERR__ <<
"\n" << ss.str();
1857 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1863 makeSystemLogbookEntry(
"Run " + runNumber +
" starting.");
1865 broadcastMessage(theStateMachine_.getCurrentMessage());
1868 saveGroupNameAndKey(theConfigurationTableGroup_, FSM_LAST_STARTED_GROUP_ALIAS_FILE);
1872 void GatewaySupervisor::transitionStopping(toolbox::Event::Reference e)
1874 checkForAsyncError();
1876 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << __E__;
1878 makeSystemLogbookEntry(
"Run stopping.");
1880 broadcastMessage(theStateMachine_.getCurrentMessage());
1893 bool GatewaySupervisor::handleBroadcastMessageTarget(
const SupervisorInfo& appInfo,
1894 xoap::MessageReference message,
1895 const std::string& command,
1896 const unsigned int& iteration,
1898 unsigned int threadIndex)
1900 unsigned int subIteration = 0;
1901 bool subIterationsDone =
false;
1902 bool iterationsDone =
true;
1904 while(!subIterationsDone)
1906 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
1907 <<
"Supervisor instance = '" << appInfo.getName()
1908 <<
"' [LID=" << appInfo.getId() <<
"] in Context '"
1909 << appInfo.getContextName() <<
"' [URL=" << appInfo.getURL()
1910 <<
"] Command = " << command << __E__;
1912 checkForAsyncError();
1914 subIterationsDone =
true;
1915 RunControlStateMachine::theProgressBar_.step();
1921 parameters.addParameter(
"subIterationIndex", subIteration);
1922 SOAPUtilities::addParameters(message, parameters);
1925 if(iteration || subIteration)
1926 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
1927 <<
"Adding iteration parameters " << iteration <<
"." << subIteration
1930 RunControlStateMachine::theProgressBar_.step();
1932 if(iteration == 0 && subIteration == 0)
1934 for(
unsigned int j = 0; j < 4; ++j)
1935 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
1936 <<
"Sending message to Supervisor " << appInfo.getName()
1937 <<
" [LID=" << appInfo.getId() <<
"]: " << command << __E__;
1941 if(subIteration == 0)
1943 for(
unsigned int j = 0; j < 4; ++j)
1944 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
1945 <<
"Sending message to Supervisor " << appInfo.getName()
1946 <<
" [LID=" << appInfo.getId() <<
"]: " << command
1947 <<
" (iteration: " << iteration <<
")" << __E__;
1951 for(
unsigned int j = 0; j < 4; ++j)
1952 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
1953 <<
"Sending message to Supervisor " << appInfo.getName()
1954 <<
" [LID=" << appInfo.getId() <<
"]: " << command
1955 <<
" (iteration: " << iteration
1956 <<
", sub-iteration: " << subIteration <<
")" << __E__;
1964 std::lock_guard<std::mutex> lock(broadcastCommandMessageIndexMutex_);
1965 parameters.addParameter(
"commandId", broadcastCommandMessageIndex_++);
1967 SOAPUtilities::addParameters(message, parameters);
1970 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
1971 <<
"Sending... \t" << SOAPUtilities::translate(message) << std::endl;
1975 reply = send(appInfo.getDescriptor(), message);
1977 catch(
const xdaq::exception::Exception& e)
1980 __SS__ <<
"Error! Gateway Supervisor can NOT " << command
1981 <<
" Supervisor instance = '" << appInfo.getName()
1982 <<
"' [LID=" << appInfo.getId() <<
"] in Context '"
1983 << appInfo.getContextName() <<
"' [URL=" << appInfo.getURL()
1985 <<
"Xoap message failure. Did the target Supervisor crash? Try "
1986 "re-initializing or restarting otsdaq."
1988 __COUT_ERR__ << ss.str();
1989 __MOUT_ERR__ << ss.str();
1993 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
1994 <<
"Try again.." << __E__;
1999 parameters.addParameter(
"retransmission",
"1");
2000 SOAPUtilities::addParameters(message, parameters);
2007 std::lock_guard<std::mutex> lock(
2008 broadcastCommandMessageIndexMutex_);
2009 parameters.addParameter(
"commandId",
2010 broadcastCommandMessageIndex_++);
2012 SOAPUtilities::addParameters(message, parameters);
2015 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
2016 <<
"Re-Sending... " << SOAPUtilities::translate(message)
2019 reply = send(appInfo.getDescriptor(), message);
2021 catch(
const xdaq::exception::Exception& e)
2023 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
2024 <<
"Second try failed.." << __E__;
2025 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
2027 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
2028 <<
"2nd try passed.." << __E__;
2031 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
2032 <<
"Reply received = " << reply << __E__;
2034 if((reply != command +
"Done") && (reply != command +
"Response") &&
2035 (reply != command +
"Iterate") && (reply != command +
"SubIterate"))
2037 __SS__ <<
"Error! Gateway Supervisor can NOT " << command
2038 <<
" Supervisor instance = '" << appInfo.getName()
2039 <<
"' [LID=" << appInfo.getId() <<
"] in Context '"
2040 << appInfo.getContextName() <<
"' [URL=" << appInfo.getURL()
2043 __COUT_ERR__ << ss.str() << __E__;
2044 __MOUT_ERR__ << ss.str() << __E__;
2046 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
2047 <<
"Getting error message..." << __E__;
2050 xoap::MessageReference errorMessage =
2051 sendWithSOAPReply(appInfo.getDescriptor(),
2052 SOAPUtilities::makeSOAPMessageReference(
2053 "StateMachineErrorMessageRequest"));
2055 parameters.addParameter(
"ErrorMessage");
2056 SOAPUtilities::receive(errorMessage, parameters);
2058 std::string error = parameters.getValue(
"ErrorMessage");
2061 std::stringstream err;
2062 err <<
"Unknown error from Supervisor instance = '"
2063 << appInfo.getName() <<
"' [LID=" << appInfo.getId()
2064 <<
"] in Context '" << appInfo.getContextName()
2065 <<
"' [URL=" << appInfo.getURL()
2066 <<
"]. If the problem persists or is repeatable, please notify "
2071 __SS__ <<
"Received error from Supervisor instance = '"
2072 << appInfo.getName() <<
"' [LID=" << appInfo.getId()
2073 <<
"] in Context '" << appInfo.getContextName()
2074 <<
"' [URL=" << appInfo.getURL()
2075 <<
"].\n\n Error Message = " << error << __E__;
2077 __COUT_ERR__ << ss.str() << __E__;
2078 __MOUT_ERR__ << ss.str() << __E__;
2080 if(command ==
"Error")
2084 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
2086 catch(
const xdaq::exception::Exception& e)
2089 __SS__ <<
"Error! Gateway Supervisor failed to read error message from "
2090 "Supervisor instance = '"
2091 << appInfo.getName() <<
"' [LID=" << appInfo.getId()
2092 <<
"] in Context '" << appInfo.getContextName()
2093 <<
"' [URL=" << appInfo.getURL() <<
"].\n\n"
2094 <<
"Xoap message failure. Did the target Supervisor crash? Try "
2095 "re-initializing or restarting otsdaq."
2097 __COUT_ERR__ << ss.str();
2098 __MOUT_ERR__ << ss.str();
2099 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
2102 else if(reply == command +
"Iterate")
2109 iterationsDone =
false;
2110 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
2111 <<
"Supervisor instance = '" << appInfo.getName()
2112 <<
"' [LID=" << appInfo.getId() <<
"] in Context '"
2113 << appInfo.getContextName() <<
"' [URL=" << appInfo.getURL()
2114 <<
"] flagged for another iteration to " << command
2115 <<
"... (iteration: " << iteration <<
")" << __E__;
2118 else if(reply == command +
"SubIterate")
2125 subIterationsDone =
false;
2126 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
2127 <<
"Supervisor instance = '" << appInfo.getName()
2128 <<
"' [LID=" << appInfo.getId() <<
"] in Context '"
2129 << appInfo.getContextName() <<
"' [URL=" << appInfo.getURL()
2130 <<
"] flagged for another sub-iteration to " << command
2131 <<
"... (iteration: " << iteration
2132 <<
", sub-iteration: " << subIteration <<
")" << __E__;
2136 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
2137 <<
"Supervisor instance = '" << appInfo.getName()
2138 <<
"' [LID=" << appInfo.getId() <<
"] in Context '"
2139 << appInfo.getContextName() <<
"' [URL=" << appInfo.getURL()
2140 <<
"] was " << command <<
"'d correctly!" << __E__;
2144 __COUT__ <<
"Broadcast thread " << threadIndex <<
"\t"
2145 <<
"Completed sub-iteration: " << subIteration << __E__;
2150 return iterationsDone;
2158 void GatewaySupervisor::broadcastMessageThread(
2159 GatewaySupervisor* supervisorPtr,
2160 GatewaySupervisor::BroadcastThreadStruct* threadStruct)
2162 __COUT__ <<
"Broadcast thread " << threadStruct->threadIndex_ <<
"\t"
2163 <<
"starting..." << __E__;
2165 while(!threadStruct->exitThread_)
2171 std::lock_guard<std::mutex> lock(threadStruct->threadMutex);
2172 if(threadStruct->workToDo_)
2174 __COUT__ <<
"Broadcast thread " << threadStruct->threadIndex_ <<
"\t"
2175 <<
"starting work..." << __E__;
2179 if(supervisorPtr->handleBroadcastMessageTarget(
2180 threadStruct->getAppInfo(),
2181 threadStruct->getMessage(),
2182 threadStruct->getCommand(),
2183 threadStruct->getIteration(),
2184 threadStruct->getReply(),
2185 threadStruct->threadIndex_))
2186 threadStruct->getIterationsDone() =
true;
2188 catch(toolbox::fsm::exception::Exception
const& e)
2190 __COUT__ <<
"Broadcast thread " << threadStruct->threadIndex_ <<
"\t"
2191 <<
"going into error: " << e.what() << __E__;
2193 threadStruct->getReply() = e.what();
2194 threadStruct->error_ =
true;
2195 threadStruct->workToDo_ =
false;
2196 threadStruct->working_ =
false;
2200 if(!threadStruct->getIterationsDone())
2202 __COUT__ <<
"Broadcast thread " << threadStruct->threadIndex_ <<
"\t"
2203 <<
"flagged for another iteration." << __E__;
2206 std::lock_guard<std::mutex> lock(
2207 supervisorPtr->broadcastIterationsDoneMutex_);
2208 supervisorPtr->broadcastIterationsDone_ =
false;
2211 __COUT__ <<
"Broadcast thread " << threadStruct->threadIndex_ <<
"\t"
2212 <<
"done with work." << __E__;
2214 threadStruct->workToDo_ =
false;
2219 __COUT__ <<
"Broadcast thread " << threadStruct->threadIndex_ <<
"\t"
2220 <<
"exited." << __E__;
2221 threadStruct->working_ =
false;
2229 void GatewaySupervisor::broadcastMessage(xoap::MessageReference message)
2231 RunControlStateMachine::theProgressBar_.step();
2234 allSupervisorInfo_.setSupervisorStatus(
this, theStateMachine_.getCurrentStateName());
2236 std::string command = SOAPUtilities::translate(message).getCommand();
2239 broadcastIterationsDone_ =
false;
2242 std::vector<std::vector<const SupervisorInfo*>> orderedSupervisors;
2246 orderedSupervisors = allSupervisorInfo_.getOrderedSupervisorDescriptors(command);
2248 catch(
const std::runtime_error& e)
2250 __SS__ <<
"Error getting supervisor priority. Was there a change in the context?"
2251 <<
" Remember, if the context was changed, it is safest to relaunch "
2253 << e.what() << __E__;
2254 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
2257 RunControlStateMachine::theProgressBar_.step();
2261 GatewaySupervisor::BroadcastMessageIterationsDoneStruct supervisorIterationsDone;
2264 for(
const auto& vectorAtPriority : orderedSupervisors)
2265 supervisorIterationsDone.push(
2266 vectorAtPriority.size());
2270 unsigned int iteration = 0;
2271 unsigned int subIteration;
2272 unsigned int iterationBreakpoint;
2277 xoap::MessageReference originalMessage =
2278 SOAPUtilities::makeSOAPMessageReference(SOAPUtilities::translate(message));
2280 __COUT__ <<
"=========> Broadcasting state machine command = " << command << __E__;
2282 unsigned int numberOfThreads = 1;
2286 numberOfThreads = CorePropertySupervisorBase::getSupervisorTableNode()
2287 .getNode(
"NumberOfStateMachineBroadcastThreads")
2288 .getValue<
unsigned int>();
2293 __COUT__ <<
"Number of threads not in configuration, so defaulting to "
2294 << numberOfThreads << __E__;
2299 if(numberOfThreads == 1)
2300 numberOfThreads = 0;
2302 __COUTV__(numberOfThreads);
2304 std::vector<GatewaySupervisor::BroadcastThreadStruct> broadcastThreadStructs(
2309 for(
unsigned int i = 0; i < numberOfThreads; ++i)
2311 broadcastThreadStructs[i].threadIndex_ = i;
2314 [](GatewaySupervisor* supervisorPtr,
2315 GatewaySupervisor::BroadcastThreadStruct* threadStruct) {
2316 GatewaySupervisor::broadcastMessageThread(supervisorPtr, threadStruct);
2319 &broadcastThreadStructs[i])
2323 RunControlStateMachine::theProgressBar_.step();
2331 broadcastIterationsDone_ =
true;
2334 std::lock_guard<std::mutex> lock(broadcastIterationBreakpointMutex_);
2335 iterationBreakpoint = broadcastIterationBreakpoint_;
2338 if(iterationBreakpoint < (
unsigned int)-1)
2339 __COUT__ <<
"Iteration breakpoint currently is " << iterationBreakpoint
2341 if(iteration >= iterationBreakpoint)
2343 broadcastIterationsDone_ =
false;
2344 __COUT__ <<
"Waiting at transition breakpoint - iteration = " << iteration
2346 usleep(5 * 1000 * 1000 );
2351 __COUT__ <<
"Starting iteration: " << iteration << __E__;
2353 for(
unsigned int i = 0; i < supervisorIterationsDone.size(); ++i)
2355 for(
unsigned int j = 0; j < supervisorIterationsDone.size(i); ++j)
2357 checkForAsyncError();
2359 if(supervisorIterationsDone[i][j])
2365 message = SOAPUtilities::makeSOAPMessageReference(
2366 SOAPUtilities::translate(originalMessage));
2373 parameters.addParameter(
"iterationIndex", iteration);
2374 SOAPUtilities::addParameters(message, parameters);
2380 assignedJob =
false;
2383 for(
unsigned int k = 0; k < numberOfThreads; ++k)
2385 if(!broadcastThreadStructs[k].workToDo_)
2389 __COUT__ <<
"Giving work to thread " << k << __E__;
2391 std::lock_guard<std::mutex> lock(
2392 broadcastThreadStructs[k].threadMutex);
2393 broadcastThreadStructs[k].setMessage(
2398 supervisorIterationsDone[i][j]);
2406 __COUT__ <<
"No free broadcast threads, "
2407 <<
"waiting for an available thread..." << __E__;
2408 usleep(100 * 1000 );
2410 }
while(!assignedJob);
2414 if(handleBroadcastMessageTarget(
2415 appInfo, message, command, iteration, reply))
2416 supervisorIterationsDone[i][j] =
true;
2418 broadcastIterationsDone_ =
false;
2428 <<
"Done with priority level. Waiting for threads to finish..."
2434 for(
unsigned int i = 0; i < numberOfThreads; ++i)
2435 if(broadcastThreadStructs[i].workToDo_)
2438 __COUT__ <<
"Still waiting on thread " << i <<
"..."
2440 usleep(100 * 1000 );
2443 else if(broadcastThreadStructs[i].error_)
2445 __COUT__ <<
"Found thread in error! Throwing state "
2447 << broadcastThreadStructs[i].getReply() << __E__;
2448 XCEPT_RAISE(toolbox::fsm::exception::Exception,
2449 broadcastThreadStructs[i].getReply());
2452 __COUT__ <<
"All threads done with priority level work." << __E__;
2463 if(iteration || !broadcastIterationsDone_)
2464 __COUT__ <<
"Completed iteration: " << iteration << __E__;
2467 }
while(!broadcastIterationsDone_);
2469 RunControlStateMachine::theProgressBar_.step();
2473 __COUT__ <<
"Exception caught, exiting broadcast threads..." << __E__;
2480 for(
unsigned int i = 0; i < numberOfThreads; ++i)
2481 broadcastThreadStructs[i].exitThread_ =
true;
2482 usleep(100 * 1000 );
2489 __COUT__ <<
"All transitions completed. Wrapping up, exiting broadcast threads..."
2498 for(
unsigned int i = 0; i < numberOfThreads; ++i)
2499 broadcastThreadStructs[i].exitThread_ =
true;
2500 usleep(100 * 1000 );
2503 __COUT__ <<
"Broadcast complete." << __E__;
2507 void GatewaySupervisor::wait(
int milliseconds, std::string who)
const
2509 for(
int s = 1; s <= milliseconds; s++)
2514 __COUT__ << s <<
" msecs " << who << __E__;
2523 void GatewaySupervisor::loginRequest(xgi::Input* in, xgi::Output* out)
2525 __COUT__ <<
"Start" << __E__;
2526 cgicc::Cgicc cgi(in);
2527 std::string Command = CgiDataUtilities::getData(cgi,
"RequestType");
2528 __COUT__ <<
"*** Login RequestType = " << Command << __E__;
2537 std::vector<std::string> loggedOutUsernames;
2538 theWebUsers_.cleanupExpiredEntries(&loggedOutUsernames);
2539 for(
unsigned int i = 0; i < loggedOutUsernames.size();
2541 makeSystemLogbookEntry(loggedOutUsernames[i] +
" login timed out.");
2543 if(Command ==
"sessionId")
2552 std::string uuid = CgiDataUtilities::postData(cgi,
"uuid");
2554 std::string sid = theWebUsers_.createNewLoginSession(
2555 uuid, cgi.getEnvironment().getRemoteAddr() );
2561 else if(Command ==
"checkCookie")
2565 std::string jumbledUser;
2566 std::string cookieCode;
2577 uuid = CgiDataUtilities::postData(cgi,
"uuid");
2578 jumbledUser = CgiDataUtilities::postData(cgi,
"ju");
2579 cookieCode = CgiDataUtilities::postData(cgi,
"cc");
2587 uid = theWebUsers_.isCookieCodeActiveForLogin(
2592 if(uid == theWebUsers_.NOT_FOUND_IN_DATABASE)
2594 __COUT__ <<
"cookieCode invalid" << __E__;
2599 __COUT__ <<
"cookieCode is good." << __E__;
2604 theWebUsers_.insertSettingsForUser(uid, &xmldoc);
2606 xmldoc.outputXmlDocument((std::ostringstream*)out);
2608 else if(Command ==
"login")
2619 std::string uuid = CgiDataUtilities::postData(cgi,
"uuid");
2620 std::string newAccountCode = CgiDataUtilities::postData(cgi,
"nac");
2621 std::string jumbledUser = CgiDataUtilities::postData(cgi,
"ju");
2622 std::string jumbledPw = CgiDataUtilities::postData(cgi,
"jp");
2629 uint64_t uid = theWebUsers_.attemptActiveSession(
2634 cgi.getEnvironment()
2637 if(uid == theWebUsers_.NOT_FOUND_IN_DATABASE)
2639 __COUT__ <<
"Login invalid." << __E__;
2641 if(newAccountCode !=
"1")
2642 newAccountCode =
"0";
2645 makeSystemLogbookEntry(theWebUsers_.getUsersUsername(uid) +
" logged in.");
2651 theWebUsers_.insertSettingsForUser(uid, &xmldoc);
2655 if(uid != theWebUsers_.NOT_FOUND_IN_DATABASE)
2657 uint64_t asCnt = theWebUsers_.getActiveSessionCountForUser(uid) -
2660 sprintf(asStr,
"%lu", asCnt);
2661 xmldoc.addTextElementToData(
"user_active_session_count", asStr);
2664 xmldoc.outputXmlDocument((std::ostringstream*)out);
2666 else if(Command ==
"cert")
2677 std::string uuid = CgiDataUtilities::postData(cgi,
"uuid");
2678 std::string jumbledEmail =
2679 cgicc::form_urldecode(CgiDataUtilities::getData(cgi,
"httpsUser"));
2680 std::string username =
"";
2681 std::string cookieCode =
"";
2687 uint64_t uid = theWebUsers_.attemptActiveSessionWithCert(
2692 cgi.getEnvironment()
2695 if(uid == theWebUsers_.NOT_FOUND_IN_DATABASE)
2697 __COUT__ <<
"cookieCode invalid" << __E__;
2699 if(cookieCode !=
"1")
2703 makeSystemLogbookEntry(theWebUsers_.getUsersUsername(uid) +
" logged in.");
2709 theWebUsers_.insertSettingsForUser(uid, &xmldoc);
2713 if(uid != theWebUsers_.NOT_FOUND_IN_DATABASE)
2715 uint64_t asCnt = theWebUsers_.getActiveSessionCountForUser(uid) -
2718 sprintf(asStr,
"%lu", asCnt);
2719 xmldoc.addTextElementToData(
"user_active_session_count", asStr);
2722 xmldoc.outputXmlDocument((std::ostringstream*)out);
2724 else if(Command ==
"logout")
2726 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
2727 std::string logoutOthers = CgiDataUtilities::postData(cgi,
"LogoutOthers");
2733 if(theWebUsers_.cookieCodeLogout(cookieCode,
2734 logoutOthers ==
"1",
2736 cgi.getEnvironment().getRemoteAddr()) !=
2737 theWebUsers_.NOT_FOUND_IN_DATABASE)
2741 if(!theWebUsers_.isUserIdActive(uid))
2742 makeSystemLogbookEntry(theWebUsers_.getUsersUsername(uid) +
2748 __COUT__ <<
"Invalid Command" << __E__;
2752 __COUT__ <<
"Done" << __E__;
2756 void GatewaySupervisor::tooltipRequest(xgi::Input* in, xgi::Output* out)
2758 __COUT__ <<
"Start" << __E__;
2759 cgicc::Cgicc cgi(in);
2761 std::string Command = CgiDataUtilities::getData(cgi,
"RequestType");
2762 __COUT__ <<
"Tooltip RequestType = " << Command << __E__;
2769 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
2772 if(!theWebUsers_.cookieCodeIsActiveForRequest(
2773 cookieCode, 0 , &uid,
"0" ,
false ))
2783 if(Command ==
"check")
2785 WebUsers::tooltipCheckForUsername(theWebUsers_.getUsersUsername(uid),
2787 CgiDataUtilities::getData(cgi,
"srcFile"),
2788 CgiDataUtilities::getData(cgi,
"srcFunc"),
2789 CgiDataUtilities::getData(cgi,
"srcId"));
2791 else if(Command ==
"setNeverShow")
2793 WebUsers::tooltipSetNeverShowForUsername(
2794 theWebUsers_.getUsersUsername(uid),
2796 CgiDataUtilities::getData(cgi,
"srcFile"),
2797 CgiDataUtilities::getData(cgi,
"srcFunc"),
2798 CgiDataUtilities::getData(cgi,
"srcId"),
2799 CgiDataUtilities::getData(cgi,
"doNeverShow") ==
"1" ?
true :
false,
2800 CgiDataUtilities::getData(cgi,
"temporarySilence") ==
"1" ?
true :
false);
2803 __COUT__ <<
"Command Request, " << Command <<
", not recognized." << __E__;
2805 xmldoc.outputXmlDocument((std::ostringstream*)out,
false,
true);
2807 __COUT__ <<
"Done" << __E__;
2814 void GatewaySupervisor::setSupervisorPropertyDefaults()
2816 CorePropertySupervisorBase::setSupervisorProperty(
2817 CorePropertySupervisorBase::SUPERVISOR_PROPERTIES.UserPermissionsThreshold,
2818 std::string() +
"*=1 | gatewayLaunchOTS=-1 | gatewayLaunchWiz=-1");
2824 void GatewaySupervisor::forceSupervisorPropertyValues()
2830 CorePropertySupervisorBase::setSupervisorProperty(
2831 CorePropertySupervisorBase::SUPERVISOR_PROPERTIES.AutomatedRequestTypes,
2832 "getSystemMessages | getCurrentState | getIterationPlanStatus");
2833 CorePropertySupervisorBase::setSupervisorProperty(
2834 CorePropertySupervisorBase::SUPERVISOR_PROPERTIES.RequireUserLockRequestTypes,
2835 "gatewayLaunchOTS | gatewayLaunchWiz");
2841 void GatewaySupervisor::request(xgi::Input* in, xgi::Output* out)
2849 __COUT__ <<
"Waiting for FSM access" << __E__;
2850 std::lock_guard<std::mutex> lock(stateMachineAccessMutex_);
2852 __COUT__ <<
"Have FSM access" << __E__;
2854 cgicc::Cgicc cgiIn(in);
2856 std::string requestType = CgiDataUtilities::getData(cgiIn,
"RequestType");
2860 CgiDataUtilities::postData(cgiIn,
"CookieCode"));
2862 CorePropertySupervisorBase::getRequestUserInfo(userInfo);
2875 if(!theWebUsers_.xmlRequestOnGateway(cgiIn, out, &xmlOut, userInfo))
2907 if(requestType ==
"getSettings")
2909 std::string accounts = CgiDataUtilities::getData(cgiIn,
"accounts");
2911 __COUT__ <<
"Get Settings Request" << __E__;
2912 __COUT__ <<
"accounts = " << accounts << __E__;
2913 theWebUsers_.insertSettingsForUser(userInfo.uid_, &xmlOut, accounts ==
"1");
2915 else if(requestType ==
"viewCodeContent")
2918 else if(requestType ==
"setSettings")
2920 std::string bgcolor = CgiDataUtilities::postData(cgiIn,
"bgcolor");
2921 std::string dbcolor = CgiDataUtilities::postData(cgiIn,
"dbcolor");
2922 std::string wincolor = CgiDataUtilities::postData(cgiIn,
"wincolor");
2923 std::string layout = CgiDataUtilities::postData(cgiIn,
"layout");
2924 std::string syslayout = CgiDataUtilities::postData(cgiIn,
"syslayout");
2926 __COUT__ <<
"Set Settings Request" << __E__;
2927 __COUT__ <<
"bgcolor = " << bgcolor << __E__;
2928 __COUT__ <<
"dbcolor = " << dbcolor << __E__;
2929 __COUT__ <<
"wincolor = " << wincolor << __E__;
2930 __COUT__ <<
"layout = " << layout << __E__;
2931 __COUT__ <<
"syslayout = " << syslayout << __E__;
2933 theWebUsers_.changeSettingsForUser(
2934 userInfo.uid_, bgcolor, dbcolor, wincolor, layout, syslayout);
2935 theWebUsers_.insertSettingsForUser(
2936 userInfo.uid_, &xmlOut,
true);
2938 else if(requestType ==
"accountSettings")
2940 std::string type = CgiDataUtilities::postData(
2944 if(type ==
"updateAccount")
2946 else if(type ==
"createAccount")
2948 else if(type ==
"deleteAccount")
2951 std::string username = CgiDataUtilities::postData(cgiIn,
"username");
2952 std::string displayname = CgiDataUtilities::postData(cgiIn,
"displayname");
2953 std::string email = CgiDataUtilities::postData(cgiIn,
"useremail");
2954 std::string permissions = CgiDataUtilities::postData(cgiIn,
"permissions");
2955 std::string accounts = CgiDataUtilities::getData(cgiIn,
"accounts");
2957 __COUT__ <<
"accountSettings Request" << __E__;
2958 __COUT__ <<
"type = " << type <<
" - " << type_int << __E__;
2959 __COUT__ <<
"username = " << username << __E__;
2960 __COUT__ <<
"useremail = " << email << __E__;
2961 __COUT__ <<
"displayname = " << displayname << __E__;
2962 __COUT__ <<
"permissions = " << permissions << __E__;
2964 theWebUsers_.modifyAccountSettings(
2965 userInfo.uid_, type_int, username, displayname, email, permissions);
2967 __COUT__ <<
"accounts = " << accounts << __E__;
2969 theWebUsers_.insertSettingsForUser(userInfo.uid_, &xmlOut, accounts ==
"1");
2971 else if(requestType ==
"stateMatchinePreferences")
2973 std::string set = CgiDataUtilities::getData(cgiIn,
"set");
2974 const std::string DEFAULT_FSM_VIEW =
"Default_FSM_View";
2976 theWebUsers_.setGenericPreference(
2979 CgiDataUtilities::getData(cgiIn, DEFAULT_FSM_VIEW));
2981 theWebUsers_.getGenericPreference(
2982 userInfo.uid_, DEFAULT_FSM_VIEW, &xmlOut);
2984 else if(requestType ==
"getAliasList")
2986 std::string username = theWebUsers_.getUsersUsername(userInfo.uid_);
2987 std::string fsmName = CgiDataUtilities::getData(cgiIn,
"fsmName");
2988 __COUT__ <<
"fsmName = " << fsmName << __E__;
2990 std::string stateMachineAliasFilter =
"*";
2992 std::map<std::string ,
2994 aliasMap = CorePropertySupervisorBase::theConfigurationManager_
2995 ->getActiveGroupAliases();
2999 CorePropertySupervisorBase::theConfigurationManager_
3000 ->getSupervisorTableNode(supervisorContextUID_,
3001 supervisorApplicationUID_);
3003 if(!configLinkNode.isDisconnected())
3008 configLinkNode.getNode(
"LinkToStateMachineTable");
3009 if(!fsmLinkNode.isDisconnected())
3010 stateMachineAliasFilter =
3011 fsmLinkNode.getNode(fsmName +
"/SystemAliasFilter")
3012 .getValue<std::string>();
3014 __COUT_INFO__ <<
"FSM Link disconnected." << __E__;
3016 catch(std::runtime_error& e)
3018 __COUT_INFO__ << e.what() << __E__;
3022 __COUT_ERR__ <<
"Unknown error. Should never happen." << __E__;
3026 __COUT_INFO__ <<
"FSM Link disconnected." << __E__;
3028 __COUT__ <<
"stateMachineAliasFilter = " << stateMachineAliasFilter << __E__;
3035 stateMachineAliasFilter.size() && stateMachineAliasFilter[0] ==
'!';
3036 std::vector<std::string> filterArr;
3043 while((f = stateMachineAliasFilter.find(
'*', i)) != std::string::npos)
3045 tmp = stateMachineAliasFilter.substr(i, f - i);
3047 filterArr.push_back(tmp);
3051 if(i <= stateMachineAliasFilter.size())
3053 tmp = stateMachineAliasFilter.substr(i);
3054 filterArr.push_back(tmp);
3060 for(
auto& aliasMapPair : aliasMap)
3066 if(filterArr.size() == 1)
3068 if(filterArr[0] !=
"" && filterArr[0] !=
"*" &&
3069 aliasMapPair.first != filterArr[0])
3070 filterMatch =
false;
3075 for(f = 0; f < filterArr.size(); ++f)
3077 if(!filterArr[f].size())
3082 if((i = aliasMapPair.first.find(filterArr[f])) != 0)
3084 filterMatch =
false;
3089 filterArr.size() - 1)
3091 if(aliasMapPair.first.rfind(filterArr[f]) !=
3092 aliasMapPair.first.size() - filterArr[f].size())
3094 filterMatch =
false;
3098 else if((i = aliasMapPair.first.find(filterArr[f])) ==
3101 filterMatch =
false;
3108 filterMatch = !filterMatch;
3115 xmlOut.addTextElementToData(
"config_alias", aliasMapPair.first);
3116 xmlOut.addTextElementToData(
3118 TableGroupKey::getFullGroupString(aliasMapPair.second.first,
3119 aliasMapPair.second.second)
3122 std::string groupComment, groupAuthor, groupCreationTime;
3125 CorePropertySupervisorBase::theConfigurationManager_
3126 ->loadTableGroup(aliasMapPair.second.first,
3127 aliasMapPair.second.second,
3137 xmlOut.addTextElementToData(
"config_comment", groupComment);
3138 xmlOut.addTextElementToData(
"config_author", groupAuthor);
3139 xmlOut.addTextElementToData(
"config_create_time",
3144 __COUT_WARN__ <<
"Failed to load group metadata." << __E__;
3150 std::string fn = FSM_LAST_GROUP_ALIAS_PATH + FSM_LAST_GROUP_ALIAS_FILE_START +
3151 username +
"." + FSM_USERS_PREFERENCES_FILETYPE;
3152 __COUT__ <<
"Load preferences: " << fn << __E__;
3153 FILE* fp = fopen(fn.c_str(),
"r");
3156 char tmpLastAlias[500];
3157 fscanf(fp,
"%*s %s", tmpLastAlias);
3158 __COUT__ <<
"tmpLastAlias: " << tmpLastAlias << __E__;
3160 xmlOut.addTextElementToData(
"UserLastConfigAlias", tmpLastAlias);
3164 else if(requestType ==
"getAppStatus")
3166 for(
auto it : allSupervisorInfo_.getAllSupervisorInfo())
3170 auto appInfo = it.second;
3172 xmlOut.addTextElementToData(
"name",
3174 xmlOut.addTextElementToData(
3175 "id", std::to_string(appInfo.getId()));
3176 xmlOut.addTextElementToData(
"status", appInfo.getStatus());
3177 xmlOut.addTextElementToData(
3179 StringMacros::getTimestampString(
3180 appInfo.getLastStatusTime()));
3181 xmlOut.addTextElementToData(
3182 "progress", std::to_string(appInfo.getProgress()));
3183 xmlOut.addTextElementToData(
"class",
3184 appInfo.getClass());
3185 xmlOut.addTextElementToData(
"url",
3187 xmlOut.addTextElementToData(
"context",
3188 appInfo.getContextName());
3192 else if(requestType ==
"getContextMemberNames")
3195 CorePropertySupervisorBase::theConfigurationManager_->__GET_CONFIG__(
3198 auto contexts = contextTable->getContexts();
3199 for(
const auto& context : contexts)
3201 xmlOut.addTextElementToData(
3202 "ContextMember", context.contextUID_);
3206 else if(requestType ==
"getSystemMessages")
3208 xmlOut.addTextElementToData(
3210 theSystemMessenger_.getSystemMessage(
3211 theWebUsers_.getUsersDisplayName(userInfo.uid_)));
3213 xmlOut.addTextElementToData(
3214 "username_with_lock",
3215 theWebUsers_.getUserWithLock());
3219 else if(requestType ==
"setUserWithLock")
3221 std::string username = CgiDataUtilities::postData(cgiIn,
"username");
3222 std::string lock = CgiDataUtilities::postData(cgiIn,
"lock");
3223 std::string accounts = CgiDataUtilities::getData(cgiIn,
"accounts");
3225 __COUTV__(username);
3227 __COUTV__(accounts);
3228 __COUTV__(userInfo.uid_);
3230 std::string tmpUserWithLock = theWebUsers_.getUserWithLock();
3231 if(!theWebUsers_.setUserWithLock(userInfo.uid_, lock ==
"1", username))
3232 xmlOut.addTextElementToData(
3234 std::string(
"Set user lock action failed. You must have valid "
3235 "permissions and ") +
3236 "locking user must be currently logged in.");
3238 theWebUsers_.insertSettingsForUser(userInfo.uid_, &xmlOut, accounts ==
"1");
3240 if(tmpUserWithLock !=
3243 theSystemMessenger_.addSystemMessage(
3245 theWebUsers_.getUserWithLock() ==
""
3246 ? tmpUserWithLock +
" has unlocked ots."
3247 : theWebUsers_.getUserWithLock() +
" has locked ots.");
3249 else if(requestType ==
"getStateMachine")
3252 std::vector<toolbox::fsm::State> states;
3253 states = theStateMachine_.getStates();
3256 std::string transName;
3257 std::string transParameter;
3260 for(
unsigned int i = 0; i < states.size(); ++i)
3262 stateStr[0] = states[i];
3263 DOMElement* stateParent = xmlOut.addTextElementToData(
"state", stateStr);
3265 xmlOut.addTextElementToParent(
3266 "state_name", theStateMachine_.getStateName(states[i]), stateParent);
3273 std::map<std::string, toolbox::fsm::State, std::less<std::string>> trans =
3274 theStateMachine_.getTransitions(states[i]);
3275 std::set<std::string> actionNames = theStateMachine_.getInputs(states[i]);
3277 std::map<std::string, toolbox::fsm::State, std::less<std::string>>::
3278 iterator it = trans.begin();
3279 std::set<std::string>::iterator ait = actionNames.begin();
3287 for(; it != trans.end() && ait != actionNames.end(); ++it, ++ait)
3289 stateStr[0] = it->second;
3291 if(stateStr[0] ==
'R')
3294 xmlOut.addTextElementToParent(
3295 "state_transition", stateStr, stateParent);
3299 xmlOut.addTextElementToParent(
3300 "state_transition_action", *ait, stateParent);
3302 transName = theStateMachine_.getTransitionName(states[i], *ait);
3305 xmlOut.addTextElementToParent(
3306 "state_transition_name", transName, stateParent);
3308 theStateMachine_.getTransitionParameter(states[i], *ait);
3311 xmlOut.addTextElementToParent(
3312 "state_transition_parameter", transParameter, stateParent);
3315 else if(stateStr[0] ==
'C')
3318 xmlOut.addTextElementToParent(
3319 "state_transition", stateStr, stateParent);
3323 xmlOut.addTextElementToParent(
3324 "state_transition_action", *ait, stateParent);
3326 transName = theStateMachine_.getTransitionName(states[i], *ait);
3329 xmlOut.addTextElementToParent(
3330 "state_transition_name", transName, stateParent);
3332 theStateMachine_.getTransitionParameter(states[i], *ait);
3335 xmlOut.addTextElementToParent(
3336 "state_transition_parameter", transParameter, stateParent);
3343 ait = actionNames.begin();
3346 for(; it != trans.end() && ait != actionNames.end(); ++it, ++ait)
3350 stateStr[0] = it->second;
3352 if(stateStr[0] ==
'R')
3354 else if(stateStr[0] ==
'C')
3357 xmlOut.addTextElementToParent(
3358 "state_transition", stateStr, stateParent);
3362 xmlOut.addTextElementToParent(
3363 "state_transition_action", *ait, stateParent);
3365 transName = theStateMachine_.getTransitionName(states[i], *ait);
3368 xmlOut.addTextElementToParent(
3369 "state_transition_name", transName, stateParent);
3371 theStateMachine_.getTransitionParameter(states[i], *ait);
3374 xmlOut.addTextElementToParent(
3375 "state_transition_parameter", transParameter, stateParent);
3379 else if(requestType ==
"getStateMachineNames")
3383 CorePropertySupervisorBase::theConfigurationManager_
3384 ->getSupervisorTableNode(supervisorContextUID_,
3385 supervisorApplicationUID_);
3390 configLinkNode.getNode(
"LinkToStateMachineTable").getChildren();
3391 for(
const auto& fsmNode : fsmNodes)
3392 xmlOut.addTextElementToData(
"stateMachineName", fsmNode.first);
3396 __COUT__ <<
"Caught exception, assuming no valid FSM names." << __E__;
3397 xmlOut.addTextElementToData(
"stateMachineName",
"");
3400 else if(requestType ==
"getIterationPlanStatus")
3403 theIterator_.handleCommandRequest(xmlOut, requestType,
"");
3405 else if(requestType ==
"getCurrentState")
3407 xmlOut.addTextElementToData(
"current_state",
3408 theStateMachine_.getCurrentStateName());
3409 xmlOut.addTextElementToData(
"in_transition",
3410 theStateMachine_.isInTransition() ?
"1" :
"0");
3411 if(theStateMachine_.isInTransition())
3412 xmlOut.addTextElementToData(
3413 "transition_progress",
3414 RunControlStateMachine::theProgressBar_.readPercentageString());
3416 xmlOut.addTextElementToData(
"transition_progress",
"100");
3419 sprintf(tmp,
"%lu", theStateMachine_.getTimeInState());
3420 xmlOut.addTextElementToData(
"time_in_state", tmp);
3427 std::string fsmName = CgiDataUtilities::getData(cgiIn,
"fsmName");
3436 if(!theStateMachine_.isInTransition())
3438 std::string stateMachineRunAlias =
"Run";
3442 CorePropertySupervisorBase::theConfigurationManager_
3443 ->getSupervisorTableNode(supervisorContextUID_,
3444 supervisorApplicationUID_);
3446 if(!configLinkNode.isDisconnected())
3451 configLinkNode.getNode(
"LinkToStateMachineTable");
3452 if(!fsmLinkNode.isDisconnected())
3453 stateMachineRunAlias =
3454 fsmLinkNode.getNode(fsmName +
"/RunDisplayAlias")
3455 .getValue<std::string>();
3459 catch(std::runtime_error& e)
3468 __COUT_ERR__ <<
"Unknown error. Should never happen." << __E__;
3470 __COUT_INFO__ <<
"No state machine Run alias. Ignoring and "
3471 "assuming alias of '"
3472 << stateMachineRunAlias <<
".'" << __E__;
3481 xmlOut.addTextElementToData(
"stateMachineRunAlias", stateMachineRunAlias);
3485 if(theStateMachine_.getCurrentStateName() ==
"Running" ||
3486 theStateMachine_.getCurrentStateName() ==
"Paused")
3489 "Current %s Number: %u",
3490 stateMachineRunAlias.c_str(),
3491 getNextRunNumber(activeStateMachineName_) - 1);
3493 if(RunControlStateMachine::asyncSoftFailureReceived_)
3497 xmlOut.addTextElementToData(
3498 "soft_error", RunControlStateMachine::getErrorMessage());
3503 "Next %s Number: %u",
3504 stateMachineRunAlias.c_str(),
3505 getNextRunNumber(fsmName));
3506 xmlOut.addTextElementToData(
"run_number", tmp);
3509 else if(requestType ==
"cancelStateMachineTransition")
3511 __SS__ <<
"State transition was cancelled by user!" << __E__;
3512 __MCOUT__(ss.str());
3513 RunControlStateMachine::theStateMachine_.setErrorMessage(ss.str());
3514 RunControlStateMachine::asyncFailureReceived_ =
true;
3516 else if(requestType ==
"getErrorInStateMatchine")
3518 xmlOut.addTextElementToData(
"FSM_Error", theStateMachine_.getErrorMessage());
3520 else if(requestType ==
"getDesktopIcons")
3527 CorePropertySupervisorBase::theConfigurationManager_->__GET_CONFIG__(
3529 std::vector<DesktopIconTable::DesktopIcon> icons =
3530 iconTable->getAllDesktopIcons();
3532 std::string iconString =
"";
3547 std::map<std::string, WebUsers::permissionLevel_t> userPermissionLevelsMap =
3548 theWebUsers_.getPermissionsForUser(userInfo.uid_);
3549 std::map<std::string, WebUsers::permissionLevel_t>
3550 iconPermissionThresholdsMap;
3552 bool firstIcon =
true;
3553 for(
const auto& icon : icons)
3555 __COUTV__(icon.caption_);
3556 __COUTV__(icon.permissionThresholdString_);
3558 CorePropertySupervisorBase::extractPermissionsMapFromString(
3559 icon.permissionThresholdString_, iconPermissionThresholdsMap);
3561 if(!CorePropertySupervisorBase::doPermissionsGrantAccess(
3562 userPermissionLevelsMap, iconPermissionThresholdsMap))
3573 iconString += icon.caption_;
3574 iconString +=
"," + icon.alternateText_;
3576 "," + std::string(icon.enforceOneWindowInstance_ ?
"1" :
"0");
3578 "," + std::string(
"1");
3582 iconString +=
"," + icon.imageURL_;
3583 iconString +=
"," + icon.windowContentURL_;
3584 iconString +=
"," + icon.folderPath_;
3586 __COUTV__(iconString);
3588 xmlOut.addTextElementToData(
"iconList", iconString);
3590 else if(requestType ==
"addDesktopIcon")
3592 GatewaySupervisor::handleAddDesktopIconRequest(
3593 theWebUsers_.getUsersUsername(userInfo.uid_), cgiIn, xmlOut);
3595 else if(requestType ==
"gatewayLaunchOTS" || requestType ==
"gatewayLaunchWiz")
3600 __COUT_WARN__ << requestType <<
" requestType received! " << __E__;
3601 __MOUT_WARN__ << requestType <<
" requestType received! " << __E__;
3604 theWebUsers_.saveActiveSessions();
3608 if(requestType ==
"gatewayLaunchOTS")
3609 GatewaySupervisor::launchStartOTSCommand(
3610 "LAUNCH_OTS", CorePropertySupervisorBase::theConfigurationManager_);
3611 else if(requestType ==
"gatewayLaunchWiz")
3612 GatewaySupervisor::launchStartOTSCommand(
3613 "LAUNCH_WIZ", CorePropertySupervisorBase::theConfigurationManager_);
3615 else if(requestType ==
"resetUserTooltips")
3617 WebUsers::resetAllUserTooltips(theWebUsers_.getUsersUsername(userInfo.uid_));
3619 else if(requestType ==
"silenceUserTooltips")
3621 WebUsers::silenceAllUserTooltips(
3622 theWebUsers_.getUsersUsername(userInfo.uid_));
3626 __SS__ <<
"requestType Request, " << requestType <<
", not recognized."
3631 catch(
const std::runtime_error& e)
3633 __SS__ <<
"An error was encountered handling requestType '" << requestType
3634 <<
"':" << e.what() << __E__;
3635 __COUT__ <<
"\n" << ss.str();
3636 xmlOut.addTextElementToData(
"Error", ss.str());
3640 __SS__ <<
"An unknown error was encountered handling requestType '" << requestType
3642 <<
"Please check the printouts to debug." << __E__;
3643 __COUT__ <<
"\n" << ss.str();
3644 xmlOut.addTextElementToData(
"Error", ss.str());
3648 xmlOut.outputXmlDocument(
3649 (std::ostringstream*)out,
3660 void GatewaySupervisor::launchStartOTSCommand(
const std::string& command,
3663 __COUT__ <<
"launch StartOTS Command = " << command << __E__;
3664 __COUT__ <<
"Extracting target context hostnames... " << __E__;
3666 std::vector<std::string> hostnames;
3673 auto contexts = contextTable->getContexts();
3675 for(
const auto& context : contexts)
3677 if(!context.status_)
3682 for(i = 0; i < context.address_.size(); ++i)
3683 if(context.address_[i] ==
'/')
3685 hostnames.push_back(context.address_.substr(j));
3686 __COUT__ <<
"StartOTS.sh hostname = " << hostnames.back() << __E__;
3691 __SS__ <<
"\nRelaunch of otsdaq interrupted! "
3692 <<
"The Configuration Manager could not be initialized." << __E__;
3697 for(
const auto& hostname : hostnames)
3699 std::string fn = (std::string(__ENV__(
"SERVICE_DATA_PATH")) +
3700 "/StartOTS_action_" + hostname +
".cmd");
3701 FILE* fp = fopen(fn.c_str(),
"w");
3704 fprintf(fp, command.c_str());
3709 __SS__ <<
"Unable to open command file: " << fn << __E__;
3717 for(
const auto& hostname : hostnames)
3719 std::string fn = (std::string(__ENV__(
"SERVICE_DATA_PATH")) +
3720 "/StartOTS_action_" + hostname +
".cmd");
3721 FILE* fp = fopen(fn.c_str(),
"r");
3725 fgets(line, 100, fp);
3728 if(strcmp(line, command.c_str()) == 0)
3730 __SS__ <<
"The command looks to have been ignored by " << hostname
3731 <<
". Is StartOTS.sh still running on that node?" << __E__;
3738 __SS__ <<
"Unable to open command file for verification: " << fn << __E__;
3747 xoap::MessageReference GatewaySupervisor::supervisorCookieCheck(
3748 xoap::MessageReference message)
3755 parameters.addParameter(
"CookieCode");
3756 parameters.addParameter(
"RefreshOption");
3757 parameters.addParameter(
"IPAddress");
3758 SOAPUtilities::receive(message, parameters);
3759 std::string cookieCode = parameters.getValue(
"CookieCode");
3760 std::string refreshOption =
3761 parameters.getValue(
"RefreshOption");
3763 std::string ipAddress =
3764 parameters.getValue(
"IPAddress");
3770 std::map<std::string , WebUsers::permissionLevel_t>
3771 userGroupPermissionsMap;
3772 std::string userWithLock =
"";
3773 uint64_t activeSessionIndex, uid;
3774 theWebUsers_.cookieCodeIsActiveForRequest(cookieCode,
3775 &userGroupPermissionsMap,
3778 refreshOption ==
"1",
3780 &activeSessionIndex);
3786 retParameters.addParameter(
"CookieCode", cookieCode);
3787 retParameters.addParameter(
3788 "Permissions", StringMacros::mapToString(userGroupPermissionsMap).c_str());
3789 retParameters.addParameter(
"UserWithLock", userWithLock);
3790 retParameters.addParameter(
"Username", theWebUsers_.getUsersUsername(uid));
3791 retParameters.addParameter(
"DisplayName", theWebUsers_.getUsersDisplayName(uid));
3792 sprintf(tmpStringForConversions_,
"%lu", activeSessionIndex);
3793 retParameters.addParameter(
"ActiveSessionIndex", tmpStringForConversions_);
3797 return SOAPUtilities::makeSOAPMessageReference(
"CookieResponse", retParameters);
3803 xoap::MessageReference GatewaySupervisor::supervisorGetActiveUsers(
3804 xoap::MessageReference message)
3809 SOAPParameters parameters(
"UserList", theWebUsers_.getActiveUsersString());
3810 return SOAPUtilities::makeSOAPMessageReference(
"ActiveUserResponse", parameters);
3817 xoap::MessageReference GatewaySupervisor::supervisorSystemMessage(
3818 xoap::MessageReference message)
3822 parameters.addParameter(
"ToUser");
3823 parameters.addParameter(
"Message");
3824 SOAPUtilities::receive(message, parameters);
3826 __COUT__ <<
"toUser: " << parameters.getValue(
"ToUser").substr(0, 10)
3827 <<
", message: " << parameters.getValue(
"Message").substr(0, 10) << __E__;
3829 theSystemMessenger_.addSystemMessage(parameters.getValue(
"ToUser"),
3830 parameters.getValue(
"Message"));
3831 return SOAPUtilities::makeSOAPMessageReference(
"SystemMessageResponse");
3838 xoap::MessageReference GatewaySupervisor::supervisorSystemLogbookEntry(
3839 xoap::MessageReference message)
3843 parameters.addParameter(
"EntryText");
3844 SOAPUtilities::receive(message, parameters);
3846 __COUT__ <<
"EntryText: " << parameters.getValue(
"EntryText").substr(0, 10) << __E__;
3848 makeSystemLogbookEntry(parameters.getValue(
"EntryText"));
3850 return SOAPUtilities::makeSOAPMessageReference(
"SystemLogbookResponse");
3858 xoap::MessageReference GatewaySupervisor::supervisorLastConfigGroupRequest(
3859 xoap::MessageReference message)
3863 parameters.addParameter(
"ActionOfLastGroup");
3864 SOAPUtilities::receive(message, parameters);
3866 return GatewaySupervisor::lastConfigGroupRequestHandler(parameters);
3875 xoap::MessageReference GatewaySupervisor::lastConfigGroupRequestHandler(
3878 std::string action = parameters.getValue(
"ActionOfLastGroup");
3879 __COUT__ <<
"ActionOfLastGroup: " << action.substr(0, 10) << __E__;
3881 std::string fileName =
"";
3882 if(action ==
"Configured")
3883 fileName = FSM_LAST_CONFIGURED_GROUP_ALIAS_FILE;
3884 else if(action ==
"Started")
3885 fileName = FSM_LAST_STARTED_GROUP_ALIAS_FILE;
3888 __COUT_ERR__ <<
"Invalid last group action requested." << __E__;
3889 return SOAPUtilities::makeSOAPMessageReference(
"LastConfigGroupResponseFailure");
3891 std::string timeString;
3893 loadGroupNameAndKey(fileName, timeString);
3897 retParameters.addParameter(
"GroupName", theGroup.first);
3898 retParameters.addParameter(
"GroupKey", theGroup.second.toString());
3899 retParameters.addParameter(
"GroupAction", action);
3900 retParameters.addParameter(
"GroupActionTime", timeString);
3902 return SOAPUtilities::makeSOAPMessageReference(
"LastConfigGroupResponse",
3913 unsigned int GatewaySupervisor::getNextRunNumber(
const std::string& fsmNameIn)
3915 std::string runNumberFileName = RUN_NUMBER_PATH +
"/";
3916 std::string fsmName = fsmNameIn ==
"" ? activeStateMachineName_ : fsmNameIn;
3918 for(
unsigned int i = 0; i < fsmName.size(); ++i)
3919 if((fsmName[i] >=
'a' && fsmName[i] <=
'z') ||
3920 (fsmName[i] >=
'A' && fsmName[i] <=
'Z') ||
3921 (fsmName[i] >=
'0' && fsmName[i] <=
'9'))
3922 runNumberFileName += fsmName[i];
3923 runNumberFileName += RUN_NUMBER_FILE_NAME;
3926 std::ifstream runNumberFile(runNumberFileName.c_str());
3927 if(!runNumberFile.is_open())
3929 __COUT__ <<
"Can't open file: " << runNumberFileName << __E__;
3931 __COUT__ <<
"Creating file and setting Run Number to 1: " << runNumberFileName
3933 FILE* fp = fopen(runNumberFileName.c_str(),
"w");
3937 runNumberFile.open(runNumberFileName.c_str());
3938 if(!runNumberFile.is_open())
3940 __SS__ <<
"Error. Can't create file: " << runNumberFileName << __E__;
3941 __COUT_ERR__ << ss.str();
3945 std::string runNumberString;
3946 runNumberFile >> runNumberString;
3947 runNumberFile.close();
3948 return atoi(runNumberString.c_str());
3952 bool GatewaySupervisor::setNextRunNumber(
unsigned int runNumber,
3953 const std::string& fsmNameIn)
3955 std::string runNumberFileName = RUN_NUMBER_PATH +
"/";
3956 std::string fsmName = fsmNameIn ==
"" ? activeStateMachineName_ : fsmNameIn;
3958 for(
unsigned int i = 0; i < fsmName.size(); ++i)
3959 if((fsmName[i] >=
'a' && fsmName[i] <=
'z') ||
3960 (fsmName[i] >=
'A' && fsmName[i] <=
'Z') ||
3961 (fsmName[i] >=
'0' && fsmName[i] <=
'9'))
3962 runNumberFileName += fsmName[i];
3963 runNumberFileName += RUN_NUMBER_FILE_NAME;
3964 __COUT__ <<
"runNumberFileName: " << runNumberFileName << __E__;
3966 std::ofstream runNumberFile(runNumberFileName.c_str());
3967 if(!runNumberFile.is_open())
3969 __SS__ <<
"Can't open file: " << runNumberFileName << __E__;
3970 __COUT__ << ss.str();
3973 std::stringstream runNumberStream;
3974 runNumberStream << runNumber;
3975 runNumberFile << runNumberStream.str().c_str();
3976 runNumberFile.close();
3987 GatewaySupervisor::loadGroupNameAndKey(
const std::string& fileName,
3988 std::string& returnedTimeString)
3990 std::string fullPath = FSM_LAST_GROUP_ALIAS_PATH +
"/" + fileName;
3992 FILE* groupFile = fopen(fullPath.c_str(),
"r");
3995 __COUT__ <<
"Can't open file: " << fullPath << __E__;
3997 __COUT__ <<
"Returning empty groupName and key -1" << __E__;
3999 return std::pair<std::string ,
TableGroupKey>(
"", TableGroupKey());
4006 fgets(line, 500, groupFile);
4007 theGroup.first = line;
4009 fgets(line, 500, groupFile);
4011 sscanf(line,
"%d", &key);
4012 theGroup.second = key;
4014 fgets(line, 500, groupFile);
4016 sscanf(line,
"%ld", ×tamp);
4020 returnedTimeString = StringMacros::getTimestampString(timestamp);
4023 __COUT__ <<
"theGroup.first= " << theGroup.first
4024 <<
" theGroup.second= " << theGroup.second << __E__;
4030 void GatewaySupervisor::saveGroupNameAndKey(
4031 const std::pair<std::string /*group name*/, TableGroupKey>& theGroup,
4032 const std::string& fileName)
4034 std::string fullPath = FSM_LAST_GROUP_ALIAS_PATH +
"/" + fileName;
4036 std::ofstream groupFile(fullPath.c_str());
4037 if(!groupFile.is_open())
4039 __SS__ <<
"Error. Can't open file: " << fullPath << __E__;
4040 __COUT_ERR__ <<
"\n" << ss.str();
4043 std::stringstream outss;
4044 outss << theGroup.first <<
"\n" << theGroup.second <<
"\n" << time(0);
4045 groupFile << outss.str().c_str();
4050 void GatewaySupervisor::handleAddDesktopIconRequest(
const std::string& author,
4051 cgicc::Cgicc& cgiIn,
4054 std::string iconCaption =
4055 CgiDataUtilities::getData(cgiIn,
"iconCaption");
4056 std::string iconAltText =
4057 CgiDataUtilities::getData(cgiIn,
"iconAltText");
4058 std::string iconFolderPath =
4059 CgiDataUtilities::getData(cgiIn,
"iconFolderPath");
4060 std::string iconImageURL =
4061 CgiDataUtilities::getData(cgiIn,
"iconImageURL");
4062 std::string iconWindowURL =
4063 CgiDataUtilities::getData(cgiIn,
"iconWindowURL");
4064 std::string iconPermissions =
4065 CgiDataUtilities::getData(cgiIn,
"iconPermissions");
4066 std::string windowLinkedApp =
4067 CgiDataUtilities::getData(cgiIn,
"iconLinkedApp");
4068 unsigned int windowLinkedAppLID =
4069 CgiDataUtilities::getDataAsInt(cgiIn,
"iconLinkedAppLID");
4070 bool enforceOneWindowInstance =
4071 CgiDataUtilities::getData(cgiIn,
"iconEnforceOneWindowInstance") ==
"1"
4075 std::string windowParameters = StringMacros::decodeURIComponent(
4076 CgiDataUtilities::postData(cgiIn,
"iconParameters"));
4079 __COUTV__(iconCaption);
4080 __COUTV__(iconAltText);
4081 __COUTV__(iconFolderPath);
4082 __COUTV__(iconImageURL);
4083 __COUTV__(iconWindowURL);
4084 __COUTV__(iconPermissions);
4085 __COUTV__(windowLinkedApp);
4086 __COUTV__(windowLinkedAppLID);
4087 __COUTV__(enforceOneWindowInstance);
4089 __COUTV__(windowParameters);
4093 ConfigurationSupervisorBase::handleAddDesktopIconXML(
4103 windowLinkedAppLID ,
4104 enforceOneWindowInstance ,