source: Evidence/Evidence.cc@ 209

Last change on this file since 209 was 209, checked in by ogrimm, 15 years ago
Service histories now available via DimRpc from DColl
File size: 11.8 KB
Line 
1/********************************************************************\
2
3 General code to start a server of the Evidence Control System
4
5 - The server is started with the given name.
6 - DIM exit and error handlers are implemented.
7 - The Status service is published (special format, see below).
8 It can be updated with the State() method. The text will also be logged.
9 - If the severity of a State() call is FATAL, exit() will be called (with
10 this severity, the call to State() is guranteed not to return).
11 - Configuration data can be requested by GetConfig().
12 - Signal handlers to ignore common signals are installed.
13 These signals will then cause pause() to return which can be used
14 by the application to terminate gracefully.
15 - The static method ToString() converts the contents of a
16 DIMInfo service into text
17 - A terminate-handler is installed for catching unhandled C++ exceptions.
18
19 All memory allocated by the non-static methods will be freed by the
20 class destructor.
21
22 Oliver Grimm, March 2009
23
24\********************************************************************/
25
26#include "Evidence.h"
27using namespace std;
28
29//////////////////////////
30// EvidenceServer Class //
31//////////////////////////
32
33EvidenceServer *ThisServer;
34
35// Constructor starts server with given name
36EvidenceServer::EvidenceServer(const char *Name) {
37
38 // Initialize
39 Status = NULL;
40 StdOutText = NULL;
41 ExitRequest = false;
42 ThisServer = this;
43 ServerName = Name;
44
45 // Catch some signals
46 signal(SIGQUIT, &SignalHandler); // CTRL-Backspace
47 signal(SIGTERM, &SignalHandler); // Termination signal
48 signal(SIGINT, &SignalHandler); // CTRL-C
49 signal(SIGHUP, &SignalHandler); // Terminal closed
50
51 // Catch C++ unhandled exceptions
52 set_terminate(Terminate);
53
54 // Subscribe to modify service for keeping track of config file changes
55 ModifyInfo = new class ConfigUpdate();
56
57 // Start server
58 string Rev(EVIDENCE_REVISION);
59 Rev = Rev.substr(1, Rev.size()-3);
60 snprintf(InitMsg, sizeof(InitMsg), "Server started (%s, compiled %s %s)", Rev.c_str(),__DATE__, __TIME__);
61
62 Status = new DimService((ServerName+"/Status").c_str(), (char *) "C", InitMsg, strlen(InitMsg)+1);
63 StdOut = new DimService((ServerName+"/Textout").c_str(), (char *) "");
64
65 start(Name);
66 addExitHandler(this);
67}
68
69// Destructor: Free memory
70EvidenceServer::~EvidenceServer() {
71
72 State(INFO, "Server stopped");
73
74 for (unsigned int i=0; i<ConfigList.size(); i++) {
75 delete[] ConfigList[i].Value;
76 }
77 delete ModifyInfo;
78
79 delete Status;
80 delete StdOut;
81}
82
83// DIM exit handler
84void EvidenceServer::exitHandler(int Code) {
85
86 State(INFO, "Exit handler called (DIM exit code %d)", Code);
87 exit(EXIT_SUCCESS);
88}
89
90// DIM error handler
91void EvidenceServer::errorHandler(int Severity, int Code, char *Message) {
92 State(ERROR, "%s (DIM error code %d, severity %d)\n", Message, Code, Severity);
93}
94
95// Set status of server
96//
97// The message format is special: after the string-terminating '\0' the Severity
98// is given, terminated by another '\0' The buffer for the DIM service must have
99// the same lifetime as the DIM service. If Severity is FATAL, exit() will be invoked.
100void EvidenceServer::State(StateType Severity, const char *Format, ...) {
101
102 static const char* StateString[] = {"Info", "Warn", "Error", "Fatal"};
103 static char ErrorString[] = "vasprintf() failed in State()";
104 static char SBuf[STATUS_SIZE];
105 char TBuf[STATUS_SIZE];
106 char *Tmp;
107
108 // Assemble message from application
109 va_list ArgumentPointer;
110 va_start(ArgumentPointer, Format);
111 if (vasprintf(&Tmp, Format, ArgumentPointer) == -1) Tmp = ErrorString;
112 va_end(ArgumentPointer);
113
114 // Create normal string
115 snprintf(TBuf, sizeof(TBuf), "%s (%s): %s", Status->getName(), StateString[Severity], Tmp);
116
117 // Create string with severity encoding
118 snprintf(SBuf, sizeof(SBuf), "%s**", Tmp);
119 SBuf[strlen(SBuf)-2] = '\0';
120 SBuf[strlen(SBuf)+1] = Severity;
121
122 if (Tmp != ErrorString) free(Tmp);
123
124 // Send message to console and log file
125 printf("%s\n", TBuf);
126 DimClient::sendCommandNB("DColl/Log", TBuf);
127
128 // Update DIM status service (including severity encoding)
129 if (Status != NULL) Status->updateService(SBuf, strlen(SBuf)+2);
130
131 // Terminate if message type is fatal
132 if (Severity == FATAL) exit(EXIT_FAILURE);
133}
134
135// Set text of StdOut service
136void EvidenceServer::SetStdOut(char *Text) {
137
138 // Copy text to permanent buffer
139 char *Tmp = new char[strlen(Text)+1];
140 strcpy(Tmp, Text);
141 StdOut->updateService(Tmp);
142
143 // Delete old buffer and save new buffer pointer
144 delete[] StdOutText;
145 StdOutText = Tmp;
146}
147
148// Get configuration data
149//
150// Program terminates if data is missing and no default given. Actual configuration
151// request will be made only if config file has modification since last request.
152// The memory allocated by all calls to this function will be freed by
153// the destructor.
154char* EvidenceServer::GetConfig(string Item, const char *Default) {
155
156 int ItemNo = -1;
157
158 // Check if configuration request already in list
159 for (unsigned int i=0; i<ConfigList.size(); i++) if (ConfigList[i].Name == Item) {
160 // Return original value if still up to date
161 if (ConfigList[i].Time >= ModifyInfo->LastModifyTime) return ConfigList[i].Value;
162
163 // Otherwise, free memory of old value
164 delete[] ConfigList[i].Value;
165 ItemNo = i;
166 break;
167 }
168
169 // Make configuration request
170 DimRpcInfo Config((char *) "ConfigRequest", NO_LINK);
171 Config.setData((char *) (ServerName + " " + Item).c_str());
172 char *Result = Config.getString();
173
174 // Terminate if not successful
175 if (!EvidenceServer::ServiceOK(&Config)) {
176 State(FATAL, "Configuration server unreachable, can't get '%s'", Item.c_str());
177 }
178
179 if (strlen(Result) == 0) {
180 if (Default == NULL) State(FATAL, "Missing configuration data '%s'", Item.c_str());
181 Result = (char *) Default;
182 }
183
184 // Enlarge list if necessary
185 if (ItemNo == -1) {
186 struct ConfigItem New;
187 ConfigList.push_back(New);
188 ItemNo = ConfigList.size()-1;
189 }
190
191 // Create new entry in item list, allocate memory and copy data to this memory
192 ConfigList[ItemNo].Value = new char [strlen(Result)+1];
193 ConfigList[ItemNo].Name = Item;
194 strcpy(ConfigList[ItemNo].Value, Result);
195 ConfigList[ItemNo].Time = ModifyInfo->LastModifyTime;
196
197 // Return address to configuration value
198 return ConfigList[ItemNo].Value;
199}
200
201
202// ====== Static methods ======
203
204// Signal handler (causes pause() and other syscalls to return)
205void EvidenceServer::SignalHandler(int Signal) {
206
207 static bool Called = false;
208
209 if (!Called) {
210 Called = true;
211 ThisServer->ExitRequest = true;
212 return;
213 }
214
215 // If invoked twice, call exit()
216 ThisServer->State(ThisServer->WARN, "Signal handler called again, invoking exit() (signal %d)", Signal);
217 exit(EXIT_FAILURE);
218}
219
220// C++ exception handler (derived from gcc __verbose_terminate_handler())
221void EvidenceServer::Terminate() {
222
223 static char Msg[STATUS_SIZE];
224 static bool Terminating = false;
225
226 if (Terminating) {
227 snprintf(Msg, sizeof(Msg), "%s: Terminate() called recursively, calling abort()", ThisServer->Status->getName());
228 printf("%s\n", Msg);
229 DimClient::sendCommandNB("DColl/Log", Msg);
230 abort();
231 }
232
233 Terminating = true;
234
235 // Make sure there was an exception; terminate is also called for an
236 // attempt to rethrow when there is no suitable exception.
237 type_info *Type = abi::__cxa_current_exception_type();
238 if (Type != NULL) {
239 int Status = -1;
240 char *Demangled = NULL;
241
242 Demangled = abi::__cxa_demangle(Type->name(), 0, 0, &Status);
243 snprintf(Msg, sizeof(Msg), "Terminate() called after throwing an instance of '%s'", Status==0 ? Demangled : Type->name());
244 free(Demangled);
245
246 // If exception derived from std::exception, more information.
247 try { __throw_exception_again; }
248 catch (exception &E) {
249 snprintf(Msg+strlen(Msg), sizeof(Msg)-strlen(Msg), " (what(): %s)", E.what());
250 }
251 catch (...) { }
252 }
253 else snprintf(Msg, sizeof(Msg), "Terminate() called without an active exception");
254
255 ThisServer->State(FATAL, Msg);
256}
257
258
259// Translates DIMInfo to string (memory has to be freed by caller)
260char *EvidenceServer::ToString(DimInfo *Item) {
261
262 char *Text;
263
264 // Safety check
265 if (Item->getSize() < 1) return NULL;
266
267 // Structure: print hex representation (3 characters per byte)
268 if (strlen(Item->getFormat()) != 1) {
269 int Size = 3*Item->getSize()+1, N;
270 if ((Text = (char *) malloc(Size)) == NULL) return NULL;
271
272 char *CurrPos = Text;
273 for (int i=0; i<Item->getSize(); i++) {
274 N = snprintf(CurrPos, Size, "%02x ", *((char *) Item->getData() + i));
275 if (N<0 || N>=Size) {
276 free(Text);
277 if (asprintf(&Text, "Structure length %d bytes, buffer overflow in ToString()", Item->getSize()) == -1) return NULL;
278 else return Text;
279 }
280 Size -= N;
281 CurrPos += N;
282 }
283 return Text;
284 }
285
286 // String: terminating \0 is enforced
287 if (toupper(*(Item->getFormat())) == 'C') {
288 *(Item->getString() + Item->getSize() - 1) = '\0';
289 if (asprintf(&Text, "%s", Item->getString()) == -1) return NULL;
290 return Text;
291 }
292
293 // Number array
294 int Size;
295 switch (toupper(*(Item->getFormat()))) {
296 case 'I':
297 case 'L': Size = sizeof(int); break;
298 case 'S': Size = sizeof(short); break;
299 case 'F': Size = sizeof(float); break;
300 case 'D': Size = sizeof(double); break;
301 case 'X': Size = sizeof(long long); break;
302 default: return NULL;
303 }
304
305 int Max, Mem = Item->getSize()*Size*4+1;
306 char *Pos;
307
308 if ((Text = (char *) malloc(Mem)) == NULL) return NULL;
309
310 *Text = '\0';
311 for (int i=0; i<Item->getSize()/Size; i++) {
312 Pos = Text+strlen(Text);
313 Max = Mem-strlen(Text);
314
315 switch (toupper(*(Item->getFormat()))) {
316 case 'I':
317 case 'L': snprintf(Pos, Max, "%d ", *((int *) Item->getData() + i));
318 break;
319 case 'S': snprintf(Pos, Max, "%hd ", *((short *) Item->getData() + i));
320 break;
321 case 'F': snprintf(Pos, Max, "%.5f ", *((float *) Item->getData() + i));
322 break;
323 case 'D': snprintf(Pos, Max, "%.5f ", *((double *) Item->getData() + i));
324 break;
325 case 'X': snprintf(Pos, Max, "%lld ", *((long long *) Item->getData() + i));
326 break;
327 }
328 }
329
330 return Text;
331}
332
333// Checks if service contents indicates not available
334bool EvidenceServer::ServiceOK(DimInfo *Item) {
335
336 return !((Item->getSize() == strlen(NO_LINK)+1) &&
337 (memcmp(Item->getData(), NO_LINK, Item->getSize()) == 0));
338}
339
340bool EvidenceServer::ServiceOK(DimRpcInfo *Item) {
341
342 return !((Item->getSize() == strlen(NO_LINK)+1) &&
343 (memcmp(Item->getData(), NO_LINK, Item->getSize()) == 0));
344}
345
346///////////////////////////
347// EvidenceHistory Class //
348///////////////////////////
349
350// Organisaztion of history buffer
351// F | T S D | T S D | 0 0 ...... | T S D | T S D | 0 -1
352//
353// F: Offset of oldest entry T: Time S: Size D: Data
354// F, T, S: int
355
356// Marker for history buffer
357const int EvidenceHistory::WrapMark[] = {0, -1};
358const int EvidenceHistory::EndMark[] = {0, 0};
359
360// Constructor
361EvidenceHistory::EvidenceHistory(std::string Name): Name(Name) {
362
363 Buffer = NULL;
364}
365
366// Destructor
367EvidenceHistory::~EvidenceHistory() {
368
369 delete[] Buffer;
370}
371
372// Requests service history
373bool EvidenceHistory::GetHistory() {
374
375 DimRpcInfo R((char *) "ServiceHistory", NO_LINK);
376 R.setData((char *) Name.c_str());
377 if (!EvidenceServer::ServiceOK(&R)) return false;
378
379 delete[] Buffer;
380 BufferSize = R.getSize();
381 Buffer = new char [BufferSize];
382
383 memcpy(Buffer, R.getData(), BufferSize);
384 Offset = *(int *) Buffer;
385
386 return true;
387}
388
389// Returns next item in history buffer
390bool EvidenceHistory::Next(int &Time, int &Size, void *&Data) {
391
392 if (Buffer == NULL) return false;
393
394 // Check for wrap around
395 if (memcmp(Buffer+Offset, WrapMark, sizeof(WrapMark)) == 0) Offset = 4;
396
397 // Check if at end of ring buffer
398 if (memcmp(Buffer+Offset, EndMark, sizeof(EndMark)) == 0) return false;
399
400 Time = *(int *) (Buffer + Offset);
401 Size = *(int *) (Buffer + Offset + sizeof(int));
402 Data = Buffer + Offset + 2*sizeof(int);
403
404 Offset += *((int *) (Buffer + Offset) + 1) + 2*sizeof(int);
405
406 return true;
407}
Note: See TracBrowser for help on using the repository browser.