]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/libopensrf/osrf_system.c
added a basic signal handler for the top-level C process which sends SIGTERM to its...
[OpenSRF.git] / src / libopensrf / osrf_system.c
1 #include <opensrf/osrf_system.h>
2 #include <opensrf/osrf_application.h>
3 #include <opensrf/osrf_prefork.h>
4 #include <signal.h>
5
6 static void report_child_status( pid_t pid, int status );
7 struct child_node;
8 typedef struct child_node ChildNode;
9
10 static void handleKillSignal(int signo) {
11     /* we are the top-level process and we've been 
12      * killed. Kill all of our children */
13     kill(0, SIGTERM);
14     sleep(1); /* give the children a chance to die before we reap them */
15     pid_t child_pid;
16     int status;
17     while( (child_pid=waitpid(-1,&status,WNOHANG)) > 0) 
18         osrfLogInfo(OSRF_LOG_MARK, "Killed child %d", child_pid);
19     _exit(0);
20 }
21
22
23 struct child_node
24 {
25         ChildNode* pNext;
26         ChildNode* pPrev;
27         pid_t pid;
28         char* app;
29         char* libfile;
30 };
31
32 static ChildNode* child_list;
33
34 static transport_client* osrfGlobalTransportClient = NULL;
35
36 static void add_child( pid_t pid, const char* app, const char* libfile );
37 static void delete_child( ChildNode* node );
38 static void delete_all_children( void );
39 static ChildNode* seek_child( pid_t pid );
40
41 transport_client* osrfSystemGetTransportClient( void ) {
42         return osrfGlobalTransportClient;
43 }
44
45 void osrfSystemIgnoreTransportClient() {
46         osrfGlobalTransportClient = NULL;
47 }
48
49 int osrf_system_bootstrap_client( char* config_file, char* contextnode ) {
50         return osrfSystemBootstrapClientResc(config_file, contextnode, NULL);
51 }
52
53 int osrfSystemInitCache( void ) {
54
55         jsonObject* cacheServers = osrf_settings_host_value_object("/cache/global/servers/server");
56         char* maxCache = osrf_settings_host_value("/cache/global/max_cache_time");
57
58         if( cacheServers && maxCache) {
59
60                 if( cacheServers->type == JSON_ARRAY ) {
61                         int i;
62                         const char* servers[cacheServers->size];
63                         for( i = 0; i != cacheServers->size; i++ ) {
64                                 servers[i] = jsonObjectGetString( jsonObjectGetIndex(cacheServers, i) );
65                                 osrfLogInfo( OSRF_LOG_MARK, "Adding cache server %s", servers[i]);
66                         }
67                         osrfCacheInit( servers, cacheServers->size, atoi(maxCache) );
68
69                 } else {
70                         const char* servers[] = { jsonObjectGetString(cacheServers) };          
71                         osrfLogInfo( OSRF_LOG_MARK, "Adding cache server %s", servers[0]);
72                         osrfCacheInit( servers, 1, atoi(maxCache) );
73                 }
74
75         } else {
76                 osrfLogError( OSRF_LOG_MARK,  "Missing config value for /cache/global/servers/server _or_ "
77                         "/cache/global/max_cache_time");
78         }
79
80         return 0;
81 }
82
83
84 int osrfSystemBootstrap( char* hostname, char* configfile, char* contextNode ) {
85         if( !(hostname && configfile && contextNode) ) return -1;
86
87         /* first we grab the settings */
88         if(!osrfSystemBootstrapClientResc(configfile, contextNode, "settings_grabber" )) {
89                 osrfLogError( OSRF_LOG_MARK,
90                         "Unable to bootstrap for host %s from configuration file %s",
91                         hostname, configfile );
92                 return -1;
93         }
94
95         int retcode = osrf_settings_retrieve(hostname);
96         osrf_system_disconnect_client();
97
98         if( retcode ) {
99                 osrfLogError( OSRF_LOG_MARK,
100                         "Unable to retrieve settings for host %s from configuration file %s",
101                         hostname, configfile );
102                 return -1;
103         }
104
105         /** daemonize me **/
106         /* background and let our children do their thing */
107         /* NOTE: This has been moved from below the 'if (apps)' block below ... move it back if things go crazy */
108         daemonize();
109
110         jsonObject* apps = osrf_settings_host_value_object("/activeapps/appname");
111         osrfStringArray* arr = osrfNewStringArray(8);
112         
113         if(apps) {
114                 int i = 0;
115
116                 if(apps->type == JSON_STRING) {
117                         osrfStringArrayAdd(arr, jsonObjectGetString(apps));
118
119                 } else {
120                         const jsonObject* app;
121                         while( (app = jsonObjectGetIndex(apps, i++)) ) 
122                                 osrfStringArrayAdd(arr, jsonObjectGetString(app));
123                 }
124
125                 char* appname = NULL;
126                 i = 0;
127                 while( (appname = osrfStringArrayGetString(arr, i++)) ) {
128
129                         char* lang = osrf_settings_host_value("/apps/%s/language", appname);
130
131                         if(lang && !strcasecmp(lang,"c"))  {
132
133                                 char* libfile = osrf_settings_host_value("/apps/%s/implementation", appname);
134                 
135                                 if(! (appname && libfile) ) {
136                                         osrfLogWarning( OSRF_LOG_MARK, "Missing appname / libfile in settings config");
137                                         continue;
138                                 }
139
140                                 osrfLogInfo( OSRF_LOG_MARK, "Launching application %s with implementation %s", appname, libfile);
141                 
142                                 pid_t pid;
143                 
144                                 if( (pid = fork()) ) { 
145                                         // store pid in local list for re-launching dead children...
146                                         add_child( pid, appname, libfile );
147                                         osrfLogInfo( OSRF_LOG_MARK, "Running application child %s: process id %ld",
148                                                                  appname, (long) pid );
149         
150                                 } else {
151                 
152                                         osrfLogInfo( OSRF_LOG_MARK, " * Running application %s\n", appname);
153                                         if( osrfAppRegisterApplication( appname, libfile ) == 0 ) 
154                                                 osrf_prefork_run(appname);
155         
156                                         osrfLogDebug( OSRF_LOG_MARK, "Server exiting for app %s and library %s\n", appname, libfile );
157                                         exit(0);
158                                 }
159                         } // language == c
160                 } 
161         } // should we do something if there are no apps? does the wait(NULL) below do that for us?
162
163         osrfStringArrayFree(arr);
164
165     signal(SIGTERM, handleKillSignal);
166     signal(SIGINT, handleKillSignal);
167         
168         while(1) {
169                 errno = 0;
170                 int status;
171                 pid_t pid = wait( &status );
172                 if(-1 == pid) {
173                         if(errno == ECHILD)
174                                 osrfLogError(OSRF_LOG_MARK, "We have no more live services... exiting");
175                         else
176                                 osrfLogError(OSRF_LOG_MARK, "Exiting top-level system loop with error: %s", strerror(errno));
177                         break;
178                 } else {
179                         report_child_status( pid, status );
180                 }
181         }
182
183         delete_all_children();
184         return 0;
185 }
186
187
188 static void report_child_status( pid_t pid, int status )
189 {
190         const char* app;
191         const char* libfile;
192         ChildNode* node = seek_child( pid );
193
194         if( node ) {
195                 app     = node->app     ? node->app     : "[unknown]";
196                 libfile = node->libfile ? node->libfile : "[none]";
197         } else
198                 app = libfile = NULL;
199         
200         if( WIFEXITED( status ) )
201         {
202                 int rc = WEXITSTATUS( status );  // return code of child process
203                 if( rc )
204                         osrfLogError( OSRF_LOG_MARK, "Child process %ld (app %s) exited with return code %d",
205                                                   (long) pid, app, rc );
206                 else
207                         osrfLogInfo( OSRF_LOG_MARK, "Child process %ld (app %s) exited normally",
208                                                   (long) pid, app );
209         }
210         else if( WIFSIGNALED( status ) )
211         {
212                 osrfLogError( OSRF_LOG_MARK, "Child process %ld (app %s) killed by signal %d",
213                                           (long) pid, app, WTERMSIG( status) );
214         }
215         else if( WIFSTOPPED( status ) )
216         {
217                 osrfLogError( OSRF_LOG_MARK, "Child process %ld (app %s) stopped by signal %d",
218                                           (long) pid, app, (int) WSTOPSIG( status ) );
219         }
220
221         delete_child( node );
222 }
223
224 /*----------- Routines to manage list of children --*/
225
226 static void add_child( pid_t pid, const char* app, const char* libfile )
227 {
228         /* Construct new child node */
229         
230         ChildNode* node = safe_malloc( sizeof( ChildNode ) );
231
232         node->pid = pid;
233
234         if( app )
235                 node->app = strdup( app );
236         else
237                 node->app = NULL;
238
239         if( libfile )
240                 node->libfile = strdup( libfile );
241         else
242                 node->libfile = NULL;
243         
244         /* Add new child node to the head of the list */
245
246         node->pNext = child_list;
247         node->pPrev = NULL;
248
249         if( child_list )
250                 child_list->pPrev = node;
251
252         child_list = node;
253 }
254
255 static void delete_child( ChildNode* node ) {
256
257         /* Sanity check */
258
259         if( ! node )
260                 return;
261         
262         /* Detach the node from the list */
263
264         if( node->pPrev )
265                 node->pPrev->pNext = node->pNext;
266         else
267                 child_list = node->pNext;
268
269         if( node->pNext )
270                 node->pNext->pPrev = node->pPrev;
271
272         /* Deallocate the node and its payload */
273
274         free( node->app );
275         free( node->libfile );
276         free( node );
277 }
278
279 static void delete_all_children( void ) {
280
281         while( child_list )
282                 delete_child( child_list );
283 }
284
285 static ChildNode* seek_child( pid_t pid ) {
286
287         /* Return a pointer to the child node for the */
288         /* specified process ID, or NULL if not found */
289         
290         ChildNode* node = child_list;
291         while( node ) {
292                 if( node->pid == pid )
293                         break;
294                 else
295                         node = node->pNext;
296         }
297
298         return node;
299 }
300
301 /*----------- End of routines to manage list of children --*/
302
303
304 int osrfSystemBootstrapClientResc( char* config_file, char* contextnode, char* resource ) {
305
306         int failure = 0;
307
308         if(osrfSystemGetTransportClient()) {
309                 osrfLogInfo(OSRF_LOG_MARK, "Client is already bootstrapped");
310                 return 1; /* we already have a client connection */
311         }
312
313         if( !( config_file && contextnode ) && ! osrfConfigHasDefaultConfig() ) {
314                 osrfLogError( OSRF_LOG_MARK, "No Config File Specified\n" );
315                 return -1;
316         }
317
318         if( config_file ) {
319                 osrfConfig* cfg = osrfConfigInit( config_file, contextnode );
320                 if(cfg)
321                         osrfConfigSetDefaultConfig(cfg);
322                 else
323                         return 0;   /* Can't load configuration?  Bail out */
324         }
325
326
327         char* log_file          = osrfConfigGetValue( NULL, "/logfile");
328         if(!log_file) {
329                 fprintf(stderr, "No log file specified in configuration file %s\n",
330                                 config_file);
331                 return -1;
332         }
333
334         char* log_level         = osrfConfigGetValue( NULL, "/loglevel" );
335         osrfStringArray* arr    = osrfNewStringArray(8);
336         osrfConfigGetValueList(NULL, arr, "/domain");
337
338         char* username          = osrfConfigGetValue( NULL, "/username" );
339         char* password          = osrfConfigGetValue( NULL, "/passwd" );
340         char* port              = osrfConfigGetValue( NULL, "/port" );
341         char* unixpath          = osrfConfigGetValue( NULL, "/unixpath" );
342         char* facility          = osrfConfigGetValue( NULL, "/syslog" );
343         char* actlog            = osrfConfigGetValue( NULL, "/actlog" );
344
345         /* if we're a source-client, tell the logger */
346         char* isclient = osrfConfigGetValue(NULL, "/client");
347         if( isclient && !strcasecmp(isclient,"true") )
348                 osrfLogSetIsClient(1);
349         free(isclient);
350
351         int llevel = 0;
352         int iport = 0;
353         if(port) iport = atoi(port);
354         if(log_level) llevel = atoi(log_level);
355
356         if(!strcmp(log_file, "syslog")) {
357                 osrfLogInit( OSRF_LOG_TYPE_SYSLOG, contextnode, llevel );
358                 osrfLogSetSyslogFacility(osrfLogFacilityToInt(facility));
359                 if(actlog) osrfLogSetSyslogActFacility(osrfLogFacilityToInt(actlog));
360
361         } else {
362                 osrfLogInit( OSRF_LOG_TYPE_FILE, contextnode, llevel );
363                 osrfLogSetFile( log_file );
364         }
365
366
367         /* Get a domain, if one is specified */
368         const char* domain = osrfStringArrayGetString( arr, 0 ); /* just the first for now */
369         if(!domain) {
370                 fprintf(stderr, "No domain specified in configuration file %s\n", config_file);
371                 osrfLogError( OSRF_LOG_MARK, "No domain specified in configuration file %s\n", config_file);
372                 failure = 1;
373         }
374
375         if(!username) {
376                 fprintf(stderr, "No username specified in configuration file %s\n", config_file);
377                 osrfLogError( OSRF_LOG_MARK, "No username specified in configuration file %s\n", config_file);
378                 failure = 1;
379         }
380
381         if(!password) {
382                 fprintf(stderr, "No password specified in configuration file %s\n", config_file);
383                 osrfLogError( OSRF_LOG_MARK, "No password specified in configuration file %s\n", config_file);
384                 failure = 1;
385         }
386
387         if((iport <= 0) && !unixpath) {
388                 fprintf(stderr, "No unixpath or valid port in configuration file %s\n", config_file);
389                 osrfLogError( OSRF_LOG_MARK, "No unixpath or valid port in configuration file %s\n",
390                         config_file);
391                 failure = 1;
392         }
393
394         if (failure) {
395                 osrfStringArrayFree(arr);
396                 free(log_level);
397                 free(username);
398                 free(password);
399                 free(port);
400                 free(unixpath);
401                 free(facility);
402                 free(actlog);
403                 return 0;
404         }
405
406         osrfLogInfo( OSRF_LOG_MARK, "Bootstrapping system with domain %s, port %d, and unixpath %s",
407                 domain, iport, unixpath ? unixpath : "(none)" );
408         transport_client* client = client_init( domain, iport, unixpath, 0 );
409
410         const char* host;
411         host = getenv("HOSTNAME");
412
413         char tbuf[32];
414         tbuf[0] = '\0';
415         snprintf(tbuf, 32, "%f", get_timestamp_millis());
416
417         if(!host) host = "";
418         if(!resource) resource = "";
419
420         int len = strlen(resource) + 256;
421         char buf[len];
422         buf[0] = '\0';
423         snprintf(buf, len - 1, "%s_%s_%s_%ld", resource, host, tbuf, (long) getpid() );
424
425         if(client_connect( client, username, password, buf, 10, AUTH_DIGEST )) {
426                 /* child nodes will leak the parents client... but we can't free
427                         it without disconnecting the parents client :( */
428                 osrfGlobalTransportClient = client;
429         }
430
431         osrfStringArrayFree(arr);
432         free(actlog);
433         free(facility);
434         free(log_level);
435         free(log_file);
436         free(username);
437         free(password);
438         free(port);     
439         free(unixpath);
440
441         if(osrfGlobalTransportClient)
442                 return 1;
443
444         return 0;
445 }
446
447 int osrf_system_disconnect_client( void ) {
448         client_disconnect( osrfGlobalTransportClient );
449         client_free( osrfGlobalTransportClient );
450         osrfGlobalTransportClient = NULL;
451         return 0;
452 }
453
454 int osrf_system_shutdown( void ) {
455         osrfConfigCleanup();
456     osrfCacheCleanup();
457         osrf_system_disconnect_client();
458         osrf_settings_free_host_config(NULL);
459         osrfAppSessionCleanup();
460         osrfLogCleanup();
461         return 1;
462 }
463
464
465
466