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

Last change on this file since 15900 was 15430, checked in by tbretz, 12 years ago
Implemented the possibility to send an interrupt request (irq) to a runing JavaScript.
File size: 16.9 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 Info("Interrupt request received ["+str+"]");
146 return fInterruptHandler(evt);
147}
148
149bool StateMachineDimControl::SendDimCommand(const string &server, string str, ostream &lout)
150{
151 const lock_guard<mutex> guard(fMutex);
152
153 if (fServerList.find(server)==fServerList.end())
154 throw runtime_error("SendDimCommand - Server '"+server+"' not online.");
155
156 str = Tools::Trim(str);
157
158 // Find the delimiter between the command name and the data
159 size_t p0 = str.find_first_of(' ');
160 if (p0==string::npos)
161 p0 = str.length();
162
163 // Get just the command name separated from the data
164 const string name = str.substr(0, p0);
165
166 // Compile the command which will be sent to the state-machine
167 for (auto is=fServiceList.begin(); is!=fServiceList.end(); is++)
168 {
169 if (str.empty() && is->server==server)
170 return true;
171
172 if (is->server!=server || is->service!=name)
173 continue;
174
175 if (!is->iscmd)
176 throw runtime_error("'"+server+"/"+name+" not a command.");
177
178 // Avoid compiler warning of unused parameter
179 lout << flush;
180
181 // Convert the user entered data according to the format string
182 // into a data block which will be attached to the event
183#ifndef DEBUG
184 ostringstream sout;
185 const Converter conv(sout, is->format, false);
186#else
187 const Converter conv(lout, is->format, false);
188#endif
189 if (!conv)
190 throw runtime_error("Couldn't properly parse the format... ignored.");
191
192#ifdef DEBUG
193 lout << kBlue << server << '/' << name;
194#endif
195 const vector<char> v = conv.GetVector(str.substr(p0));
196#ifdef DEBUG
197 lout << kBlue << " [" << v.size() << "]" << endl;
198#endif
199 const string cmd = server + '/' + name;
200 const int rc = DimClient::sendCommand(cmd.c_str(), (void*)v.data(), v.size());
201 if (!rc)
202 throw runtime_error("ERROR - Sending command "+cmd+" failed.");
203
204 return true;
205 }
206
207 if (!str.empty())
208 throw runtime_error("SendDimCommand - Format information for "+server+"/"+name+" not yet available.");
209
210 return false;
211}
212
213int StateMachineDimControl::PrintStates(std::ostream &out, const std::string &serv)
214{
215 const lock_guard<mutex> guard(fMutex);
216
217 int rc = 0;
218 for (auto it=fServerList.begin(); it!=fServerList.end(); it++)
219 {
220 if (!serv.empty() && *it!=serv)
221 continue;
222
223 out << kRed << "----- " << *it << " -----" << endl;
224
225 int cnt = 0;
226 for (auto is=fStateDescriptionList.begin(); is!=fStateDescriptionList.end(); is++)
227 {
228 const string &server = is->first.first;
229
230 if (server!=*it)
231 continue;
232
233 const int32_t &state = is->first.second;
234 const string &name = is->second.first;
235 const string &comment = is->second.second;
236
237 out << kBold << setw(5) << state << kReset << ": ";
238 out << kYellow << name;
239 if (!comment.empty())
240 out << kBlue << " (" << comment << ")";
241 out << endl;
242
243 cnt++;
244 }
245
246 if (cnt==0)
247 out << " <no states>" << endl;
248 else
249 rc++;
250
251 out << endl;
252 }
253
254 return rc;
255}
256
257int StateMachineDimControl::PrintDescription(std::ostream &out, bool iscmd, const std::string &serv, const std::string &service)
258{
259 const lock_guard<mutex> guard(fMutex);
260
261 int rc = 0;
262 for (auto it=fServerList.begin(); it!=fServerList.end(); it++)
263 {
264 if (!serv.empty() && *it!=serv)
265 continue;
266
267 out << kRed << "----- " << *it << " -----" << endl << endl;
268
269 for (auto is=fServiceList.begin(); is!=fServiceList.end(); is++)
270 {
271 if (is->server!=*it)
272 continue;
273
274 if (!service.empty() && is->service!=service)
275 continue;
276
277 if (is->iscmd!=iscmd)
278 continue;
279
280 rc++;
281
282 out << " " << is->service;
283 if (!is->format.empty())
284 out << '[' << is->format << ']';
285
286 const auto id = fServiceDescriptionList.find(*it+"/"+is->service);
287 if (id!=fServiceDescriptionList.end())
288 {
289 const vector<Description> &v = id->second;
290
291 for (auto j=v.begin()+1; j!=v.end(); j++)
292 out << " <" << j->name << ">";
293 out << endl;
294
295 if (!v[0].comment.empty())
296 out << " " << v[0].comment << endl;
297
298 for (auto j=v.begin()+1; j!=v.end(); j++)
299 {
300 out << " " << kGreen << j->name;
301 if (!j->comment.empty())
302 out << kReset << ": " << kBlue << j->comment;
303 if (!j->unit.empty())
304 out << kYellow << " [" << j->unit << "]";
305 out << endl;
306 }
307 }
308 out << endl;
309 }
310 out << endl;
311 }
312
313 return rc;
314}
315
316int StateMachineDimControl::HandleStateChange(const string &server, DimDescriptions *dim)
317{
318 fMutex.lock();
319 const State descr = dim->description();
320 const State state = State(dim->state(), descr.index==DimState::kNotAvailable?"":descr.name, descr.comment, dim->cur.first);
321 fCurrentStateList[server] = state;
322 fMutex.unlock();
323
324 fStateCallback(server, state);
325
326 return GetCurrentState();
327}
328
329State StateMachineDimControl::GetServerState(const std::string &server)
330{
331 const lock_guard<mutex> guard(fMutex);
332
333 const auto it = fCurrentStateList.find(server);
334 return it==fCurrentStateList.end() ? State() : it->second;
335}
336
337int StateMachineDimControl::HandleStates(const string &server, DimDescriptions *dim)
338{
339 const lock_guard<mutex> guard(fMutex);
340
341 const auto is = fCurrentStateList.find(server);
342 for (auto it=dim->states.begin(); it!=dim->states.end(); it++)
343 {
344 fStateDescriptionList[make_pair(server, it->index)] = make_pair(it->name, it->comment);
345 if (is==fCurrentStateList.end())
346 continue;
347
348 State &s = is->second;
349 if (s.index==it->index)
350 {
351 s.name = it->name;
352 s.comment = it->comment;
353 }
354 }
355
356 return GetCurrentState();
357}
358
359int StateMachineDimControl::HandleDescriptions(DimDescriptions *dim)
360{
361 const lock_guard<mutex> guard(fMutex);
362
363 for (auto it=dim->descriptions.begin(); it!=dim->descriptions.end(); it++)
364 fServiceDescriptionList[it->front().name].assign(it->begin(), it->end());
365
366 return GetCurrentState();
367}
368
369std::vector<Description> StateMachineDimControl::GetDescription(const std::string &service)
370{
371 const lock_guard<mutex> guard(fMutex);
372
373 const auto it = fServiceDescriptionList.find(service);
374 return it==fServiceDescriptionList.end() ? vector<Description>() : it->second;
375}
376
377int StateMachineDimControl::HandleServerAdd(const string &server)
378{
379 if (server!="DIS_DNS")
380 {
381 struct Find : string
382 {
383 Find(const string &ref) : string(ref) { }
384 bool operator()(const DimDescriptions *dim) { return *this==dim->server; }
385 };
386
387 if (find_if(fDimDescriptionsList.begin(), fDimDescriptionsList.end(),
388 Find(server))==fDimDescriptionsList.end())
389 {
390 DimDescriptions *d = new DimDescriptions(server);
391
392 fDimDescriptionsList.push_back(d);
393 d->SetCallback(bind(&StateMachineDimControl::HandleStateChange, this, server, d));
394 d->SetCallbackStates(bind(&StateMachineDimControl::HandleStates, this, server, d));
395 d->SetCallbackDescriptions(bind(&StateMachineDimControl::HandleDescriptions, this, d));
396 d->Subscribe(*this);
397 }
398 }
399
400 // Make a copy of the list to be able to
401 // lock the access to the list
402
403 const lock_guard<mutex> guard(fMutex);
404 fServerList.insert(server);
405
406 return GetCurrentState();
407}
408
409int StateMachineDimControl::HandleServerRemove(const string &server)
410{
411 const lock_guard<mutex> guard(fMutex);
412 fServerList.erase(server);
413
414 return GetCurrentState();
415}
416
417vector<string> StateMachineDimControl::GetServerList()
418{
419 vector<string> rc;
420
421 const lock_guard<mutex> guard(fMutex);
422
423 rc.reserve(fServerList.size());
424 for (auto it=fServerList.begin(); it!=fServerList.end(); it++)
425 rc.push_back(*it);
426
427 return rc;
428}
429
430vector<string> StateMachineDimControl::GetCommandList(const string &server)
431{
432 const lock_guard<mutex> guard(fMutex);
433
434 const string s = server.substr(0, server.length()-1);
435
436 if (fServerList.find(s)==fServerList.end())
437 return vector<string>();
438
439 vector<string> rc;
440
441 for (auto it=fServiceList.begin(); it!=fServiceList.end(); it++)
442 if (it->iscmd && it->server==s)
443 rc.push_back(server+it->service);
444
445 return rc;
446}
447
448vector<string> StateMachineDimControl::GetCommandList()
449{
450 vector<string> rc;
451
452 const lock_guard<mutex> guard(fMutex);
453
454 for (auto it=fServiceList.begin(); it!=fServiceList.end(); it++)
455 if (it->iscmd)
456 rc.push_back(it->server+"/"+it->service);
457
458 return rc;
459}
460
461set<Service> StateMachineDimControl::GetServiceList()
462{
463 const lock_guard<mutex> guard(fMutex);
464 return fServiceList;
465}
466
467vector<State> StateMachineDimControl::GetStates(const string &server)
468{
469 const lock_guard<mutex> guard(fMutex);
470
471 vector<State> rc;
472
473 for (auto it=fStateDescriptionList.begin(); it!=fStateDescriptionList.end(); it++)
474 {
475 if (it->first.first!=server)
476 continue;
477
478 rc.push_back(State(it->first.second, it->second.first, it->second.second));
479 }
480
481 return rc;
482}
483
484
485int StateMachineDimControl::HandleAddService(const Service &svc)
486{
487 // Make a copy of the list to be able to
488 // lock the access to the list
489 const lock_guard<mutex> guard(fMutex);
490 fServiceList.insert(svc);
491
492 return GetCurrentState();
493}
494
495bool StateMachineDimControl::HasServer(const std::string &server)
496{
497 const lock_guard<mutex> guard(fMutex);
498 return fServerList.find(server)!=fServerList.end();
499}
500
501StateMachineDimControl::StateMachineDimControl(ostream &out) : StateMachineDim(out, fIsServer?"DIM_CONTROL":"")
502{
503 fDim.Subscribe(*this);
504 fDimList.Subscribe(*this);
505
506 fDimList.SetCallbackServerAdd (bind(&StateMachineDimControl::HandleServerAdd, this, placeholders::_1));
507 fDimList.SetCallbackServerRemove(bind(&StateMachineDimControl::HandleServerRemove, this, placeholders::_1));
508 fDimList.SetCallbackServiceAdd (bind(&StateMachineDimControl::HandleAddService, this, placeholders::_1));
509
510 // State names
511 AddStateName(0, "Idle", "No script currently in processing.");
512 AddStateName(1, "Loading", "Script is loading.");
513 AddStateName(2, "Compiling", "JavaScript is compiling.");
514 AddStateName(3, "Running", "Script is running.");
515
516 AddEvent("START", "C", 0)
517 (bind(&StateMachineDimControl::StartScript, this, placeholders::_1, ".js "))
518 ("Start a JavaScript");
519
520 AddEvent("EXECUTE", "C", 0)
521 (bind(&StateMachineDimControl::StartScript, this, placeholders::_1, ".x "))
522 ("Execute a batch script");
523
524 AddEvent("STOP", "C")
525 (bind(&StateMachineDimControl::StopScript, this))
526 ("Stop a runnning batch script or JavaScript");
527
528 AddEvent("INTERRUPT", "C")
529 (bind(&StateMachineDimControl::InterruptScript, this, placeholders::_1))
530 ("Send an interrupt request (IRQ) to a running JavaScript");
531}
532
533StateMachineDimControl::~StateMachineDimControl()
534{
535 for (auto it=fDimDescriptionsList.begin(); it!=fDimDescriptionsList.end(); it++)
536 delete *it;
537}
538
539int StateMachineDimControl::EvalOptions(Configuration &conf)
540{
541 fDebug = conf.Get<bool>("debug");
542 fUser = conf.Get<string>("user");
543 fScriptUser = fUser;
544
545 // FIXME: Check fUser for quotes!
546
547 const map<string, string> &js = conf.GetOptions<string>("JavaScript.");
548 for (auto it=js.begin(); it!=js.end(); it++)
549 {
550 string key = it->first;
551 string val = it->second;
552
553 // Escape key
554 boost::replace_all(key, "\\", "\\\\");
555 boost::replace_all(key, "'", "\\'");
556 boost::replace_all(key, "\"", "\\\"");
557
558 // Escape value
559 boost::replace_all(val, "\\", "\\\\");
560 boost::replace_all(val, "'", "\\'");
561 boost::replace_all(val, "\"", "\\\"");
562
563 fArgumentsJS += " '"+key +"'='"+val+"'";
564 }
565
566 // fVerbosity = 40;
567
568 // if (conf.Has("verbosity"))
569 // fVerbosity = conf.Get<uint32_t>("verbosity");
570
571 // if (conf.Get<bool>("quiet"))
572 // fVerbosity = 90;
573
574#if BOOST_VERSION < 104600
575 const string fname = boost::filesystem::path(conf.GetName()).filename();
576#else
577 const string fname = boost::filesystem::path(conf.GetName()).filename().string();
578#endif
579
580 if (fname=="dimserver")
581 return -1;
582
583 if (conf.Get<bool>("stop"))
584 return !Dim::SendCommand("DIM_CONTROL/STOP", fUser);
585
586 if (conf.Has("interrupt"))
587 return !Dim::SendCommand("DIM_CONTROL/INTERRUPT", conf.Get<string>("interrupt")+"\n"+fUser);
588
589 if (conf.Has("start"))
590 return !Dim::SendCommand("DIM_CONTROL/START", conf.Get<string>("start")+" user='"+fUser+"'"+fArgumentsJS);
591
592 if (conf.Has("batch"))
593 return !Dim::SendCommand("DIM_CONTROL/EXECUTE", conf.Get<string>("batch")+" user='"+fUser+"'");
594
595 if (conf.Has("msg"))
596 return !Dim::SendCommand("CHAT/MSG", fUser+": "+conf.Get<string>("msg"));
597
598 if (conf.Has("restart"))
599 return !Dim::SendCommand(conf.Get<string>("restart")+"/EXIT", uint32_t(126));
600
601 return -1;
602}
Note: See TracBrowser for help on using the repository browser.