summaryrefslogtreecommitdiff
path: root/src/bitz-server.cpp
blob: e99078ef59d9477da066194ad1c8c8c1f40a3fd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
 *	bitz-server, An ICAP server implementation in C++
 *	Copyright (C) 2012	Uditha Atukorala
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation; either version 3 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <syslog.h>
#include <sys/stat.h>
#include <sys/wait.h>

#include <spdlog/spdlog.h>

#include <config.h>
#include "bitz-server.h"

namespace bitz {

	namespace server {

		static server_t globals;

		void init() {

			// initialise defaults
			globals.pid         = -1;
			globals.pidfd       = -1;
			globals.manager     = NULL;
			globals.terminating = 0;
			globals.daemon      = false;

			// signal handlers
			init_signal_handlers();

		}


		void init_signal_handlers() {

			sigset_t ignore_mask;

			// set signal mask - signals we want to block
			sigemptyset(&ignore_mask);
			sigaddset(&ignore_mask, SIGTSTP);				// ignore Tty stop signals
			sigaddset(&ignore_mask, SIGTTOU);				// ignore Tty background writes
			sigaddset(&ignore_mask, SIGTTIN);				// ignore Tty background reads
			sigprocmask(SIG_BLOCK, &ignore_mask, NULL);		// block the above specified signals

			init_sigchld_handler();
			init_sigterm_handler();
			init_sigquit_handler();
			init_sigint_handler();

		}


		void init_sigchld_handler() {

			struct sigaction sa;

			// block all other signals
			sigfillset( &sa.sa_mask );

			// signal handler proc
			sa.sa_sigaction = &sigchld_handler;

			// flags
			sa.sa_flags = SA_SIGINFO;

			if ( sigaction( SIGCHLD, &sa, NULL ) < 0 ) {
				exit( EXIT_FAILURE );
			}

		}


		void sigchld_handler( int sig, siginfo_t *siginfo, void *context ) {

			pid_t worker_pid;
			int status;

			auto logger = spdlog::get( "bitz-server" );
			logger->trace( "[{}] inside zombie reaper", getpid() );
			while ( ( worker_pid = waitpid( WAIT_ANY, &status, WNOHANG ) ) > 0 ) {
				logger->trace( "[reaper] child {} terminated with status {}", worker_pid, status );

				if ( globals.manager != NULL ) {
					globals.manager->reap_worker( worker_pid );
				}
			}

		}


		void init_sigterm_handler() {

			struct sigaction sa;

			// block all other signals
			sigfillset( &sa.sa_mask );

			// signal handler proc
			sa.sa_sigaction = &sigterm_handler;

			// flags
			sa.sa_flags = SA_SIGINFO;

			if ( sigaction( SIGTERM, &sa, NULL ) < 0 ) {
				exit( EXIT_FAILURE );
			}

		}


		void sigterm_handler( int sig, siginfo_t *siginfo, void *context ) {

			auto logger = spdlog::get( "bitz-server" );
			logger->trace( "[{}] inside SIGTERM handler", getpid() );
			termination_handler( sig, siginfo, context );

		}


		void init_sigquit_handler() {

			struct sigaction sa;

			// block all other signals
			sigfillset( &sa.sa_mask );

			// signal handler proc
			sa.sa_sigaction = &sigquit_handler;

			// flags
			sa.sa_flags = SA_SIGINFO;

			if ( sigaction( SIGQUIT, &sa, NULL ) < 0 ) {
				exit( EXIT_FAILURE );
			}

		}


		void sigquit_handler( int sig, siginfo_t *siginfo, void *context ) {

			auto logger = spdlog::get( "bitz-server" );
			logger->trace( "[{}] inside SIGQUIT handler", getpid() );
			termination_handler( sig, siginfo, context );

		}


		void init_sigint_handler() {

			struct sigaction sa;

			// block all other signals
			sigfillset( &sa.sa_mask );

			// signal handler proc
			sa.sa_sigaction = &sigint_handler;

			// flags
			sa.sa_flags = SA_SIGINFO;

			if ( sigaction( SIGINT, &sa, NULL ) < 0 ) {
				exit( EXIT_FAILURE );
			}

		}


		void sigint_handler(  int sig, siginfo_t *siginfo, void *context ) {

			auto logger = spdlog::get( "bitz-server" );
			logger->trace( "[{}] inside SIGQINT handler", getpid() );
			termination_handler( sig, siginfo, context );

		}


		void daemonize( const char *rundir, const char *pidfile ) {

			pid_t pid;
			long i;
			char str[10];

			/* fork daemon */
			pid = fork();
			if ( pid < 0 ) {
				exit( EXIT_FAILURE );
			}

			// exit the parent
			if ( pid > 0 ) {
				exit( EXIT_SUCCESS );
			}

			// get a new process group
			if ( setsid() < 0 ) {
				exit(EXIT_FAILURE);
			}


			// 2nd fork (to make PID != SID)
			pid = fork();
			if ( pid < 0 ) {
				exit( EXIT_FAILURE );
			}

			// exit the parent
			if ( pid > 0 ) {
				exit( EXIT_SUCCESS );
			}


			/* child (a.k.a daemon) continues */
			// set file permissions (750)
			umask( 027 );

			// change running directory
			chdir( rundir );

			// close all open file descriptors
			for ( int fd = sysconf( _SC_OPEN_MAX ); fd > 0; fd-- ) {
				close( fd );
			}


			// logger (syslog)
			setlogmask( LOG_UPTO( LOG_INFO ) );
			openlog( PACKAGE_NAME, LOG_CONS, LOG_USER );

			// notify
			syslog( LOG_NOTICE, "starting daemon (version %s)", PACKAGE_VERSION );


			/* lock pid file to ensure we have only one copy */

			globals.pidfd = open( pidfile, O_RDWR | O_CREAT, 0600 );
			if ( globals.pidfd == -1 ) {
				syslog( LOG_ERR, "could not open pid lock file: %s", pidfile );
				exit( EXIT_FAILURE );
			}

			if ( lockf( globals.pidfd, F_TLOCK, 0 ) == -1 ) {
				syslog( LOG_ERR, "could not lock pid lock file: %s", pidfile);
				exit( EXIT_FAILURE );
			}

			// get and format pid
			globals.pid = getpid();
			sprintf( str, "%d\n", globals.pid );

			// write pid to lockfile
			write( globals.pidfd, str, strlen( str ) );

			// update status
			globals.daemon = true;

		}


		void shutdown() {

			// notify
			if ( globals.daemon && ( getpid() == globals.pid ) ) {
				syslog( LOG_NOTICE, "shutting down daemon (version %s)", PACKAGE_VERSION );
			}

			// close pid file
			if ( globals.pidfd != -1 ) {
				close( globals.pidfd );
			}

			// flush logs
			spdlog::get( "bitz-server" )->flush();

			// close logger (syslog)
			closelog();

		}


		void termination_handler( int sig, siginfo_t * sig_info, void * context ) {

			pid_t pid = getpid();
			auto logger = spdlog::get( "bitz-server" );
			logger->trace( "[{}] inside termination handler", pid );

			// exit by re-raising the signal if termination
			// already in progress
			if ( globals.terminating ) {
				logger->warn( "[{}] already terminating", pid );

				raise( sig );
			}

			// update termination status
			globals.terminating = 1;


			if ( globals.manager != NULL ) {

				// shutdown the manager
				globals.manager->shutdown();

				// clean-up
				delete globals.manager;

			}

			// cleanup
			shutdown();

			// re-raise the signal after reactivating the signal's default action
			signal( sig, SIG_DFL );
			raise( sig );

		}


		options_t read_options( int argc, char **argv ) {

			int optidx, optchar;
			options_t options;

			options.config_file = "";

			struct option lopts[] = {
				{ "config", required_argument, 0, 'c' },
				{ "debug", no_argument, &options.debug_flag, 1 },
				{ "help", no_argument, 0, 'h' },
				{ "usage", no_argument, 0, 'h' },
				{ "version", no_argument, 0, 'v' },
				{ 0, 0, 0, 0 }
			};

			while ( true ) {

				optidx  = 0;
				optchar = getopt_long( argc, argv, "c:hv", lopts, &optidx );

				// sanity check
				if ( optchar == -1 ) {
					break;
				}

				switch ( optchar ) {
					case 0:
						// TODO:
						break;

					case 'c':
						options.config_file = optarg;
						break;

					case 'h':
						print_usage();
						exit( EXIT_SUCCESS );
						break;

					case 'v':
						print_version();
						exit( EXIT_SUCCESS );

					case '?':
						print_usage();
						exit( EXIT_FAILURE );
						break;

					default:
						// TODO:
						break;
				}

			}

			return options;

		}


		void print_version() {

			std::cout << PACKAGE_STRING << std::endl;
			std::cout << "" << std::endl;
			std::cout << "Copyright (C) 2012-2013 Uditha Atukorala" << std::endl;
			std::cout << "" << std::endl;
			std::cout << "This program is free software; you can redistribute it and/or modify" << std::endl;
			std::cout << "it under the terms of the GNU General Public License as published by" << std::endl;
			std::cout << "the Free Software Foundation; either version 3 of the License, or" << std::endl;
			std::cout << "(at your option) any later version." << std::endl;
			std::cout << "" << std::endl;
			std::cout << "This program is distributed in the hope that it will be useful," << std::endl;
			std::cout << "but WITHOUT ANY WARRANTY; without even the implied warranty of" << std::endl;
			std::cout << "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the" << std::endl;
			std::cout << "GNU General Public License (http://gnu.org/licenses/gpl.html)" << std::endl;
			std::cout << "for more details." << std::endl;
			std::cout << "" << std::endl;

		}


		void print_usage() {

			std::cout << "usage: " << PACKAGE_NAME << " "
				<< "[--version] [--help] [--usage] [--debug] [--config=<config file>]"
				<< std::endl;

			std::cout << "" << std::endl;
			std::cout << "See the man pages for more information" << std::endl;

		}


		void start( int port, unsigned int children, int max_requests, int comm_timeout ) {

			try {
				globals.manager = new bitz::Manager( port );
				globals.manager->spawn( children, max_requests, comm_timeout );
			} catch ( bitz::ManagerException &mex ) {
				syslog( LOG_ERR, "failed to start, exception: %s", mex.what() );
				exit( EXIT_FAILURE );
			}

		}


		void run() {

			sigset_t mask, oldmask;

			// sanity check
			if ( globals.manager == NULL ) {
				return;
			}

			// block termination signals until we are ready
			sigemptyset( &mask );
			sigaddset( &mask, SIGTERM );
			sigaddset( &mask, SIGQUIT );
			sigaddset( &mask, SIGINT );
			sigprocmask ( SIG_BLOCK, &mask, &oldmask );

			// loop until a termination signal is received
			while (! globals.terminating ) {

				// capture any signals
				sigsuspend( &oldmask );

				// unblock termination signals
				sigprocmask( SIG_UNBLOCK, &mask, NULL );

				// manage workers
				globals.manager->manage_workers();

				// block termination signals
				sigprocmask( SIG_BLOCK, &mask, &oldmask );

			}

		}

	} /* end of namespace server */

} /* end of namespace bitz */