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