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

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