source: Evidence/Evidence.cc @ 152

Last change on this file since 152 was 152, checked in by ogrimm, 11 years ago
Updates
File size: 6.6 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       
18  All memory allocated by the non-static methods will be freed by the
19  class destructor.
20 
21  Oliver Grimm, December 2009
22 
23\********************************************************************/
24
25#include "Evidence.h"
26
27bool EvidenceServer::ExitRequest = false;
28string __StatusName;
29
30// Constructor starts server with given name
31EvidenceServer::EvidenceServer(const char *Name) {
32
33  // Initialize
34  Status = NULL;
35  ConfigList = NULL;
36  ConfigNum = 0;
37  __StatusName = string(Name) + "/Status";
38 
39  // Catch some signals
40  signal(SIGQUIT, &SignalHandler);  // CTRL-Backspace
41  signal(SIGTERM, &SignalHandler);  // Termination signal
42  signal(SIGINT, &SignalHandler);   // CTRL-C
43  signal(SIGHUP, &SignalHandler);   // Terminal closed
44 
45  // Catch C++ unhandled exceptions
46  set_terminate(Terminate);
47 
48  // Start server
49  Status = new DimService(__StatusName.c_str(), (char *) "Server started");
50
51  start(Name);
52  addExitHandler(this);
53}
54
55// Destructor: Free memory
56EvidenceServer::~EvidenceServer() {
57
58  for (unsigned int i=0; i<ConfigNum; i++) {
59        delete[] ConfigList[i].Name;
60        delete[] ConfigList[i].Value;
61  }
62  free(ConfigList);
63}
64
65// DIM exit handler
66void EvidenceServer::exitHandler(int Code) {
67  State(INFO, "Server stopped (DIM exit code %d)", Code);
68  exit(EXIT_SUCCESS);
69}
70
71// DIM error handler
72void EvidenceServer::errorHandler(int Severity, int Code, char *Message) {   
73  State(ERROR, "%s (DIM error code %d, severity %d)\n", Message, Code, Severity);
74}
75
76// Set status of server
77//
78// The message format is special: after the string-terminating '\0' the Severity
79// is given, terminated by another '\0'  The buffer for the DIM service must have
80// the same lifetime as the DIM service. If Severity is FATAL, exit() will be invoked.
81void EvidenceServer::State(StateType Severity, const char *Format, ...) {
82
83  static const char* StateString[] = {"Info", "Warn", "Error", "Fatal"};
84  static char ErrorString[] = "vasprintf() failed in State()";
85  static char SBuf[STATUS_SIZE];
86  char TBuf[STATUS_SIZE];
87  char *Tmp;
88 
89  // Assemble message from application
90  va_list ArgumentPointer;
91  va_start(ArgumentPointer, Format);
92  if (vasprintf(&Tmp, Format, ArgumentPointer) == -1) Tmp = ErrorString;
93  va_end(ArgumentPointer);
94
95  snprintf(TBuf, sizeof(TBuf), "%s (%s): %s", __StatusName.c_str(), StateString[Severity], Tmp); // Normal string
96  snprintf(SBuf, sizeof(SBuf), "%s*%c", Tmp, (char) Severity);
97  *(strrchr(SBuf, '*')) = '\0';  // String with severity encoding
98  if (Tmp != ErrorString) free(Tmp);
99 
100  // Send message to console and log file
101  printf("%s\n", TBuf);
102  if (Severity != INFO) DimClient::sendCommand("DColl/Log", TBuf);
103
104  // Update DIM status service (including severity encoding)
105  if (Status != NULL) Status->updateService(SBuf, strlen(SBuf)+2);
106
107  // Terminate if message type is fatal
108  if (Severity == FATAL) exit(EXIT_FAILURE);
109}
110
111// Get configuration data (program terminates if data is missing)
112//
113// The memory allocated by all calls to this function will be freed by
114// the destructor.
115char* EvidenceServer::GetConfig(const char *Item, const char *Default) {
116 
117  // Determine configuration file update time
118  DimCurrentInfo ModifyTime("Config/ModifyTime", 0);
119  int Time = ModifyTime.getInt(), ItemNo = -1;
120 
121  // Check if configuration request already in list
122  for (unsigned int i=0; i<ConfigNum; i++) {
123    if (strcmp(ConfigList[i].Name, Item) == 0) {
124          // Return original value if still up to date
125          if (ConfigList[i].Time >= Time) return ConfigList[i].Value;
126
127          // Otherwise, free memory of old value
128          delete[] ConfigList[i].Name;
129          delete[] ConfigList[i].Value;   
130          ItemNo = i;
131          break;
132        }
133  } 
134 
135  // Make configuration request
136  DimRpcInfo Config((char *) "ConfigRequest", (char *) "");
137  Config.setData((char *) Item);
138  char *Result = Config.getString();
139 
140  // Terminate if not successful
141  if (strlen(Result) == 0) {
142    if (Default == NULL) State(FATAL, "Missing configuration data '%s'", Item);
143        Result = (char *) Default;
144  }
145
146  // Enlarge memory to hold new pointer if necessary
147  if (ItemNo == -1) {
148        void *N = realloc(ConfigList, sizeof(struct ConfigItem)*(++ConfigNum));
149        if (N == NULL) {
150          State(WARN, "Could not realloc() memory for configuration, will lose memory (%s)", strerror(errno));
151          ConfigNum--; 
152        }
153        else ConfigList = (struct ConfigItem *) N;
154       
155        ItemNo = ConfigNum-1;
156  }
157 
158  // Allocate memory for strings, and copy data to this memory
159  ConfigList[ItemNo].Value = new char [strlen(Result)+1];
160  ConfigList[ItemNo].Name = new char [strlen(Item)+1];
161  strcpy(ConfigList[ItemNo].Name, Item);
162  strcpy(ConfigList[ItemNo].Value, Result);
163
164  ConfigList[ItemNo].Time = Time;
165 
166  // Return address to configuration value 
167  return ConfigList[ItemNo].Value;
168}
169
170
171// ====== Static methods ======
172
173// Signal handler (causes pause() and other syscalls to return)
174void EvidenceServer::SignalHandler(int) {
175
176  EvidenceServer::ExitRequest = true;
177}
178
179// C++ exception handler
180void EvidenceServer::Terminate() {
181
182  string Msg = __StatusName + ": Caught unhandled exception";
183  printf("%s\n", Msg.c_str());
184  DimClient::sendCommand("DColl/Log", Msg.c_str());
185 
186  abort();
187}
188
189// Translates DIMInfo to string (memory has to be freed by caller)
190// No DIM structures are supported (only a single number or string is converted)
191char *EvidenceServer::ToString(DimInfo *Item) {
192
193  char *Text;
194  int R;
195 
196  if (strlen(Item->getFormat()) != 1) return NULL;
197 
198  switch (*(Item->getFormat())) {
199    case 'I':  R = asprintf(&Text, "%d", Item->getInt());   break;
200    case 'C':  R = asprintf(&Text, "%s", Item->getString());   break;
201    case 'S':  R = asprintf(&Text, "%hd", Item->getShort());   break;
202    case 'F':  R = asprintf(&Text, "%.5f", Item->getFloat());   break;
203    case 'D':  R = asprintf(&Text, "%.5f", Item->getDouble());   break;
204    case 'X':  R = asprintf(&Text, "%lld", Item->getLonglong());   break;
205    default: return NULL;
206  }
207
208  return (R == -1) ? NULL : Text;
209}
Note: See TracBrowser for help on using the repository browser.