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