source: trunk/FACT++/src/StateMachineDimControl.cc@ 16879

Last change on this file since 16879 was 16830, checked in by tbretz, 11 years ago
Print a warning if an interrupt request is received but no script is running.
File size: 17.0 KB
Line 
1#include "StateMachineDimControl.h"
2
3#include <boost/filesystem.hpp>
4
5#include "Dim.h"
6#include "Event.h"
7#include "Readline.h"
8#include "InterpreterV8.h"
9#include "Configuration.h"
10#include "Converter.h"
11
12#include "tools.h"
13
14using namespace std;
15
16// ------------------------------------------------------------------------
17
18bool StateMachineDimControl::fIsServer = false;
19
20string StateMachineDimControl::Line(const string &txt, char fill)
21{
22 const int n = (55-txt.length())/2;
23
24 ostringstream out;
25 out << setfill(fill);
26 out << setw(n) << fill << ' ';
27 out << txt;
28 out << ' ' << setw(n) << fill;
29
30 if (2*n+txt.length()+2 != 57)
31 out << fill;
32
33 return out.str();
34}
35
36int StateMachineDimControl::ChangeState(int qos, const Time &, int scriptdepth, string scriptfile, string user)
37{
38 string msg;
39 /*
40 switch (qos)
41 {
42 case -4: msg = "End"; break;
43 case -3: msg = "Loading"; break;
44 case -2: msg = "Compiling"; break;
45 case -1: msg = "Running"; break;
46 default:
47 {
48 ostringstream out;
49 out << "Label " << qos;
50 msg = out.str();
51 }
52 }
53 */
54
55 //if (qos<0)
56 msg += to_string(scriptdepth);
57
58 msg += ":"+scriptfile+"["+user+":"+to_string(getpid())+"]";
59
60 //if (fDebug)
61 //Write(time, Line(msg, qos<-1 ? '=' :'-'), MessageImp::kInternal);
62
63 if (qos==-4)
64 fScriptUser = fUser;
65
66 SetCurrentState(qos+4, msg.c_str());
67 //SetCurrentState(qos+4, Line(msg, qos<-1 ? '=' :'-').c_str());
68 return GetCurrentState();
69
70 //return qos+4;
71}
72
73int StateMachineDimControl::ChangeState(int state)
74{
75 return ChangeState(state, Time(), Readline::GetScriptDepth(), Readline::GetScript(), fScriptUser);
76 /*
77 === This might be necessary for thread safety,
78 === but it break that the signal for the start of a new
79 === script arrives synchronously before the first output
80 === from the script
81
82 // Post an anonymous event to the event loop
83 Event evt("");
84 evt.AssignFunction(bind(&StateMachineDimControl::ChangeState, this,
85 qos, time, Readline::GetScriptDepth(),
86 Readline::GetScript(), fScriptUser));
87 return PostEvent(evt);
88 */
89}
90
91int StateMachineDimControl::StartScript(const EventImp &imp, const string &cmd)
92{
93 string opt(imp.GetString());
94
95 const map<string,string> data = Tools::Split(opt, true);
96 if (imp.GetSize()==0 || opt.size()==0 || opt[0]==0)
97 {
98 Error("File name missing in DIM_CONTROL/START");
99 return GetCurrentState();
100 }
101
102 if (fDebug)
103 Debug("Start '"+opt+"' received.");
104
105 if (fDebug)
106 Debug("Received data: "+imp.GetString());
107
108 const auto user = data.find("user");
109 fScriptUser = user==data.end() ? fUser : user->second;
110
111 if (fDebug)
112 {
113 for (auto it=data.begin(); it!=data.end(); it++)
114 Debug(" Arg: "+it->first+" = "+it->second);
115 }
116
117 string emit = cmd+imp.GetString();
118 if (cmd==".js ")
119 emit += fArgumentsJS;
120
121 Readline::SetExternalInput(emit);
122 return GetCurrentState();
123}
124
125int StateMachineDimControl::StopScript()
126{
127 Info("Stop received.");
128
129 Readline::StopScript();
130 InterpreterV8::JsStop();
131 return GetCurrentState();
132}
133
134int StateMachineDimControl::InterruptScript(const EventImp &evt)
135{
136 if (!fInterruptHandler)
137 return GetCurrentState();
138
139 string str = evt.GetString();
140
141 const size_t p = str.find_last_of('\n');
142 if (p!=string::npos)
143 str[p] = ':';
144
145 if (GetCurrentState()<3)
146 {
147 Warn("Interrupt request received ["+str+"]... but no running script.");
148 return GetCurrentState();
149 }
150
151 Info("Interrupt request received ["+str+"]");
152 return fInterruptHandler(evt);
153}
154
155bool StateMachineDimControl::SendDimCommand(const string &server, string str, ostream &lout)
156{
157 const lock_guard<mutex> guard(fMutex);
158
159 if (fServerList.find(server)==fServerList.end())
160 throw runtime_error("SendDimCommand - Server '"+server+"' not online.");
161
162 str = Tools::Trim(str);
163
164 // Find the delimiter between the command name and the data
165 size_t p0 = str.find_first_of(' ');
166 if (p0==string::npos)
167 p0 = str.length();
168
169 // Get just the command name separated from the data
170 const string name = str.substr(0, p0);
171
172 // Compile the command which will be sent to the state-machine
173 for (auto is=fServiceList.begin(); is!=fServiceList.end(); is++)
174 {
175 if (str.empty() && is->server==server)
176 return true;
177
178 if (is->server!=server || is->service!=name)
179 continue;
180
181 if (!is->iscmd)
182 throw runtime_error("'"+server+"/"+name+" not a command.");
183
184 // Avoid compiler warning of unused parameter
185 lout << flush;
186
187 // Convert the user entered data according to the format string
188 // into a data block which will be attached to the event
189#ifndef DEBUG
190 ostringstream sout;
191 const Converter conv(sout, is->format, false);
192#else
193 const Converter conv(lout, is->format, false);
194#endif
195 if (!conv)
196 throw runtime_error("Couldn't properly parse the format... ignored.");
197
198#ifdef DEBUG
199 lout << kBlue << server << '/' << name;
200#endif
201 const vector<char> v = conv.GetVector(str.substr(p0));
202#ifdef DEBUG
203 lout << kBlue << " [" << v.size() << "]" << endl;
204#endif
205 const string cmd = server + '/' + name;
206 const int rc = DimClient::sendCommand(cmd.c_str(), (void*)v.data(), v.size());
207 if (!rc)
208 throw runtime_error("ERROR - Sending command "+cmd+" failed.");
209
210 return true;
211 }
212
213 if (!str.empty())
214 throw runtime_error("SendDimCommand - Format information for "+server+"/"+name+" not yet available.");
215
216 return false;
217}
218
219int StateMachineDimControl::PrintStates(std::ostream &out, const std::string &serv)
220{
221 const lock_guard<mutex> guard(fMutex);
222
223 int rc = 0;
224 for (auto it=fServerList.begin(); it!=fServerList.end(); it++)
225 {
226 if (!serv.empty() && *it!=serv)
227 continue;
228
229 out << kRed << "----- " << *it << " -----" << endl;
230
231 int cnt = 0;
232 for (auto is=fStateDescriptionList.begin(); is!=fStateDescriptionList.end(); is++)
233 {
234 const string &server = is->first.first;
235
236 if (server!=*it)
237 continue;
238
239 const int32_t &state = is->first.second;
240 const string &name = is->second.first;
241 const string &comment = is->second.second;
242
243 out << kBold << setw(5) << state << kReset << ": ";
244 out << kYellow << name;
245 if (!comment.empty())
246 out << kBlue << " (" << comment << ")";
247 out << endl;
248
249 cnt++;
250 }
251
252 if (cnt==0)
253 out << " <no states>" << endl;
254 else
255 rc++;
256
257 out << endl;
258 }
259
260 return rc;
261}
262
263int StateMachineDimControl::PrintDescription(std::ostream &out, bool iscmd, const std::string &serv, const std::string &service)
264{
265 const lock_guard<mutex> guard(fMutex);
266
267 int rc = 0;
268 for (auto it=fServerList.begin(); it!=fServerList.end(); it++)
269 {
270 if (!serv.empty() && *it!=serv)
271 continue;
272
273 out << kRed << "----- " << *it << " -----" << endl << endl;
274
275 for (auto is=fServiceList.begin(); is!=fServiceList.end(); is++)
276 {
277 if (is->server!=*it)
278 continue;
279
280 if (!service.empty() && is->service!=service)
281 continue;
282
283 if (is->iscmd!=iscmd)
284 continue;
285
286 rc++;
287
288 out << " " << is->service;
289 if (!is->format.empty())
290 out << '[' << is->format << ']';
291
292 const auto id = fServiceDescriptionList.find(*it+"/"+is->service);
293 if (id!=fServiceDescriptionList.end())
294 {
295 const vector<Description> &v = id->second;
296
297 for (auto j=v.begin()+1; j!=v.end(); j++)
298 out << " <" << j->name << ">";
299 out << endl;
300
301 if (!v[0].comment.empty())
302 out << " " << v[0].comment << endl;
303
304 for (auto j=v.begin()+1; j!=v.end(); j++)
305 {
306 out << " " << kGreen << j->name;
307 if (!j->comment.empty())
308 out << kReset << ": " << kBlue << j->comment;
309 if (!j->unit.empty())
310 out << kYellow << " [" << j->unit << "]";
311 out << endl;
312 }
313 }
314 out << endl;
315 }
316 out << endl;
317 }
318
319 return rc;
320}
321
322int StateMachineDimControl::HandleStateChange(const string &server, DimDescriptions *dim)
323{
324 fMutex.lock();
325 const State descr = dim->description();
326 const State state = State(dim->state(), descr.index==DimState::kNotAvailable?"":descr.name, descr.comment, dim->cur.first);
327 fCurrentStateList[server] = state;
328 fMutex.unlock();
329
330 fStateCallback(server, state);
331
332 return GetCurrentState();
333}
334
335State StateMachineDimControl::GetServerState(const std::string &server)
336{
337 const lock_guard<mutex> guard(fMutex);
338
339 const auto it = fCurrentStateList.find(server);
340 return it==fCurrentStateList.end() ? State() : it->second;
341}
342
343int StateMachineDimControl::HandleStates(const string &server, DimDescriptions *dim)
344{
345 const lock_guard<mutex> guard(fMutex);
346
347 const auto is = fCurrentStateList.find(server);
348 for (auto it=dim->states.begin(); it!=dim->states.end(); it++)
349 {
350 fStateDescriptionList[make_pair(server, it->index)] = make_pair(it->name, it->comment);
351 if (is==fCurrentStateList.end())
352 continue;
353
354 State &s = is->second;
355 if (s.index==it->index)
356 {
357 s.name = it->name;
358 s.comment = it->comment;
359 }
360 }
361
362 return GetCurrentState();
363}
364
365int StateMachineDimControl::HandleDescriptions(DimDescriptions *dim)
366{
367 const lock_guard<mutex> guard(fMutex);
368
369 for (auto it=dim->descriptions.begin(); it!=dim->descriptions.end(); it++)
370 fServiceDescriptionList[it->front().name].assign(it->begin(), it->end());
371
372 return GetCurrentState();
373}
374
375std::vector<Description> StateMachineDimControl::GetDescription(const std::string &service)
376{
377 const lock_guard<mutex> guard(fMutex);
378
379 const auto it = fServiceDescriptionList.find(service);
380 return it==fServiceDescriptionList.end() ? vector<Description>() : it->second;
381}
382
383int StateMachineDimControl::HandleServerAdd(const string &server)
384{
385 if (server!="DIS_DNS")
386 {
387 struct Find : string
388 {
389 Find(const string &ref) : string(ref) { }
390 bool operator()(const DimDescriptions *dim) { return *this==dim->server; }
391 };
392
393 if (find_if(fDimDescriptionsList.begin(), fDimDescriptionsList.end(),
394 Find(server))==fDimDescriptionsList.end())
395 {
396 DimDescriptions *d = new DimDescriptions(server);
397
398 fDimDescriptionsList.push_back(d);
399 d->SetCallback(bind(&StateMachineDimControl::HandleStateChange, this, server, d));
400 d->SetCallbackStates(bind(&StateMachineDimControl::HandleStates, this, server, d));
401 d->SetCallbackDescriptions(bind(&StateMachineDimControl::HandleDescriptions, this, d));
402 d->Subscribe(*this);
403 }
404 }
405
406 // Make a copy of the list to be able to
407 // lock the access to the list
408
409 const lock_guard<mutex> guard(fMutex);
410 fServerList.insert(server);
411
412 return GetCurrentState();
413}
414
415int StateMachineDimControl::HandleServerRemove(const string &server)
416{
417 const lock_guard<mutex> guard(fMutex);
418 fServerList.erase(server);
419
420 return GetCurrentState();
421}
422
423vector<string> StateMachineDimControl::GetServerList()
424{
425 vector<string> rc;
426
427 const lock_guard<mutex> guard(fMutex);
428
429 rc.reserve(fServerList.size());
430 for (auto it=fServerList.begin(); it!=fServerList.end(); it++)
431 rc.push_back(*it);
432
433 return rc;
434}
435
436vector<string> StateMachineDimControl::GetCommandList(const string &server)
437{
438 const lock_guard<mutex> guard(fMutex);
439
440 const string s = server.substr(0, server.length()-1);
441
442 if (fServerList.find(s)==fServerList.end())
443 return vector<string>();
444
445 vector<string> rc;
446
447 for (auto it=fServiceList.begin(); it!=fServiceList.end(); it++)
448 if (it->iscmd && it->server==s)
449 rc.push_back(server+it->service);
450
451 return rc;
452}
453
454vector<string> StateMachineDimControl::GetCommandList()
455{
456 vector<string> rc;
457
458 const lock_guard<mutex> guard(fMutex);
459
460 for (auto it=fServiceList.begin(); it!=fServiceList.end(); it++)
461 if (it->iscmd)
462 rc.push_back(it->server+"/"+it->service);
463
464 return rc;
465}
466
467set<Service> StateMachineDimControl::GetServiceList()
468{
469 const lock_guard<mutex> guard(fMutex);
470 return fServiceList;
471}
472
473vector<State> StateMachineDimControl::GetStates(const string &server)
474{
475 const lock_guard<mutex> guard(fMutex);
476
477 vector<State> rc;
478
479 for (auto it=fStateDescriptionList.begin(); it!=fStateDescriptionList.end(); it++)
480 {
481 if (it->first.first!=server)
482 continue;
483
484 rc.emplace_back(it->first.second, it->second.first, it->second.second);
485 }
486
487 return rc;
488}
489
490
491int StateMachineDimControl::HandleAddService(const Service &svc)
492{
493 // Make a copy of the list to be able to
494 // lock the access to the list
495 const lock_guard<mutex> guard(fMutex);
496 fServiceList.insert(svc);
497
498 return GetCurrentState();
499}
500
501bool StateMachineDimControl::HasServer(const std::string &server)
502{
503 const lock_guard<mutex> guard(fMutex);
504 return fServerList.find(server)!=fServerList.end();
505}
506
507StateMachineDimControl::StateMachineDimControl(ostream &out) : StateMachineDim(out, fIsServer?"DIM_CONTROL":"")
508{
509 fDim.Subscribe(*this);
510 fDimList.Subscribe(*this);
511
512 fDimList.SetCallbackServerAdd (bind(&StateMachineDimControl::HandleServerAdd, this, placeholders::_1));
513 fDimList.SetCallbackServerRemove(bind(&StateMachineDimControl::HandleServerRemove, this, placeholders::_1));
514 fDimList.SetCallbackServiceAdd (bind(&StateMachineDimControl::HandleAddService, this, placeholders::_1));
515
516 // State names
517 AddStateName(0, "Idle", "No script currently in processing.");
518 AddStateName(1, "Loading", "Script is loading.");
519 AddStateName(2, "Compiling", "JavaScript is compiling.");
520 AddStateName(3, "Running", "Script is running.");
521
522 AddEvent("START", "C", 0)
523 (bind(&StateMachineDimControl::StartScript, this, placeholders::_1, ".js "))
524 ("Start a JavaScript");
525
526 AddEvent("EXECUTE", "C", 0)
527 (bind(&StateMachineDimControl::StartScript, this, placeholders::_1, ".x "))
528 ("Execute a batch script");
529
530 AddEvent("STOP", "C")
531 (bind(&StateMachineDimControl::StopScript, this))
532 ("Stop a runnning batch script or JavaScript");
533
534 AddEvent("INTERRUPT", "C")
535 (bind(&StateMachineDimControl::InterruptScript, this, placeholders::_1))
536 ("Send an interrupt request (IRQ) to a running JavaScript");
537}
538
539StateMachineDimControl::~StateMachineDimControl()
540{
541 for (auto it=fDimDescriptionsList.begin(); it!=fDimDescriptionsList.end(); it++)
542 delete *it;
543}
544
545int StateMachineDimControl::EvalOptions(Configuration &conf)
546{
547 fDebug = conf.Get<bool>("debug");
548 fUser = conf.Get<string>("user");
549 fScriptUser = fUser;
550
551 // FIXME: Check fUser for quotes!
552
553 const map<string, string> &js = conf.GetOptions<string>("JavaScript.");
554 for (auto it=js.begin(); it!=js.end(); it++)
555 {
556 string key = it->first;
557 string val = it->second;
558
559 // Escape key
560 boost::replace_all(key, "\\", "\\\\");
561 boost::replace_all(key, "'", "\\'");
562 boost::replace_all(key, "\"", "\\\"");
563
564 // Escape value
565 boost::replace_all(val, "\\", "\\\\");
566 boost::replace_all(val, "'", "\\'");
567 boost::replace_all(val, "\"", "\\\"");
568
569 fArgumentsJS += " '"+key +"'='"+val+"'";
570 }
571
572 // fVerbosity = 40;
573
574 // if (conf.Has("verbosity"))
575 // fVerbosity = conf.Get<uint32_t>("verbosity");
576
577 // if (conf.Get<bool>("quiet"))
578 // fVerbosity = 90;
579
580#if BOOST_VERSION < 104600
581 const string fname = boost::filesystem::path(conf.GetName()).filename();
582#else
583 const string fname = boost::filesystem::path(conf.GetName()).filename().string();
584#endif
585
586 if (fname=="dimserver")
587 return -1;
588
589 if (conf.Get<bool>("stop"))
590 return !Dim::SendCommand("DIM_CONTROL/STOP", fUser);
591
592 if (conf.Has("interrupt"))
593 return !Dim::SendCommand("DIM_CONTROL/INTERRUPT", conf.Get<string>("interrupt")+"\n"+fUser);
594
595 if (conf.Has("start"))
596 return !Dim::SendCommand("DIM_CONTROL/START", conf.Get<string>("start")+" user='"+fUser+"'"+fArgumentsJS);
597
598 if (conf.Has("batch"))
599 return !Dim::SendCommand("DIM_CONTROL/EXECUTE", conf.Get<string>("batch")+" user='"+fUser+"'");
600
601 if (conf.Has("msg"))
602 return !Dim::SendCommand("CHAT/MSG", fUser+": "+conf.Get<string>("msg"));
603
604 if (conf.Has("restart"))
605 return !Dim::SendCommand(conf.Get<string>("restart")+"/EXIT", uint32_t(126));
606
607 return -1;
608}
Note: See TracBrowser for help on using the repository browser.