source: trunk/FACT++/src/dimctrl.cc@ 13838

Last change on this file since 13838 was 13797, checked in by tbretz, 13 years ago
Start the server as late as possible -- but it must be started before the scripts are executed.
File size: 8.1 KB
Line 
1#ifndef FACT_DimCtrl
2#define FACT_DimCtrl
3
4#include "Main.h"
5#include "tools.h"
6#include "MessageDim.h"
7#include "RemoteControl.h"
8
9using namespace std;
10
11// ========================================================================
12
13
14/*
15 Extract usage clause(s) [if any] for SYNOPSIS.
16 Translators: "Usage" and "or" here are patterns (regular expressions) which
17 are used to match the usage synopsis in program output. An example from cp
18 (GNU coreutils) which contains both strings:
19 Usage: cp [OPTION]... [-T] SOURCE DEST
20 or: cp [OPTION]... SOURCE... DIRECTORY
21 or: cp [OPTION]... -t DIRECTORY SOURCE...
22 */
23void PrintUsage()
24{
25 cout << "\n"
26 "The console connects to all available Dim Servers and allows to "
27 "easily access all of their commands.\n"
28 "\n"
29 "Usage: dimctrl [-c type] [OPTIONS]\n"
30 " or: dimctrl [OPTIONS]\n\n";
31 cout << endl;
32}
33
34void PrintHelp()
35{
36 Main::PrintUsage();
37}
38
39// A simple dummy state machine
40class DimCtrl : public MainImp, public DimCommandHandler, public MessageDimTX
41{
42 int fLabel;
43 int fStop;
44 int fVerbosity;
45 bool fDebug;
46 bool fIsServer;
47 string fUser;
48
49 DimDescribedService fSrvState;
50 DimCommand fDimStart;
51 DimCommand fDimStop;
52
53 map<string,string> fData;
54 string fScript;
55 string fScriptUser;
56
57 void ProcessStart()
58 {
59 if (!fScript.empty() || fLabel>-3)
60 {
61 Error("Script execution still in progress.");
62 return;
63 }
64
65 string opt(fDimStart.getString());
66
67 fData = Tools::Split(opt);
68
69 if (opt.size()>0)
70 Debug("Start '"+opt+"' received.");
71
72 if (fDebug)
73 Debug("Received data: "+string(fDimStart.getString()));
74
75 if (opt.size()==0)
76 {
77 if (fData.size()==0)
78 Error("File name missing in DIM_CONTROL/START");
79 else
80 Error("Equal sign missing in argument '"+fData.begin()->first+"'");
81
82 return;
83 }
84
85 const auto user = fData.find("user");
86 if (user!=fData.end())
87 fScriptUser = user->second;
88
89 if (fDebug)
90 {
91 for (auto it=fData.begin(); it!=fData.end(); it++)
92 Debug(" Arg: "+it->first+" = "+it->second);
93 }
94
95 fScript = opt;
96 }
97
98 void commandHandler()
99 {
100 if (getCommand()==&fDimStop)
101 {
102 const string user = fDimStop.getSize()>0 ? fDimStop.getString() : "";
103
104 string msg = "Stop received";
105 if (!user.empty())
106 msg += " from user '"+user+"'";
107
108 Debug(msg);
109 Readline::SetLabel(-2);
110 }
111
112 if (getCommand()==&fDimStart)
113 ProcessStart();
114 }
115
116public:
117 DimCtrl(ostream &out=cout) : MessageDimTX("DIM_CONTROL", out),
118 fLabel(-3), fStop(-1), fVerbosity(0), fDebug(false), fIsServer(false),
119 fSrvState("DIM_CONTROL/STATE", "C",
120 "Provides the state of the state machine as quality of service."
121 "|Text[string]:A human readable string sent by the last state change."),
122 fDimStart("DIM_CONTROL/START", "C", this),
123 fDimStop("DIM_CONTROL/STOP", "C", this)
124 {
125 }
126 ~DimCtrl()
127 {
128 DimServer::stop();
129 }
130
131 bool check(string &str)
132 {
133 for (auto c=str.begin(); c<str.end(); c++)
134 {
135 if ((*c>='A' && *c<='Z') || *c=='_')
136 continue;
137
138 if (*c++!=':')
139 return false;
140
141 if (c==str.end())
142 return false;
143
144 if (*c!=' ')
145 return false;
146
147 str = string(c+1, str.end());
148 return true;
149 }
150
151 return false;
152 }
153
154 string Line(const string &txt, char fill)
155 {
156 const int n = (55-txt.length())/2;
157
158 ostringstream out;
159 out << setfill(fill);
160 out << setw(n) << fill << ' ';
161 out << txt;
162 out << ' ' << setw(n) << fill;
163
164 if (2*n+txt.length()+2 != 57)
165 out << fill;
166
167 return out.str();
168 }
169
170 int Write(const Time &time, const std::string &txt, int qos=kMessage)
171 {
172 if (txt=="")
173 {
174 ostringstream pid;
175 pid << getpid();
176
177 fLabel = qos;
178
179 string msg;
180 switch (fLabel)
181 {
182 case -3: msg = "End"; break;
183 case -2: msg = "Load"; break;
184 case -1: msg = "Begin"; break;
185 default:
186 {
187 ostringstream out;
188 out << "Label " << fLabel;
189 msg = out.str();
190 }
191 }
192
193 msg += ": "+Readline::GetScript()+" [";
194 if (!fScriptUser.empty())
195 msg += fScriptUser+":"+pid.str();
196 msg += "]";
197
198 if (fDebug)
199 MessageDimTX::Write(time, Line(msg, fLabel<-1 ? '=' :'-'), 90);
200
201 fSrvState.setQuality(fLabel);
202 return fSrvState.Update(msg);
203 }
204
205 if (qos<fVerbosity)
206 return 0;
207
208 // Avoid recursions
209 if (fIsServer && txt.substr(0, 13)=="DIM_CONTROL: ")
210 return 0;
211
212 // Don't send received messages via dim
213 string cpy(txt);
214 if (fIsServer && check(cpy))
215 return MessageImp::Write(time, cpy, qos);
216
217 // Send all of our own messages via dim
218 return MessageDimTX::Write(time, txt, qos);
219 }
220
221 int EvalOptions(Configuration &conf)
222 {
223 fVerbosity = 90;
224
225 fUser = conf.Get<string>("user");
226 fScriptUser = fUser;
227
228 if (conf.Get<bool>("stop"))
229 return Dim::SendCommand("DIM_CONTROL/STOP", fUser) + 1;
230
231 if (conf.Has("start"))
232 return Dim::SendCommand("DIM_CONTROL/START", conf.Get<string>("start")+" user="+fUser) + 1;
233
234 fVerbosity = 40;
235
236 if (conf.Has("verbosity"))
237 fVerbosity = conf.Get<uint32_t>("verbosity");
238
239 if (conf.Get<bool>("quiet"))
240 fVerbosity = 90;
241
242 fIsServer = conf.Get<bool>("server");
243 fDebug = conf.Get<bool>("debug");
244
245 if (fIsServer)
246 {
247 // Sleep needed to ensure that the server can send
248 // an EXIT if another instance is already running
249 DimServer::start("DIM_CONTROL");
250 //sleep(1);
251 fSrvState.setQuality(-3);
252 fSrvState.Update("[boot]");
253 }
254
255 return -1;
256 }
257
258 void Stop(int stop=0) { fStop = stop; Readline::SetLabel(0); }
259 int Run(bool)
260 {
261 while (fStop<0)
262 {
263 const string s = fScript;
264 if (!s.empty())
265 {
266 Readline::Instance()->Execute(s, fData);
267 fScript = "";
268 fScriptUser = fUser;
269 }
270
271 usleep(1000);
272 }
273
274 return fStop;
275 }
276
277};
278
279void SetupConfiguration(Configuration &conf)
280{
281 po::options_description control("Dim Control");
282 control.add_options()
283 ("server", po_bool(false), "Start dimctrl as a dim server")
284 ("verbosity,v", var<uint32_t>()->implicit_value(0), "Set a new verbosity level (see MessageImp)")
285 ("quiet,q", po_bool(false), "Suppress all output except comments (log-level>=90)")
286 ("debug", po_bool(false), "Print the labels for debugging purpose")
287 ("start", var<string>(), "Start a script with the given name at the given label (script.dim[:N])")
288 ("stop", po_switch(), "Stop a currently running script")
289 ("user,u", var<string>(""), "A user name - just for logging purposes (default is ${USER})")
290 ;
291
292 conf.AddEnv("user", "USER");
293
294 conf.AddOptions(control);
295}
296
297int main(int argc, const char *argv[])
298{
299 Configuration conf(argv[0]);
300 conf.SetPrintUsage(PrintUsage);
301 Main::SetupConfiguration(conf);
302 SetupConfiguration(conf);
303
304 if (!conf.DoParse(argc, argv, PrintHelp))
305 return -1;
306
307 if (!conf.Has("console"))
308 return Main::execute<RemoteStream, DimCtrl>(conf);
309
310 if (conf.Get<int>("console")==0)
311 return Main::execute<RemoteShell, DimCtrl>(conf);
312 else
313 return Main::execute<RemoteConsole, DimCtrl>(conf);
314
315 return 0;
316}
317#endif
Note: See TracBrowser for help on using the repository browser.