1 #include "otsdaq-utilities/MacroMaker/MacroMakerSupervisor.h"
3 #include "otsdaq/CodeEditor/CodeEditor.h"
4 #include "otsdaq/ConfigurationInterface/ConfigurationManager.h"
5 #include "otsdaq/FECore/FEVInterface.h"
6 #include "otsdaq/Macros/StringMacros.h"
8 #include "otsdaq/NetworkUtilities/TransceiverSocket.h"
20 #include "otsdaq/TableCore/TableGroupKey.h"
22 #define MACROS_DB_PATH std::string(__ENV__("SERVICE_DATA_PATH")) + "/MacroData/"
23 #define MACROS_HIST_PATH std::string(__ENV__("SERVICE_DATA_PATH")) + "/MacroHistory/"
24 #define MACROS_SEQUENCE_PATH std::string(__ENV__("SERVICE_DATA_PATH")) + "/MacroSequence/"
25 #define MACROS_EXPORT_PATH std::string("/MacroExport/")
26 #define USER_FEMACROTEST_PREF_PATH \
27 std::string(__ENV__("SERVICE_DATA_PATH")) + "/FEMacroTestPreferences/"
28 #define FEMACROTEST_PREF_FILETYPE "pref"
30 #define SEQUENCE_FILE_NAME \
31 std::string(__ENV__("SERVICE_DATA_PATH")) + "/OtsWizardData/sequence.dat"
32 #define SEQUENCE_OUT_FILE_NAME \
33 std::string(__ENV__("SERVICE_DATA_PATH")) + "/OtsWizardData/sequence.out"
38 #define __MF_SUBJECT__ "MacroMaker"
46 __SUP_COUT__ <<
"Constructing..." << __E__;
51 mkdir(((std::string)MACROS_DB_PATH).c_str(), 0755);
52 mkdir(((std::string)MACROS_HIST_PATH).c_str(), 0755);
53 mkdir(((std::string)MACROS_SEQUENCE_PATH).c_str(), 0755);
54 mkdir((__ENV__(
"SERVICE_DATA_PATH") + MACROS_EXPORT_PATH).c_str(), 0755);
55 mkdir(((std::string)USER_FEMACROTEST_PREF_PATH).c_str(), 0755);
58 &MacroMakerSupervisor::frontEndCommunicationRequest,
63 if(CorePropertySupervisorBase::allSupervisorInfo_.isMacroMakerMode())
65 __SUP_COUT__ <<
"Starting constructor for Macro Maker mode." << __E__;
67 xgi::bind(
this, &MacroMakerSupervisor::requestIcons,
"requestIcons");
68 xgi::bind(
this, &MacroMakerSupervisor::verification,
"Verify");
69 xgi::bind(
this, &MacroMakerSupervisor::tooltipRequest,
"TooltipRequest");
70 xgi::bind(
this, &MacroMakerSupervisor::requestWrapper,
"Request");
72 &MacroMakerSupervisor::supervisorSequenceCheck,
73 "SupervisorSequenceCheck",
76 __SUP_COUT__ <<
"Completed constructor for Macro Maker mode." << __E__;
79 __SUP_COUT__ <<
"Not Macro Maker only mode." << __E__;
85 if(CorePropertySupervisorBase::allSupervisorInfo_.isMacroMakerMode())
91 ConfigurationManager::XDAQ_APPLICATION_TABLE_NAME);
96 FEPluginTypetoFEsMap_.clear();
97 FEtoSupervisorMap_.clear();
98 FEtoPluginTypeMap_.clear();
101 __SUP_COUT__ <<
"FEs for app MacroMakerFESupervisor"
107 .
getNode(
"MacroMakerFESupervisor")
108 .
getNode(
"LinkToSupervisorTable")
109 .
getNode(
"LinkToFEInterfaceTable")
112 for(
auto& fe : feChildren)
114 if(!fe.second.status())
117 __SUP_COUTV__(fe.first);
118 FEtoSupervisorMap_[fe.first] =
119 atoi(__ENV__(
"FE_SUPERVISOR_ID"));
121 std::string pluginType =
122 fe.second.getNode(
"FEInterfacePluginName").getValue();
123 FEPluginTypetoFEsMap_[pluginType].emplace(fe.first);
124 FEtoPluginTypeMap_[fe.first] = pluginType;
128 __SUP_COUTV__(StringMacros::mapToString(FEtoSupervisorMap_));
129 __SUP_COUTV__(StringMacros::mapToString(FEPluginTypetoFEsMap_));
130 __SUP_COUTV__(StringMacros::mapToString(FEtoPluginTypeMap_));
135 bool enableRemoteControl =
false;
138 __ENV__(
"OTS_MACROMAKER_UDP_PORT");
139 __ENV__(
"OTS_MACROMAKER_UDP_IP");
140 enableRemoteControl =
true;
142 catch(
const std::runtime_error& e)
144 __SUP_COUT__ <<
"Ignoring MacroMaker server env var error: " << e.what()
149 __SUP_COUT__ <<
"Ignoring unknown error reading OTS_MACROMAKER_UDP_PORT/"
150 "OTS_MACROMAKER_UDP_IP env vars."
154 if(enableRemoteControl)
156 __SUP_COUT_INFO__ <<
"Enabling remote control over UDP..." << __E__;
160 MacroMakerSupervisor::RemoteControlWorkLoop(s);
166 __SUP_COUT_INFO__ <<
"Remote control over UDP is disabled." << __E__;
169 __SUP_COUT__ <<
"Constructed." << __E__;
173 MacroMakerSupervisor::~MacroMakerSupervisor(
void) { destroy(); }
176 void MacroMakerSupervisor::init(
void)
181 allFESupervisorInfo_ =
182 SupervisorInfoMap(allSupervisorInfo_.getAllFETypeSupervisorInfo());
187 void MacroMakerSupervisor::destroy(
void)
199 void MacroMakerSupervisor::tooltipRequest(xgi::Input* in, xgi::Output* out)
201 cgicc::Cgicc cgi(in);
209 if(securityCode_.compare(submittedSequence) != 0)
211 __COUT__ <<
"Unauthorized Request made, security sequence doesn't match!"
223 if(Command ==
"check")
231 else if(Command ==
"setNeverShow")
234 WebUsers::DEFAULT_ADMIN_USERNAME,
243 __COUT__ <<
"Command Request, " << Command <<
", not recognized." << __E__;
249 void MacroMakerSupervisor::verification(xgi::Input* in, xgi::Output* out)
251 cgicc::Cgicc cgi(in);
253 __COUT__ <<
"submittedSequence=" << submittedSequence <<
" " << time(0) << __E__;
255 std::string securityWarning =
"";
257 if(securityCode_.compare(submittedSequence) != 0)
259 __COUT__ <<
"Unauthorized Request made, security sequence doesn't match!"
261 *out <<
"Invalid code.";
267 __COUT__ <<
"*** Successfully authenticated security sequence "
268 <<
"@ " << time(0) << __E__;
273 securityWarning =
"&secure=False";
277 *out <<
"<!DOCTYPE HTML><html lang='en'><head><title>ots MacroMaker mode</title>" <<
280 "<link rel='apple-touch-icon' sizes='57x57' href='/WebPath/images/otsdaqIcons/apple-icon-57x57.png'>\
281 <link rel='apple-touch-icon' sizes='60x60' href='/WebPath/images/otsdaqIcons/apple-icon-60x60.png'>\
282 <link rel='apple-touch-icon' sizes='72x72' href='/WebPath/images/otsdaqIcons/apple-icon-72x72.png'>\
283 <link rel='apple-touch-icon' sizes='76x76' href='/WebPath/images/otsdaqIcons/apple-icon-76x76.png'>\
284 <link rel='apple-touch-icon' sizes='114x114' href='/WebPath/images/otsdaqIcons/apple-icon-114x114.png'>\
285 <link rel='apple-touch-icon' sizes='120x120' href='/WebPath/images/otsdaqIcons/apple-icon-120x120.png'>\
286 <link rel='apple-touch-icon' sizes='144x144' href='/WebPath/images/otsdaqIcons/apple-icon-144x144.png'>\
287 <link rel='apple-touch-icon' sizes='152x152' href='/WebPath/images/otsdaqIcons/apple-icon-152x152.png'>\
288 <link rel='apple-touch-icon' sizes='180x180' href='/WebPath/images/otsdaqIcons/apple-icon-180x180.png'>\
289 <link rel='icon' type='image/png' sizes='192x192' href='/WebPath/images/otsdaqIcons/android-icon-192x192.png'>\
290 <link rel='icon' type='image/png' sizes='32x32' href='/WebPath/images/otsdaqIcons/favicon-32x32.png'>\
291 <link rel='icon' type='image/png' sizes='96x96' href='/WebPath/images/otsdaqIcons/favicon-96x96.png'>\
292 <link rel='icon' type='image/png' sizes='16x16' href='/WebPath/images/otsdaqIcons/favicon-16x16.png'>\
293 <link rel='manifest' href='/WebPath/images/otsdaqIcons/manifest.json'>\
294 <meta name='msapplication-TileColor' content='#ffffff'>\
295 <meta name='msapplication-TileImage' content='/ms-icon-144x144.png'>\
296 <meta name='theme-color' content='#ffffff'>"
300 <<
"<frameset col='100%' row='100%'><frame "
301 "src='/WebPath/html/MacroMakerSupervisor.html?urn="
302 << this->getApplicationDescriptor()->getLocalId() << securityWarning
303 <<
"'></frameset></html>";
307 void MacroMakerSupervisor::generateURL()
309 defaultSequence_ =
true;
312 FILE* fp = fopen((SEQUENCE_FILE_NAME).c_str(),
"r");
315 __SUP_COUT_INFO__ <<
"Sequence length file found: " << SEQUENCE_FILE_NAME
318 fgets(line, 100, fp);
319 sscanf(line,
"%d", &length);
324 defaultSequence_ =
false;
330 <<
"(Reverting to default wiz security) Sequence length file NOT found: "
331 << SEQUENCE_FILE_NAME << __E__;
335 __SUP_COUT__ <<
"Sequence length = " << length << __E__;
339 const char alphanum[] =
341 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
342 "abcdefghijklmnopqrstuvwxyz";
344 for(
int i = 0; i < length; ++i)
346 securityCode_ += alphanum[rand() % (
sizeof(alphanum) - 1)];
349 __SUP_COUT__ << __ENV__(
"HOSTNAME") <<
":" << __ENV__(
"PORT")
350 <<
"/urn:xdaq-application:lid="
351 << this->getApplicationDescriptor()->getLocalId()
352 <<
"/Verify?code=" << securityCode_ << __E__;
358 fp = fopen((SEQUENCE_OUT_FILE_NAME).c_str(),
"w");
361 fprintf(fp,
"%s", securityCode_.c_str());
365 __SUP_COUT_ERR__ <<
"Sequence output file NOT found: " << SEQUENCE_OUT_FILE_NAME
372 void MacroMakerSupervisor::requestIcons(xgi::Input* in, xgi::Output* out)
374 cgicc::Cgicc cgi(in);
379 if(securityCode_.compare(submittedSequence) != 0)
381 __COUT__ <<
"Unauthorized Request made, security sequence doesn't match! "
387 __COUT__ <<
"***Successfully authenticated security sequence. " << time(0)
400 *out <<
"Macro Maker "
401 ",MM,0,1,icon-MacroMaker.png,/WebPath/html/"
402 "MacroMaker.html?urn=290,/"
404 ",CFG,0,1,icon-Configure.png,/WebPath/html/"
405 "FEMacroTest.html?urn=290,/"
407 <<
",Code Editor,CODE,0,1,icon-CodeEditor.png,/urn:xdaq-application:lid=240/,/"
411 std::string iconFile = std::string(__ENV__(
"USER_DATA")) +
"/MacroMakerModeIcons.dat";
412 __COUT__ <<
"Macro Maker mode user icons file: " << iconFile << __E__;
413 FILE* fp = fopen(iconFile.c_str(),
"r");
416 __COUT__ <<
"Macro Maker mode user icons loading from " << iconFile << __E__;
417 fseek(fp, 0, SEEK_END);
418 const unsigned long fileSize = ftell(fp);
419 std::string fileString(fileSize, 0);
421 if(fread(&fileString[0], 1, fileSize, fp) != fileSize)
423 __COUT_ERR__ <<
"Unable to read proper size string from icons file!" << __E__;
428 __COUTV__(fileString);
432 __COUT__ <<
"Macro Maker mode user icons file not found: " << iconFile << __E__;
439 xoap::MessageReference MacroMakerSupervisor::supervisorSequenceCheck(
440 xoap::MessageReference message)
445 SOAPUtilities::receive(message, parameters);
447 std::string submittedSequence = parameters.getValue(
"sequence");
451 std::map<std::string , WebUsers::permissionLevel_t> permissionMap;
453 if(securityCode_ == submittedSequence)
454 permissionMap.emplace(
455 std::pair<std::string /*groupName*/, WebUsers::permissionLevel_t>(
459 __COUT__ <<
"Unauthorized Request made, security sequence doesn't match!"
462 permissionMap.emplace(
463 std::pair<std::string /*groupName*/, WebUsers::permissionLevel_t>(
464 WebUsers::DEFAULT_USER_GROUP, WebUsers::PERMISSION_LEVEL_INACTIVE));
471 return SOAPUtilities::makeSOAPMessageReference(
"SequenceResponse", retParameters);
481 std::string ipAddressForRemoteControlOverUDP = __ENV__(
482 "OTS_MACROMAKER_UDP_IP");
483 int portForRemoteControlOverUDP = atoi(__ENV__(
484 "OTS_MACROMAKER_UDP_PORT"));
485 bool acknowledgementEnabled =
488 __COUTV__(ipAddressForRemoteControlOverUDP);
489 __COUTV__(portForRemoteControlOverUDP);
490 __COUTV__(acknowledgementEnabled);
493 portForRemoteControlOverUDP);
501 __SS__ <<
"FATAL Console error. Could not initialize socket at ip '"
502 << ipAddressForRemoteControlOverUDP <<
"' and port "
503 << portForRemoteControlOverUDP
504 <<
". Perhaps it is already in use? Exiting Remote Control "
505 "SOAPUtilities::receive loop."
512 __COUT__ <<
"UDP Remote Control workloop starting..." << __E__;
522 buffer, 0 , 1 ,
false ) !=
525 __COUT__ <<
"UDP Remote Control packet received of size = " << buffer.size()
531 if(buffer ==
"GetFrontendMacroInfo")
533 std::string macroPath = (std::string)MACROS_DB_PATH +
"NO-USER" +
"/";
534 mkdir(macroPath.c_str(), 0755);
535 std::string histPath =
536 (std::string)MACROS_HIST_PATH +
"NO-USER" +
"/";
537 mkdir(histPath.c_str(), 0755);
540 theSupervisor->getFEMacroList(xmldoc,
"NO-USER");
542 std::stringstream out;
546 __COUT__ <<
"out: " << out.str();
547 sock.acknowledge(out.str(),
552 else if(buffer.find(
"RunFrontendMacro") == 0)
556 std::vector<std::string> bufferFields =
558 if(bufferFields.size() < 8)
560 __SS__ <<
"Missing input arguments for running FE Macro: "
561 << bufferFields.size() <<
" vs 8 expected" << __E__;
565 std::string feClassSelected = bufferFields[1];
566 std::string feUIDSelected =
568 std::string macroType = bufferFields[3];
569 std::string macroName =
573 std::string outputArgs =
575 bool saveOutputs = bufferFields[7] ==
"1";
576 std::string username =
"NO-USER";
577 std::string userGroupPermission =
"allUsers: 255";
580 std::set<std::string> feUIDs;
582 std::string expandUID =
583 feUIDSelected.empty() ?
"*" : feUIDSelected;
588 for(
auto& feTypePair : theSupervisor->FEPluginTypetoFEsMap_)
590 if(feClassSelected.empty() || feClassSelected ==
"*" ||
591 feClassSelected == feTypePair.first)
592 for(
auto& uid : feTypePair.second)
601 auto group = std::make_shared<runFEMacroGroupStruct>();
602 group->historyFeClassSelected_ =
603 feClassSelected.empty() ?
"*" : feClassSelected;
604 group->historyFeUIDSelected_ =
605 feUIDSelected.empty() ?
"*" : feUIDSelected;
606 group->historyMacroType_ = macroType;
607 group->historyMacroName_ = macroName;
608 group->historyInputArgs_ = inputArgs;
609 group->historyOutputArgs_ = outputArgs;
610 group->historySaveOutputs_ = saveOutputs;
611 group->historyUsername_ = username;
613 for(
const std::string& uid : feUIDs)
614 group->tasks_.push_back(
615 std::make_shared<runFEMacroStruct>(xmldoc,
624 userGroupPermission));
627 std::lock_guard<std::mutex> lock(
628 theSupervisor->feMacroRunThreadStructMutex_);
629 group->groupID_ = ++theSupervisor->feMacroRunGroupIDCounter_;
630 if(theSupervisor->feMacroRunGroupIDCounter_ == 0)
631 group->groupID_ = ++theSupervisor->feMacroRunGroupIDCounter_;
633 for(
auto& task : group->tasks_)
635 task->bar_ = std::make_unique<ProgressBar>();
636 task->bar_->reset(macroName,
637 task->parameters_.feUIDSelected_);
639 theSupervisor->feMacroRunThreadStruct_.emplace_back(group);
642 std::thread([group, theSupervisor]() {
643 MacroMakerSupervisor::runFEMacroGroupSchedulerThread(
644 group, theSupervisor);
647 auto lastProgressSend = std::chrono::steady_clock::now();
648 while(!group->allDone())
652 auto now = std::chrono::steady_clock::now();
653 if(std::chrono::duration_cast<std::chrono::seconds>(
654 now - lastProgressSend)
657 lastProgressSend = now;
659 int totalProgress = 0;
662 std::lock_guard<std::mutex> lock(
663 theSupervisor->feMacroRunThreadStructMutex_);
664 for(
auto& task : group->tasks_)
667 if(task->feMacroRunDone_)
668 totalProgress += 100;
670 totalProgress += task->bar_->read();
675 (taskCount > 0) ? (totalProgress / taskCount) : 0;
680 sock.acknowledge(std::string(
"<progress>") +
681 std::to_string(percent) +
"</progress>",
687 std::string taskError;
688 for(
auto& task : group->tasks_)
690 if(task->parameters_.feMacroRunError_ !=
"")
692 taskError = task->parameters_.feMacroRunError_;
699 std::lock_guard<std::mutex> lock(
700 theSupervisor->feMacroRunThreadStructMutex_);
702 i < theSupervisor->feMacroRunThreadStruct_.size();
704 if(theSupervisor->feMacroRunThreadStruct_[i].get() ==
707 theSupervisor->feMacroRunThreadStruct_.erase(
708 theSupervisor->feMacroRunThreadStruct_.begin() + i);
713 if(!taskError.empty())
719 std::stringstream out;
723 __COUT__ <<
"out: " << out.str();
724 sock.acknowledge(out.str(),
731 __SS__ <<
"Unrecognized UDP command received: " << buffer << __E__;
735 catch(
const std::runtime_error& e)
737 __COUT_ERR__ <<
"Error during UDP command handling: " << e.what()
739 sock.acknowledge(std::string(
"Error: ") + e.what(),
true );
743 __COUT_ERR__ <<
"Unknown error caught during UDP command handling - "
746 sock.acknowledge(std::string(
"Error: ") +
"unknown error caught",
750 __COUT__ <<
"Done handling command '" << buffer <<
"'" << __E__;
760 void MacroMakerSupervisor::requestWrapper(xgi::Input* in, xgi::Output* out)
763 if(!CorePropertySupervisorBase::allSupervisorInfo_.isMacroMakerMode())
765 __SUP_COUTT__ <<
"Default request wrapper" << __E__;
766 return CoreSupervisorBase::requestWrapper(in, out);
770 __SUP_COUTT__ <<
"MacroMaker mode request handler!" << __E__;
774 cgicc::Cgicc cgiIn(in);
779 if(securityCode_.compare(submittedSequence) != 0)
781 __COUT__ <<
"Unauthorized Request made, security sequence doesn't match! "
783 *out << WebUsers::REQ_NO_PERMISSION_RESPONSE.c_str();
788 __SUP_COUTT__ <<
"***Successfully authenticated security sequence. " << time(0)
795 __SUP_COUT_TYPE__(TLVL_DEBUG + 10) << __COUT_HDR__ <<
"requestType " << requestType
796 <<
" files: " << cgiIn.getFiles().size() << __E__;
799 WebUsers::RequestUserInfo userInfo(
805 userInfo.username_ =
"admin";
806 userInfo.displayName_ =
"Admin";
807 userInfo.usernameWithLock_ =
"admin";
808 userInfo.userSessionIndex_ = 0;
809 std::map<std::string , WebUsers::permissionLevel_t> initPermissions = {
814 __SUP_COUTT__ <<
"requestType: " << requestType << __E__;
815 else if(!userInfo.automatedCommand_)
816 __SUP_COUT__ <<
"requestType: " << requestType << __E__;
818 if(userInfo.NonXMLRequestType_)
824 catch(
const std::runtime_error& e)
826 __SUP_SS__ <<
"An error was encountered handling requestType '" << requestType
827 <<
"':" << e.what() << __E__;
828 __SUP_COUT_ERR__ <<
"\n" << ss.str();
832 __SUP_SS__ <<
"An unknown error was encountered handling requestType '"
833 << requestType <<
".' "
834 <<
"Please check the printouts to debug." << __E__;
839 catch(
const std::exception& e)
841 ss <<
"Exception message: " << e.what();
846 __SUP_COUT_ERR__ <<
"\n" << ss.str();
855 request(requestType, cgiIn, xmlOut, userInfo);
856 __SUP_COUTT__ <<
"Request '" << requestType <<
"' complete." << __E__;
858 catch(
const std::runtime_error& e)
860 __SUP_SS__ <<
"An error was encountered handling requestType '" << requestType
861 <<
"':" << e.what() << __E__;
862 __SUP_COUT_ERR__ <<
"\n" << ss.str();
863 xmlOut.addTextElementToData(
"Error", ss.str());
867 __SUP_SS__ <<
"An unknown error was encountered handling requestType '"
868 << requestType <<
".' "
869 <<
"Please check the printouts to debug." << __E__;
874 catch(
const std::exception& e)
876 ss <<
"Exception message: " << e.what();
881 __SUP_COUT_ERR__ <<
"\n" << ss.str();
882 xmlOut.addTextElementToData(
"Error", ss.str());
887 unsigned int occurance = 0;
891 __SUP_COUT_ERR__ <<
"'" << requestType <<
"' ERROR encountered: " << err
897 __SUP_COUTVS__(10, userInfo.NoXmlWhiteSpace_);
902 !userInfo.NoXmlWhiteSpace_ );
906 void MacroMakerSupervisor::request(
const std::string& requestType,
909 const WebUsers::RequestUserInfo& userInfo)
912 std::chrono::steady_clock::time_point requestStart = std::chrono::steady_clock::now();
913 time_t requestStartTime = time(0);
916 std::string username =
"";
917 for(
unsigned int i = 0; i < userInfo.username_.size(); ++i)
918 if((userInfo.username_[i] >=
'a' && userInfo.username_[i] <=
'z') ||
919 (userInfo.username_[i] >=
'A' && userInfo.username_[i] <=
'Z') ||
920 (userInfo.username_[i] >=
'0' && userInfo.username_[i] <=
'9') ||
921 userInfo.username_[i] >=
'-' || userInfo.username_[i] <=
'_')
922 username += userInfo.username_[i];
924 if(username.size() < 2)
926 __SUP_SS__ <<
"Illegal username '" << userInfo.username_ <<
"' received."
931 __SUP_COUT__ <<
"User name is " << userInfo.username_ <<
"." << __E__;
932 __SUP_COUT__ <<
"User permission level for request '" << requestType <<
"' is "
933 << unsigned(userInfo.permissionLevel_) <<
"." << __E__;
937 if(requestType ==
"loadFEHistory")
939 std::string histPath = (std::string)MACROS_HIST_PATH + userInfo.username_ +
"/";
940 mkdir(histPath.c_str(), 0755);
943 if(requestType ==
"loadFEMacroSequences")
945 std::string seqPath =
946 (std::string)MACROS_SEQUENCE_PATH + userInfo.username_ +
"/";
947 mkdir(seqPath.c_str(), 0755);
950 if(requestType ==
"getPermission")
952 xmlOut.addTextElementToData(
"Permission",
953 std::to_string(
unsigned(userInfo.permissionLevel_)));
956 std::string publicPath = (std::string)MACROS_DB_PATH +
"publicMacros/";
957 mkdir(publicPath.c_str(), 0755);
958 std::string exportPath =
959 __ENV__(
"SERVICE_DATA_PATH") + MACROS_EXPORT_PATH + userInfo.username_ +
"/";
960 mkdir(exportPath.c_str(), 0755);
963 handleRequest(requestType, xmlOut, cgiIn, userInfo);
965 __SUP_COUTT__ <<
"Total MacroMaker request time: "
966 << artdaq::TimeUtils::GetElapsedTime(requestStart) <<
" = "
967 << time(0) - requestStartTime <<
" seconds" << __E__;
969 catch(
const std::runtime_error& e)
971 __SS__ <<
"Error occurred handling request '" << requestType <<
"': " << e.what()
973 __SUP_COUT__ << ss.str();
974 xmlOut.addTextElementToData(
"Error", ss.str());
978 __SS__ <<
"Unknown error occurred handling request '" << requestType <<
"!'" << __E__;
983 catch(
const std::exception& e)
985 ss <<
"Exception message: " << e.what();
990 __SUP_COUT__ << ss.str();
991 xmlOut.addTextElementToData(
"Error", ss.str());
996 void MacroMakerSupervisor::handleRequest(
const std::string Command,
999 const WebUsers::RequestUserInfo& userInfo)
1001 if(Command ==
"FElist")
1004 std::string macroPath = (std::string)MACROS_DB_PATH + userInfo.username_ +
"/";
1005 mkdir(macroPath.c_str(), 0755);
1006 std::string histPath = (std::string)MACROS_HIST_PATH + userInfo.username_ +
"/";
1007 mkdir(histPath.c_str(), 0755);
1011 else if(Command ==
"writeData")
1012 writeData(xmldoc, cgi, userInfo.username_);
1013 else if(Command ==
"readData")
1014 readData(xmldoc, cgi, userInfo.username_);
1015 else if(Command ==
"createMacro")
1016 createMacro(xmldoc, cgi, userInfo.username_);
1017 else if(Command ==
"loadMacros")
1018 loadMacros(xmldoc, userInfo.username_);
1019 else if(Command ==
"loadHistory")
1020 loadHistory(xmldoc, userInfo.username_);
1021 else if(Command ==
"deleteMacro")
1022 deleteMacro(xmldoc, cgi, userInfo.username_);
1023 else if(Command ==
"editMacro")
1024 editMacro(xmldoc, cgi, userInfo.username_);
1025 else if(Command ==
"clearHistory")
1026 clearHistory(userInfo.username_);
1027 else if(Command ==
"exportMacro")
1028 exportMacro(xmldoc, cgi, userInfo.username_);
1029 else if(Command ==
"exportFEMacro")
1030 exportFEMacro(xmldoc, cgi, userInfo.username_);
1031 else if(Command ==
"getFEMacroList")
1035 std::string macroPath = (std::string)MACROS_DB_PATH + userInfo.username_ +
"/";
1036 mkdir(macroPath.c_str(), 0755);
1037 std::string histPath = (std::string)MACROS_HIST_PATH + userInfo.username_ +
"/";
1038 mkdir(histPath.c_str(), 0755);
1040 getFEMacroList(xmldoc, userInfo.username_);
1042 else if(Command ==
"runFEMacro")
1044 runFEMacro(xmldoc, cgi, userInfo);
1045 else if(Command ==
"loadFEHistory")
1047 loadFEHistory(xmldoc, userInfo.username_);
1048 else if(Command ==
"clearFEHistory")
1050 clearFEHistory(userInfo.username_);
1051 else if(Command ==
"loadFEMacroSequences")
1052 loadFEMacroSequences(xmldoc, userInfo.username_);
1053 else if(Command ==
"saveFEMacroSequence")
1054 saveFEMacroSequence(cgi, userInfo.username_);
1055 else if(Command ==
"getFEMacroSequence")
1056 getFEMacroSequence(xmldoc, cgi, userInfo.username_);
1057 else if(Command ==
"deleteFEMacroSequence")
1058 deleteFEMacroSequence(cgi, userInfo.username_);
1059 else if(Command ==
"makeSequencePublic")
1060 makeSequencePublic(cgi, userInfo.username_);
1061 else if(Command ==
"saveFEMacroTestPreferences")
1063 int twoColumnView = CgiDataUtilities::postDataAsInt(cgi,
"twoColumnView");
1064 int showSequencePane = CgiDataUtilities::postDataAsInt(cgi,
"showSequencePane");
1065 int dynamicDropdown = CgiDataUtilities::postDataAsInt(cgi,
"dynamicDropdown");
1067 if(userInfo.username_ ==
"")
1069 __SUP_COUT_ERR__ <<
"Invalid user found! user=" << userInfo.username_
1071 xmldoc.addTextElementToData(
"Error",
"Error - Invalid user found.");
1075 std::string fn = (std::string)USER_FEMACROTEST_PREF_PATH + userInfo.username_ +
1076 "." + (std::string)FEMACROTEST_PREF_FILETYPE;
1078 FILE* fp = fopen(fn.c_str(),
"w");
1082 __THROW__(ss.str() +
"Could not open file: " + fn);
1084 fprintf(fp,
"twoColumnView %d\n", twoColumnView);
1085 fprintf(fp,
"showSequencePane %d\n", showSequencePane);
1086 fprintf(fp,
"dynamicDropdown %d\n", dynamicDropdown);
1089 else if(Command ==
"loadFEMacroTestPreferences")
1091 if(userInfo.username_ ==
"")
1093 __SUP_COUT_ERR__ <<
"Invalid user found! user=" << userInfo.username_
1095 xmldoc.addTextElementToData(
"Error",
"Error - Invalid user found.");
1099 std::string fn = (std::string)USER_FEMACROTEST_PREF_PATH + userInfo.username_ +
1100 "." + (std::string)FEMACROTEST_PREF_FILETYPE;
1102 FILE* fp = fopen(fn.c_str(),
"r");
1105 __SUP_COUT__ <<
"Returning defaults." << __E__;
1106 xmldoc.addTextElementToData(
"twoColumnView",
"0");
1107 xmldoc.addTextElementToData(
"showSequencePane",
"0");
1108 xmldoc.addTextElementToData(
"dynamicDropdown",
"0");
1111 unsigned int twoColumnView = 0, showSequencePane = 0, dynamicDropdown = 0;
1112 fscanf(fp,
"%*s %u", &twoColumnView);
1113 fscanf(fp,
"%*s %u", &showSequencePane);
1114 fscanf(fp,
"%*s %u", &dynamicDropdown);
1118 sprintf(tmpStr,
"%u", twoColumnView);
1119 xmldoc.addTextElementToData(
"twoColumnView", tmpStr);
1120 sprintf(tmpStr,
"%u", showSequencePane);
1121 xmldoc.addTextElementToData(
"showSequencePane", tmpStr);
1122 sprintf(tmpStr,
"%u", dynamicDropdown);
1123 xmldoc.addTextElementToData(
"dynamicDropdown", tmpStr);
1126 xmldoc.addTextElementToData(
"Error",
1127 "Command '" + Command +
1128 "' not recognized by the Macro Maker Supervisor "
1129 "(was it intended for another Supervisor?).");
1133 xoap::MessageReference MacroMakerSupervisor::frontEndCommunicationRequest(
1134 xoap::MessageReference message)
1141 SOAPUtilities::receive(message, typeParameter);
1143 std::string type = typeParameter.getValue(
"type");
1145 std::string error =
"";
1147 if(type ==
"initFElist")
1149 __SUP_COUTV__(type);
1154 rxParameters.
addParameter(
"SubsystemCommonOverrideList");
1155 SOAPUtilities::receive(message, rxParameters);
1157 std::string groupName = rxParameters.getValue(
"groupName");
1158 std::string groupKey = rxParameters.getValue(
"groupKey");
1159 std::string subsystemCommonList = rxParameters.getValue(
"SubsystemCommonList");
1160 std::string subsystemCommonOverrideList =
1161 rxParameters.getValue(
"SubsystemCommonOverrideList");
1163 __SUP_COUTV__(groupName);
1164 __SUP_COUTV__(groupKey);
1165 __SUP_COUTV__(subsystemCommonList);
1166 __SUP_COUTV__(subsystemCommonOverrideList);
1169 std::map<std::string ,
TableVersion> mergeInTables, overrideTables;
1172 if(!subsystemCommonList.empty())
1174 subsystemCommonList =
1176 __COUT__ <<
"Transition parameter SubsystemCommonList: "
1177 << subsystemCommonList << __E__;
1184 if(!subsystemCommonOverrideList.empty())
1186 subsystemCommonOverrideList =
1188 __COUT__ <<
"Transition parameter SubsystemCommonOverrideList: "
1189 << subsystemCommonOverrideList << __E__;
1211 ConfigurationManager::LoadGroupType::ALL_TYPES,
1220 const SupervisorInfoMap& feTypeSupervisors =
1221 CorePropertySupervisorBase::allSupervisorInfo_.getAllFETypeSupervisorInfo();
1224 cfgMgr.
getNode(ConfigurationManager::XDAQ_APPLICATION_TABLE_NAME);
1226 __SUP_COUT__ <<
"Number of FE Supervisors found = " << feTypeSupervisors.size()
1229 FEPluginTypetoFEsMap_.clear();
1230 FEtoSupervisorMap_.clear();
1231 FEtoPluginTypeMap_.clear();
1232 for(
auto& feApp : feTypeSupervisors)
1234 __SUP_COUTT__ <<
"FEs for app " << feApp.first <<
":"
1235 << feApp.second.getName() << __E__;
1237 auto feChildren = appsNode.
getNode(feApp.second.getName())
1238 .
getNode(
"LinkToSupervisorTable")
1239 .
getNode(
"LinkToFEInterfaceTable")
1242 for(
auto& fe : feChildren)
1244 if(!fe.second.status())
1247 __SUP_COUTTV__(fe.first);
1248 FEtoSupervisorMap_[fe.first] = feApp.first;
1250 std::string pluginType =
1251 fe.second.getNode(
"FEInterfacePluginName").getValue();
1252 FEPluginTypetoFEsMap_[pluginType].emplace(fe.first);
1253 FEtoPluginTypeMap_[fe.first] = pluginType;
1261 else if(type ==
"feSend" ||
1262 type ==
"feMacro" ||
1263 type ==
"feMacroMultiDimensionalStart" ||
1264 type ==
"feMacroMultiDimensionalCheck" ||
1265 type ==
"macroMultiDimensionalStart" ||
1266 type ==
"macroMultiDimensionalCheck")
1268 __SUP_COUTV__(type);
1271 SOAPUtilities::receive(message, rxParameters);
1273 std::string targetInterfaceID = rxParameters.getValue(
"targetInterfaceID");
1275 __SUP_COUTV__(targetInterfaceID);
1277 auto feIt = FEtoSupervisorMap_.find(targetInterfaceID);
1278 if(feIt == FEtoSupervisorMap_.end())
1280 __SUP_SS__ <<
"Destination front end interface ID '" << targetInterfaceID
1281 <<
"' was not found in the list of front ends." << __E__;
1285 unsigned int FESupervisorIndex = feIt->second;
1286 __SUP_COUT__ <<
"Found supervisor index: " << FESupervisorIndex << __E__;
1288 SupervisorInfoMap::iterator it = allFESupervisorInfo_.find(FESupervisorIndex);
1289 if(it == allFESupervisorInfo_.end())
1291 __SUP_SS__ <<
"Error transmitting request to FE Supervisor '"
1292 << targetInterfaceID <<
":" << FESupervisorIndex <<
".' \n\n"
1293 <<
"The FE Supervisor Index does not exist. Have you configured "
1294 "the state machine properly?"
1299 if(type ==
"macroMultiDimensionalStart")
1305 SOAPUtilities::receive(message, rxParameters);
1306 std::string macroName = rxParameters.getValue(
"macroName");
1307 __SUP_COUTV__(macroName);
1309 std::string macroString;
1310 loadMacro(macroName, macroString);
1314 SOAPUtilities::addParameters(message, parameters);
1319 __SUP_COUT_INFO__ <<
"Forwarding (fresh message) to LID="
1320 << it->second.getId() <<
" URL=" << it->second.getURL()
1326 SOAPCommand incomingCmd = SOAPUtilities::translate(message);
1327 xoap::MessageReference freshMessage =
1328 SOAPUtilities::makeSOAPMessageReference(
"FECommunication");
1332 incomingCmd.getParameters().getValue(
"requester"));
1333 fwdParams.
addParameter(
"targetInterfaceID", targetInterfaceID);
1334 if(type ==
"feMacro")
1337 "feMacroName", incomingCmd.getParameters().getValue(
"feMacroName"));
1339 incomingCmd.getParameters().getValue(
"inputArgs"));
1341 else if(type ==
"feSend")
1344 incomingCmd.getParameters().getValue(
"value"));
1346 else if(type ==
"feMacroMultiDimensionalStart")
1349 "feMacroName", incomingCmd.getParameters().getValue(
"feMacroName"));
1351 incomingCmd.getParameters().getValue(
"inputArgs"));
1353 "enableSavingOutput",
1354 incomingCmd.getParameters().getValue(
"enableSavingOutput"));
1357 incomingCmd.getParameters().getValue(
"outputFilePath"));
1360 incomingCmd.getParameters().getValue(
"outputFileRadix"));
1362 else if(type ==
"macroMultiDimensionalStart")
1365 incomingCmd.getParameters().getValue(
"macroName"));
1367 "macroString", incomingCmd.getParameters().getValue(
"macroString"));
1369 incomingCmd.getParameters().getValue(
"inputArgs"));
1371 "enableSavingOutput",
1372 incomingCmd.getParameters().getValue(
"enableSavingOutput"));
1375 incomingCmd.getParameters().getValue(
"outputFilePath"));
1378 incomingCmd.getParameters().getValue(
"outputFileRadix"));
1380 else if(type ==
"feMacroMultiDimensionalCheck")
1383 "feMacroName", incomingCmd.getParameters().getValue(
"feMacroName"));
1385 else if(type ==
"macroMultiDimensionalCheck")
1388 incomingCmd.getParameters().getValue(
"macroName"));
1390 SOAPUtilities::addParameters(freshMessage, fwdParams);
1392 xoap::MessageReference replyMessage = SOAPMessenger::sendWithSOAPReply(
1393 it->second.getDescriptor(), freshMessage);
1395 if(type !=
"feSend")
1397 std::string replyStr =
1398 SOAPUtilities::translate(replyMessage).getCommand();
1400 if(replyStr ==
"Fault")
1404 std::string fullReply;
1405 replyMessage->writeTo(fullReply);
1406 __SUP_COUT_WARN__ <<
"SOAP Fault detail for target '"
1407 << targetInterfaceID <<
"': " << fullReply
1415 return replyMessage;
1418 catch(
const xdaq::exception::Exception& e)
1420 __SUP_SS__ <<
"Error forwarding FE Communication request to FE Supervisor '"
1421 << targetInterfaceID <<
":" << FESupervisorIndex <<
".' "
1422 <<
"Have you configured the state machine properly?\n\n"
1423 << e.what() << __E__;
1429 __SUP_SS__ <<
"Unrecognized FE Communication type: " << type << __E__;
1433 return SOAPUtilities::makeSOAPMessageReference(
"Received");
1435 catch(
const std::runtime_error& e)
1437 __SUP_SS__ <<
"Error processing FE communication request: " << e.what() << __E__;
1438 __SUP_COUT_ERR__ << ss.str();
1440 xoap::MessageReference returnMessage =
1441 SOAPUtilities::makeSOAPMessageReference(
"Error");
1445 SOAPUtilities::addParameters(returnMessage, parameters);
1446 return returnMessage;
1450 xoap::MessageReference returnMessage =
1451 SOAPUtilities::makeSOAPMessageReference(
"Error");
1453 __SUP_SS__ <<
"Unknown error processing FE communication request." << __E__;
1458 catch(
const std::exception& e)
1460 ss <<
"Exception message: " << e.what();
1465 __SUP_COUT_ERR__ << ss.str();
1469 SOAPUtilities::addParameters(returnMessage, parameters);
1470 return returnMessage;
1476 __SUP_COUT__ <<
"Getting FE list!!!!!!!!!" << __E__;
1488 SupervisorInfoMap::const_iterator it;
1489 std::string oneInterface;
1490 std::string rxFEList;
1491 std::string rxFrontEndError;
1493 size_t lastColonIndex;
1497 for(
auto& appInfo : allFESupervisorInfo_)
1505 __SUP_COUT__ <<
"FESupervisor LID = " << appInfo.second.getId()
1506 <<
" name = " << appInfo.second.getName() << __E__;
1510 xoap::MessageReference retMsg =
1511 SOAPMessenger::sendWithSOAPReply(appInfo.second.getDescriptor(),
1512 "MacroMakerSupervisorRequest",
1514 SOAPUtilities::receive(retMsg, rxParameters);
1516 __SUP_COUT__ <<
"Received MacroMaker response: "
1517 << SOAPUtilities::translate(retMsg).getCommand() <<
"==>"
1518 << SOAPUtilities::translate(retMsg) << __E__;
1520 if(SOAPUtilities::translate(retMsg).getCommand() ==
"Fault")
1522 __SUP_SS__ <<
"Unrecognized command received!" << __E__;
1526 catch(
const xdaq::exception::Exception& e)
1528 __SUP_SS__ <<
"Error transmitting request to FE Supervisor LID = "
1529 << appInfo.second.getId() <<
" name = " << appInfo.second.getName()
1531 << e.what() << __E__;
1535 rxFEList = rxParameters.getValue(
"FEList");
1536 rxFrontEndError = rxParameters.getValue(
"frontEndError");
1538 __SUP_COUT__ <<
"FE List received: \n" << rxFEList << __E__;
1540 if(rxFrontEndError !=
"")
1542 __SUP_SS__ <<
"FE Errors received: \n" << rxFrontEndError << __E__;
1546 std::istringstream allInterfaces(rxFEList);
1547 while(std::getline(allInterfaces, oneInterface))
1549 __SUP_COUTV__(oneInterface);
1550 xmldoc.addTextElementToData(
"FE", oneInterface);
1552 lastColonIndex = oneInterface.rfind(
':');
1553 if(lastColonIndex == std::string::npos)
1555 __SUP_SS__ <<
"Last colon could not be found in " << oneInterface
1559 oneInterface = oneInterface.substr(lastColonIndex);
1561 __SUP_COUTV__(oneInterface);
1571 const std::string& username)
1573 __SUP_COUT__ <<
"MacroMaker writing..." << __E__;
1586 __SUP_COUT__ <<
"Write Address: " << Address <<
" Data: " << Data << __E__;
1587 __SUP_COUTV__(interfaces);
1589 std::string command =
"w:" + Address +
":" + Data;
1590 std::string format = addressFormatStr +
":" + dataFormatStr;
1591 appendCommandToHistory(command, format, time, interfaces, username);
1594 txParameters.
addParameter(
"Request",
"UniversalWrite");
1598 __SUP_COUT__ <<
"Here comes the array from multiselect box for WRITE, behold: \n"
1599 << supervisorIndexArray <<
"\n"
1600 << interfaceIndexArray << __E__;
1604 std::vector<std::string> interfaceIndices;
1605 std::istringstream f(interfaceIndexArray);
1607 while(getline(f, s,
','))
1608 interfaceIndices.push_back(s);
1609 std::vector<int> supervisorIndices;
1610 std::istringstream g(supervisorIndexArray);
1612 while(getline(g, t,
','))
1613 supervisorIndices.push_back(std::stoi(t));
1615 for(
unsigned int i = 0; i < supervisorIndices.size(); i++)
1617 unsigned int FESupervisorIndex = supervisorIndices[i];
1618 std::string interfaceIndex = interfaceIndices[i];
1620 txParameters.
addParameter(
"InterfaceID", interfaceIndex);
1622 __SUP_COUT__ <<
"The index of the supervisor instance is: " << FESupervisorIndex
1624 __SUP_COUT__ <<
"...and the interface ID is: " << interfaceIndex << __E__;
1626 SupervisorInfoMap::iterator it = allFESupervisorInfo_.find(FESupervisorIndex);
1627 if(it == allFESupervisorInfo_.end())
1629 __SUP_SS__ <<
"Error transmitting request to FE Supervisor '"
1630 << interfaceIndex <<
":" << FESupervisorIndex <<
".' \n\n"
1631 <<
"The FE Index doesn't exist. Have you configured the state "
1639 xoap::MessageReference replyMessage = SOAPMessenger::sendWithSOAPReply(
1640 it->second.getDescriptor(),
"MacroMakerSupervisorRequest", txParameters);
1642 __SUP_COUT__ <<
"Response received: "
1643 << SOAPUtilities::translate(replyMessage) << __E__;
1647 SOAPUtilities::receive(replyMessage, rxParameters);
1649 std::string error = rxParameters.getValue(
"Error");
1650 __SUP_COUTV__(error);
1655 __SUP_SS__ <<
"Error transmitting request to FE Supervisor '"
1656 << interfaceIndex <<
":" << FESupervisorIndex <<
".' "
1657 <<
"Have you configured the state machine properly?\n\n"
1662 catch(
const xdaq::exception::Exception& e)
1664 __SUP_SS__ <<
"Error transmitting request to FE Supervisor '"
1665 << interfaceIndex <<
":" << FESupervisorIndex <<
".' "
1666 <<
"Have you configured the state machine properly?\n\n"
1667 << e.what() << __E__;
1677 const std::string& username)
1679 __SUP_COUT__ <<
"@@@@@@@ MacroMaker wants to read data @@@@@@@@" << __E__;
1690 __SUP_COUT__ <<
"Read Address: " << Address << __E__;
1691 __SUP_COUTV__(interfaces);
1700 __SUP_COUT__ <<
"Here comes the array from multiselect box for READ, behold: "
1701 << supervisorIndexArray <<
"," << interfaceIndexArray << __E__;
1705 std::vector<std::string> interfaceIndices;
1706 std::istringstream f(interfaceIndexArray);
1708 while(getline(f, s,
','))
1709 interfaceIndices.push_back(s);
1710 std::vector<int> supervisorIndices;
1711 std::istringstream g(supervisorIndexArray);
1713 while(getline(g, t,
','))
1714 supervisorIndices.push_back(std::stoi(t));
1716 for(
unsigned int i = 0; i < supervisorIndices.size(); i++)
1718 unsigned int FESupervisorIndex = supervisorIndices[i];
1719 std::string interfaceIndex = interfaceIndices[i];
1721 txParameters.
addParameter(
"InterfaceID", interfaceIndex);
1723 __SUP_COUT__ <<
"The index of the supervisor instance is: " << FESupervisorIndex
1725 __SUP_COUT__ <<
"...and the interface ID is: " << interfaceIndex << __E__;
1727 SupervisorInfoMap::iterator it = allFESupervisorInfo_.find(FESupervisorIndex);
1728 if(it == allFESupervisorInfo_.end())
1730 __SUP_SS__ <<
"Error transmitting request to FE Supervisor '"
1731 << interfaceIndex <<
":" << FESupervisorIndex <<
".' \n\n"
1732 <<
"The FE Index doesn't exist. Have you configured the state "
1740 xoap::MessageReference retMsg = SOAPMessenger::sendWithSOAPReply(
1741 it->second.getDescriptor(),
"MacroMakerSupervisorRequest", txParameters);
1743 __SUP_COUT__ <<
"Response received: " << SOAPUtilities::translate(retMsg)
1748 SOAPUtilities::receive(retMsg, rxParameters);
1750 std::string error = rxParameters.getValue(
"Error");
1751 __SUP_COUTV__(error);
1756 __SUP_SS__ <<
"Error transmitting request to FE Supervisor '"
1757 << interfaceIndex <<
":" << FESupervisorIndex <<
".' "
1758 <<
"Have you configured the state machine properly?\n\n"
1763 catch(
const xdaq::exception::Exception& e)
1765 __SUP_SS__ <<
"Error transmitting request to FE Supervisor '"
1766 << interfaceIndex <<
":" << FESupervisorIndex <<
".' "
1767 <<
"Have you configured the state machine properly?\n\n"
1768 << e.what() << __E__;
1772 std::string dataReadResult = rxParameters.getValue(
"dataResult");
1773 __SUP_COUT__ <<
"Data reading result received: " << dataReadResult << __E__;
1774 xmldoc.addTextElementToData(
"readData", dataReadResult);
1775 std::string command =
"r:" + Address +
":" + dataReadResult;
1776 std::string format = addressFormatStr +
":" + dataFormatStr;
1777 appendCommandToHistory(command, format, time, interfaces, username);
1784 const std::string& username)
1786 __SUP_COUT__ <<
"MacroMaker wants to create a macro!!!!!!!!!" << __E__;
1795 __SUP_COUTV__(Name);
1796 __SUP_COUTV__(Sequence);
1797 __SUP_COUTV__(Notes);
1798 __SUP_COUTV__(Time);
1799 __SUP_COUTV__(isMacroPublic);
1800 __SUP_COUTV__(isMacroLSBF);
1802 __SUP_COUTV__(MACROS_DB_PATH);
1804 std::string fileName = Name +
".dat";
1805 std::string fullPath;
1806 if(isMacroPublic ==
"true")
1807 fullPath = (std::string)MACROS_DB_PATH +
"publicMacros/" + fileName;
1809 fullPath = (std::string)MACROS_DB_PATH + username +
"/" + fileName;
1811 __SUP_COUTV__(fullPath);
1813 std::ofstream macrofile(fullPath.c_str());
1814 if(macrofile.is_open())
1817 macrofile <<
"\"name\":\"" << Name <<
"\",\n";
1818 macrofile <<
"\"sequence\":\"" << Sequence <<
"\",\n";
1819 macrofile <<
"\"time\":\"" << Time <<
"\",\n";
1820 macrofile <<
"\"notes\":\"" << Notes <<
"\",\n";
1821 macrofile <<
"\"LSBF\":\"" << isMacroLSBF <<
"\"\n";
1822 macrofile <<
"}@" << __E__;
1827 __SUP_SS__ <<
"Unable to open file" << __E__;
1840 void MacroMakerSupervisor::loadMacro(
const std::string& macroName,
1841 std::string& macroString,
1842 const std::string& username )
1844 __SUP_COUTV__(macroName);
1847 std::string fullPath, line;
1849 for(
unsigned int i = 0; i < 2; ++i)
1852 fullPath = (std::string)MACROS_DB_PATH + username +
"/";
1854 fullPath = (std::string)MACROS_DB_PATH +
"publicMacros/";
1856 fullPath += macroName;
1857 if(macroName.find(
".dat") != macroName.size() - 4)
1859 __SUP_COUTV__(fullPath);
1861 std::ifstream read(fullPath.c_str());
1866 getline(read, line);
1867 macroString += line;
1874 __SUP_COUT__ <<
"Unable to open file: " << fullPath << __E__;
1878 if(macroString !=
"")
1882 if(macroString ==
"")
1884 __SUP_SS__ <<
"Unable to locate file for macro '" << macroName
1885 <<
"'... does it exist?" << __E__;
1887 ss <<
" Attempted username was '" << username <<
".'" << __E__;
1891 __SUP_COUTV__(macroString);
1895 void MacroMakerSupervisor::loadMacroNames(
1896 const std::string& username,
1897 std::pair<std::vector<std::string> ,
1898 std::vector<std::string> >& returnMacroNames)
1902 std::string fullPath = (std::string)MACROS_DB_PATH + username +
"/";
1903 if((dir = opendir(fullPath.c_str())) != NULL)
1906 while((ent = readdir(dir)) != NULL)
1909 if((
unsigned)strlen(ent->d_name) > 4)
1913 ((fullPath + (std::string)ent->d_name)).c_str());
1918 returnMacroNames.second.push_back(ent->d_name);
1921 __SUP_COUT__ <<
"Unable to open file" << __E__;
1928 __SUP_COUT__ <<
"Looping through privateMacros folder failed! Wrong directory"
1931 fullPath = (std::string)MACROS_DB_PATH +
"publicMacros/";
1932 if((dir = opendir(fullPath.c_str())) != NULL)
1935 while((ent = readdir(dir)) != NULL)
1938 if((
unsigned)strlen(ent->d_name) > 4)
1942 ((fullPath + (std::string)ent->d_name)).c_str());
1946 returnMacroNames.first.push_back(ent->d_name);
1950 __SUP_COUT__ <<
"Unable to open file" << __E__;
1957 __SUP_COUT__ << fullPath << __E__;
1958 __SUP_COUT__ <<
"Looping through MacroData folder failed! Wrong directory"
1966 const std::string& username)
1970 std::string returnStr =
"";
1971 std::string fullPath = (std::string)MACROS_DB_PATH + username +
"/";
1972 if((dir = opendir(fullPath.c_str())) != NULL)
1975 while((ent = readdir(dir)) != NULL)
1978 if((
unsigned)strlen(ent->d_name) > 4)
1982 ((fullPath + (std::string)ent->d_name)).c_str());
1985 std::stringstream buffer;
1988 getline(read, line);
1992 returnStr += buffer.str();
1997 __SUP_COUT__ <<
"Unable to open file" << __E__;
2000 std::string returnMacroStr = returnStr.substr(0, returnStr.size() - 1);
2002 __SUP_COUT__ <<
"Loading existing macros! " << returnMacroStr << __E__;
2005 xmldoc.addTextElementToData(
"returnMacroStr", returnMacroStr);
2009 __SUP_COUT__ <<
"Looping through privateMacros folder failed! Wrong directory"
2012 fullPath = (std::string)MACROS_DB_PATH +
"publicMacros/";
2014 if((dir = opendir(fullPath.c_str())) != NULL)
2017 while((ent = readdir(dir)) != NULL)
2020 if((
unsigned)strlen(ent->d_name) > 4)
2024 ((fullPath + (std::string)ent->d_name)).c_str());
2027 std::stringstream buffer;
2030 getline(read, line);
2034 returnStr += buffer.str();
2038 __SUP_COUT__ <<
"Unable to open file" << __E__;
2041 std::string returnPublicStr = returnStr.substr(0, returnStr.size() - 1);
2042 __SUP_COUT__ <<
"Loading existing public macros: " << returnPublicStr << __E__;
2044 xmldoc.addTextElementToData(
"returnPublicStr", returnPublicStr);
2048 __SUP_COUT__ << fullPath << __E__;
2049 __SUP_COUT__ <<
"Looping through MacroData folder failed! Wrong directory"
2055 void MacroMakerSupervisor::appendCommandToHistory(std::string Command,
2058 std::string Interfaces,
2059 const std::string& username)
2061 std::string fileName =
"history.hist";
2062 std::string fullPath = (std::string)MACROS_HIST_PATH + username +
"/" + fileName;
2063 __SUP_COUT__ << fullPath << __E__;
2064 std::ofstream histfile(fullPath.c_str(), std::ios::app);
2065 if(histfile.is_open())
2068 histfile <<
"\"Command\":\"" << Command <<
"\",\n";
2069 histfile <<
"\"Format\":\"" << Format <<
"\",\n";
2070 histfile <<
"\"Time\":\"" << Time <<
"\",\n";
2071 histfile <<
"\"Interfaces\":\"" << Interfaces <<
"\"\n";
2072 histfile <<
"}#" << __E__;
2077 __SUP_SS__ <<
"Unable to open history.hist at " << fullPath << __E__;
2083 void MacroMakerSupervisor::appendCommandToHistory(std::string feClass,
2085 std::string macroType,
2086 std::string macroName,
2087 std::string inputArgs,
2088 std::string outputArgs,
2090 const std::string& username,
2092 time_t completeTime)
2095 launchTime = time(0);
2096 if(completeTime == 0)
2097 completeTime = launchTime;
2099 std::string fileName =
"FEhistory.hist";
2100 std::string fullPath = (std::string)MACROS_HIST_PATH + username +
"/" + fileName;
2102 auto feHistoryIt = lastFeCommandToHistory_.find(username);
2104 (feHistoryIt != lastFeCommandToHistory_.end() &&
2105 feHistoryIt->second.size() == 7 && feHistoryIt->second[0] == feClass &&
2106 feHistoryIt->second[1] == feUID && feHistoryIt->second[2] == macroType &&
2107 feHistoryIt->second[3] == macroName && feHistoryIt->second[4] == inputArgs &&
2108 feHistoryIt->second[5] == outputArgs &&
2109 feHistoryIt->second[6] == (saveOutputs ?
"1" :
"0"));
2111 unsigned int repeatCount;
2112 time_t origLaunchTime;
2116 repeatCount = lastFeRepeatCount_[username] + 1;
2117 origLaunchTime = lastFeLaunchTime_[username];
2119 auto posIt = lastFeRecordFilePos_.find(username);
2120 if(posIt != lastFeRecordFilePos_.end() && posIt->second > 0)
2122 struct stat fileStat;
2123 if(stat(fullPath.c_str(), &fileStat) == 0 &&
2124 fileStat.st_size >= posIt->second)
2126 truncate(fullPath.c_str(), posIt->second);
2130 __SUP_COUTT__ <<
"Incrementing repeat count to " << repeatCount
2131 <<
" for command to history from user " << username << __E__;
2136 origLaunchTime = launchTime;
2139 struct stat fileStat;
2141 if(stat(fullPath.c_str(), &fileStat) == 0)
2142 filePos = fileStat.st_size;
2144 __SUP_COUT__ << fullPath << __E__;
2145 std::ofstream histfile(fullPath.c_str(), std::ios::app);
2146 if(histfile.is_open())
2149 histfile <<
"\"feClass\":\"" << feClass <<
"\",\n";
2150 histfile <<
"\"feUID\":\"" << feUID <<
"\",\n";
2151 histfile <<
"\"macroType\":\"" << macroType <<
"\",\n";
2152 histfile <<
"\"macroName\":\"" << macroName <<
"\",\n";
2153 histfile <<
"\"inputArgs\":\"" << inputArgs <<
"\",\n";
2154 histfile <<
"\"outputArgs\":\"" << outputArgs <<
"\",\n";
2155 histfile <<
"\"launchTime\":\"" << origLaunchTime <<
"\",\n";
2156 histfile <<
"\"completeTime\":\"" << completeTime <<
"\",\n";
2158 histfile <<
"\"repeatCount\":\"" << repeatCount <<
"\",\n";
2160 histfile <<
"\"saveOutputs\":\"" << 1 <<
"\"\n";
2162 histfile <<
"\"saveOutputs\":\"" << 0 <<
"\"\n";
2163 histfile <<
"}#" << __E__;
2166 lastFeCommandToHistory_[username].clear();
2167 feHistoryIt = lastFeCommandToHistory_.find(username);
2168 feHistoryIt->second.push_back(feClass);
2169 feHistoryIt->second.push_back(feUID);
2170 feHistoryIt->second.push_back(macroType);
2171 feHistoryIt->second.push_back(macroName);
2172 feHistoryIt->second.push_back(inputArgs);
2173 feHistoryIt->second.push_back(outputArgs);
2174 feHistoryIt->second.push_back((saveOutputs ?
"1" :
"0"));
2176 lastFeRepeatCount_[username] = repeatCount;
2177 lastFeRecordFilePos_[username] = filePos;
2178 lastFeLaunchTime_[username] = origLaunchTime;
2182 __SUP_SS__ <<
"Unable to open FEhistory.hist at " << fullPath << __E__;
2189 void MacroMakerSupervisor::loadFEMacroSequences(
HttpXmlDocument& xmldoc,
2190 const std::string& username)
2192 __SUP_COUT__ <<
"loadFEMacroSequences for " << username << __E__;
2195 std::string fullPath = (std::string)MACROS_SEQUENCE_PATH + username +
"/";
2196 std::string sequences =
"";
2197 __SUP_COUTV__(fullPath);
2198 if((dir = opendir(fullPath.c_str())) != NULL)
2201 while((ent = readdir(dir)) != NULL)
2205 ((fullPath + (std::string)ent->d_name)).c_str());
2209 sequences += ent->d_name + std::string(
";");
2212 __SUP_COUT__ <<
"Unable to open file" << __E__;
2218 __SUP_COUT__ <<
"Looping through MacroSequence/" + username +
2219 " folder failed! Invalid directory."
2223 if(username == WebUsers::DEFAULT_ADMIN_USERNAME)
2226 xmldoc.addTextElementToData(
"FEsequences", sequences);
2231 fullPath = (std::string)MACROS_SEQUENCE_PATH + WebUsers::DEFAULT_ADMIN_USERNAME +
"/";
2233 if((dir = opendir(fullPath.c_str())) != NULL)
2236 while((ent = readdir(dir)) != NULL)
2240 ((fullPath + (std::string)ent->d_name)).c_str());
2244 sequences += std::string(
"public/") + ent->d_name + std::string(
";");
2247 __SUP_COUT__ <<
"Unable to open file" << __E__;
2253 __SUP_COUT__ <<
"Looping through MacroSequence/" +
2254 WebUsers::DEFAULT_ADMIN_USERNAME +
2255 " folder failed! Invalid directory."
2260 xmldoc.addTextElementToData(
"FEsequences", sequences);
2264 void MacroMakerSupervisor::saveFEMacroSequence(cgicc::Cgicc& cgi,
2265 const std::string& username)
2270 std::string FEsequence =
2272 bool overwrite = CgiDataUtilities::getDataAsInt(cgi,
"overwrite");
2274 __SUP_COUTV__(overwrite);
2275 __SUP_COUTV__(name);
2276 __SUP_COUTV__(FEsequence);
2279 std::string fixedName =
"";
2280 for(
size_t i = 0; i < name.size(); ++i)
2281 if(!(name[i] ==
' ' || name[i] ==
'-' || name[i] ==
'_' ||
2282 (name[i] >=
'0' && name[i] <=
'9') || (name[i] >=
'A' && name[i] <=
'Z') ||
2283 (name[i] >=
'a' && name[i] <=
'z')))
2286 <<
"Illegal character in Sequence name (position " << i
2287 <<
") - only alphanumeric, spaces, dashes, and underscores allowed!"
2292 fixedName += name[i];
2293 __SUP_COUTV__(fixedName);
2295 std::string fullPath =
2296 (std::string)MACROS_SEQUENCE_PATH + username +
"/" + fixedName +
".dat";
2297 __SUP_COUTV__(fullPath);
2300 if(!overwrite && std::filesystem::exists(fullPath))
2302 __SUP_SS__ <<
"Please choose another Sequence name! A sequence with the same "
2303 "resulting filename already exists at "
2304 << fullPath << __E__;
2308 std::ofstream seqfile(fullPath.c_str());
2309 if(seqfile.is_open())
2311 seqfile << FEsequence << __E__;
2316 __SUP_SS__ <<
"Unable to open file to save FE Macro Sequence at " << fullPath
2323 void MacroMakerSupervisor::getFEMacroSequence(
HttpXmlDocument& xmldoc,
2325 const std::string& username)
2329 __SUP_COUTV__(name);
2331 bool isPublic = (name.find(
"public/") == 0 ? true :
false);
2332 __SUP_COUTV__(isPublic);
2335 std::string fixedName =
"";
2336 for(
size_t i = (isPublic ? std::string(
"public/").size() : 0); i < name.size(); ++i)
2337 if(!(name[i] ==
' ' || name[i] ==
'-' || name[i] ==
'_' ||
2338 (name[i] >=
'0' && name[i] <=
'9') || (name[i] >=
'A' && name[i] <=
'Z') ||
2339 (name[i] >=
'a' && name[i] <=
'z')))
2341 __COUT__ <<
"Illegal character in Sequence name (position " << i
2342 <<
") - only alphanumeric, spaces, dashes, and underscores allowed!"
2346 fixedName += name[i];
2347 __SUP_COUTV__(fixedName);
2350 std::string fullPath =
2351 (std::string)MACROS_SEQUENCE_PATH + username +
"/" + fixedName +
".dat";
2352 __SUP_COUT__ << fullPath << __E__;
2354 std::ifstream read(fullPath.c_str());
2356 unsigned long long fileSize;
2358 if(!isPublic && read.is_open())
2360 read.seekg(0, std::ios::end);
2361 fileSize = read.tellg();
2362 response =
new char[fileSize + 1];
2363 response[fileSize] =
'\0';
2364 read.seekg(0, std::ios::beg);
2367 read.read(response, fileSize);
2370 xmldoc.addTextElementToData(
"FEsequence", &response[0]);
2377 __SUP_COUT__ <<
"Unable to open " << fullPath <<
"! Trying public area..."
2381 std::string publicFullPath = (std::string)MACROS_SEQUENCE_PATH +
2382 WebUsers::DEFAULT_ADMIN_USERNAME +
"/" + fixedName +
2384 __SUP_COUT__ << publicFullPath << __E__;
2386 std::ifstream read(publicFullPath.c_str());
2388 unsigned long long fileSize;
2392 read.seekg(0, std::ios::end);
2393 fileSize = read.tellg();
2394 response =
new char[fileSize + 1];
2395 response[fileSize] =
'\0';
2396 read.seekg(0, std::ios::beg);
2399 read.read(response, fileSize);
2402 xmldoc.addTextElementToData(
"FEsequence", &response[0]);
2408 __SUP_SS__ <<
"Unable to open FE Macro Sequence at " << fullPath <<
" or "
2409 << publicFullPath << __E__;
2416 void MacroMakerSupervisor::deleteFEMacroSequence(cgicc::Cgicc& cgi,
2417 const std::string& username)
2421 __SUP_COUTV__(name);
2423 bool isPublic = (name.find(
"public/") == 0 ? true :
false);
2424 __SUP_COUTV__(isPublic);
2427 std::string fixedName =
"";
2428 for(
size_t i = (isPublic ? std::string(
"public/").size() : 0); i < name.size(); ++i)
2429 if(!(name[i] ==
' ' || name[i] ==
'-' || name[i] ==
'_' ||
2430 (name[i] >=
'0' && name[i] <=
'9') || (name[i] >=
'A' && name[i] <=
'Z') ||
2431 (name[i] >=
'a' && name[i] <=
'z')))
2433 __COUT__ <<
"Illegal character in Sequence name (position " << i
2434 <<
") - only alphanumeric, spaces, dashes, and underscores allowed!"
2438 fixedName += name[i];
2439 __SUP_COUTV__(fixedName);
2442 std::string fullPath =
2443 (std::string)MACROS_SEQUENCE_PATH + username +
"/" + fixedName +
".dat";
2445 fullPath = (std::string)MACROS_SEQUENCE_PATH + WebUsers::DEFAULT_ADMIN_USERNAME +
2446 "/" + fixedName +
".dat";
2447 __SUP_COUT__ << fullPath << __E__;
2450 if(!std::filesystem::exists(fullPath))
2453 <<
"The specified Sequence name does not exist! Looking for sequence file at "
2454 << fullPath << __E__;
2458 std::remove(fullPath.c_str());
2459 __SUP_COUT__ <<
"Successfully deleted " << fullPath << __E__;
2463 void MacroMakerSupervisor::makeSequencePublic(cgicc::Cgicc& cgi,
2464 const std::string& username)
2468 __SUP_COUTV__(name);
2470 bool isPublic = (name.find(
"public/") == 0 ? true :
false);
2471 __SUP_COUTV__(isPublic);
2474 __SUP_SS__ <<
"The specified Sequence name is already designated as public."
2480 std::string fixedName =
"";
2481 for(
size_t i = 0; i < name.size(); ++i)
2482 if(!(name[i] ==
' ' || name[i] ==
'-' || name[i] ==
'_' ||
2483 (name[i] >=
'0' && name[i] <=
'9') || (name[i] >=
'A' && name[i] <=
'Z') ||
2484 (name[i] >=
'a' && name[i] <=
'z')))
2486 __COUT__ <<
"Illegal character in Sequence name (position " << i
2487 <<
") - only alphanumeric, spaces, dashes, and underscores allowed!"
2491 fixedName += name[i];
2492 __SUP_COUTV__(fixedName);
2495 std::string source =
2496 (std::string)MACROS_SEQUENCE_PATH + username +
"/" + fixedName +
".dat";
2497 __SUP_COUT__ << source << __E__;
2498 std::string destination = (std::string)MACROS_SEQUENCE_PATH +
2499 WebUsers::DEFAULT_ADMIN_USERNAME +
"/" + fixedName +
".dat";
2500 __SUP_COUT__ << destination << __E__;
2502 if(std::filesystem::exists(destination))
2504 __SUP_SS__ <<
"The sequence name '" << fixedName
2505 <<
"' already exists in the admin/public location: " << destination
2511 std::filesystem::copy_file(
2512 source, destination, std::filesystem::copy_options::skip_existing);
2513 __SUP_COUT__ <<
"Successfully made " << fixedName
2514 <<
" public at path: " << destination << __E__;
2519 const std::string& username)
2521 std::string fileName = MACROS_HIST_PATH + username +
"/" +
"history.hist";
2523 std::ifstream read(fileName.c_str());
2524 __SUP_COUT__ << fileName << __E__;
2530 unsigned long long fileSz, i = 0, MAX_HISTORY_SIZE = 100000;
2534 read.seekg(0, std::ios::end);
2535 fileSz = read.tellg();
2536 returnStr =
new char[fileSz + 1];
2537 returnStr[fileSz] =
'\0';
2538 read.seekg(0, std::ios::beg);
2541 read.read(returnStr, fileSz);
2545 if(fileSz > MAX_HISTORY_SIZE)
2547 i = fileSz - MAX_HISTORY_SIZE;
2548 for(; i < fileSz; ++i)
2549 if(returnStr[i] ==
'#')
2558 FILE* fp = fopen(fileName.c_str(),
"w");
2562 __SS__ <<
"Big problem with macromaker history file: " << fileName
2566 fwrite(&returnStr[i], fileSz - i, 1, fp);
2570 __SUP_COUT__ <<
"Loading user history! " << __E__;
2573 returnStr[fileSz - 2] =
'\0';
2575 xmldoc.addTextElementToData(
"returnHistStr", &returnStr[i]);
2580 __SUP_COUT__ <<
"Unable to open history.hist" << __E__;
2586 const std::string& username)
2588 std::string fileName = MACROS_HIST_PATH + username +
"/" +
"FEhistory.hist";
2590 std::ifstream read(fileName.c_str());
2591 __SUP_COUT__ << fileName << __E__;
2593 if(!read.is_open() && username != WebUsers::DEFAULT_ADMIN_USERNAME)
2595 __SUP_COUT__ <<
"Unable to open FE history.hist.. Defaulting to admin's FE "
2596 "history as starting point."
2600 MACROS_HIST_PATH + WebUsers::DEFAULT_ADMIN_USERNAME +
"/" +
"FEhistory.hist";
2601 read.open(fileName.c_str());
2608 unsigned long long fileSize;
2609 unsigned long long i = 0;
2610 unsigned long long MAX_HISTORY_SIZE = 100000;
2613 read.seekg(0, std::ios::end);
2614 fileSize = read.tellg();
2615 returnStr =
new char[fileSize + 1];
2616 returnStr[fileSize] =
'\0';
2617 read.seekg(0, std::ios::beg);
2620 read.read(returnStr, fileSize);
2624 if(fileSize > MAX_HISTORY_SIZE)
2626 i = fileSize - MAX_HISTORY_SIZE;
2627 for(; i < fileSize; ++i)
2629 if(returnStr[i] ==
'#')
2639 FILE* fp = fopen(fileName.c_str(),
"w");
2643 __SS__ <<
"Big problem with FE history file: " << fileName << __E__;
2646 fwrite(&returnStr[i], fileSize - i, 1, fp);
2650 __SUP_COUT__ <<
"Loading user history! " << __E__;
2653 returnStr[fileSize - 2] =
'\0';
2655 xmldoc.addTextElementToData(
"returnHistStr", &returnStr[i]);
2660 __SUP_COUT__ <<
"Unable to open FE history.hist" << __E__;
2667 const std::string& username)
2672 std::string fileName = MacroName +
".dat";
2673 std::string fullPath;
2674 if(isMacroPublic ==
"true")
2675 fullPath = (std::string)MACROS_DB_PATH +
"publicMacros/" + fileName;
2677 fullPath = (std::string)MACROS_DB_PATH + username +
"/" + fileName;
2679 __SUP_COUT__ << fullPath << __E__;
2681 std::remove(fullPath.c_str());
2682 __SUP_COUT__ <<
"Successfully deleted " << MacroName;
2683 xmldoc.addTextElementToData(
"deletedMacroName", MacroName);
2689 const std::string& username)
2701 __SUP_COUTV__(oldMacroName);
2702 __SUP_COUTV__(newMacroName);
2703 __SUP_COUTV__(FESequence);
2704 __SUP_COUTV__(Notes);
2705 __SUP_COUTV__(Time);
2706 __SUP_COUTV__(isMacroPublic);
2707 __SUP_COUTV__(isMacroLSBF);
2709 __SUP_COUTV__(MACROS_DB_PATH);
2711 std::string fileName = oldMacroName +
".dat";
2712 std::string fullPath;
2713 if(isMacroPublic ==
"true")
2714 fullPath = (std::string)MACROS_DB_PATH +
"publicMacros/" + fileName;
2716 fullPath = (std::string)MACROS_DB_PATH + username +
"/" + fileName;
2718 __SUP_COUTV__(fullPath);
2720 std::ofstream macrofile(fullPath.c_str());
2721 if(macrofile.is_open())
2724 macrofile <<
"\"name\":\"" << newMacroName <<
"\",\n";
2725 macrofile <<
"\"FEsequence\":\"" << FESequence <<
"\",\n";
2726 macrofile <<
"\"time\":\"" << Time <<
"\",\n";
2727 macrofile <<
"\"notes\":\"" << Notes <<
"\",\n";
2728 macrofile <<
"\"LSBF\":\"" << isMacroLSBF <<
"\"\n";
2729 macrofile <<
"}@" << __E__;
2733 __SUP_COUT__ <<
"Unable to open file" << __E__;
2735 if(oldMacroName != newMacroName)
2739 rename((MACROS_DB_PATH + username +
"/" + oldMacroName +
".dat").c_str(),
2740 (MACROS_DB_PATH + username +
"/" + newMacroName +
".dat").c_str());
2742 xmldoc.addTextElementToData(
"newMacroName", newMacroName);
2744 xmldoc.addTextElementToData(
"newMacroName",
"ERROR");
2749 void MacroMakerSupervisor::clearHistory(
const std::string& username)
2751 std::string fileName =
"history.hist";
2752 std::string fullPath = (std::string)MACROS_HIST_PATH + username +
"/" + fileName;
2754 std::remove(fullPath.c_str());
2755 __SUP_COUT__ <<
"Successfully deleted " << fullPath;
2759 void MacroMakerSupervisor::clearFEHistory(
const std::string& username)
2761 std::string fileName =
"FEhistory.hist";
2762 std::string fullPath = (std::string)MACROS_HIST_PATH + username +
"/" + fileName;
2764 std::remove(fullPath.c_str());
2768 lastFeCommandToHistory_.erase(username);
2769 lastFeRepeatCount_.erase(username);
2770 lastFeRecordFilePos_.erase(username);
2771 lastFeLaunchTime_.erase(username);
2773 __SUP_COUT__ <<
"Successfully deleted " << fullPath;
2779 const std::string& username)
2784 std::string macroNotes =
2787 __SUP_COUTV__(pluginName);
2788 __SUP_COUTV__(macroName);
2789 __SUP_COUTV__(macroSequence);
2792 for(
unsigned int i = 0; i < macroNotes.length(); ++i)
2793 if(macroNotes[i] ==
'\r' || macroNotes[i] ==
'\n')
2794 macroNotes[i] =
' ';
2795 __SUP_COUTV__(macroNotes);
2797 std::stringstream ss(macroSequence);
2798 std::string command;
2799 std::vector<std::string> commands;
2801 while(getline(ss, command,
','))
2802 commands.push_back(command);
2806 std::map<std::string , std::set<std::string> >
2807 specialsCodeMap = CodeEditor::getSpecialsMap();
2810 auto specialsCodeMapIt = specialsCodeMap.find(CodeEditor::SPECIAL_TYPE_FEInterface);
2811 if(specialsCodeMapIt == specialsCodeMap.end())
2814 <<
"Could not find any FE Interface plugins in source code. Does MacroMaker "
2815 <<
"have access to the source code? Check that the Supervisor context places "
2817 <<
"location with access to the source code." << __E__;
2822 std::string headerFile = pluginName +
".h";
2823 std::string sourceFile = pluginName +
"_interface.cc";
2824 bool foundHeaderFile =
false;
2825 bool foundSourceFile =
false;
2826 for(
const auto& filePath : specialsCodeMapIt->second)
2828 if(!foundHeaderFile && filePath.find(headerFile) != std::string::npos)
2830 foundHeaderFile =
true;
2831 headerFile = filePath;
2832 __SUP_COUT__ <<
"found headerFile=" << filePath << __E__;
2834 if(!foundSourceFile && filePath.find(sourceFile) != std::string::npos)
2836 foundSourceFile =
true;
2837 sourceFile = filePath;
2838 __SUP_COUT__ <<
"found sourceFile=" << filePath << __E__;
2841 if(foundSourceFile && foundHeaderFile)
2845 if(!foundHeaderFile)
2847 __SS__ <<
"Could not find the header file for the FE Interface plugins at '"
2848 << headerFile <<
".' Does MacroMaker "
2849 <<
"have access to the source code? Check that the Supervisor context "
2850 "places MacroMaker in a "
2851 <<
"location with access to the source code." << __E__;
2854 if(!foundSourceFile)
2856 __SS__ <<
"Could not find the source file for the FE Interface plugins at '"
2857 << sourceFile <<
".' Does MacroMaker "
2858 <<
"have access to the source code? Check that the Supervisor context "
2859 "places MacroMaker in a "
2860 <<
"location with access to the source code." << __E__;
2873 char timeBuffer[100];
2876 struct tm* timeinfo;
2879 timeinfo = localtime(&rawtime);
2881 strftime(timeBuffer, 100,
"%b-%d-%Y %I:%M:%S", timeinfo);
2884 std::string contents;
2889 CodeEditor::readFile(CodeEditor::SOURCE_BASE_PATH, sourceFile, contents);
2893 xmldoc.addTextElementToData(
"sourceFile", sourceFile);
2894 xmldoc.addTextElementToData(
"headerFile", headerFile);
2897 if(contents.find(pluginName +
"::" + macroName) != std::string::npos)
2899 __SS__ <<
"The function definition '" << (pluginName +
"::" + macroName)
2900 <<
"(...)' already exists in the source file '" << sourceFile
2901 <<
".' Duplicate functions are not allowed - please rename the macro or "
2902 "modify the source file."
2907 std::stringstream codess;
2908 std::set<std::string> inArgNames, outArgNames;
2920 auto insertPos = contents.find(pluginName +
"::" + pluginName);
2921 if(insertPos == std::string::npos)
2923 __SS__ <<
"Could not find the code insert position in the source file '"
2924 << sourceFile <<
".' The FE plugin class constructor must be '"
2925 << pluginName <<
":" << pluginName <<
"' - is this the case?" << __E__;
2928 __SUP_COUTV__(insertPos);
2930 insertPos = contents.find(
"{", insertPos);
2931 if(insertPos == std::string::npos)
2933 __SS__ <<
"Could not find the code insert position in the source file '"
2935 <<
".' The FE plugin class constructor must begin with '{"
2936 <<
"' - is this the case?" << __E__;
2940 __SUP_COUTV__(insertPos);
2942 insert =
"\n\t//registration of FEMacro '" + macroName +
"' generated, " +
2943 timeBuffer +
", by '" + username +
"' using MacroMaker.\n\t" +
2944 "FEVInterface::registerFEMacroFunction(\"" + macroName +
2945 "\",//feMacroName \n\t\t" +
2946 "static_cast<FEVInterface::frontEndMacroFunction_t>(&" + pluginName +
2947 "::" + macroName +
"), //feMacroFunction \n\t\t" +
2948 "std::vector<std::string>{";
2951 for(
const auto& inArg : inArgNames)
2957 insert +=
"\"" + inArg +
"\"";
2960 insert +=
"}, //namesOfInputArgs \n\t\t";
2961 insert +=
"std::vector<std::string>{";
2964 for(
const auto& outArg : outArgNames)
2970 insert +=
"\"" + outArg +
"\"";
2973 insert +=
"}, //namesOfOutputArgs \n\t\t";
2974 insert +=
"1); //requiredUserPermissions \n\n";
2976 __SUP_COUTV__(insert);
2977 contents = contents.substr(0, insertPos) + insert + contents.substr(insertPos);
2982 auto insertPos = contents.rfind(
"DEFINE_OTS_INTERFACE");
2983 if(insertPos == std::string::npos)
2985 __SS__ <<
"Could not find the code insert position in the source file '"
2987 <<
".' The FE plugin class must end with a 'DEFINE_OTS_INTERFACE("
2988 << pluginName <<
")' - is this the case?" << __E__;
2991 __SUP_COUTV__(insertPos);
2995 "============================================================================"
2996 "============================================\n//" +
2997 macroName +
"\n" +
"//\tFEMacro '" + macroName +
"' generated, " +
2998 timeBuffer +
", by '" + username +
"' using MacroMaker.\n" +
2999 "//\tMacro Notes: " + macroNotes +
"\n" +
"void " + pluginName +
3000 "::" + macroName +
"(__ARGS__)\n{\n\t" +
3001 "__CFG_COUT__ << \"# of input args = \" << argsIn.size() << __E__; \n\t" +
3002 "__CFG_COUT__ << \"# of output args = \" << argsOut.size() << __E__; \n\t" +
3003 "for(auto &argIn:argsIn) \n\t\t" +
3004 "__CFG_COUT__ << argIn.first << \": \" << argIn.second << __E__; \n\n\t" +
3005 "//macro commands section \n" + codess.str() +
"\n\n\t" +
3006 "for(auto &argOut:argsOut) \n\t\t" +
3007 "__CFG_COUT__ << argOut.first << \": \" << argOut.second << __E__; \n\n" +
3008 "} //end " + macroName +
"()\n\n";
3011 CodeEditor::writeFile(CodeEditor::SOURCE_BASE_PATH,
3014 "MacroMaker-" + username,
3021 CodeEditor::readFile(CodeEditor::SOURCE_BASE_PATH, headerFile, contents);
3026 auto insertPos = contents.rfind(
"};");
3027 if(insertPos == std::string::npos)
3029 __SS__ <<
"Could not find the code insert position in the header file '"
3031 <<
".' The FE plugin class must end with a '};' - is this the case?"
3036 __SUP_COUTV__(insertPos);
3038 insert =
"\npublic: // FEMacro '" + macroName +
"' generated, " + timeBuffer +
3039 ", by '" + username +
"' using MacroMaker.\n\t" +
"void " + macroName +
3042 __SUP_COUTV__(insert);
3043 CodeEditor::writeFile(CodeEditor::SOURCE_BASE_PATH,
3046 "MacroMaker-" + username,
3056 const std::string& username)
3060 std::string macroNotes =
3063 __SUP_COUTV__(macroName);
3064 __SUP_COUTV__(macroSequence);
3067 for(
unsigned int i = 0; i < macroNotes.length(); ++i)
3068 if(macroNotes[i] ==
'\r' || macroNotes[i] ==
'\n')
3069 macroNotes[i] =
' ';
3070 __SUP_COUTV__(macroNotes);
3072 std::stringstream ss(macroSequence);
3073 std::string command;
3074 std::vector<std::string> commands;
3076 while(getline(ss, command,
','))
3077 commands.push_back(command);
3079 std::string fileName = macroName +
".cc";
3081 std::string fullPath =
3082 __ENV__(
"SERVICE_DATA_PATH") + MACROS_EXPORT_PATH + username +
"/" + fileName;
3083 __SUP_COUT__ << fullPath << __E__;
3084 std::ofstream exportFile(fullPath.c_str(), std::ios::trunc);
3085 if(exportFile.is_open())
3087 exportFile <<
"//Generated Macro Name:\t" << macroName <<
"\n";
3088 exportFile <<
"//Macro Notes: " << macroNotes <<
"\n";
3092 struct tm* timeinfo;
3096 timeinfo = localtime(&rawtime);
3098 strftime(buffer, 100,
"%b-%d-%Y %I:%M:%S", timeinfo);
3099 exportFile <<
"//Generated Time: \t\t" << buffer <<
"\n";
3102 exportFile <<
"//Paste this whole file into an interface to transfer Macro "
3105 createCode(exportFile, commands);
3109 xmldoc.addTextElementToData(
3111 "$USER_DATA/ServiceData/" + MACROS_EXPORT_PATH + username +
"/" + fileName);
3114 __SUP_COUT__ <<
"Unable to open file" << __E__;
3119 void MacroMakerSupervisor::createCode(std::ostream& out,
3120 const std::vector<std::string>& commands,
3121 const std::string& tabOffset,
3123 std::set<std::string>* inArgNames,
3124 std::set<std::string>* outArgNames)
3127 std::set<std::string > argInHasBeenInitializedSet;
3128 bool addressIsVariable, dataIsVariable;
3130 out << tabOffset <<
"{";
3133 << tabOffset <<
"\t"
3134 <<
"char *address \t= new char[universalAddressSize_]{0}; //create address "
3135 "buffer of interface size and init to all 0";
3137 << tabOffset <<
"\t"
3138 <<
"char *data \t\t= new char[universalDataSize_]{0}; //create data buffer "
3139 "of interface size and init to all 0";
3142 << tabOffset <<
"\t"
3143 <<
"uint64_t macroAddress; //create macro address buffer (size 8 bytes)";
3145 << tabOffset <<
"\t"
3146 <<
"uint64_t macroData; //create macro address buffer (size 8 bytes)";
3149 << tabOffset <<
"\t"
3150 <<
"std::map<std::string /*arg name*/,uint64_t /*arg val*/> macroArgs; //create "
3151 "map from arg name to 64-bit number";
3154 for(
unsigned int i = 0; i < commands.size(); i++)
3156 std::stringstream sst(commands[i]);
3158 std::vector<std::string>
3160 while(getline(sst, tokens,
':'))
3161 oneCommand.push_back(tokens);
3162 while(oneCommand.size() < 4)
3163 oneCommand.push_back(
"");
3191 addressIsVariable = isArgumentVariable(oneCommand[2]);
3192 dataIsVariable = isArgumentVariable(oneCommand[3]);
3194 __SUP_COUTV__(addressIsVariable);
3195 __SUP_COUTV__(dataIsVariable);
3197 out <<
"\n\n" << tabOffset <<
"\t// command-#" << i <<
": ";
3199 if(oneCommand[1][0] ==
'w' || oneCommand[1][0] ==
'r')
3201 if(oneCommand[1][0] ==
'w')
3203 else if(oneCommand[1][0] ==
'r')
3206 if(addressIsVariable)
3207 out << oneCommand[2];
3209 out <<
"0x" << oneCommand[2];
3210 out <<
" /*address*/,";
3214 out << oneCommand[3] <<
" /*data*/";
3215 else if(oneCommand[1][0] ==
'w')
3216 out <<
"0x" << oneCommand[3] <<
" /*data*/";
3217 else if(oneCommand[1][0] ==
'r')
3221 else if(oneCommand[1][0] ==
'd')
3223 out <<
"delay(" << oneCommand[2] <<
");\n";
3224 out << tabOffset <<
"\t"
3225 <<
"__CFG_COUT__ << \"Sleeping for... \" << " << oneCommand[2]
3226 <<
" << \" milliseconds \" << __E__;\n";
3227 out << tabOffset <<
"\t"
3228 <<
"usleep(" << oneCommand[2] <<
"*1000 /* microseconds */);\n";
3233 __SS__ <<
"FATAL ERROR: Unknown command '" << oneCommand[1]
3234 <<
"'... command is not w, r or d" << __E__;
3240 if(addressIsVariable)
3242 if(argInHasBeenInitializedSet.find(oneCommand[2]) ==
3243 argInHasBeenInitializedSet.end())
3245 argInHasBeenInitializedSet.emplace(oneCommand[2]);
3250 out << tabOffset <<
"\t"
3251 <<
"macroArgs[\"" << oneCommand[2]
3253 "theXDAQContextConfigTree_.getNode(theConfigurationPath_)."
3256 << tabOffset <<
"\t\t\"" << oneCommand[2]
3257 <<
"\").getValue<uint64_t>();";
3262 inArgNames->emplace(oneCommand[2]);
3265 out << tabOffset <<
"\t"
3266 <<
"macroArgs[\"" << oneCommand[2] <<
"\"] = __GET_ARG_IN__(\""
3267 << oneCommand[2] <<
"\", uint64_t);";
3270 out <<
"\t//get macro address argument";
3272 << tabOffset <<
"\tmemcpy(address,¯oArgs[\"" << oneCommand[2]
3273 <<
"\"],8); //copy macro address argument to buffer";
3277 out << tabOffset <<
"\t"
3278 <<
"macroAddress = 0x" << oneCommand[2]
3279 <<
"; memcpy(address,¯oAddress,8);"
3280 <<
"\t//copy macro address to buffer";
3285 if(oneCommand[1] ==
"w")
3289 if(argInHasBeenInitializedSet.find(oneCommand[3]) ==
3290 argInHasBeenInitializedSet
3293 argInHasBeenInitializedSet.emplace(oneCommand[3]);
3298 inArgNames->emplace(oneCommand[3]);
3302 << tabOffset <<
"\t"
3303 <<
"macroArgs[\"" << oneCommand[3]
3304 <<
"\"] = __GET_ARG_IN__(\"" << oneCommand[3]
3305 <<
"\", uint64_t); //initialize from input arguments";
3311 << tabOffset <<
"\t"
3312 <<
"macroArgs[\"" << oneCommand[3]
3314 "theXDAQContextConfigTree_.getNode(theConfigurationPath_)."
3317 << tabOffset <<
"\t\t\"" << oneCommand[3]
3318 <<
"\").getValue<uint64_t>(); //initialize from "
3319 "configuration tree";
3322 out <<
"\t//get macro data argument";
3324 << tabOffset <<
"\tmemcpy(data,¯oArgs[\"" << oneCommand[3]
3325 <<
"\"],8); //copy macro data argument to buffer";
3330 << tabOffset <<
"\t"
3331 <<
"macroData = 0x" << oneCommand[3] <<
"; memcpy(data,¯oData,8);"
3332 <<
"\t//copy macro data to buffer";
3335 << tabOffset <<
"\t"
3336 <<
"universalWrite(address,data);";
3341 << tabOffset <<
"\t"
3342 <<
"universalRead(address,data);";
3344 std::string outputArgName;
3347 outputArgName = oneCommand[3];
3351 sprintf(str,
"outArg%d", i);
3352 outputArgName = str;
3354 __SUP_COUTV__(outputArgName);
3356 out << tabOffset <<
"\t"
3357 <<
"memcpy(¯oArgs[\"" << outputArgName
3358 <<
"\"],data,8); //copy buffer to argument map";
3363 << tabOffset <<
"\t"
3364 <<
"__SET_ARG_OUT__(\"" << outputArgName <<
"\",macroArgs[\""
3365 << outputArgName <<
"\"]); //update output argument result";
3368 outArgNames->emplace(outputArgName);
3369 argInHasBeenInitializedSet.emplace(
3374 out <<
"\n\n" << tabOffset <<
"\tdelete[] address; //free the memory";
3375 out <<
"\n" << tabOffset <<
"\tdelete[] data; //free the memory";
3376 out <<
"\n" << tabOffset <<
"}";
3378 __SUP_COUT__ <<
"Done with code generation." << __E__;
3384 bool MacroMakerSupervisor::isArgumentVariable(
const std::string& argumentString)
3386 for(
unsigned int i = 0; i < argumentString.length(); ++i)
3389 if(!((argumentString[i] >=
'0' && argumentString[i] <=
'9') ||
3390 (argumentString[i] >=
'a' && argumentString[i] <=
'f') ||
3391 (argumentString[i] >=
'A' && argumentString[i] <=
'F')))
3406 std::string MacroMakerSupervisor::generateHexArray(
const std::string& sourceHexString,
3409 std::stringstream retSs;
3411 std::string srcHexStr = sourceHexString;
3412 __SUP_COUT__ <<
"Translating: \n";
3413 __SUP_COUT__ << srcHexStr << __E__;
3415 if(srcHexStr.size() % 2)
3416 srcHexStr =
"0" + srcHexStr;
3418 numOfBytes = srcHexStr.size() / 2;
3419 retSs <<
"[" << numOfBytes <<
"] = {";
3421 for(
int i = 0; i < numOfBytes * 2; i += 2)
3424 if(!((srcHexStr[i] >=
'0' && srcHexStr[i] <=
'9') ||
3425 (srcHexStr[i] >=
'a' && srcHexStr[i] <=
'f') ||
3426 (srcHexStr[i] >=
'A' && srcHexStr[i] <=
'F')) ||
3427 !((srcHexStr[i + 1] >=
'0' && srcHexStr[i + 1] <=
'9') ||
3428 (srcHexStr[i + 1] >=
'a' && srcHexStr[i + 1] <=
'f') ||
3429 (srcHexStr[i + 1] >=
'A' && srcHexStr[i + 1] <=
'F')))
3437 retSs <<
"0x" << srcHexStr[srcHexStr.size() - 1 - i - 1]
3438 << srcHexStr[srcHexStr.size() - 1 - i];
3442 __SUP_COUT__ << retSs.str() << __E__;
3450 const WebUsers::RequestUserInfo& userInfo)
3453 __SUP_COUTT__ << __E__;
3455 uint64_t NotDoneID = CgiDataUtilities::getDataAsUint64_t(cgi,
"NotDoneID");
3458 std::lock_guard<std::mutex> lock(feMacroRunThreadStructMutex_);
3460 __SUP_COUTT__ <<
"Checking NotDoneID = " << NotDoneID << __E__;
3462 time_t now = time(0);
3463 size_t target_i = -1;
3464 for(
size_t i = 0; i < feMacroRunThreadStruct_.size(); ++i)
3466 auto& group = feMacroRunThreadStruct_[i];
3467 if(group->groupID_ == NotDoneID)
3469 __SUP_COUTT__ <<
"Found group NotDoneID = " << NotDoneID << __E__;
3472 else if(group->allDone())
3475 time_t latestDone = 0;
3476 for(
const auto& t : group->tasks_)
3477 if(t->parameters_.doneTime_ > latestDone)
3478 latestDone = t->parameters_.doneTime_;
3479 if(latestDone >= 0 && now - latestDone > 5 * 60 )
3481 __SUP_COUTT__ <<
"Cleaning up completed group " << group->groupID_
3483 feMacroRunThreadStruct_.erase(feMacroRunThreadStruct_.begin() + i);
3487 else if(now - group->startTime_ > 5 * 60 )
3489 std::string targets;
3490 std::string feMacroName;
3491 for(
const auto& t : group->tasks_)
3493 if(!targets.empty())
3495 targets += t->parameters_.feUIDSelected_;
3496 if(feMacroName.empty())
3497 feMacroName = t->parameters_.macroName_;
3499 __SUP_COUT_WARN__ <<
"Found old FE Macro group that has not completed"
3500 <<
" (groupID=" << group->groupID_ <<
", targets=["
3501 << targets <<
"], FE macro name=" << feMacroName <<
")"
3507 if(target_i >= feMacroRunThreadStruct_.size())
3510 <<
"Attempted to check recent FE Macro run completion with invalid ID="
3512 <<
". Perhaps this FE Macro completed more than 5 minutes ago?" << __E__;
3516 auto& targetGroup = feMacroRunThreadStruct_[target_i];
3517 if(targetGroup->allDone())
3519 __SUP_COUT__ <<
"Found all done for group NotDoneID = " << NotDoneID << __E__;
3520 for(
auto& task : targetGroup->tasks_)
3522 task->bar_->complete();
3525 for(
auto& task : targetGroup->tasks_)
3527 if(task->parameters_.feMacroRunError_ !=
"")
3529 __SUP_SS__ << task->parameters_.feMacroRunError_;
3536 std::ostringstream oss;
3537 for(
auto& task : targetGroup->tasks_)
3538 task->parameters_.xmldoc_.outputXmlDocument(&oss);
3539 __SUP_COUTT__ <<
"xmldoc: " << oss.str() << __E__;
3541 for(
auto& task : targetGroup->tasks_)
3543 __SUP_COUT__ <<
"FE macro group complete." << __E__;
3547 __SUP_COUT__ <<
"Found still going for group NotDoneID = " << NotDoneID
3550 xmldoc.addNumberElementToData(
"NotDoneID", NotDoneID);
3553 for(
auto& task : targetGroup->tasks_)
3555 DOMElement* progParent = xmldoc.addTextElementToData(
3556 "feMacroProgress", task->parameters_.feUIDSelected_);
3557 if(task->feMacroRunDone_)
3563 int rp = task->realProgress_.load();
3567 "progress", std::to_string(rp), progParent);
3572 "progress", std::to_string(task->bar_->read()), progParent);
3582 std::string feUIDSelected =
3585 std::string macroName =
3589 bool saveOutputs = CgiDataUtilities::getDataAsInt(cgi,
"saveOutputs") == 1;
3591 __SUP_COUTTV__(feClassSelected);
3592 __SUP_COUTTV__(feUIDSelected);
3593 __SUP_COUTTV__(macroType);
3594 __SUP_COUTTV__(macroName);
3595 __SUP_COUTTV__(inputArgs);
3596 __SUP_COUTTV__(outputArgs);
3597 __SUP_COUTTV__(saveOutputs);
3598 __SUP_COUTTV__(userInfo.username_);
3602 std::set<std::string> feUIDs;
3604 std::string expandUID = feUIDSelected.empty() ?
"*" : feUIDSelected;
3605 if(expandUID !=
"*")
3612 for(
auto& feTypePair : FEPluginTypetoFEsMap_)
3614 if(feClassSelected.empty() || feClassSelected ==
"*" ||
3615 feClassSelected == feTypePair.first)
3616 for(
auto& uid : feTypePair.second)
3617 feUIDs.emplace(uid);
3621 feUIDs.emplace(feUIDSelected);
3626 auto group = std::make_shared<runFEMacroGroupStruct>();
3627 group->historyFeClassSelected_ = feClassSelected.empty() ?
"*" : feClassSelected;
3628 group->historyFeUIDSelected_ = feUIDSelected.empty() ?
"*" : feUIDSelected;
3629 group->historyMacroType_ = macroType;
3630 group->historyMacroName_ = macroName;
3631 group->historyInputArgs_ = inputArgs;
3632 group->historyOutputArgs_ = outputArgs;
3633 group->historySaveOutputs_ = saveOutputs;
3634 group->historyUsername_ = userInfo.username_;
3635 for(
const std::string& uid : feUIDs)
3637 group->tasks_.push_back(std::make_shared<runFEMacroStruct>(
3650 std::lock_guard<std::mutex> lock(feMacroRunThreadStructMutex_);
3651 group->groupID_ = ++feMacroRunGroupIDCounter_;
3652 if(feMacroRunGroupIDCounter_ == 0)
3654 ++feMacroRunGroupIDCounter_;
3656 for(
auto& task : group->tasks_)
3658 task->bar_ = std::make_unique<ProgressBar>();
3659 task->bar_->reset(macroName, task->parameters_.feUIDSelected_);
3661 feMacroRunThreadStruct_.emplace_back(group);
3664 std::thread([group,
this]() {
3665 MacroMakerSupervisor::runFEMacroGroupSchedulerThread(group,
this);
3674 size_t sleepTime = 10 * 1000;
3677 for(
int i = 0; i < 2; ++i)
3679 if(group->allDone())
3681 __SUP_COUTT__ <<
"All FE macro tasks marked done" << __E__;
3682 for(
const auto& task : group->tasks_)
3683 if(task->parameters_.doneTime_ > group->completeTime_)
3684 group->completeTime_ = task->parameters_.doneTime_;
3689 __SUP_COUTT__ <<
"FE macros not all done, sleeping..." << __E__;
3694 if(!group->allDone())
3696 xmldoc.addNumberElementToData(
"NotDoneID", group->groupID_);
3700 std::lock_guard<std::mutex> lock(feMacroRunThreadStructMutex_);
3701 for(
auto& task : group->tasks_)
3703 DOMElement* progParent = xmldoc.addTextElementToData(
3704 "feMacroProgress", task->parameters_.feUIDSelected_);
3705 if(task->feMacroRunDone_)
3711 int rp = task->realProgress_.load();
3715 "progress", std::to_string(rp), progParent);
3720 "progress", std::to_string(task->bar_->read()), progParent);
3728 for(
auto& task : group->tasks_)
3730 if(task->parameters_.feMacroRunError_ !=
"")
3732 __SUP_SS__ << task->parameters_.feMacroRunError_;
3739 std::ostringstream oss;
3740 for(
auto& task : group->tasks_)
3741 task->parameters_.xmldoc_.outputXmlDocument(
3742 &oss,
false ,
true );
3743 __SUP_COUTT__ <<
"xmldoc: " << oss.str() << __E__;
3745 for(
auto& task : group->tasks_)
3749 std::lock_guard<std::mutex> lock(feMacroRunThreadStructMutex_);
3750 for(
size_t i = 0; i < feMacroRunThreadStruct_.size(); ++i)
3752 if(feMacroRunThreadStruct_[i].get() == group.get())
3754 feMacroRunThreadStruct_.erase(feMacroRunThreadStruct_.begin() + i);
3759 __SUP_COUT__ <<
"All FE macros complete." << __E__;
3762 std::lock_guard<std::mutex> lock(feMacroRunThreadStructMutex_);
3763 for(
const auto& g : feMacroRunThreadStruct_)
3764 __SUP_COUTT__ <<
"[] groupID_ = " << g->groupID_ << __E__;
3768 catch(
const std::runtime_error& e)
3770 __SUP_SS__ <<
"Error processing FE communication request: " << e.what() << __E__;
3771 __SUP_COUT_ERR__ << ss.str();
3772 xmldoc.addTextElementToData(
"Error", ss.str());
3776 __SUP_SS__ <<
"Unknown error processing FE communication request." << __E__;
3781 catch(
const std::exception& e)
3783 ss <<
"Exception message: " << e.what();
3788 __SUP_COUT_ERR__ << ss.str();
3790 xmldoc.addTextElementToData(
"Error", ss.str());
3795 void MacroMakerSupervisor::runFEMacroGroupSchedulerThread(
3799 if(!group || !mmSupervisor || group->tasks_.empty())
3802 __COUT__ <<
"FE macro group scheduler started. groupID=" << group->groupID_
3803 <<
" tasks=" << group->tasks_.size() << __E__;
3805 std::size_t maxThreads = StringMacros::getConcurrencyCount();
3808 if(maxThreads > group->tasks_.size())
3809 maxThreads = group->tasks_.size();
3811 std::vector<std::pair<std::shared_ptr<runFEMacroStruct>, std::future<void>>> active;
3812 active.reserve(maxThreads);
3813 std::size_t nextTaskIndex = 0;
3815 auto launchTask = [&](std::shared_ptr<runFEMacroStruct> task) {
3816 active.emplace_back(task, std::async(std::launch::async, [task, mmSupervisor]() {
3817 MacroMakerSupervisor::runFEMacroThread(task,
3822 while(nextTaskIndex < group->tasks_.size() || !active.empty())
3824 while(nextTaskIndex < group->tasks_.size() && active.size() < maxThreads)
3825 launchTask(group->tasks_[nextTaskIndex++]);
3828 std::lock_guard<std::mutex> lock(mmSupervisor->feMacroRunThreadStructMutex_);
3829 for(
const auto& activeTask : active)
3830 if(activeTask.first && !activeTask.first->feMacroRunDone_ &&
3831 activeTask.first->bar_)
3832 activeTask.first->bar_->step();
3835 bool anyFinished =
false;
3836 for(
size_t i = 0; i < active.size();)
3838 if(active[i].second.wait_for(std::chrono::milliseconds(0)) ==
3839 std::future_status::ready)
3841 __COUTT__ <<
"FE macro group scheduler task complete. groupID="
3843 <<
" uid=" << active[i].first->parameters_.feUIDSelected_
3845 active[i].second.get();
3846 active.erase(active.begin() + i);
3857 for(
const auto& task : group->tasks_)
3858 if(task->parameters_.doneTime_ > group->completeTime_)
3859 group->completeTime_ = task->parameters_.doneTime_;
3861 if(!group->historySaved_)
3863 mmSupervisor->appendCommandToHistory(group->historyFeClassSelected_,
3864 group->historyFeUIDSelected_,
3865 group->historyMacroType_,
3866 group->historyMacroName_,
3867 group->historyInputArgs_,
3868 group->historyOutputArgs_,
3869 group->historySaveOutputs_,
3870 group->historyUsername_,
3872 group->completeTime_);
3873 group->historySaved_ =
true;
3876 __COUT__ <<
"FE macro group scheduler ended. groupID=" << group->groupID_ << __E__;
3878 catch(
const std::exception& e)
3880 __SS__ <<
"Error during FE macro group scheduler thread: " << e.what() << __E__;
3881 __COUT_ERR__ << ss.str();
3885 __COUT_ERR__ <<
"Unknown error during FE macro group scheduler thread." << __E__;
3890 void MacroMakerSupervisor::runFEMacroThread(
3891 std::shared_ptr<runFEMacroStruct> feMacroRunThreadStruct,
3895 feMacroRunThreadStruct->parameters_.threadID_ =
3896 std::hash<std::thread::id>{}(std::this_thread::get_id());
3898 __COUT__ <<
"runFEMacro thread started... threadid = " << std::this_thread::get_id()
3899 <<
" " << mmSupervisor <<
" getpid()=" << getpid()
3900 <<
" gettid()=" << gettid() << __E__;
3902 mmSupervisor->runFEMacro(feMacroRunThreadStruct->parameters_.xmldoc_,
3903 feMacroRunThreadStruct->parameters_.feClassSelected_,
3904 feMacroRunThreadStruct->parameters_.feUIDSelected_,
3905 feMacroRunThreadStruct->parameters_.macroType_,
3906 feMacroRunThreadStruct->parameters_.macroName_,
3907 feMacroRunThreadStruct->parameters_.inputArgs_,
3908 feMacroRunThreadStruct->parameters_.outputArgs_,
3909 feMacroRunThreadStruct->parameters_.saveOutputs_,
3910 feMacroRunThreadStruct->parameters_.runningUsername_,
3911 feMacroRunThreadStruct->parameters_.userGroupPermissions_,
3913 &feMacroRunThreadStruct->realProgress_);
3915 feMacroRunThreadStruct->parameters_.doneTime_ = time(0);
3916 feMacroRunThreadStruct->feMacroRunDone_ =
true;
3917 __COUT__ <<
"runFEMacro thread done. threadid = " << std::this_thread::get_id()
3921 catch(
const std::runtime_error& e)
3923 __SS__ <<
"Error during runFEMacro thread: " << e.what() << __E__;
3924 __COUT_ERR__ << ss.str();
3925 feMacroRunThreadStruct->parameters_.feMacroRunError_ = ss.str();
3926 feMacroRunThreadStruct->parameters_.doneTime_ = time(0);
3927 feMacroRunThreadStruct->feMacroRunDone_ =
true;
3931 __SS__ <<
"Unknown error during runFEMacro thread." << __E__;
3936 catch(
const std::exception& e)
3938 ss <<
"Exception message: " << e.what();
3943 __COUT_ERR__ << ss.str();
3944 feMacroRunThreadStruct->parameters_.feMacroRunError_ = ss.str();
3945 feMacroRunThreadStruct->parameters_.doneTime_ = time(0);
3946 feMacroRunThreadStruct->feMacroRunDone_ =
true;
3951 std::string feClassSelected,
3952 std::string feUIDSelected,
3953 const std::string& macroType,
3954 const std::string& macroName,
3955 const std::string& inputArgs,
3956 const std::string outputArgs,
3958 const std::string& username,
3959 const std::string& userGroupPermissions,
3961 std::atomic<int>* realProgressOut)
3963 __SUP_COUTV__(feClassSelected);
3964 __SUP_COUTV__(feUIDSelected);
3965 __SUP_COUTV__(macroType);
3966 __SUP_COUTV__(macroName);
3967 __SUP_COUTV__(inputArgs);
3968 __SUP_COUTV__(outputArgs);
3969 __SUP_COUTV__(saveOutputs);
3970 __SUP_COUTV__(username);
3971 __SUP_COUTV__(userGroupPermissions);
3973 time_t launchTime = time(0);
3974 auto saveHistoryIfRequested = [&]() {
3978 appendCommandToHistory(feClassSelected,
3988 saveToHistory =
false;
3991 std::set<std::string > feUIDs;
3993 if(feUIDSelected ==
"")
3994 feUIDSelected =
"*";
3995 if(feClassSelected ==
"")
3996 feClassSelected =
"*";
3998 if(feClassSelected ==
"" || feUIDSelected ==
"" || macroType ==
"" || macroName ==
"")
4000 __SUP_SS__ <<
"Illegal empty front-end parameter." << __E__;
4003 else if(feUIDSelected !=
"*")
4010 if(feClassSelected ==
"*")
4012 for(
auto& feTypePair : FEPluginTypetoFEsMap_)
4013 for(
auto& feUID : feTypePair.second)
4014 feUIDs.emplace(feUID);
4018 auto typeIt = FEPluginTypetoFEsMap_.find(feClassSelected);
4019 if(typeIt == FEPluginTypetoFEsMap_.end())
4021 __SUP_SS__ <<
"Illegal front-end type parameter '" << feClassSelected
4022 <<
"' not in list of types." << __E__;
4026 for(
auto& feUID : typeIt->second)
4027 feUIDs.emplace(feUID);
4033 std::string macroString;
4034 if(macroType ==
"public")
4035 loadMacro(macroName, macroString);
4036 else if(macroType ==
"private")
4037 loadMacro(macroName, macroString, username);
4039 __SUP_COUTV__(macroString);
4046 std::string filename =
"/macroOutput_" + std::to_string(time(0)) +
"_" +
4047 std::to_string(clock()) +
".txt";
4049 __SUP_COUTV__(filename);
4050 fp = fopen((CodeEditor::OTSDAQ_DATA_PATH + filename).c_str(),
"w");
4053 __SUP_SS__ <<
"Failed to open file to save macro output '"
4054 << CodeEditor::OTSDAQ_DATA_PATH << filename <<
"'..." << __E__;
4058 fprintf(fp,
"############################\n");
4060 "### Running '%s' at time %s\n",
4064 "### \t Target front-ends (count=%lu): %s\n",
4067 fprintf(fp,
"### \t\t Inputs: %s\n", inputArgs.c_str());
4068 fprintf(fp,
"############################\n\n\n");
4070 xmldoc.addTextElementToData(
"feMacroRunArgs_name",
"Filename");
4071 xmldoc.addTextElementToData(
"feMacroRunArgs_value",
4072 "$OTSDAQ_DATA/" + filename);
4076 for(
auto& feUID : feUIDs)
4078 auto feIt = FEtoSupervisorMap_.find(feUID);
4079 if(feIt == FEtoSupervisorMap_.end())
4081 __SUP_SS__ <<
"Destination front end interface ID '" << feUID
4082 <<
"' was not found in the list of front ends." << __E__;
4083 ss <<
"\n\nHere is the map:\n\n"
4088 unsigned int FESupervisorIndex = feIt->second;
4089 __SUP_COUT__ <<
"Found supervisor index: " << FESupervisorIndex << __E__;
4091 SupervisorInfoMap::iterator it = allFESupervisorInfo_.find(FESupervisorIndex);
4092 if(it == allFESupervisorInfo_.end())
4095 <<
"Error transmitting request to FE Supervisor '" << feUID <<
":"
4096 << FESupervisorIndex <<
".' \n\n"
4097 <<
"The FE Supervisor Index does not exist. Have you configured "
4098 "the state machine properly?"
4105 if(macroType ==
"fe")
4106 txParameters.
addParameter(
"Request",
"RunInterfaceMacro");
4108 txParameters.
addParameter(
"Request",
"RunMacroMakerMacro");
4110 if(macroType ==
"fe")
4119 txParameters.
addParameter(
"userPermissions", userGroupPermissions);
4131 "Running '%s' at time %s\n",
4135 "\t Target front-end: '%s::%s'\n",
4136 FEtoPluginTypeMap_[feUID].c_str(),
4139 "\t\t Inputs: %s\n",
4144 xoap::MessageReference retMsg = SOAPMessenger::sendWithSOAPReply(
4145 it->second.getDescriptor(),
4146 "MacroMakerSupervisorRequest",
4149 SOAPUtilities::receive(retMsg, rxParameters);
4156 std::string notDoneTaskID = rxParameters.getValue(
"NotDoneTaskID");
4157 int asyncPollCount = 0;
4158 useconds_t pollSleepUs = 100 * 1000;
4159 if(!notDoneTaskID.empty())
4161 usleep(pollSleepUs);
4163 while(notDoneTaskID !=
"")
4171 xoap::MessageReference pollRetMsg =
4172 SOAPMessenger::sendWithSOAPReply(it->second.getDescriptor(),
4173 "MacroMakerSupervisorRequest",
4181 SOAPUtilities::receive(pollRetMsg, rxParameters);
4186 std::string progressStr = rxParameters.getValue(
"Progress");
4187 if(!progressStr.empty())
4188 realProgressOut->store(std::stoi(progressStr));
4191 notDoneTaskID = rxParameters.getValue(
"NotDoneTaskID");
4193 if(!notDoneTaskID.empty())
4195 usleep(pollSleepUs);
4197 if(pollSleepUs > 2000 * 1000 )
4198 pollSleepUs = 2000 * 1000;
4204 std::string outputResults = rxParameters.getValue(
"outputArgs");
4205 std::string error = rxParameters.getValue(
"Error");
4208 __SUP_COUTT__ <<
"outputArgs = " << outputResults << __E__;
4212 __SS__ <<
"Attempted FE Macro Failed. Attempted target "
4213 <<
"was UID=" << feUID
4214 <<
" at feSupervisorID=" << FESupervisorIndex <<
"." << __E__;
4215 ss <<
"\n\n The error was:\n\n" << error << __E__;
4216 __SUP_COUT_ERR__ <<
"\n" << ss.str();
4217 xmldoc.addTextElementToData(
"Error", ss.str());
4218 saveHistoryIfRequested();
4225 DOMElement* feMacroExecParent =
4226 xmldoc.addTextElementToData(
"feMacroExec", macroName);
4232 "fe_type", FEtoPluginTypeMap_[feUID], feMacroExecParent);
4234 "fe_context", it->second.getContextName(), feMacroExecParent);
4236 "fe_supervisor", it->second.getName(), feMacroExecParent);
4238 "fe_hostname", it->second.getHostname(), feMacroExecParent);
4240 std::istringstream inputStream(outputResults);
4241 std::string splitVal, argName, argValue;
4242 while(getline(inputStream, splitVal,
';'))
4244 std::istringstream pairInputStream(splitVal);
4245 getline(pairInputStream, argName,
',');
4246 getline(pairInputStream, argValue,
',');
4251 "\t\t Output '%s' = %s\n",
4258 "outputArgs_name", argName, feMacroExecParent);
4260 "outputArgs_value", argValue, feMacroExecParent);
4262 __SUP_COUTT__ << argName <<
": " << argValue << __E__;
4266 __SUP_COUTT__ <<
"runFEMacro() chk3." << __E__;
4273 saveHistoryIfRequested();
4280 saveHistoryIfRequested();
4282 __SUP_COUT__ <<
"runFEMacro() done." << __E__;
4289 const std::string& username)
4291 __SUP_COUT__ <<
"Getting FE Macro list" << __E__;
4294 txParameters.
addParameter(
"Request",
"GetInterfaceMacros");
4299 std::string oneInterface;
4300 std::string rxFEMacros;
4304 for(
auto& appInfo : allFESupervisorInfo_)
4306 __SUP_COUT__ <<
"FESupervisor LID = " << appInfo.second.getId()
4307 <<
" name = " << appInfo.second.getName() << __E__;
4309 xoap::MessageReference retMsg = SOAPMessenger::sendWithSOAPReply(
4310 appInfo.second.getDescriptor(),
"MacroMakerSupervisorRequest", txParameters);
4311 SOAPUtilities::receive(retMsg, rxParameters);
4313 rxFEMacros = rxParameters.getValue(
"FEMacros");
4315 __SUP_COUT__ <<
"FE Macros received: \n" << rxFEMacros << __E__;
4317 std::istringstream allInterfaces(rxFEMacros);
4318 while(std::getline(allInterfaces, oneInterface))
4322 xmldoc.addTextElementToData(
"FEMacros", oneInterface);
4328 std::pair<std::vector<std::string> ,
4329 std::vector<std::string> >
4331 loadMacroNames(username, macroNames);
4333 __SUP_COUT__ <<
"Public macro count: " << macroNames.first.size() << __E__;
4334 __SUP_COUT__ <<
"Private macro count: " << macroNames.second.size() << __E__;
4336 std::string macroString;
4345 for(
int i = 0; i < 2; ++i)
4346 for(
auto& macroName : (i ? macroNames.second : macroNames.first))
4349 loadMacro(macroName, macroString, username);
4354 std::stringstream xmlMacroStream;
4355 xmlMacroStream << macro.macroName_;
4356 xmlMacroStream <<
":"
4358 xmlMacroStream <<
":" << macro.namesOfInputArguments_.size();
4359 for(
auto& inputArg : macro.namesOfInputArguments_)
4360 xmlMacroStream <<
":" << inputArg;
4361 xmlMacroStream <<
":" << macro.namesOfOutputArguments_.size();
4362 for(
auto& inputArg : macro.namesOfOutputArguments_)
4363 xmlMacroStream <<
":" << inputArg;
4365 xmldoc.addTextElementToData(i ?
"PrivateMacro" :
"PublicMacro",
4366 xmlMacroStream.str());
static std::string postData(cgicc::Cgicc &cgi, const std::string &needle)
static std::string getOrPostData(cgicc::Cgicc &cgi, const std::string &needle)
static std::string getData(cgicc::Cgicc &cgi, const std::string &needle)
ConfigurationTree getNode(const std::string &nodeString, bool doNotThrowOnBrokenUIDLinks=false) const
void loadTableGroup(const std::string &tableGroupName, const TableGroupKey &tableGroupKey, bool doActivate=false, std::map< std::string, TableVersion > *groupMembers=0, ProgressBar *progressBar=0, std::string *accumulateWarnings=0, std::string *groupComment=0, std::string *groupAuthor=0, std::string *groupCreateTime=0, bool doNotLoadMember=false, std::string *groupTypeString=0, std::map< std::string, std::string > *groupAliases=0, ConfigurationManager::LoadGroupType groupTypeToLoad=ConfigurationManager::LoadGroupType::ALL_TYPES, bool ignoreVersionTracking=false, std::map< std::string, TableVersion > mergeInTables={}, std::map< std::string, TableVersion > overrideTables={})
ConfigurationTree getNode(const std::string &nodeName, bool doNotThrowOnBrokenUIDLinks=false) const
std::vector< std::pair< std::string, ConfigurationTree > > getChildren(std::map< std::string, std::string > filterMap=std::map< std::string, std::string >(), bool byPriority=false, bool onlyStatusTrue=false) const
void getRequestUserInfo(WebUsers::RequestUserInfo &requestUserInfo)
friend friend class MacroMakerSupervisor
virtual void nonXmlRequest(const std::string &requestType, cgicc::Cgicc &cgiIn, std::ostream &out, const WebUsers::RequestUserInfo &userInfo)
void copyDataChildren(HttpXmlDocument &document)
std::string getMatchingValue(const std::string &field, const unsigned int occurance=0)
void outputXmlDocument(std::ostringstream *out, bool dispStdOut=false, bool allowWhiteSpace=false, bool printErrors=false)
virtual void forceSupervisorPropertyValues(void) override
override to force supervisor property values (and ignore user settings)
void addParameter(const std::string name, const std::string value)
static void tooltipSetNeverShowForUsername(const std::string &username, HttpXmlDocument *xmldoc, const std::string &srcFile, const std::string &srcFunc, const std::string &srcId, bool doNeverShow, bool temporarySilence)
static void tooltipCheckForUsername(const std::string &username, HttpXmlDocument *xmldoc, const std::string &srcFile, const std::string &srcFunc, const std::string &srcId)
xercesc::DOMElement * addTextElementToParent(const std::string &childName, const std::string &childText, xercesc::DOMElement *parent)
void INIT_MF(const char *name)
static std::string getTimestampString(const std::string &linuxTimeInSeconds)
static void getVectorFromString(const std::string &inputString, std::vector< std::string > &listToReturn, const std::set< char > &delimiter={',', '|', '&'}, const std::set< char > &whitespace={' ', '\t', '\n', '\r'}, std::vector< char > *listOfDelimiters=0, bool decodeURIComponents=false)
static void getSetFromString(const std::string &inputString, std::set< std::string > &setToReturn, const std::set< char > &delimiter={',', '|', '&'}, const std::set< char > &whitespace={' ', '\t', '\n', '\r'})
static std::string setToString(const std::set< T > &setToReturn, const std::string &delimeter=", ")
static std::string vectorToString(const std::vector< T > &setToReturn, const std::string &delimeter=", ")
static std::string mapToString(const std::map< std::string, T > &mapToReturn, const std::string &primaryDelimeter=", ", const std::string &secondaryDelimeter=": ")
static void getMapFromString(const std::string &inputString, std::map< S, T > &mapToReturn, const std::set< char > &pairPairDelimiter={',', '|', '&'}, const std::set< char > &nameValueDelimiter={'=', ':'}, const std::set< char > &whitespace={' ', '\t', '\n', '\r'})
static std::string decodeURIComponent(const std::string &data)