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