1 #include "otsdaq-core/GatewaySupervisor/GatewaySupervisor.h"
2 #include "otsdaq-core/MessageFacility/MessageFacility.h"
3 #include "otsdaq-core/Macros/CoutHeaderMacros.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"
15 #include "otsdaq-core/NetworkUtilities/TransceiverSocket.h"
19 #include <cgicc/HTMLClasses.h>
20 #include <cgicc/HTTPCookie.h>
21 #include <cgicc/HTMLDoctype.h>
22 #include <cgicc/HTTPHeader.h>
23 #include <xgi/Utils.h>
25 #include <xoap/Method.h>
26 #include <xdaq/NamespaceURI.h>
27 #include <toolbox/task/WorkLoopFactory.h>
28 #include <toolbox/fsm/FailedEvent.h>
38 #define ICON_FILE_NAME std::string(getenv("SERVICE_DATA_PATH")) + "/OtsWizardData/iconList.dat"
39 #define RUN_NUMBER_PATH std::string(getenv("SERVICE_DATA_PATH")) + "/RunNumber/"
40 #define RUN_NUMBER_FILE_NAME "NextRunNumber.txt"
41 #define FSM_LAST_GROUP_ALIAS_PATH std::string(getenv("SERVICE_DATA_PATH")) + "/RunControlData/"
42 #define FSM_LAST_GROUP_ALIAS_FILE_START std::string("FSMLastGroupAlias-")
43 #define FSM_USERS_PREFERENCES_FILETYPE "pref"
45 #define CORE_TABLE_INFO_FILENAME ((getenv("SERVICE_DATA_PATH") == NULL)?(std::string(getenv("USER_DATA"))+"/ServiceData"):(std::string(getenv("SERVICE_DATA_PATH")))) + "/CoreTableInfoNames.dat"
48 #define __MF_SUBJECT__ "GatewaySupervisor"
56 :xdaq::Application (s)
61 ,stateMachineWorkLoopManager_ (toolbox::task::bind(this, &GatewaySupervisor::stateMachineThread,"StateMachine"))
62 ,stateMachineSemaphore_ (toolbox::BSem::FULL)
63 ,infoRequestWorkLoopManager_ (toolbox::task::bind(this, &GatewaySupervisor::infoRequestThread, "InfoRequest"))
64 ,infoRequestSemaphore_ (toolbox::BSem::FULL)
65 ,activeStateMachineName_ ("")
69 INIT_MF(
"GatewaySupervisor");
70 __COUT__ << std::endl;
73 mkdir((FSM_LAST_GROUP_ALIAS_PATH).c_str(), 0755);
74 mkdir((RUN_NUMBER_PATH).c_str(), 0755);
76 securityType_ = theWebUsers_.getSecurity();
78 __COUT__ <<
"Security: " << securityType_ << std::endl;
80 xgi::bind(
this, &GatewaySupervisor::Default,
"Default");
81 xgi::bind(
this, &GatewaySupervisor::loginRequest,
"LoginRequest");
82 xgi::bind(
this, &GatewaySupervisor::request,
"Request");
83 xgi::bind(
this, &GatewaySupervisor::stateMachineXgiHandler,
"StateMachineXgiHandler");
84 xgi::bind(
this, &GatewaySupervisor::infoRequestHandler,
"InfoRequestHandler");
85 xgi::bind(
this, &GatewaySupervisor::infoRequestResultHandler,
"InfoRequestResultHandler");
86 xgi::bind(
this, &GatewaySupervisor::tooltipRequest,
"TooltipRequest");
88 xoap::bind(
this, &GatewaySupervisor::supervisorCookieCheck,
"SupervisorCookieCheck", XDAQ_NS_URI);
89 xoap::bind(
this, &GatewaySupervisor::supervisorGetActiveUsers,
"SupervisorGetActiveUsers", XDAQ_NS_URI);
90 xoap::bind(
this, &GatewaySupervisor::supervisorSystemMessage,
"SupervisorSystemMessage", XDAQ_NS_URI);
91 xoap::bind(
this, &GatewaySupervisor::supervisorGetUserInfo,
"SupervisorGetUserInfo", XDAQ_NS_URI);
92 xoap::bind(
this, &GatewaySupervisor::supervisorSystemLogbookEntry,
"SupervisorSystemLogbookEntry", XDAQ_NS_URI);
93 xoap::bind(
this, &GatewaySupervisor::supervisorLastConfigGroupRequest,
"SupervisorLastConfigGroupRequest", XDAQ_NS_URI);
106 GatewaySupervisor::~GatewaySupervisor(
void)
108 delete theConfigurationManager_;
109 makeSystemLogbookEntry(
"ots halted.");
113 void GatewaySupervisor::init(
void)
116 allSupervisorInfo_.init(getApplicationContext());
118 supervisorGuiHasBeenLoaded_ =
false;
122 supervisorContextUID_ = contextConfiguration->getContextUID(
123 getApplicationContext()->getContextDescriptor()->getURL()
125 __COUT__ <<
"Context UID:" << supervisorContextUID_ << std::endl;
127 supervisorApplicationUID_ = contextConfiguration->getApplicationUID(
128 getApplicationContext()->getContextDescriptor()->getURL(),
129 getApplicationDescriptor()->getLocalId()
132 __COUT__ <<
"Application UID:" << supervisorApplicationUID_ << std::endl;
134 ConfigurationTree configLinkNode = theConfigurationManager_->getSupervisorConfigurationNode(
135 supervisorContextUID_, supervisorApplicationUID_);
137 std::string supervisorUID;
138 if(!configLinkNode.isDisconnected())
139 supervisorUID = configLinkNode.getValue();
141 supervisorUID = ViewColumnInfo::DATATYPE_LINK_DEFAULT;
143 __COUT__ <<
"GatewaySupervisor UID:" << supervisorUID << std::endl;
148 bool enableStateChanges =
false;
152 configLinkNode.getNode(
"EnableStateChangesOverUDP").getValue<
bool>();
157 if(enableStateChanges)
159 __COUT__ <<
"Enabling state changes over UDP..." << __E__;
161 std::thread([](GatewaySupervisor *s){ GatewaySupervisor::StateChangerWorkLoop(s); },
this).detach();
164 __COUT__ <<
"State changes over UDP are disabled." << __E__;
172 const std::set<std::string>& contextMemberNames = theConfigurationManager_->getContextMemberNames();
173 const std::set<std::string>& backboneMemberNames = theConfigurationManager_->getBackboneMemberNames();
174 const std::set<std::string>& iterateMemberNames = theConfigurationManager_->getIterateMemberNames();
176 FILE * fp = fopen((CORE_TABLE_INFO_FILENAME).c_str(),
"r");
178 __COUT__ <<
"Updating core tables table..." << __E__;
182 std::vector<unsigned int> foundVector;
184 for(
const auto &name:contextMemberNames)
186 foundVector.push_back(
false);
188 while(fgets(line,100,fp))
190 if(strlen(line) < 1)
continue;
191 line[strlen(line)-1] =
'\0';
192 if(strcmp(line,name.c_str()) == 0)
194 foundVector.back() =
true;
201 for(
const auto &name:backboneMemberNames)
203 foundVector.push_back(
false);
205 while(fgets(line,100,fp))
207 if(strlen(line) < 1)
continue;
208 line[strlen(line)-1] =
'\0';
209 if(strcmp(line,name.c_str()) == 0)
211 foundVector.back() =
true;
218 for(
const auto &name:iterateMemberNames)
220 foundVector.push_back(
false);
222 while(fgets(line,100,fp))
224 if(strlen(line) < 1)
continue;
225 line[strlen(line)-1] =
'\0';
226 if(strcmp(line,name.c_str()) == 0)
228 foundVector.back() =
true;
242 fp = fopen((CORE_TABLE_INFO_FILENAME).c_str(),
"a");
246 for(
const auto &name:contextMemberNames)
249 fprintf(fp,
"%s\n",name.c_str());
253 for(
const auto &name:backboneMemberNames)
256 fprintf(fp,
"%s\n",name.c_str());
260 for(
const auto &name:iterateMemberNames)
263 fprintf(fp,
"%s\n",name.c_str());
271 __SS__ <<
"Failed to open core table info file for appending: " << CORE_TABLE_INFO_FILENAME << std::endl;
278 fp = fopen((CORE_TABLE_INFO_FILENAME).c_str(),
"w");
281 for(
const auto &name:contextMemberNames)
282 fprintf(fp,
"%s\n",name.c_str());
283 for(
const auto &name:backboneMemberNames)
284 fprintf(fp,
"%s\n",name.c_str());
285 for(
const auto &name:iterateMemberNames)
286 fprintf(fp,
"%s\n",name.c_str());
291 __SS__ <<
"Failed to open core table info file: " << CORE_TABLE_INFO_FILENAME << std::endl;
302 void GatewaySupervisor::StateChangerWorkLoop(GatewaySupervisor *theSupervisor)
304 ConfigurationTree configLinkNode = theSupervisor->theConfigurationManager_->getSupervisorConfigurationNode(
305 theSupervisor->supervisorContextUID_, theSupervisor->supervisorApplicationUID_);
308 std::string myip = configLinkNode.getNode(
"IPAddressForStateChangesOverUDP").getValue<std::string>();
309 int myport = configLinkNode.getNode(
"PortForStateChangesOverUDP").getValue<
int>();
310 bool ackEnabled = configLinkNode.getNode(
"EnableAckForStateChangesOverUDP").getValue<
bool>();
312 __COUT__ <<
"ip = " << myip << __E__;
313 __COUT__ <<
"port = " << myport << __E__;
314 __COUT__ <<
"ackEnabled = " << ackEnabled << __E__;
325 __SS__ <<
"FATAL Console error. Could not initialize socket at ip '" << myip <<
327 myport <<
". Perhaps it is already in use? Exiting State Changer receive loop." << std::endl;
328 __COUT__ << ss.str();
329 throw std::runtime_error(ss.str());
333 unsigned int i,firsti;
335 std::string errorStr;
336 std::string command, fsmName;
337 std::vector<std::string> parameters;
347 if(sock.receive(buffer,0 ,1,
350 __COUT__ <<
"UDP State Changer received size = " << buffer.size() << __E__;
352 command =
"", fsmName =
"";
356 for(firsti=0,i=0;i<buffer.size();++i)
362 command = buffer.substr(firsti,i-firsti);
363 __COUT__ <<
"command = " << command << __E__;
365 else if(fsmName ==
"")
367 fsmName = buffer.substr(firsti,i-firsti);
368 __COUT__ <<
"fsmName = " << fsmName << __E__;
372 parameters.push_back(buffer.substr(firsti,i-firsti));
374 __COUT__ <<
"parameter[" << parameters.size()-1 <<
375 "] = " << command << __E__;
386 if(theSupervisor->VERBOSE_MUTEX) __COUT__ <<
"Waiting for FSM access" << __E__;
387 std::lock_guard<std::mutex> lock(theSupervisor->stateMachineAccessMutex_);
388 if(theSupervisor->VERBOSE_MUTEX) __COUT__ <<
"Have FSM access" << __E__;
390 errorStr = theSupervisor->attemptStateMachineTransition(
393 WebUsers::DEFAULT_STATECHANGER_USERNAME ,
394 WebUsers::DEFAULT_STATECHANGER_USERNAME,
400 __SS__ <<
"UDP State Changer failed to execute command because of the following error: " << errorStr;
401 __COUT_ERR__ << ss.str();
402 __MOUT_ERR__ << ss.str();
403 if(ackEnabled) sock.acknowledge(errorStr,
true );
407 __SS__ <<
"Successfully executed state change command '" << command <<
".'" << __E__;
408 __COUT_INFO__ << ss.str();
409 __MOUT_INFO__ << ss.str();
410 if(ackEnabled) sock.acknowledge(
"Done",
true );
424 void GatewaySupervisor::makeSystemLogbookEntry(std::string entryText)
426 __COUT__ <<
"Making System Logbook Entry: " << entryText << std::endl;
428 SupervisorInfoMap logbookInfoMap = allSupervisorInfo_.getAllLogbookTypeSupervisorInfo();
430 if(logbookInfoMap.size() == 0)
432 __COUT__ <<
"No logbooks found! Here is entry: " << entryText << std::endl;
433 __MOUT__ <<
"No logbooks found! Here is entry: " << entryText << std::endl;
438 __COUT__ <<
"Making logbook entry: " << entryText << std::endl;
439 __MOUT__ <<
"Making logbook entry: " << entryText << std::endl;
445 std::string replace[] =
446 {
"\"",
"'",
"&",
"<",
">",
"\n",
" "};
448 {
"%22",
"%27",
"%26",
"%3C",
"%3E",
"%0A%0D",
"%20%20"};
453 for(
int i=0;i<numOfKeys;++i)
455 while((f=entryText.find(replace[i])) != std::string::npos)
457 entryText = entryText.substr(0,f) + with[i] +
458 entryText.substr(f+replace[i].length());
469 for(
auto& logbookInfo: logbookInfoMap)
471 xoap::MessageReference retMsg = SOAPMessenger::sendWithSOAPReply(
472 logbookInfo.second.getDescriptor(),
473 "MakeSystemLogbookEntry",parameters);
478 receive(retMsg, retParameters);
480 __COUT__ <<
"Returned Status: " << retParameters.getValue(
"Status") << std::endl;
486 void GatewaySupervisor::Default(xgi::Input* in, xgi::Output* out)
487 throw (xgi::exception::Exception)
490 if (!supervisorGuiHasBeenLoaded_ && (supervisorGuiHasBeenLoaded_ =
true))
491 makeSystemLogbookEntry(
"ots started.");
494 "<!DOCTYPE HTML><html lang='en'><head><title>ots</title>" <<
497 "<link rel='apple-touch-icon' sizes='57x57' href='/WebPath/images/otsdaqIcons/apple-icon-57x57.png'>\
498 <link rel='apple-touch-icon' sizes='60x60' href='/WebPath/images/otsdaqIcons/apple-icon-60x60.png'>\
499 <link rel='apple-touch-icon' sizes='72x72' href='/WebPath/images/otsdaqIcons/apple-icon-72x72.png'>\
500 <link rel='apple-touch-icon' sizes='76x76' href='/WebPath/images/otsdaqIcons/apple-icon-76x76.png'>\
501 <link rel='apple-touch-icon' sizes='114x114' href='/WebPath/images/otsdaqIcons/apple-icon-114x114.png'>\
502 <link rel='apple-touch-icon' sizes='120x120' href='/WebPath/images/otsdaqIcons/apple-icon-120x120.png'>\
503 <link rel='apple-touch-icon' sizes='144x144' href='/WebPath/images/otsdaqIcons/apple-icon-144x144.png'>\
504 <link rel='apple-touch-icon' sizes='152x152' href='/WebPath/images/otsdaqIcons/apple-icon-152x152.png'>\
505 <link rel='apple-touch-icon' sizes='180x180' href='/WebPath/images/otsdaqIcons/apple-icon-180x180.png'>\
506 <link rel='icon' type='image/png' sizes='192x192' href='/WebPath/images/otsdaqIcons/android-icon-192x192.png'>\
507 <link rel='icon' type='image/png' sizes='32x32' href='/WebPath/images/otsdaqIcons/favicon-32x32.png'>\
508 <link rel='icon' type='image/png' sizes='96x96' href='/WebPath/images/otsdaqIcons/favicon-96x96.png'>\
509 <link rel='icon' type='image/png' sizes='16x16' href='/WebPath/images/otsdaqIcons/favicon-16x16.png'>\
510 <link rel='manifest' href='/WebPath/images/otsdaqIcons/manifest.json'>\
511 <meta name='msapplication-TileColor' content='#ffffff'>\
512 <meta name='msapplication-TileImage' content='/ms-icon-144x144.png'>\
513 <meta name='theme-color' content='#ffffff'>" <<
516 "<frameset col='100%' row='100%'>" <<
517 "<frame src='/WebPath/html/Desktop.html?urn=" <<
518 this->getApplicationDescriptor()->getLocalId() <<
"=securityType=" <<
519 securityType_ <<
"'></frameset></html>";
525 void GatewaySupervisor::stateMachineXgiHandler(xgi::Input* in, xgi::Output* out)
526 throw (xgi::exception::Exception)
529 if(VERBOSE_MUTEX) __COUT__ <<
"Waiting for FSM access" << std::endl;
530 std::lock_guard<std::mutex> lock(stateMachineAccessMutex_);
531 if(VERBOSE_MUTEX) __COUT__ <<
"Have FSM access" << std::endl;
533 cgicc::Cgicc cgi(in);
535 uint8_t userPermissions;
537 std::string userWithLock;
538 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
539 if (!theWebUsers_.cookieCodeIsActiveForRequest(cookieCode, &userPermissions,
540 &uid,
"0", 1, &userWithLock))
546 std::string command = CgiDataUtilities::getData(cgi,
"StateMachine");
549 std::string username =
"";
550 username = theWebUsers_.getUsersUsername(uid);
551 if (userWithLock !=
"" && userWithLock != username)
553 *out << WebUsers::REQ_USER_LOCKOUT_RESPONSE;
554 __COUT__ <<
"User " << username <<
" is locked out. " << userWithLock <<
" has lock." << std::endl;
560 std::string fsmName = CgiDataUtilities::getData(cgi,
"fsmName");
561 std::string fsmWindowName = CgiDataUtilities::getData(cgi,
"fsmWindowName");
562 fsmWindowName = CgiDataUtilities::decodeURIComponent(fsmWindowName);
563 std::string currentState = theStateMachine_.getCurrentStateName();
565 __COUT__ <<
"Check for Handled by theIterator_" << std::endl;
568 if((activeStateMachineWindowName_ ==
"" ||
569 activeStateMachineWindowName_ ==
"iterator") &&
570 theIterator_.handleCommandRequest(xmldoc,command,fsmWindowName))
572 __COUT__ <<
"Handled by theIterator_" << std::endl;
573 xmldoc.outputXmlDocument((std::ostringstream*) out,
false);
578 if (theStateMachine_.isInTransition())
580 __SS__ <<
"Error - Can not accept request because the State Machine is already in transition!" << std::endl;
581 __COUT_ERR__ <<
"\n" << ss.str();
583 xmldoc.addTextElementToData(
"state_tranisition_attempted",
"0");
584 xmldoc.addTextElementToData(
"state_tranisition_attempted_err",
586 xmldoc.outputXmlDocument((std::ostringstream*) out,
false,
true);
598 if(activeStateMachineName_ !=
"" &&
599 activeStateMachineName_ != fsmName)
601 __COUT__ <<
"currentState = " <<
602 currentState << std::endl;
603 if(currentState !=
"Halted" &&
604 currentState !=
"Initial")
608 __SS__ <<
"Error - Can not accept request because the State Machine " <<
609 "with window name '" <<
610 activeStateMachineWindowName_ <<
"' (UID: " <<
611 activeStateMachineName_ <<
") "
613 "in control of State Machine progress. ";
614 ss <<
"\n\nIn order for this State Machine with window name '" <<
615 fsmWindowName <<
"' (UID: " << fsmName <<
") "
616 "to control progress, please transition to Halted using the active " <<
617 "State Machine '" << activeStateMachineWindowName_ <<
".'" << std::endl;
618 __COUT_ERR__ <<
"\n" << ss.str();
620 xmldoc.addTextElementToData(
"state_tranisition_attempted",
"0");
621 xmldoc.addTextElementToData(
"state_tranisition_attempted_err",
623 xmldoc.outputXmlDocument((std::ostringstream*) out,
false,
true);
628 activeStateMachineName_ =
"";
629 activeStateMachineWindowName_ =
"";
638 std::vector<std::string> parameters;
639 if(command ==
"Configure")
640 parameters.push_back(CgiDataUtilities::postData(cgi,
"ConfigurationAlias"));
641 attemptStateMachineTransition(&xmldoc,out,command,fsmName,fsmWindowName,
642 username,parameters);
645 std::string GatewaySupervisor::attemptStateMachineTransition(
647 const std::string& command,
648 const std::string& fsmName,
const std::string& fsmWindowName,
649 const std::string& username,
650 const std::vector<std::string>& commandParameters)
652 std::string errorStr =
"";
654 std::string currentState = theStateMachine_.getCurrentStateName();
655 __COUT__ <<
"State Machine command = " << command << std::endl;
656 __COUT__ <<
"fsmName = " << fsmName << std::endl;
657 __COUT__ <<
"fsmWindowName = " << fsmWindowName << std::endl;
658 __COUT__ <<
"activeStateMachineName_ = " << activeStateMachineName_ << std::endl;
661 if (command ==
"Configure")
663 if(currentState !=
"Halted")
665 __SS__ <<
"Error - Can only transition to Configured if the current " <<
666 "state is Halted. Perhaps your state machine is out of sync." <<
668 __COUT_ERR__ <<
"\n" << ss.str();
671 if(xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted",
"0");
672 if(xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted_err",
674 if(out) xmldoc->outputXmlDocument((std::ostringstream*) out,
false,
true);
681 if(!commandParameters.size())
683 __SS__ <<
"Error - Can only transition to Configured if a Configuration Alias parameter is provided." <<
685 __COUT_ERR__ <<
"\n" << ss.str();
688 if(xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted",
"0");
689 if(xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted_err",
691 if(out) xmldoc->outputXmlDocument((std::ostringstream*) out,
false,
true);
696 parameters.addParameter(
"ConfigurationAlias",
697 commandParameters[0]);
699 std::string configurationAlias = parameters.getValue(
"ConfigurationAlias");
700 __COUT__ <<
"Configure --> Name: ConfigurationAlias Value: " <<
701 configurationAlias << std::endl;
704 std::string fn = FSM_LAST_GROUP_ALIAS_PATH + FSM_LAST_GROUP_ALIAS_FILE_START +
705 username +
"." + FSM_USERS_PREFERENCES_FILETYPE;
707 __COUT__ <<
"Save FSM preferences: " << fn << std::endl;
708 FILE *fp = fopen(fn.c_str(),
"w");
711 __SS__ << (
"Could not open file: " + fn) << std::endl;
712 __COUT_ERR__ << ss.str();
713 throw std::runtime_error(ss.str());
715 fprintf(fp,
"FSM_last_configuration_alias %s",configurationAlias.c_str());
718 activeStateMachineName_ = fsmName;
719 activeStateMachineWindowName_ = fsmWindowName;
721 else if (command ==
"Start")
723 if(currentState !=
"Configured")
725 __SS__ <<
"Error - Can only transition to Configured if the current " <<
726 "state is Halted. Perhaps your state machine is out of sync. " <<
727 "(Likely the server was restarted or another user changed the state)" <<
729 __COUT_ERR__ <<
"\n" << ss.str();
732 if(xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted",
"0");
733 if(xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted_err",
735 if(out) xmldoc->outputXmlDocument((std::ostringstream*) out,
false,
true);
740 unsigned int runNumber = getNextRunNumber();
741 parameters.addParameter(
"RunNumber", runNumber);
742 setNextRunNumber(++runNumber);
745 xoap::MessageReference message = SOAPUtilities::makeSOAPMessageReference(
746 command, parameters);
748 xoap::MessageReference reply = stateMachineXoapHandler(message);
752 if(xmldoc) xmldoc->addTextElementToData(
"state_tranisition_attempted",
"1");
753 if(out) xmldoc->outputXmlDocument((std::ostringstream*) out,
false);
754 __COUT__ <<
"FSM state transition launched!" << std::endl;
756 stateMachineLastCommandInput_ = command;
761 void GatewaySupervisor::stateMachineResultXgiHandler(xgi::Input* in, xgi::Output* out)
762 throw (xgi::exception::Exception)
764 cgicc::Cgicc cgi(in);
765 __COUT__ <<
"Xgi Request!" << std::endl;
767 uint8_t userPermissions;
768 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
769 if (!theWebUsers_.cookieCodeIsActiveForRequest(cookieCode,
778 std::string command = CgiDataUtilities::getData(cgi,
"StateMachine");
799 xoap::MessageReference message = SOAPUtilities::makeSOAPMessageReference(
800 CgiDataUtilities::getData(cgi,
"StateMachine"), parameters);
802 xoap::MessageReference reply = stateMachineResultXoapHandler(message);
806 __COUT__ <<
"Done - Xgi Request!" << std::endl;
810 xoap::MessageReference GatewaySupervisor::stateMachineXoapHandler(xoap::MessageReference message)
811 throw (xoap::exception::Exception)
813 __COUT__ <<
"Soap Handler!" << std::endl;
814 stateMachineWorkLoopManager_.removeProcessedRequests();
815 stateMachineWorkLoopManager_.processRequest(message);
816 __COUT__ <<
"Done - Soap Handler!" << std::endl;
821 xoap::MessageReference GatewaySupervisor::stateMachineResultXoapHandler(
822 xoap::MessageReference message)
823 throw (xoap::exception::Exception)
825 __COUT__ <<
"Soap Handler!" << std::endl;
828 __COUT__ <<
"Done - Soap Handler!" << std::endl;
833 bool GatewaySupervisor::stateMachineThread(toolbox::task::WorkLoop* workLoop)
835 stateMachineSemaphore_.take();
836 __COUT__ <<
"Re-sending message..." << SOAPUtilities::translate( stateMachineWorkLoopManager_.getMessage(workLoop)).getCommand() << std::endl;
837 std::string reply = send(
838 allSupervisorInfo_.getGatewayDescriptor(),
839 stateMachineWorkLoopManager_.getMessage(workLoop));
840 stateMachineWorkLoopManager_.report(workLoop, reply, 100,
true);
842 __COUT__ <<
"Done with message. Reply = " << reply << std::endl;
843 stateMachineSemaphore_.give();
847 __SS__ <<
"Failure to send Workloop transition command! Unrecognized transition name." << std::endl;
848 __COUT_ERR__ << ss.str();
849 __MOUT_ERR__ << ss.str();
860 void GatewaySupervisor::infoRequestHandler(xgi::Input* in, xgi::Output* out)
861 throw (xgi::exception::Exception)
863 __COUT__ <<
"Starting to Request!" << std::endl;
864 cgicc::Cgicc cgi(in);
869 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
870 uint8_t userPermissions;
871 if (!theWebUsers_.cookieCodeIsActiveForRequest(cookieCode, &userPermissions))
884 HttpXmlDocument tmpDoc = infoRequestWorkLoopManager_.processRequest(cgi);
886 xmldoc.copyDataChildren(tmpDoc);
888 xmldoc.outputXmlDocument((std::ostringstream*) out,
false);
892 void GatewaySupervisor::infoRequestResultHandler(xgi::Input* in, xgi::Output* out)
893 throw (xgi::exception::Exception)
895 __COUT__ <<
"Starting ask!" << std::endl;
896 cgicc::Cgicc cgi(in);
901 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
902 uint8_t userPermissions;
903 if (!theWebUsers_.cookieCodeIsActiveForRequest(cookieCode, &userPermissions))
912 infoRequestWorkLoopManager_.getRequestResult(cgi, xmldoc);
915 xmldoc.outputXmlDocument((std::ostringstream*) out,
false);
917 __COUT__ <<
"Done asking!" << std::endl;
921 bool GatewaySupervisor::infoRequestThread(toolbox::task::WorkLoop* workLoop)
926 infoRequestSemaphore_.take();
930 for (
unsigned long long i = 0; i < 100000000; i++)
933 vectorTest_.push_back(counterTest_);
936 infoRequestWorkLoopManager_.report(workLoop,
937 "RESULT: This is the best result ever", 50,
false);
938 std::string workLoopName = workLoop->getName();
939 __COUT__ << workLoopName <<
" test: " << counterTest_
940 <<
" vector size: " << vectorTest_.size() << std::endl;
941 wait(400,
"InfoRequestThread ----- locked");
942 infoRequestSemaphore_.give();
944 wait(200,
"InfoRequestThread");
946 infoRequestSemaphore_.take();
950 for (
unsigned long long i = 0; i < 100000000; i++)
953 vectorTest_.push_back(counterTest_);
956 wait(400,
"InfoRequestThread ----- locked");
957 __COUT__ << workLoopName <<
" test: " << counterTest_ <<
" vector size: " << vectorTest_.size() << std::endl;
958 infoRequestSemaphore_.give();
961 infoRequestWorkLoopManager_.report(workLoop,
962 theStateMachine_.getCurrentStateName(), 100,
true);
969 void GatewaySupervisor::stateInitial(toolbox::fsm::FiniteStateMachine & fsm)
970 throw (toolbox::fsm::exception::Exception)
972 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
978 void GatewaySupervisor::statePaused(toolbox::fsm::FiniteStateMachine & fsm)
979 throw (toolbox::fsm::exception::Exception)
981 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
997 void GatewaySupervisor::stateRunning(toolbox::fsm::FiniteStateMachine & fsm)
998 throw (toolbox::fsm::exception::Exception)
1001 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1017 void GatewaySupervisor::stateHalted(toolbox::fsm::FiniteStateMachine& fsm)
1018 throw (toolbox::fsm::exception::Exception)
1020 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1021 __COUT__ <<
"Fsm is in transition? " << (theStateMachine_.isInTransition()?
"yes":
"no") << std::endl;
1047 void GatewaySupervisor::stateConfigured(toolbox::fsm::FiniteStateMachine & fsm)
1048 throw (toolbox::fsm::exception::Exception)
1116 void GatewaySupervisor::inError(toolbox::fsm::FiniteStateMachine & fsm)
1117 throw (toolbox::fsm::exception::Exception)
1119 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1124 void GatewaySupervisor::enteringError(toolbox::Event::Reference e)
1125 throw (toolbox::fsm::exception::Exception)
1127 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1130 toolbox::fsm::FailedEvent& failedEvent =
dynamic_cast<toolbox::fsm::FailedEvent&
> (*e);
1131 __SS__ <<
"\nFailure performing transition from " << failedEvent.getFromState() <<
"-" <<
1132 theStateMachine_.getStateName(failedEvent.getFromState()) <<
1133 " to " << failedEvent.getToState() <<
"-" <<
1134 theStateMachine_.getStateName(failedEvent.getToState()) <<
1135 ".\n\nException:\n" << failedEvent.getException().what() << std::endl;
1136 __COUT_ERR__ <<
"\n" << ss.str();
1138 theStateMachine_.setErrorMessage(ss.str());
1141 broadcastMessage(SOAPUtilities::makeSOAPMessageReference(
"Error"));
1150 void GatewaySupervisor::transitionConfiguring(toolbox::Event::Reference e)
1151 throw (toolbox::fsm::exception::Exception)
1153 RunControlStateMachine::theProgressBar_.step();
1155 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1157 std::string systemAlias = SOAPUtilities::translate(
1158 theStateMachine_.getCurrentMessage()).getParameters().getValue(
"ConfigurationAlias");
1160 __COUT__ <<
"Transition parameter: " << systemAlias << std::endl;
1162 RunControlStateMachine::theProgressBar_.step();
1167 theConfigurationManager_->init();
1171 __SS__ <<
"\nTransition to Configuring interrupted! " <<
1172 "The Configuration Manager could not be initialized." << std::endl;
1174 __COUT_ERR__ <<
"\n" << ss.str();
1175 XCEPT_RAISE (toolbox::fsm::exception::Exception, ss.str());
1179 RunControlStateMachine::theProgressBar_.step();
1184 theConfigurationGroup_ = theConfigurationManager_->getConfigurationGroupFromAlias(systemAlias);
1188 __COUT_INFO__ <<
"Exception occurred" << std::endl;
1191 RunControlStateMachine::theProgressBar_.step();
1193 if(theConfigurationGroup_.second.isInvalid())
1195 __SS__ <<
"\nTransition to Configuring interrupted! System Alias " <<
1196 systemAlias <<
" could not be translated to a group name and key." << std::endl;
1198 __COUT_ERR__ <<
"\n" << ss.str();
1199 XCEPT_RAISE (toolbox::fsm::exception::Exception, ss.str());
1203 RunControlStateMachine::theProgressBar_.step();
1205 __COUT__ <<
"Configuration group name: " << theConfigurationGroup_.first <<
" key: " <<
1206 theConfigurationGroup_.second << std::endl;
1210 std::stringstream ss;
1211 ss <<
"Configuring '" << systemAlias <<
"' which translates to " <<
1212 theConfigurationGroup_.first <<
" (" << theConfigurationGroup_.second <<
").";
1213 makeSystemLogbookEntry(ss.str());
1216 RunControlStateMachine::theProgressBar_.step();
1221 theConfigurationManager_->loadConfigurationGroup(theConfigurationGroup_.first, theConfigurationGroup_.second,
true);
1225 tmpCfgMgr.activateConfigurationGroup(theConfigurationGroup_.first, theConfigurationGroup_.second);
1229 __SS__ <<
"\nTransition to Configuring interrupted! System Alias " <<
1230 systemAlias <<
" was translated to " << theConfigurationGroup_.first <<
1231 " (" << theConfigurationGroup_.second <<
") but could not be loaded and initialized." << std::endl;
1232 ss <<
"\n\nTo debug this problem, try activating this group in the Configuration GUI " <<
1233 " and detailed errors will be shown." << std::endl;
1234 __COUT_ERR__ <<
"\n" << ss.str();
1235 XCEPT_RAISE (toolbox::fsm::exception::Exception, ss.str());
1241 ConfigurationTree configLinkNode = theConfigurationManager_->getSupervisorConfigurationNode(
1242 supervisorContextUID_, supervisorApplicationUID_);
1243 if(!configLinkNode.isDisconnected())
1248 bool dumpConfiguration =
true;
1249 std::string dumpFilePath, dumpFileRadix, dumpFormat;
1252 ConfigurationTree fsmLinkNode = configLinkNode.getNode(
"LinkToStateMachineConfiguration").
1253 getNode(activeStateMachineName_);
1254 dumpConfiguration = fsmLinkNode.getNode(
"EnableConfigurationDumpOnConfigureTransition").
1256 dumpFilePath = fsmLinkNode.getNode(
"ConfigurationDumpOnConfigureFilePath").getValue<std::string>();
1257 dumpFileRadix = fsmLinkNode.getNode(
"ConfigurationDumpOnConfigureFileRadix").getValue<std::string>();
1258 dumpFormat = fsmLinkNode.getNode(
"ConfigurationDumpOnConfigureFormat").getValue<std::string>();
1261 catch(std::runtime_error &e)
1263 __COUT_INFO__ <<
"FSM configuration dump Link disconnected." << std::endl;
1264 dumpConfiguration =
false;
1267 if(dumpConfiguration)
1270 theConfigurationManager_->dumpActiveConfiguration(
1275 std::to_string(time(0)) +
1282 catch(std::runtime_error &e) {
1283 __SS__ <<
"\nTransition to Configuring interrupted! There was an error identified " <<
1284 "during the configuration dump attempt:\n\n " <<
1285 e.what() << std::endl;
1286 __COUT_ERR__ <<
"\n" << ss.str();
1287 XCEPT_RAISE (toolbox::fsm::exception::Exception, ss.str());
1291 __SS__ <<
"\nTransition to Configuring interrupted! There was an error identified " <<
1292 "during the configuration dump attempt.\n\n " <<
1294 __COUT_ERR__ <<
"\n" << ss.str();
1295 XCEPT_RAISE (toolbox::fsm::exception::Exception, ss.str());
1301 RunControlStateMachine::theProgressBar_.step();
1303 parameters.addParameter(
"ConfigurationGroupName", theConfigurationGroup_.first);
1304 parameters.addParameter(
"ConfigurationGroupKey", theConfigurationGroup_.second.toString());
1307 xoap::MessageReference message = theStateMachine_.getCurrentMessage();
1308 SOAPUtilities::addParameters(message,parameters);
1309 broadcastMessage(message);
1310 RunControlStateMachine::theProgressBar_.step();
1315 saveGroupNameAndKey(theConfigurationGroup_,FSM_LAST_CONFIGURED_GROUP_ALIAS_FILE);
1317 __COUT__ <<
"Done" << std::endl;
1318 RunControlStateMachine::theProgressBar_.complete();
1322 void GatewaySupervisor::transitionHalting(toolbox::Event::Reference e)
1323 throw (toolbox::fsm::exception::Exception)
1325 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1327 makeSystemLogbookEntry(
"Run halting.");
1329 broadcastMessage(theStateMachine_.getCurrentMessage());
1333 void GatewaySupervisor::transitionShuttingDown(toolbox::Event::Reference e)
1334 throw (toolbox::fsm::exception::Exception)
1336 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1338 RunControlStateMachine::theProgressBar_.step();
1339 makeSystemLogbookEntry(
"System shutting down.");
1340 RunControlStateMachine::theProgressBar_.step();
1343 launchStartOTSCommand(
"OTS_APP_SHUTDOWN");
1344 RunControlStateMachine::theProgressBar_.step();
1347 for(
int i=0;i<5;++i)
1350 RunControlStateMachine::theProgressBar_.step();
1355 void GatewaySupervisor::transitionStartingUp(toolbox::Event::Reference e)
1356 throw (toolbox::fsm::exception::Exception)
1358 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1360 RunControlStateMachine::theProgressBar_.step();
1361 makeSystemLogbookEntry(
"System starting up.");
1362 RunControlStateMachine::theProgressBar_.step();
1365 launchStartOTSCommand(
"OTS_APP_STARTUP");
1366 RunControlStateMachine::theProgressBar_.step();
1369 for(
int i=0;i<10;++i)
1372 RunControlStateMachine::theProgressBar_.step();
1377 void GatewaySupervisor::transitionInitializing(toolbox::Event::Reference e)
1378 throw (toolbox::fsm::exception::Exception)
1380 __COUT__ << theStateMachine_.getCurrentStateName() << std::endl;
1382 if(!broadcastMessage(theStateMachine_.getCurrentMessage()))
1384 __COUT_ERR__ <<
"I can't Initialize the supervisors!" << std::endl;
1387 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1388 __COUT__ <<
"Fsm current transition: " << theStateMachine_.getCurrentTransitionName(e->type()) << std::endl;
1389 __COUT__ <<
"Fsm final state: " << theStateMachine_.getTransitionFinalStateName(e->type()) << std::endl;
1393 void GatewaySupervisor::transitionPausing(toolbox::Event::Reference e)
1394 throw (toolbox::fsm::exception::Exception)
1396 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1398 makeSystemLogbookEntry(
"Run pausing.");
1400 broadcastMessage(theStateMachine_.getCurrentMessage());
1404 void GatewaySupervisor::transitionResuming(toolbox::Event::Reference e)
1405 throw (toolbox::fsm::exception::Exception)
1407 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1409 makeSystemLogbookEntry(
"Run resuming.");
1411 broadcastMessage(theStateMachine_.getCurrentMessage());
1415 void GatewaySupervisor::transitionStarting(toolbox::Event::Reference e)
1416 throw (toolbox::fsm::exception::Exception)
1418 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1421 receive(theStateMachine_.getCurrentMessage(), parameters);
1423 std::string runNumber = parameters.getValue(
"RunNumber");
1424 __COUT__ << runNumber << std::endl;
1428 ConfigurationTree configLinkNode = theConfigurationManager_->getSupervisorConfigurationNode(
1429 supervisorContextUID_, supervisorApplicationUID_);
1430 if(!configLinkNode.isDisconnected())
1434 bool dumpConfiguration =
true;
1435 std::string dumpFilePath, dumpFileRadix, dumpFormat;
1438 ConfigurationTree fsmLinkNode = configLinkNode.getNode(
"LinkToStateMachineConfiguration").
1439 getNode(activeStateMachineName_);
1440 dumpConfiguration = fsmLinkNode.getNode(
"EnableConfigurationDumpOnRunTransition").
1442 dumpFilePath = fsmLinkNode.getNode(
"ConfigurationDumpOnRunFilePath").getValue<std::string>();
1443 dumpFileRadix = fsmLinkNode.getNode(
"ConfigurationDumpOnRunFileRadix").getValue<std::string>();
1444 dumpFormat = fsmLinkNode.getNode(
"ConfigurationDumpOnRunFormat").getValue<std::string>();
1446 catch(std::runtime_error &e)
1448 __COUT_INFO__ <<
"FSM configuration dump Link disconnected." << std::endl;
1449 dumpConfiguration =
false;
1452 if(dumpConfiguration)
1455 theConfigurationManager_->dumpActiveConfiguration(
1462 std::to_string(time(0)) +
1469 catch(std::runtime_error &e) {
1470 __SS__ <<
"\nTransition to Running interrupted! There was an error identified " <<
1471 "during the configuration dump attempt:\n\n " <<
1472 e.what() << std::endl;
1473 __COUT_ERR__ <<
"\n" << ss.str();
1474 XCEPT_RAISE (toolbox::fsm::exception::Exception, ss.str());
1478 __SS__ <<
"\nTransition to Running interrupted! There was an error identified " <<
1479 "during the configuration dump attempt.\n\n " <<
1481 __COUT_ERR__ <<
"\n" << ss.str();
1482 XCEPT_RAISE (toolbox::fsm::exception::Exception, ss.str());
1489 makeSystemLogbookEntry(
"Run " + runNumber +
" starting.");
1491 broadcastMessage(theStateMachine_.getCurrentMessage());
1494 saveGroupNameAndKey(theConfigurationGroup_,FSM_LAST_STARTED_GROUP_ALIAS_FILE);
1498 void GatewaySupervisor::transitionStopping(toolbox::Event::Reference e)
1499 throw (toolbox::fsm::exception::Exception)
1501 __COUT__ <<
"Fsm current state: " << theStateMachine_.getCurrentStateName() << std::endl;
1503 makeSystemLogbookEntry(
"Run stopping.");
1505 broadcastMessage(theStateMachine_.getCurrentMessage());
1517 bool GatewaySupervisor::broadcastMessage(xoap::MessageReference message)
1518 throw (toolbox::fsm::exception::Exception)
1520 RunControlStateMachine::theProgressBar_.step();
1523 allSupervisorInfo_.setSupervisorStatus(
this,
1524 theStateMachine_.getCurrentStateName());
1526 std::string command = SOAPUtilities::translate(message).getCommand();
1527 bool proceed =
true;
1530 __COUT__ <<
"=========> Broadcasting state machine command = " << command << __E__;
1534 for(
auto& it: allSupervisorInfo_.getOrderedSupervisorDescriptors(command))
1538 RunControlStateMachine::theProgressBar_.step();
1540 __COUT__ <<
"Sending message to Supervisor " << appInfo.getName() <<
" [LID=" <<
1541 appInfo.getId() <<
"]: " << command << std::endl;
1542 __COUT__ <<
"Sending message to Supervisor " << appInfo.getName() <<
" [LID=" <<
1543 appInfo.getId() <<
"]: " << command << std::endl;
1544 __COUT__ <<
"Sending message to Supervisor " << appInfo.getName() <<
" [LID=" <<
1545 appInfo.getId() <<
"]: " << command << std::endl;
1546 __COUT__ <<
"Sending message to Supervisor " << appInfo.getName() <<
" [LID=" <<
1547 appInfo.getId() <<
"]: " << command << std::endl;
1551 reply = send(appInfo.getDescriptor(), message);
1553 catch(
const xdaq::exception::Exception &e)
1556 __SS__ <<
"Error! Gateway Supervisor can NOT " << command <<
" Supervisor instance = '" <<
1557 appInfo.getName() <<
"' [LID=" <<
1558 appInfo.getId() <<
"] in Context '" <<
1559 appInfo.getContextName() <<
"' [URL=" <<
1562 "Xoap message failure. Did the target Supervisor crash? Try re-initializing or restarting otsdaq." << std::endl;
1563 __COUT_ERR__ << ss.str();
1564 __MOUT_ERR__ << ss.str();
1568 __COUT__ <<
"Try again.." << __E__;
1569 reply = send(appInfo.getDescriptor(), message);
1571 catch(
const xdaq::exception::Exception &e)
1573 __COUT__ <<
"Failed.." << __E__;
1574 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1576 __COUT__ <<
"2nd passed.." << __E__;
1580 if (reply != command +
"Done")
1582 __SS__ <<
"Error! Gateway Supervisor can NOT " << command <<
" Supervisor instance = '" <<
1583 appInfo.getName() <<
"' [LID=" <<
1584 appInfo.getId() <<
"] in Context '" <<
1585 appInfo.getContextName() <<
"' [URL=" <<
1589 __COUT_ERR__ << ss.str() << std::endl;
1590 __MOUT_ERR__ << ss.str() << std::endl;
1592 __COUT__ <<
"Getting error message..." << std::endl;
1595 xoap::MessageReference errorMessage = sendWithSOAPReply(appInfo.getDescriptor(),
1596 SOAPUtilities::makeSOAPMessageReference(
"StateMachineErrorMessageRequest"));
1598 parameters.addParameter(
"ErrorMessage");
1599 SOAPMessenger::receive(errorMessage, parameters);
1601 std::string error = parameters.getValue(
"ErrorMessage");
1604 std::stringstream err;
1605 err <<
"Unknown error from Supervisor instance = '" <<
1606 appInfo.getName() <<
"' [LID=" <<
1607 appInfo.getId() <<
"] in Context '" <<
1608 appInfo.getContextName() <<
"' [URL=" <<
1610 "]. If the problem persists or is repeatable, please notify admins.\n\n";
1614 __SS__ <<
"Received error from Supervisor instance = '" <<
1615 appInfo.getName() <<
"' [LID=" <<
1616 appInfo.getId() <<
"] in Context '" <<
1617 appInfo.getContextName() <<
"' [URL=" <<
1619 "].\n\n Error Message = " << error << std::endl;
1621 __COUT_ERR__ << ss.str() << std::endl;
1622 __MOUT_ERR__ << ss.str() << std::endl;
1624 if(command ==
"Error")
continue;
1626 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1630 catch(
const xdaq::exception::Exception &e)
1633 __SS__ <<
"Error! Gateway Supervisor failed to read error message from Supervisor instance = '" <<
1634 appInfo.getName() <<
"' [LID=" <<
1635 appInfo.getId() <<
"] in Context '" <<
1636 appInfo.getContextName() <<
"' [URL=" <<
1639 "Xoap message failure. Did the target Supervisor crash? Try re-initializing or restarting otsdaq." << std::endl;
1640 __COUT_ERR__ << ss.str();
1641 __MOUT_ERR__ << ss.str();
1642 XCEPT_RAISE(toolbox::fsm::exception::Exception, ss.str());
1649 __COUT__ <<
"Supervisor instance = '" <<
1650 appInfo.getName() <<
"' [LID=" <<
1651 appInfo.getId() <<
"] in Context '" <<
1652 appInfo.getContextName() <<
"' [URL=" <<
1654 "] was " << command <<
"'d correctly!" << std::endl;
1659 __COUT__ <<
"Breaking out of loop." << __E__;
1664 RunControlStateMachine::theProgressBar_.step();
1670 void GatewaySupervisor::wait(
int milliseconds, std::string who)
const
1672 for (
int s = 1; s <= milliseconds; s++)
1677 __COUT__ << s <<
" msecs " << who << std::endl;
1686 void GatewaySupervisor::loginRequest(xgi::Input * in, xgi::Output * out)
1687 throw (xgi::exception::Exception)
1689 cgicc::Cgicc cgi(in);
1690 std::string Command = CgiDataUtilities::getData(cgi,
"RequestType");
1691 __COUT__ <<
"*** Login RequestType = " << Command << std::endl;
1700 std::vector<std::string> loggedOutUsernames;
1701 theWebUsers_.cleanupExpiredEntries(&loggedOutUsernames);
1702 for (
unsigned int i = 0; i < loggedOutUsernames.size(); ++i)
1703 makeSystemLogbookEntry(loggedOutUsernames[i] +
" login timed out.");
1705 if (Command ==
"sessionId")
1712 std::string uuid = CgiDataUtilities::postData(cgi,
"uuid");
1714 std::string sid = theWebUsers_.createNewLoginSession(uuid);
1716 __COUT__ <<
"uuid = " << uuid << std::endl;
1717 __COUT__ <<
"SessionId = " << sid.substr(0, 10) << std::endl;
1720 else if (Command ==
"checkCookie")
1724 std::string jumbledUser;
1725 std::string cookieCode;
1735 uuid = CgiDataUtilities::postData(cgi,
"uuid");
1736 jumbledUser = CgiDataUtilities::postData(cgi,
"ju");
1737 cookieCode = CgiDataUtilities::postData(cgi,
"cc");
1739 __COUT__ <<
"uuid = " << uuid << std::endl;
1740 __COUT__ <<
"Cookie Code = " << cookieCode.substr(0, 10) << std::endl;
1741 __COUT__ <<
"jumbledUser = " << jumbledUser.substr(0, 10) << std::endl;
1744 uid = theWebUsers_.isCookieCodeActiveForLogin(uuid, cookieCode,
1747 if (uid == theWebUsers_.NOT_FOUND_IN_DATABASE)
1749 __COUT__ <<
"cookieCode invalid" << std::endl;
1754 __COUT__ <<
"cookieCode is good." << std::endl;
1759 theWebUsers_.insertSettingsForUser(uid, &xmldoc);
1761 xmldoc.outputXmlDocument((std::ostringstream*) out);
1764 else if (Command ==
"login")
1775 std::string uuid = CgiDataUtilities::postData(cgi,
"uuid");
1776 std::string newAccountCode = CgiDataUtilities::postData(cgi,
"nac");
1777 std::string jumbledUser = CgiDataUtilities::postData(cgi,
"ju");
1778 std::string jumbledPw = CgiDataUtilities::postData(cgi,
"jp");
1780 __COUT__ <<
"jumbledUser = " << jumbledUser.substr(0, 10) << std::endl;
1781 __COUT__ <<
"jumbledPw = " << jumbledPw.substr(0, 10) << std::endl;
1782 __COUT__ <<
"uuid = " << uuid << std::endl;
1783 __COUT__ <<
"nac =-" << newAccountCode <<
"-" << std::endl;
1785 uint64_t uid = theWebUsers_.attemptActiveSession(uuid, jumbledUser,
1786 jumbledPw, newAccountCode);
1789 if (uid == theWebUsers_.NOT_FOUND_IN_DATABASE)
1791 __COUT__ <<
"cookieCode invalid" << std::endl;
1793 if (newAccountCode !=
"1")
1794 newAccountCode =
"0";
1797 __COUT__ <<
"new cookieCode = " << newAccountCode.substr(0, 10) << std::endl;
1801 theWebUsers_.insertSettingsForUser(uid, &xmldoc);
1805 if (uid != theWebUsers_.NOT_FOUND_IN_DATABASE)
1807 uint64_t asCnt = theWebUsers_.getActiveSessionCountForUser(uid) - 1;
1809 sprintf(asStr,
"%lu", asCnt);
1810 xmldoc.addTextElementToData(
"user_active_session_count", asStr);
1813 xmldoc.outputXmlDocument((std::ostringstream*) out);
1816 makeSystemLogbookEntry(
1817 theWebUsers_.getUsersUsername(uid) +
" logged in.");
1819 else if (Command ==
"cert")
1830 std::string uuid = CgiDataUtilities::postData(cgi,
"uuid");
1831 std::string jumbledEmail = cgicc::form_urldecode(CgiDataUtilities::getData(cgi,
"httpsUser"));
1832 std::string username =
"";
1833 std::string cookieCode =
"";
1835 __COUT__ <<
"CERTIFICATE LOGIN REUEST RECEVIED!!!" << std::endl;
1836 __COUT__ <<
"jumbledEmail = " << jumbledEmail << std::endl;
1837 __COUT__ <<
"uuid = " << uuid << std::endl;
1839 uint64_t uid = theWebUsers_.attemptActiveSessionWithCert(uuid, jumbledEmail,
1840 cookieCode, username);
1843 if (uid == theWebUsers_.NOT_FOUND_IN_DATABASE)
1845 __COUT__ <<
"cookieCode invalid" << std::endl;
1847 if (cookieCode !=
"1")
1851 __COUT__ <<
"new cookieCode = " << cookieCode.substr(0, 10) << std::endl;
1855 theWebUsers_.insertSettingsForUser(uid, &xmldoc);
1859 if (uid != theWebUsers_.NOT_FOUND_IN_DATABASE)
1861 uint64_t asCnt = theWebUsers_.getActiveSessionCountForUser(uid) - 1;
1863 sprintf(asStr,
"%lu", asCnt);
1864 xmldoc.addTextElementToData(
"user_active_session_count", asStr);
1867 xmldoc.outputXmlDocument((std::ostringstream*) out);
1870 makeSystemLogbookEntry(
1871 theWebUsers_.getUsersUsername(uid) +
" logged in.");
1873 else if (Command ==
"logout")
1875 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
1876 std::string logoutOthers = CgiDataUtilities::postData(cgi,
1879 __COUT__ <<
"Cookie Code = " << cookieCode.substr(0, 10) << std::endl;
1880 __COUT__ <<
"logoutOthers = " << logoutOthers << std::endl;
1883 if (theWebUsers_.cookieCodeLogout(cookieCode, logoutOthers ==
"1", &uid)
1884 != theWebUsers_.NOT_FOUND_IN_DATABASE)
1888 if (!theWebUsers_.isUserIdActive(uid))
1889 makeSystemLogbookEntry(
1890 theWebUsers_.getUsersUsername(uid) +
" logged out.");
1895 __COUT__ << __LINE__ <<
"\tInvalid Command" << std::endl;
1901 void GatewaySupervisor::tooltipRequest(xgi::Input * in, xgi::Output * out)
1902 throw (xgi::exception::Exception)
1904 cgicc::Cgicc cgi(in);
1906 std::string Command = CgiDataUtilities::getData(cgi,
"RequestType");
1907 __COUT__ <<
"Tooltip RequestType = " << Command << std::endl;
1913 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
1914 uint8_t userPermissions;
1917 if (!theWebUsers_.cookieCodeIsActiveForRequest(cookieCode, &userPermissions,
1928 if(Command ==
"check")
1930 WebUsers::tooltipCheckForUsername(
1931 theWebUsers_.getUsersUsername(uid),
1933 CgiDataUtilities::getData(cgi,
"srcFile"),
1934 CgiDataUtilities::getData(cgi,
"srcFunc"),
1935 CgiDataUtilities::getData(cgi,
"srcId"));
1937 else if(Command ==
"setNeverShow")
1939 WebUsers::tooltipSetNeverShowForUsername(
1940 theWebUsers_.getUsersUsername(uid),
1942 CgiDataUtilities::getData(cgi,
"srcFile"),
1943 CgiDataUtilities::getData(cgi,
"srcFunc"),
1944 CgiDataUtilities::getData(cgi,
"srcId"),
1945 CgiDataUtilities::getData(cgi,
"doNeverShow") ==
"1"?
true:
false,
1946 CgiDataUtilities::getData(cgi,
"temporarySilence") ==
"1"?
true:
false);
1950 __COUT__ <<
"Command Request, " << Command <<
", not recognized." << std::endl;
1952 xmldoc.outputXmlDocument((std::ostringstream*) out,
false,
true);
1956 void GatewaySupervisor::request(xgi::Input * in, xgi::Output * out)
1957 throw (xgi::exception::Exception)
1960 if(VERBOSE_MUTEX) __COUT__ <<
"Waiting for FSM access" << std::endl;
1961 std::lock_guard<std::mutex> lock(stateMachineAccessMutex_);
1962 if(VERBOSE_MUTEX) __COUT__ <<
"Have FSM access" << std::endl;
1964 cgicc::Cgicc cgi(in);
1966 std::string Command = CgiDataUtilities::getData(cgi,
"RequestType");
1973 std::string cookieCode = CgiDataUtilities::postData(cgi,
"CookieCode");
1974 uint8_t userPermissions;
1976 std::string userWithLock;
1977 bool refreshCookie = Command !=
"getSystemMessages" &&
1978 Command !=
"getCurrentState" &&
1979 Command !=
"gatewayLaunchOTS" &&
1980 Command !=
"gatewayLaunchWiz";
1982 if (!theWebUsers_.cookieCodeIsActiveForRequest(cookieCode, &userPermissions,
2017 if (Command ==
"getSettings")
2019 std::string accounts = CgiDataUtilities::getData(cgi,
"accounts");
2021 __COUT__ <<
"Get Settings Request" << std::endl;
2022 __COUT__ <<
"accounts = " << accounts << std::endl;
2023 theWebUsers_.insertSettingsForUser(uid, &xmldoc, accounts ==
"1");
2025 else if (Command ==
"setSettings")
2027 std::string bgcolor = CgiDataUtilities::postData(cgi,
"bgcolor");
2028 std::string dbcolor = CgiDataUtilities::postData(cgi,
"dbcolor");
2029 std::string wincolor = CgiDataUtilities::postData(cgi,
"wincolor");
2030 std::string layout = CgiDataUtilities::postData(cgi,
"layout");
2031 std::string syslayout = CgiDataUtilities::postData(cgi,
"syslayout");
2033 __COUT__ <<
"Set Settings Request" << std::endl;
2034 __COUT__ <<
"bgcolor = " << bgcolor << std::endl;
2035 __COUT__ <<
"dbcolor = " << dbcolor << std::endl;
2036 __COUT__ <<
"wincolor = " << wincolor << std::endl;
2037 __COUT__ <<
"layout = " << layout << std::endl;
2038 __COUT__ <<
"syslayout = " << syslayout << std::endl;
2039 theWebUsers_.changeSettingsForUser(uid, bgcolor, dbcolor, wincolor,
2041 theWebUsers_.insertSettingsForUser(uid, &xmldoc,
true);
2043 else if (Command ==
"accountSettings")
2045 std::string type = CgiDataUtilities::postData(cgi,
"type");
2048 if (type ==
"updateAccount")
2050 else if (type ==
"createAccount")
2052 else if (type ==
"deleteAccount")
2055 std::string username = CgiDataUtilities::postData(cgi,
"username");
2056 std::string displayname = CgiDataUtilities::postData(cgi,
2058 std::string email = CgiDataUtilities::postData(cgi,
"useremail");
2059 std::string permissions = CgiDataUtilities::postData(cgi,
2061 std::string accounts = CgiDataUtilities::getData(cgi,
"accounts");
2063 __COUT__ <<
"accountSettings Request" << std::endl;
2064 __COUT__ <<
"type = " << type <<
" - " << type_int << std::endl;
2065 __COUT__ <<
"username = " << username << std::endl;
2066 __COUT__ <<
"useremail = " << email << std::endl;
2067 __COUT__ <<
"displayname = " << displayname << std::endl;
2068 __COUT__ <<
"permissions = " << permissions << std::endl;
2070 theWebUsers_.modifyAccountSettings(uid, type_int, username, displayname,email,
2073 __COUT__ <<
"accounts = " << accounts << std::endl;
2075 theWebUsers_.insertSettingsForUser(uid, &xmldoc, accounts ==
"1");
2077 else if(Command ==
"stateMatchinePreferences")
2079 std::string set = CgiDataUtilities::getData(cgi,
"set");
2080 const std::string DEFAULT_FSM_VIEW =
"Default_FSM_View";
2082 theWebUsers_.setGenericPreference(uid, DEFAULT_FSM_VIEW,
2083 CgiDataUtilities::getData(cgi, DEFAULT_FSM_VIEW));
2085 theWebUsers_.getGenericPreference(uid, DEFAULT_FSM_VIEW, &xmldoc);
2087 else if(Command ==
"getAliasList")
2089 std::string username = theWebUsers_.getUsersUsername(uid);
2090 std::string fsmName = CgiDataUtilities::getData(cgi,
"fsmName");
2091 __COUT__ <<
"fsmName = " << fsmName << std::endl;
2093 std::string stateMachineAliasFilter =
"*";
2095 std::map<std::string ,
2097 theConfigurationManager_->getGroupAliasesConfiguration();
2101 ConfigurationTree configLinkNode = theConfigurationManager_->getSupervisorConfigurationNode(
2102 supervisorContextUID_, supervisorApplicationUID_);
2104 if(!configLinkNode.isDisconnected())
2108 ConfigurationTree fsmLinkNode = configLinkNode.getNode(
"LinkToStateMachineConfiguration");
2109 if(!fsmLinkNode.isDisconnected())
2110 stateMachineAliasFilter =
2111 fsmLinkNode.getNode(fsmName +
"/SystemAliasFilter").getValue<std::string>();
2113 __COUT_INFO__ <<
"FSM Link disconnected." << std::endl;
2115 catch(std::runtime_error &e) { __COUT_INFO__ << e.what() << std::endl; }
2116 catch(...) { __COUT_ERR__ <<
"Unknown error. Should never happen." << std::endl; }
2119 __COUT_INFO__ <<
"FSM Link disconnected." << std::endl;
2121 __COUT__ <<
"stateMachineAliasFilter = " << stateMachineAliasFilter << std::endl;
2128 bool invertFilter = stateMachineAliasFilter.size() && stateMachineAliasFilter[0] ==
'!';
2129 std::vector<std::string> filterArr;
2132 if(invertFilter) ++i;
2135 while((f = stateMachineAliasFilter.find(
'*',i)) != std::string::npos)
2137 tmp = stateMachineAliasFilter.substr(i,f-i);
2139 filterArr.push_back(tmp);
2144 if(i <= stateMachineAliasFilter.size())
2146 tmp = stateMachineAliasFilter.substr(i);
2147 filterArr.push_back(tmp);
2155 for(
auto& aliasMapPair : aliasMap)
2161 if(filterArr.size() == 1)
2163 if(filterArr[0] !=
"" &&
2164 filterArr[0] !=
"*" &&
2165 aliasMapPair.first != filterArr[0])
2166 filterMatch =
false;
2171 for(f=0;f<filterArr.size();++f)
2173 if(!filterArr[f].size())
continue;
2177 if((i = aliasMapPair.first.find(filterArr[f])) != 0)
2179 filterMatch =
false;
2183 else if(f == filterArr.size()-1)
2185 if(aliasMapPair.first.rfind(filterArr[f]) !=
2186 aliasMapPair.first.size() - filterArr[f].size())
2188 filterMatch =
false;
2192 else if((i = aliasMapPair.first.find(filterArr[f])) ==
2195 filterMatch =
false;
2201 if(invertFilter) filterMatch = !filterMatch;
2205 if(!filterMatch)
continue;
2207 xmldoc.addTextElementToData(
"config_alias", aliasMapPair.first);
2208 xmldoc.addTextElementToData(
"config_key",
2209 ConfigurationGroupKey::getFullGroupString(aliasMapPair.second.first,
2210 aliasMapPair.second.second).c_str());
2212 std::string groupComment, groupAuthor, groupCreationTime;
2215 theConfigurationManager_->loadConfigurationGroup(
2216 aliasMapPair.second.first,aliasMapPair.second.second,
2218 &groupComment, &groupAuthor, &groupCreationTime,
false );
2220 xmldoc.addTextElementToData(
"config_comment", groupComment);
2221 xmldoc.addTextElementToData(
"config_author", groupAuthor);
2222 xmldoc.addTextElementToData(
"config_create_time", groupCreationTime);
2226 __COUT_WARN__ <<
"Failed to load group metadata." << std::endl;
2232 std::string fn = FSM_LAST_GROUP_ALIAS_PATH + FSM_LAST_GROUP_ALIAS_FILE_START +
2233 username +
"." + FSM_USERS_PREFERENCES_FILETYPE;
2234 __COUT__ <<
"Load preferences: " << fn << std::endl;
2235 FILE *fp = fopen(fn.c_str(),
"r");
2238 char tmpLastAlias[500];
2239 fscanf(fp,
"%*s %s",tmpLastAlias);
2240 __COUT__ <<
"tmpLastAlias: " << tmpLastAlias << std::endl;
2242 xmldoc.addTextElementToData(
"UserLastConfigAlias",tmpLastAlias);
2246 else if (Command ==
"getFecList")
2248 xmldoc.addTextElementToData(
"fec_list",
"");
2250 for (
auto it: allSupervisorInfo_.getAllFETypeSupervisorInfo())
2252 xmldoc.addTextElementToParent(
"fec_url",
2253 it.second.getURL(),
"fec_list");
2254 xmldoc.addTextElementToParent(
2256 std::to_string(it.second.getId()),
"fec_list");
2259 else if (Command ==
"getSystemMessages")
2261 xmldoc.addTextElementToData(
"systemMessages",
2262 theSystemMessenger_.getSystemMessage(
2263 theWebUsers_.getUsersDisplayName(uid)));
2265 xmldoc.addTextElementToData(
"username_with_lock",
2266 theWebUsers_.getUserWithLock());
2270 else if (Command ==
"setUserWithLock")
2272 std::string username = CgiDataUtilities::postData(cgi,
"username");
2273 std::string lock = CgiDataUtilities::postData(cgi,
"lock");
2274 std::string accounts = CgiDataUtilities::getData(cgi,
"accounts");
2276 __COUT__ << Command << std::endl;
2277 __COUT__ <<
"username " << username << std::endl;
2278 __COUT__ <<
"lock " << lock << std::endl;
2279 __COUT__ <<
"accounts " << accounts << std::endl;
2280 __COUT__ <<
"uid " << uid << std::endl;
2282 std::string tmpUserWithLock = theWebUsers_.getUserWithLock();
2283 if(!theWebUsers_.setUserWithLock(uid, lock ==
"1", username))
2284 xmldoc.addTextElementToData(
"server_alert",
2285 std::string(
"Set user lock action failed. You must have valid permissions and ") +
2286 "locking user must be currently logged in.");
2288 theWebUsers_.insertSettingsForUser(uid, &xmldoc, accounts ==
"1");
2290 if (tmpUserWithLock != theWebUsers_.getUserWithLock())
2291 theSystemMessenger_.addSystemMessage(
"*", theWebUsers_.getUserWithLock()
2292 ==
"" ? tmpUserWithLock +
" has unlocked ots."
2293 : theWebUsers_.getUserWithLock()
2294 +
" has locked ots.");
2296 else if (Command ==
"getStateMachine")
2299 std::vector<toolbox::fsm::State> states;
2300 states = theStateMachine_.getStates();
2303 std::string transName;
2304 std::string transParameter;
2307 for (
unsigned int i = 0; i < states.size(); ++i)
2309 stateStr[0] = states[i];
2310 DOMElement* stateParent = xmldoc.addTextElementToData(
"state", stateStr);
2312 xmldoc.addTextElementToParent(
"state_name", theStateMachine_.getStateName(states[i]), stateParent);
2317 std::map<std::string, toolbox::fsm::State, std::less<std::string> >
2318 trans = theStateMachine_.getTransitions(states[i]);
2319 std::set<std::string> actionNames = theStateMachine_.getInputs(states[i]);
2321 std::map<std::string, toolbox::fsm::State, std::less<std::string> >::iterator it =
2323 std::set<std::string>::iterator ait = actionNames.begin();
2331 for (; it != trans.end() && ait != actionNames.end(); ++it, ++ait)
2333 stateStr[0] = it->second;
2335 if(stateStr[0] ==
'R')
2338 xmldoc.addTextElementToParent(
"state_transition", stateStr, stateParent);
2342 xmldoc.addTextElementToParent(
"state_transition_action", *ait, stateParent);
2344 transName = theStateMachine_.getTransitionName(states[i], *ait);
2347 xmldoc.addTextElementToParent(
"state_transition_name",
2348 transName, stateParent);
2349 transParameter = theStateMachine_.getTransitionParameter(states[i], *ait);
2352 xmldoc.addTextElementToParent(
"state_transition_parameter", transParameter, stateParent);
2355 else if(stateStr[0] ==
'C')
2358 xmldoc.addTextElementToParent(
"state_transition", stateStr, stateParent);
2362 xmldoc.addTextElementToParent(
"state_transition_action", *ait, stateParent);
2364 transName = theStateMachine_.getTransitionName(states[i], *ait);
2367 xmldoc.addTextElementToParent(
"state_transition_name",
2368 transName, stateParent);
2369 transParameter = theStateMachine_.getTransitionParameter(states[i], *ait);
2372 xmldoc.addTextElementToParent(
"state_transition_parameter", transParameter, stateParent);
2379 ait = actionNames.begin();
2382 for (; it != trans.end() && ait != actionNames.end(); ++it, ++ait)
2386 stateStr[0] = it->second;
2388 if(stateStr[0] ==
'R')
2390 else if(stateStr[0] ==
'C')
2393 xmldoc.addTextElementToParent(
"state_transition", stateStr, stateParent);
2397 xmldoc.addTextElementToParent(
"state_transition_action", *ait, stateParent);
2399 transName = theStateMachine_.getTransitionName(states[i], *ait);
2402 xmldoc.addTextElementToParent(
"state_transition_name",
2403 transName, stateParent);
2404 transParameter = theStateMachine_.getTransitionParameter(states[i], *ait);
2407 xmldoc.addTextElementToParent(
"state_transition_parameter", transParameter, stateParent);
2412 else if (Command ==
"getStateMachineNames")
2415 ConfigurationTree configLinkNode = theConfigurationManager_->getSupervisorConfigurationNode(
2416 supervisorContextUID_, supervisorApplicationUID_);
2420 auto fsmNodes = configLinkNode.getNode(
2421 "LinkToStateMachineConfiguration").getChildren();
2422 for(
const auto& fsmNode:fsmNodes)
2423 xmldoc.addTextElementToData(
"stateMachineName", fsmNode.first);
2427 __COUT__ <<
"Caught exception, assuming no valid FSM names." << std::endl;
2428 xmldoc.addTextElementToData(
"stateMachineName",
"");
2431 else if (Command ==
"getIterationPlanStatus")
2434 theIterator_.handleCommandRequest(xmldoc,Command,
"");
2436 else if (Command ==
"getCurrentState")
2438 xmldoc.addTextElementToData(
"current_state", theStateMachine_.getCurrentStateName());
2439 xmldoc.addTextElementToData(
"in_transition", theStateMachine_.isInTransition() ?
"1" :
"0");
2440 if (theStateMachine_.isInTransition())
2441 xmldoc.addTextElementToData(
"transition_progress", RunControlStateMachine::theProgressBar_.readPercentageString());
2443 xmldoc.addTextElementToData(
"transition_progress",
"100");
2447 sprintf(tmp,
"%lu",theStateMachine_.getTimeInState());
2448 xmldoc.addTextElementToData(
"time_in_state", tmp);
2457 std::string fsmName = CgiDataUtilities::getData(cgi,
"fsmName");
2465 if(!theStateMachine_.isInTransition())
2467 std::string stateMachineRunAlias =
"Run";
2470 ConfigurationTree configLinkNode = theConfigurationManager_->getSupervisorConfigurationNode(
2471 supervisorContextUID_, supervisorApplicationUID_);
2473 if(!configLinkNode.isDisconnected())
2477 ConfigurationTree fsmLinkNode = configLinkNode.getNode(
"LinkToStateMachineConfiguration");
2478 if(!fsmLinkNode.isDisconnected())
2479 stateMachineRunAlias =
2480 fsmLinkNode.getNode(fsmName +
"/RunDisplayAlias").getValue<std::string>();
2484 catch(std::runtime_error &e)
2492 __COUT_ERR__ <<
"Unknown error. Should never happen." << std::endl;
2494 __COUT_INFO__ <<
"No state machine Run alias. Ignoring and assuming alias of '" <<
2495 stateMachineRunAlias <<
".'" << std::endl;
2503 xmldoc.addTextElementToData(
"stateMachineRunAlias", stateMachineRunAlias);
2509 if(theStateMachine_.getCurrentStateName() ==
"Running" ||
2510 theStateMachine_.getCurrentStateName() ==
"Paused")
2511 sprintf(tmp,
"Current %s Number: %u",stateMachineRunAlias.c_str(),getNextRunNumber(activeStateMachineName_)-1);
2513 sprintf(tmp,
"Next %s Number: %u",stateMachineRunAlias.c_str(),getNextRunNumber(fsmName));
2514 xmldoc.addTextElementToData(
"run_number", tmp);
2517 else if(Command ==
"getErrorInStateMatchine")
2519 xmldoc.addTextElementToData(
"FSM_Error", theStateMachine_.getErrorMessage());
2521 else if(Command ==
"getDesktopIcons")
2524 std::string iconFileName = ICON_FILE_NAME;
2525 std::ifstream iconFile;
2526 std::string iconList =
"";
2528 iconFile.open(iconFileName.c_str());
2532 __COUT__ <<
"Error opening file: "<< iconFileName << std::endl;
2536 if(iconFile.is_open())
2538 __COUT__ <<
"Getting Desktop Icons - opened file: " << iconFileName << std::endl;
2539 while(std::getline(iconFile, line))
2548 xmldoc.addTextElementToData(
"iconList", iconList);
2551 else if(Command ==
"gatewayLaunchOTS" || Command ==
"gatewayLaunchWiz")
2555 if(userPermissions != 255)
2557 __COUT__ <<
"Insufficient Permissions" << std::endl;
2561 __COUT_WARN__ << Command <<
" command received! " << std::endl;
2562 __MOUT_WARN__ << Command <<
" command received! " << std::endl;
2566 theWebUsers_.saveActiveSessions();
2570 if(Command ==
"gatewayLaunchOTS")
2571 launchStartOTSCommand(
"LAUNCH_OTS");
2572 else if(Command ==
"gatewayLaunchWiz")
2573 launchStartOTSCommand(
"LAUNCH_WIZ");
2626 else if(Command ==
"resetUserTooltips")
2628 WebUsers::resetAllUserTooltips(theWebUsers_.getUsersUsername(uid));
2631 __COUT__ <<
"Command Request, " << Command <<
", not recognized." << std::endl;
2636 xmldoc.outputXmlDocument((std::ostringstream*) out,
false,
true);
2644 void GatewaySupervisor::launchStartOTSCommand(
const std::string& command)
2646 __COUT__ <<
"launch StartOTS Command = " << command << __E__;
2647 __COUT__ <<
"Extracting target context hostnames... " << std::endl;
2649 std::vector<std::string> hostnames;
2652 theConfigurationManager_->init();
2656 auto contexts = contextConfiguration->getContexts();
2658 for(
const auto& context: contexts)
2660 if(!context.status_)
continue;
2664 for(i=0;i<context.address_.size();++i)
2665 if(context.address_[i] ==
'/')
2667 hostnames.push_back(context.address_.substr(j));
2668 __COUT__ <<
"hostname = " << hostnames.back() << std::endl;
2673 __SS__ <<
"\nRelaunch of otsdaq interrupted! " <<
2674 "The Configuration Manager could not be initialized." << std::endl;
2679 for(
const auto& hostname: hostnames)
2681 std::string fn = (std::string(getenv(
"SERVICE_DATA_PATH")) +
2682 "/StartOTS_action_" + hostname +
".cmd");
2683 FILE* fp = fopen(fn.c_str(),
"w");
2686 fprintf(fp,command.c_str());
2691 __SS__ <<
"Unable to open command file: " << fn << std::endl;
2700 xoap::MessageReference GatewaySupervisor::supervisorGetUserInfo(
2701 xoap::MessageReference message)
2702 throw (xoap::exception::Exception)
2705 parameters.addParameter(
"CookieCode");
2706 receive(message, parameters);
2707 std::string cookieCode = parameters.getValue(
"CookieCode");
2709 std::string username, displayName;
2710 uint64_t activeSessionIndex;
2712 theWebUsers_.getUserInfoForCookie(cookieCode, &username, &displayName,
2713 &activeSessionIndex);
2720 retParameters.addParameter(
"Username", username);
2721 retParameters.addParameter(
"DisplayName", displayName);
2723 sprintf(tmpStr,
"%lu", activeSessionIndex);
2724 retParameters.addParameter(
"ActiveSessionIndex", tmpStr);
2726 return SOAPUtilities::makeSOAPMessageReference(
"UserInfoResponse",
2733 xoap::MessageReference GatewaySupervisor::supervisorCookieCheck(xoap::MessageReference message)
2734 throw (xoap::exception::Exception)
2740 parameters.addParameter(
"CookieCode");
2741 parameters.addParameter(
"RefreshOption");
2742 receive(message, parameters);
2743 std::string cookieCode = parameters.getValue(
"CookieCode");
2744 std::string refreshOption = parameters.getValue(
"RefreshOption");
2748 uint8_t userPermissions = 0;
2749 std::string userWithLock =
"";
2750 theWebUsers_.cookieCodeIsActiveForRequest(cookieCode, &userPermissions, 0,
2751 "0", refreshOption ==
"1", &userWithLock);
2757 retParameters.addParameter(
"CookieCode", cookieCode);
2759 sprintf(tmp,
"%d", userPermissions);
2760 retParameters.addParameter(
"Permissions", tmp);
2761 retParameters.addParameter(
"UserWithLock", userWithLock);
2765 return SOAPUtilities::makeSOAPMessageReference(
"CookieResponse",
2772 xoap::MessageReference GatewaySupervisor::supervisorGetActiveUsers(
2773 xoap::MessageReference message)
2774 throw (xoap::exception::Exception)
2776 __COUT__ << std::endl;
2779 parameters(
"UserList", theWebUsers_.getActiveUsersString());
2780 return SOAPUtilities::makeSOAPMessageReference(
"ActiveUserResponse",
2788 xoap::MessageReference GatewaySupervisor::supervisorSystemMessage(
2789 xoap::MessageReference message)
2790 throw (xoap::exception::Exception)
2793 parameters.addParameter(
"ToUser");
2794 parameters.addParameter(
"Message");
2795 receive(message, parameters);
2797 __COUT__ <<
"toUser: " << parameters.getValue(
"ToUser").substr(
2798 0, 10) <<
", message: " << parameters.getValue(
"Message").substr(0,
2801 theSystemMessenger_.addSystemMessage(parameters.getValue(
"ToUser"),
2802 parameters.getValue(
"Message"));
2803 return SOAPUtilities::makeSOAPMessageReference(
"SystemMessageResponse");
2810 xoap::MessageReference GatewaySupervisor::supervisorSystemLogbookEntry(
2811 xoap::MessageReference message)
2812 throw (xoap::exception::Exception)
2815 parameters.addParameter(
"EntryText");
2816 receive(message, parameters);
2818 __COUT__ <<
"EntryText: " << parameters.getValue(
"EntryText").substr(
2819 0, 10) << std::endl;
2821 makeSystemLogbookEntry(parameters.getValue(
"EntryText"));
2823 return SOAPUtilities::makeSOAPMessageReference(
"SystemLogbookResponse");
2831 xoap::MessageReference GatewaySupervisor::supervisorLastConfigGroupRequest(
2832 xoap::MessageReference message)
2833 throw (xoap::exception::Exception)
2836 parameters.addParameter(
"ActionOfLastGroup");
2837 receive(message, parameters);
2839 return GatewaySupervisor::lastConfigGroupRequestHandler(parameters);
2848 xoap::MessageReference GatewaySupervisor::lastConfigGroupRequestHandler(
2851 std::string action = parameters.getValue(
"ActionOfLastGroup");
2852 __COUT__ <<
"ActionOfLastGroup: " << action.substr(
2853 0, 10) << std::endl;
2855 std::string fileName =
"";
2856 if(action ==
"Configured")
2857 fileName = FSM_LAST_CONFIGURED_GROUP_ALIAS_FILE;
2858 else if(action ==
"Started")
2859 fileName = FSM_LAST_STARTED_GROUP_ALIAS_FILE;
2862 __COUT_ERR__ <<
"Invalid last group action requested." << std::endl;
2863 return SOAPUtilities::makeSOAPMessageReference(
"LastConfigGroupResponseFailure");
2865 std::string timeString;
2867 loadGroupNameAndKey(fileName,timeString);
2871 retParameters.addParameter(
"GroupName", theGroup.first);
2872 retParameters.addParameter(
"GroupKey", theGroup.second.toString());
2873 retParameters.addParameter(
"GroupAction", action);
2874 retParameters.addParameter(
"GroupActionTime", timeString);
2877 return SOAPUtilities::makeSOAPMessageReference(
"LastConfigGroupResponse",
2888 unsigned int GatewaySupervisor::getNextRunNumber(
const std::string &fsmNameIn)
2890 std::string runNumberFileName = RUN_NUMBER_PATH +
"/";
2891 std::string fsmName = fsmNameIn ==
""?activeStateMachineName_:fsmNameIn;
2893 for(
unsigned int i=0;i<fsmName.size();++i)
2894 if( (fsmName[i] >=
'a' && fsmName[i] <=
'z') ||
2895 (fsmName[i] >=
'A' && fsmName[i] <=
'Z') ||
2896 (fsmName[i] >=
'0' && fsmName[i] <=
'9'))
2897 runNumberFileName += fsmName[i];
2898 runNumberFileName += RUN_NUMBER_FILE_NAME;
2901 std::ifstream runNumberFile(runNumberFileName.c_str());
2902 if (!runNumberFile.is_open())
2904 __COUT__ <<
"Can't open file: " << runNumberFileName << std::endl;
2906 __COUT__ <<
"Creating file and setting Run Number to 1: " << runNumberFileName << std::endl;
2907 FILE *fp = fopen(runNumberFileName.c_str(),
"w");
2911 runNumberFile.open(runNumberFileName.c_str());
2912 if(!runNumberFile.is_open())
2914 __SS__ <<
"Error. Can't create file: " << runNumberFileName << std::endl;
2915 __COUT_ERR__ << ss.str();
2916 throw std::runtime_error(ss.str());
2919 std::string runNumberString;
2920 runNumberFile >> runNumberString;
2921 runNumberFile.close();
2922 return atoi(runNumberString.c_str());
2926 bool GatewaySupervisor::setNextRunNumber(
unsigned int runNumber,
const std::string &fsmNameIn)
2928 std::string runNumberFileName = RUN_NUMBER_PATH +
"/";
2929 std::string fsmName = fsmNameIn ==
""?activeStateMachineName_:fsmNameIn;
2931 for(
unsigned int i=0;i<fsmName.size();++i)
2932 if( (fsmName[i] >=
'a' && fsmName[i] <=
'z') ||
2933 (fsmName[i] >=
'A' && fsmName[i] <=
'Z') ||
2934 (fsmName[i] >=
'0' && fsmName[i] <=
'9'))
2935 runNumberFileName += fsmName[i];
2936 runNumberFileName += RUN_NUMBER_FILE_NAME;
2937 __COUT__ <<
"runNumberFileName: " << runNumberFileName << std::endl;
2939 std::ofstream runNumberFile(runNumberFileName.c_str());
2940 if (!runNumberFile.is_open())
2942 __SS__ <<
"Can't open file: " << runNumberFileName << std::endl;
2943 __COUT__ << ss.str();
2944 throw std::runtime_error(ss.str());
2946 std::stringstream runNumberStream;
2947 runNumberStream << runNumber;
2948 runNumberFile << runNumberStream.str().c_str();
2949 runNumberFile.close();
2959 std::pair<std::string ,
2961 std::string &returnedTimeString)
2963 std::string fullPath = FSM_LAST_GROUP_ALIAS_PATH +
"/" + fileName;
2965 FILE *groupFile = fopen(fullPath.c_str(),
"r");
2968 __COUT__ <<
"Can't open file: " << fullPath << std::endl;
2970 __COUT__ <<
"Returning empty groupName and key -1" << std::endl;
2972 return std::pair<std::string ,
2978 std::pair<std::string ,
2981 fgets(line,500,groupFile);
2982 theGroup.first = line;
2984 fgets(line,500,groupFile);
2986 sscanf(line,
"%d",&key);
2987 theGroup.second = key;
2989 fgets(line,500,groupFile);
2991 sscanf(line,
"%ld",×tamp);
2993 ::localtime_r(×tamp, &tmstruct);
2994 ::strftime(line, 30,
"%c %Z", &tmstruct);
2995 returnedTimeString = line;
2999 __COUT__ <<
"theGroup.first= " << theGroup.first <<
3000 " theGroup.second= " << theGroup.second << std::endl;
3006 void GatewaySupervisor::saveGroupNameAndKey(
const std::pair<std::string ,
3008 const std::string &fileName)
3010 std::string fullPath = FSM_LAST_GROUP_ALIAS_PATH +
"/" + fileName;
3012 std::ofstream groupFile(fullPath.c_str());
3013 if (!groupFile.is_open())
3015 __SS__ <<
"Error. Can't open file: " << fullPath << std::endl;
3016 __COUT_ERR__ <<
"\n" << ss.str();
3017 throw std::runtime_error(ss.str());
3019 std::stringstream outss;
3020 outss << theGroup.first <<
"\n" << theGroup.second <<
"\n" << time(0);
3021 groupFile << outss.str().c_str();