summaryrefslogtreecommitdiff
path: root/main.c
blob: cd82c5933b182d52f314994be03ef9118cba49b8 (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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
/* -*-pgsql-c-*- */
/*
 * $Header$
 *
 * pgpool: a language independent connection pool server for PostgreSQL 
 * written by Tatsuo Ishii
 *
 * Copyright (c) 2003-2007	PgPool Global Development Group
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby
 * granted, provided that the above copyright notice appear in all
 * copies and that both that copyright notice and this permission
 * notice appear in supporting documentation, and that the name of the
 * author not be used in advertising or publicity pertaining to
 * distribution of the software without specific, written prior
 * permission. The author makes no representations about the
 * suitability of this software for any purpose.  It is provided "as
 * is" without express or implied warranty.
 */
#include "pool.h"

#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <netdb.h>
#include <arpa/inet.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif

#include <sys/stat.h>
#include <fcntl.h>

#include <sys/wait.h>

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include <signal.h>

#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif

#include "version.h"

#define CHECK_REQUEST \
	do \
	{ \
		if (failover_request) \
		{ \
			failover(failover_signo); \
			failover_request = 0; \
		} \
		if (sigchld_request) \
		{ \
			reaper(); \
		} \
	} while (0)

#define PGPOOLMAXLITSENQUEUELENGTH 10000
static void daemonize(void);
static int read_pid_file(void);
static void write_pid_file(void);
static pid_t fork_a_child(int unix_fd, int inet_fd);
static int create_unix_domain_socket(void);
static int create_inet_domain_socket(const char *hostname);
static void myexit(int code);
static void failover(int sig);
static void reaper(void);
static int pool_pause(struct timeval *timeout);
static void pool_sleep(unsigned int second);

static RETSIGTYPE exit_handler(int sig);
static RETSIGTYPE reap_handler(int sig);
static RETSIGTYPE failover_handler(int sig);
static RETSIGTYPE health_check_timer_handler(int sig);

static void usage(void);
static void stop_me(void);
static void switch_me(void);

static struct sockaddr_un un_addr;		/* unix domain socket path */

static pid_t *pids;	/* child pid table */

static int unix_fd;	/* unix domain socket fd */
static int inet_fd;	/* inet domain socket fd */

static int exiting = 0;		/* non 0 if I'm exiting */
static int switching = 0;		/* non 0 if I'm fail overing or degenerating */
static int degenerated = 0;	/* set non 0 if already degerated */

static int not_detach = 0;		/* non 0 if non detach option (-n) is given */
int debug = 0;	/* non 0 if debug option is given (-d) */

static pid_t mypid;	/* pgpool parent process id */

long int weight_master;	/* normalized weight of master (0-RAND_MAX range) */

static int stop_sig = SIGTERM;	/* stopping signal default value */
static int switch_over_sig = SIGUSR1;	/* switch over signal default value */

static volatile sig_atomic_t health_check_timer_expired;		/* non 0 if health check timer expired */
static volatile sig_atomic_t failover_request = 0;
static volatile sig_atomic_t sigchld_request = 0;
static int pipe_fds[2]; /* for delivering signals */
static volatile int failover_signo = 0;

int myargc;
char **myargv;

/*
* pgpool main program
*/
int main(int argc, char **argv)
{
	int opt;
	char conf_file[POOLMAXPATHLEN+1];
	char hba_file[POOLMAXPATHLEN+1];
	int i;
	int pid;

	myargc = argc;
	myargv = argv;

	snprintf(conf_file, sizeof(conf_file), "%s/%s", DEFAULT_CONFIGDIR, POOL_CONF_FILE_NAME);
	snprintf(hba_file, sizeof(hba_file), "%s/%s", DEFAULT_CONFIGDIR, HBA_CONF_FILE_NAME);

	while ((opt = getopt(argc, argv, "a:df:hm:ns:")) != -1)
	{
		switch (opt)
		{
			case 'a':    /* specify hba configuration file */
				if (!optarg)
				{
					usage();
					exit(1);
				}
				strncpy(hba_file, optarg, sizeof(hba_file));
				break;

			case 'd':	/* debug option */
				debug = 1;
				break;

			case 'f':	/* specify configuration file */
				if (!optarg)
				{
					usage();
					exit(1);
				}
				strncpy(conf_file, optarg, sizeof(conf_file));
				break;

			case 'h':
				usage();
				exit(0);
				break;

			case 'm':	/* stop mode */
				if (!optarg)
				{
					usage();
					exit(1);
				}
				if (*optarg == 's' || !strcmp("smart", optarg))
					stop_sig = SIGTERM;		/* smart shutdown */
				else if (*optarg == 'f' || !strcmp("fast", optarg))
					stop_sig = SIGINT;		/* fast shutdown */
				else if (*optarg == 'i' || !strcmp("immediate", optarg))
					stop_sig = SIGQUIT;		/* immediate shutdown */
				else
				{
					usage();
					exit(1);
				}
				break;
				
			case 'n':	/* no detaching control ttys */
				not_detach = 1;
				break;

			case 's':	/* switch over request */
				if (!optarg)
				{
					usage();
					exit(1);
				}
				if (*optarg == 'm' || !strcmp("master", optarg))
					switch_over_sig = SIGUSR1;		/* stopping master */
				else if (*optarg == 's' || !strcmp("secondary", optarg))
					switch_over_sig = SIGUSR2;		/* stopping secondary */
				else
				{
					usage();
					exit(1);
				}
				break;

			default:
				usage();
				exit(1);
		}
	}

	if (pool_get_config(conf_file))
	{
		pool_error("Unable to get configuration. Exiting...");
		exit(1);
	}

	/* set current PostgreSQL backend */
	pool_config.current_backend_host_name = pool_config.backend_host_name;
	pool_config.current_backend_port = pool_config.backend_port;

	/* set load balance weight */
	if (pool_config.weight_master <= 0.0)
		weight_master = 0;
	else
		weight_master = (RAND_MAX) * (pool_config.weight_master /
									  (pool_config.weight_master + pool_config.weight_secondary));

	pool_debug("weight: %ld", weight_master);

	/* read pool_hba.conf */
	if (pool_config.enable_pool_hba)
		load_hba(hba_file);

	/*
	 * if a non-switch argument remains, then it should be either "stop" or "switch"
	 */
	if (optind == (argc - 1))
	{
		if (!strcmp(argv[optind], "stop"))
		{
			stop_me();
			exit(0);
		}
		else if (!strcmp(argv[optind], "switch"))
		{
			switch_me();
			exit(0);
		}
		else
		{
			usage();
			exit(1);
		}
	}
	/*
	 * else if no non-switch argument remains, then it should be a start request
	 */
	else if (optind == argc)
	{
		pid = read_pid_file();
		if (pid > 0)
		{
			if (kill(pid, 0) == 0)
			{
				fprintf(stderr, "pid file found. is another pgpool(%d) is running?\n", pid);
				exit(1);
			}
			else
				fprintf(stderr, "pid file found but it seems bogus. Trying to start pgpool anyway...\n");
		}
	}
	/*
	 * otherwise an error...
	 */
	else
	{
		usage();
		exit(1);
	}

	/* set signal masks */
	poolinitmask();

	if (not_detach)
		write_pid_file();
	else
		daemonize();

	mypid = getpid();

	/* set unix domain socket path */
	snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s/.s.PGSQL.%d",
			 pool_config.socket_dir,
			 pool_config.port);

	/* set up signal handlers */
	pool_signal(SIGPIPE, SIG_IGN);

	/* create unix domain socket */
	unix_fd = create_unix_domain_socket();

	/* create inet domain socket if any */
	if (pool_config.listen_addresses[0])
	{
		inet_fd = create_inet_domain_socket(pool_config.listen_addresses);
	}

	pids = malloc(pool_config.num_init_children * sizeof(pid_t));
	if (pids == NULL)
	{
		pool_error("failed to allocate pids");
		myexit(1);
	}
	memset(pids, 0, pool_config.num_init_children * sizeof(pid_t));

	/* fork the children */
	for (i=0;i<pool_config.num_init_children;i++)
	{
		pids[i] = fork_a_child(unix_fd, inet_fd);
	}

	/* set up signal handlers */
	POOL_SETMASK(&BlockSig);
	pool_signal(SIGTERM, exit_handler);
	pool_signal(SIGINT, exit_handler);
	pool_signal(SIGQUIT, exit_handler);
	pool_signal(SIGCHLD, reap_handler);
	pool_signal(SIGUSR1, failover_handler);
	pool_signal(SIGUSR2, failover_handler);
	pool_signal(SIGHUP, exit_handler);

	/* create pipe for delivering event */
	if (pipe(pipe_fds) < 0)
	{
		pool_error("failed to create pipe");
		myexit(1);
	}

	pool_log("pgpool successfully started");

	/*
	 * This is the main loop
	 */
	for (;;)
	{
		CHECK_REQUEST;

		/* do we need health checking for PostgreSQL? */
		if (!degenerated && pool_config.health_check_period > 0)
		{
			int sts;
			unsigned int sleep_time;

			pool_log("starting health checking");

			if (pool_config.health_check_timeout > 0)
			{
				/*
				 * set health checker timeout. we want to detect
				 * commnuication path failure much earlier before
				 * TCP/IP stack detects it.
				 */
				pool_signal(SIGALRM, health_check_timer_handler);
				alarm(pool_config.health_check_timeout);
			}

			/*
			 * do actual health check. trying to connect to the backend
			 */
			errno = 0;
			health_check_timer_expired = 0;
			POOL_SETMASK(&UnBlockSig);
			sts = health_check();
			POOL_SETMASK(&BlockSig);

			if (errno != EINTR || (errno == EINTR && health_check_timer_expired))
			{
				if (sts == -1)
				{
					failover(SIGUSR1);		/* master down */
				}
				else if (sts == -2)
				{
					failover(SIGUSR2);		/* secondary down */
				}
			}

			if (pool_config.health_check_timeout > 0)
			{
				/* seems ok. cancel health check timer */
				pool_signal(SIGALRM, SIG_IGN);
			}

			sleep_time = pool_config.health_check_period;
			pool_sleep(sleep_time);
		}
		else
		{
			for (;;)
			{
				int r;
				struct timeval t = {3, 0};

				POOL_SETMASK(&UnBlockSig);
				r = pool_pause(&t);
				POOL_SETMASK(&BlockSig);
				if (r > 0)
					break;
			}
		}
	}
	return 0;
}

static void usage(void)
{
	fprintf(stderr, "pgpool version %s(%s),\n",	VERSION, PGPOOLVERSION);
	fprintf(stderr, "  a generic connection pool/replication/load balance server for PostgreSQL\n\n");
	fprintf(stderr, "usage: pgpool [-f config_file][-a hba_file][-n][-d]\n");
	fprintf(stderr, "usage: pgpool [-f config_file][-a hba_file] [-m {s[mart]|f[ast]|i[mmediate]}] stop\n");
	fprintf(stderr, "usage: pgpool [-f config_file][-a hba_file] [-s {m[aster]|s[econdary]] switch\n");
	fprintf(stderr, "usage: pgpool -h\n");
	fprintf(stderr, "  config_file default path: %s/%s\n",DEFAULT_CONFIGDIR, POOL_CONF_FILE_NAME);
	fprintf(stderr, "  hba_file default path:    %s/%s\n",DEFAULT_CONFIGDIR, HBA_CONF_FILE_NAME);
	fprintf(stderr, "  -n: don't run in daemon mode. does not detatch control tty\n");
	fprintf(stderr, "  -d: debug mode. lots of debug information will be printed\n");
	fprintf(stderr, "  stop: stop pgpool\n");
	fprintf(stderr, "  switch: send switch over request to pgpool\n");
	fprintf(stderr, "  -h: print this help\n");
}

/*
* detatch control ttys
*/
static void daemonize(void)
{
	int			i;
	pid_t		pid;

	pid = fork();
	if (pid == (pid_t) -1)
	{
		pool_error("fork() failed. reason: %s", strerror(errno));
		exit(1);
		return;					/* not reached */
	}
	else if (pid > 0)
	{			/* parent */
		exit(0);
	}

#ifdef HAVE_SETSID
	if (setsid() < 0)
	{
		pool_error("setsid() failed. reason:%s", strerror(errno));
		exit(1);
	}
#endif

	i = open("/dev/null", O_RDWR);
	dup2(i, 0);
	dup2(i, 1);
	dup2(i, 2);
	close(i);

	write_pid_file();
}


/*
* stop myself
*/
static void stop_me(void)
{
	pid_t pid;

	pid = read_pid_file();
	if (pid < 0)
	{
		pool_error("could not read pid file");
		exit(1);
	}

	if (kill(pid, stop_sig) == -1)
	{
		pool_error("could not stop pid: %d. reason: %s", pid, strerror(errno));
		exit(1);
	}

	fprintf(stderr, "stop request sent to pgpool. waiting for termination...");

	while (kill(pid, 0) == 0)
	{
		fprintf(stderr, ".");
		sleep(1);
	}
	fprintf(stderr, "done.\n");
}

/*
* switch over request
*/
static void switch_me(void)
{
	pid_t pid;

	pid = read_pid_file();

	if (pid < 0)
	{
		pool_error("could read pid file");
		exit(1);
	}

	if (kill(pid, switch_over_sig) == -1)
	{
		pool_error("could not send switch over request to pid: %d. reason: %s", pid, strerror(errno));
		exit(1);
	}

	pool_log("switch over request sent");
}

/*
* read the pid file
*/
static int read_pid_file(void)
{
	FILE *fd;
	char path[POOLMAXPATHLEN];
	char pidbuf[128];

	snprintf(path, sizeof(path), "%s/%s", pool_config.logdir, PID_FILE_NAME);
	fd = fopen(path, "r");
	if (!fd)
	{
		return -1;
	}
	if (fread(pidbuf, 1, sizeof(pidbuf), fd) <= 0)
	{
		pool_error("could not read pid file as %s. reason: %s",
				   path, strerror(errno));
		fclose(fd);
		return -1;
	}
	fclose(fd);
	return(atoi(pidbuf));
}

/*
* write the pid file
*/
static void write_pid_file(void)
{
	FILE *fd;
	char path[POOLMAXPATHLEN];
	char pidbuf[128];

	snprintf(path, sizeof(path), "%s/%s", pool_config.logdir, PID_FILE_NAME);
	fd = fopen(path, "w");
	if (!fd)
	{
		pool_error("could not open pid file as %s. reason: %s",
				   path, strerror(errno));
		exit(1);
	}
	snprintf(pidbuf, sizeof(pidbuf), "%d", (int)getpid());
	fwrite(pidbuf, strlen(pidbuf), 1, fd);
	if (fclose(fd))
	{
		pool_error("could not write pid file as %s. reason: %s",
				   path, strerror(errno));
		exit(1);
	}
}

/*
* fork a child
*/
static pid_t fork_a_child(int unix_fd, int inet_fd)
{
	pid_t pid;

	pid = fork();

	if (pid == 0)
	{
		myargv = save_ps_display_args(myargc, myargv);

		/* call child main */
		POOL_SETMASK(&UnBlockSig);
		do_child(unix_fd, inet_fd);
	}
	else if (pid == -1)
	{
		pool_error("fork() failed. reason: %s", strerror(errno));
		myexit(1);
	}
	return pid;
}

/*
* create inet domain socket
*/
static int create_inet_domain_socket(const char *hostname)
{
	struct sockaddr_in addr;
	int fd;
	int status;
	int one = 1;
	int len;

	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1)
	{
		pool_error("Failed to create INET domain socket. reason: %s", strerror(errno));
		myexit(1);
	}
	if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one,
					sizeof(one))) == -1)
	{
		pool_error("setsockopt() failed. reason: %s", strerror(errno));
		myexit(1);
	}

	memset((char *) &addr, 0, sizeof(addr));
	((struct sockaddr *)&addr)->sa_family = AF_INET;

	if (strcmp(hostname, "*")==0)
	{
		addr.sin_addr.s_addr = htonl(INADDR_ANY);
	}
	else
	{
		struct hostent *hostinfo;

		hostinfo = gethostbyname(hostname);
		if (!hostinfo)
		{
			pool_error("could not resolve host name \"%s\": %s", hostname, hstrerror(h_errno));
			myexit(1);
		}
		addr.sin_addr = *(struct in_addr *) hostinfo->h_addr;
	}

	addr.sin_port = htons(pool_config.port);
	len = sizeof(struct sockaddr_in);
	status = bind(fd, (struct sockaddr *)&addr, len);
	if (status == -1)
	{
		pool_error("bind() failed. reason: %s", strerror(errno));
		myexit(1);
	}

	status = listen(fd, PGPOOLMAXLITSENQUEUELENGTH);
	if (status < 0)
	{
		pool_error("listen() failed. reason: %s", strerror(errno));
		myexit(1);
	}
	return fd;
}

/*
* create UNIX domain socket
*/
static int create_unix_domain_socket(void)
{
	struct sockaddr_un addr;
	int fd;
	int status;
	int len;

	fd = socket(AF_UNIX, SOCK_STREAM, 0);
	if (fd == -1)
	{
		pool_error("Failed to create UNIX domain socket. reason: %s", strerror(errno));
		myexit(1);
	}
	memset((char *) &addr, 0, sizeof(addr));
	((struct sockaddr *)&addr)->sa_family = AF_UNIX;
	snprintf(addr.sun_path, sizeof(addr.sun_path), un_addr.sun_path);
	len = sizeof(struct sockaddr_un);
	status = bind(fd, (struct sockaddr *)&addr, len);
	if (status == -1)
	{
		pool_error("bind() failed. reason: %s", strerror(errno));
		myexit(1);
	}

	if (chmod(un_addr.sun_path, 0777) == -1)
	{
		pool_error("chmod() failed. reason: %s", strerror(errno));
		myexit(1);
	}

	status = listen(fd, PGPOOLMAXLITSENQUEUELENGTH);
	if (status < 0)
	{
		pool_error("listen() failed. reason: %s", strerror(errno));
		myexit(1);
	}
	return fd;
}

static void myexit(int code)
{
	char path[POOLMAXPATHLEN];

	if (getpid() != mypid)
		return;

	unlink(un_addr.sun_path);
	snprintf(path, sizeof(path), "%s/%s", pool_config.logdir, PID_FILE_NAME);
	unlink(path);

	exit(code);
}

/* notice backend connection error using SIGUSR1 or SIGUSR2 */
void notice_backend_error(int master)
{
	pid_t parent = getppid();

	pool_log("notice_backend_error: master: %d fail over request from pid %d", master, getpid());

	if (master)
		kill(parent, SIGUSR1);
	else
		kill(parent, SIGUSR2);

	/* avoid race conditon with SIGCHLD */
#ifdef NOT_USED
	sleep(1);
#endif
}

static RETSIGTYPE exit_handler(int sig)
{
	int i;

	POOL_SETMASK(&AuthBlockSig);

	/*
	 * this could happend in a child process if a signal has been sent
	 * before resetting signal handler
	 */
	if (getpid() != mypid)
	{
		pool_debug("exit_handler: I am not parent");
		POOL_SETMASK(&UnBlockSig);
		exit(0);
	}

	if (sig == SIGTERM)
		pool_log("received smart shutdown request");
	else if (sig == SIGINT)
		pool_log("received fast shutdown request");
	else if (sig == SIGQUIT)
		pool_log("received immediate shutdown request");
	else if (sig == SIGHUP)
		pool_log("received idle connection close request");
	else
	{
		pool_error("exit_handler: unknown signal received %d", sig);
		POOL_SETMASK(&UnBlockSig);
		return;
	}

	exiting = 1;

	for (i = 0; i < pool_config.num_init_children; i++)
	{
		pid_t pid = pids[i];
		if (pid)
		{
			kill(pid, sig);
		}
	}

	if (sig == SIGHUP)
	{
		exiting = 0;
		POOL_SETMASK(&UnBlockSig);
		return;
	}

	POOL_SETMASK(&UnBlockSig);

	while (wait(NULL) > 0)
		;

	if (errno != ECHILD)
		pool_error("wait() failed. reason:%s", strerror(errno));

	myexit(0);
}

/*
 * handle SIGUSR1/SIGUSR2 (backend connection error, fail over request, if possible)
 *
 * if sig == SIGUSR1, we assume that the master has been down.
 * if sig == SIGUSR2, we assume that the secondary has been down.
 */
static RETSIGTYPE failover_handler(int sig)
{
	POOL_SETMASK(&BlockSig);
	failover_request = 1;
	failover_signo = sig;
	write(pipe_fds[1], "\0", 1);
	POOL_SETMASK(&UnBlockSig);
}

/*
 * Process failover request
 * failover() must be called under protecting signals.
 */
static void failover(int sig)
{
	int i;
	int replication = 0;

	pool_debug("failover_handler called");

	/*
	 * this could happen in a child process if a signal has been sent
	 * before resetting signal handler
	 */
	if (getpid() != mypid)
	{
		pool_debug("failover_handler: I am not parent");
		return;
	}

	/*
	 * processing SIGTERM, SIGINT or SIGQUIT
	 */
	if (exiting)
	{
		return;
	}

	/*
	 * processing fail over or switch over
	 */
	if (switching)
	{
		return;
	}

#ifdef NOT_USED
	/* secondary backend exists? */
	if (pool_config.secondary_backend_port == 0)
		return;
#endif

	/* 
	 * if not in replication mode/master slave mode, we treat this a restart request.
	 * otherwise we need to check if we have already failovered.
	 */
	if (pool_config.replication_enabled || pool_config.master_slave_enabled ||
		strcmp(pool_config.current_backend_host_name, pool_config.secondary_backend_host_name) ||
		pool_config.current_backend_port != pool_config.secondary_backend_port)
	{
		switching = 1;
		
		if (pool_config.replication_enabled)
		{
			replication = 1;
			degenerated = 1;

			if (sig == SIGUSR2)
			{
				pool_log("starting degeneration. shutdown secondary host %s(%d)",
						 pool_config.secondary_backend_host_name,
						 pool_config.secondary_backend_port);
				pool_config.server_status[1] = 2;		/* mark this down */
			}
			else
			{
				pool_log("starting degeneration. shutdown master host %s(%d)",
						 pool_config.backend_host_name,
						 pool_config.backend_port);
				pool_config.server_status[0] = 2;		/* mark this down */
			}
		}

		else if (pool_config.master_slave_enabled)
		{
			degenerated = 1;

			if (sig == SIGUSR2)
			{
				pool_log("starting degeneration. shutdown slave host %s(%d)",
						 pool_config.secondary_backend_host_name,
						 pool_config.secondary_backend_port);
				pool_config.server_status[1] = 2;		/* mark this down */
			}
			else
			{
				pool_log("starting degeneration. shutdown master host %s(%d)",
						 pool_config.backend_host_name,
						 pool_config.backend_port);
				pool_config.server_status[0] = 2;		/* mark this down */
			}
		}

		else if (!degenerated && pool_config.secondary_backend_port != 0)
		{
			pool_log("starting failover from %s(%d) to %s(%d)",
					   pool_config.current_backend_host_name,
					   pool_config.current_backend_port,
					   pool_config.secondary_backend_host_name,
					   pool_config.secondary_backend_port);
			pool_config.server_status[0] = 2;		/* mark this down */
		}
		else
		{
			pool_log("restarting pgpool");
		}

		/* kill all children */
		for (i = 0; i < pool_config.num_init_children; i++)
		{
			pid_t pid = pids[i];
			if (pid)
			{
				kill(pid, SIGQUIT);
				pool_debug("kill %d", pid);
			}
		}

		while (wait(NULL) > 0)
			;

		if (errno != ECHILD)
			pool_error("wait() failed. reason:%s", strerror(errno));

		if (pool_config.replication_enabled)
		{
			/* disable replicaton mode */
			pool_config.replication_enabled = 0;

			if (sig == SIGUSR1)
			{
				pool_config.current_backend_host_name = pool_config.secondary_backend_host_name;
				pool_config.current_backend_port = pool_config.secondary_backend_port;
			}
		}

		else if (pool_config.master_slave_enabled)
		{
			/* disable master/slave mode */
			pool_config.master_slave_enabled = 0;

			if (sig == SIGUSR1)
			{
				pool_config.current_backend_host_name = pool_config.secondary_backend_host_name;
				pool_config.current_backend_port = pool_config.secondary_backend_port;
			}
		}

		else if (!degenerated && pool_config.secondary_backend_port != 0)
		{
			/* fail over to secondary */
			pool_config.current_backend_host_name = pool_config.secondary_backend_host_name;
			pool_config.current_backend_port = pool_config.secondary_backend_port;
		}

		/* fork the children */
		for (i=0;i<pool_config.num_init_children;i++)
		{
			pids[i] = fork_a_child(unix_fd, inet_fd);
		}

		/*
		 * do not close unix_fd and inet_fd here. if a child dies we
		 * need to fork a new child which should inherit these fds.
		 */

		if (replication)
		{
			if (sig == SIGUSR2)
			{
				pool_log("degeneration done. shutdown secondary host %s(%d)",
						 pool_config.secondary_backend_host_name,
						 pool_config.secondary_backend_port);
			}
			else
			{
				pool_log("degeneration done. shutdown master host %s(%d)",
						 pool_config.backend_host_name,
						 pool_config.backend_port);
			}
		}
		else if (!degenerated && pool_config.secondary_backend_port != 0)
		{
			pool_log("failover from %s(%d) to %s(%d) done.",
					   pool_config.backend_host_name,
					   pool_config.backend_port,
					   pool_config.secondary_backend_host_name,
					   pool_config.secondary_backend_port);
		}
		else
		{
			pool_log("restarting pgpool done.");
		}

		switching = 0;
	}
}

/*
 * health check timer handler
 */
static RETSIGTYPE health_check_timer_handler(int sig)
{
	POOL_SETMASK(&BlockSig);
	health_check_timer_expired = 1;
	POOL_SETMASK(&UnBlockSig);
}

/*
 * handle SIGCHLD
 */
static RETSIGTYPE reap_handler(int sig)
{
	POOL_SETMASK(&BlockSig);
	sigchld_request = 1;
	write(pipe_fds[1], "\0", 1);
	POOL_SETMASK(&UnBlockSig);
}

/*
 * Attach zombie processes and restart child processes.
 * reaper() must be called under protecting signals.
 */
static void reaper(void)
{
	pid_t pid;
	int status;
	int i;

	pool_debug("reap_handler called");

	if (exiting || switching)
	{
		return;
	}
	sigchld_request = 0;

#ifdef HAVE_WAITPID
	while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
	{
#else
		while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
		{
#endif

			pool_debug("child %d exits with status %d by signal %d", pid, status, WTERMSIG(status));

			/* look for exiting child's pid */
			for (i=0;i<pool_config.num_init_children;i++)
			{
				if (pid == pids[i])
				{
					/* if found, fork a new child */
					if (!switching && !exiting && status)
					{
						pids[i] = fork_a_child(unix_fd, inet_fd);
						pool_debug("fork a new child pid %d", pids[i]);
						break;
					}
				}
			}
		}

	}

/*
 * pool_pause: A process pauses by select().
 */
static int pool_pause(struct timeval *timeout)
{
	fd_set rfds;
	int n;
	char dummy;

	FD_ZERO(&rfds);
	FD_SET(pipe_fds[0], &rfds);
	n = select(pipe_fds[0]+1, &rfds, NULL, NULL, timeout);
	if (n == 1)
		read(pipe_fds[0], &dummy, 1);
	return n;
}

/*
 * pool_pause: A process sleep using pool_pause().
 *             If a signal event occurs, it raises signal handler.
 */
static void pool_sleep(unsigned int second)
{
	struct timeval current_time, sleep_time;

	gettimeofday(&current_time, NULL);
	sleep_time.tv_sec = second + current_time.tv_sec;
	sleep_time.tv_usec = current_time.tv_usec;

	POOL_SETMASK(&UnBlockSig);
	while (sleep_time.tv_sec > current_time.tv_sec)
	{
		struct timeval timeout;
		int r;

		timeout.tv_sec = sleep_time.tv_sec - current_time.tv_sec;
		timeout.tv_usec = sleep_time.tv_usec - current_time.tv_usec;
		if (timeout.tv_usec < 0)
		{
			timeout.tv_sec--;
			timeout.tv_usec += 1000000;
		}

		r = pool_pause(&timeout);
		POOL_SETMASK(&BlockSig);
		if (r > 0)									
			CHECK_REQUEST;
		POOL_SETMASK(&UnBlockSig);
		gettimeofday(&current_time, NULL);
	}
	POOL_SETMASK(&BlockSig);
}

/*
 * check if we can connect to the backend
 * returns 0 for ok. -1 for master down, -2 for secondary down.
 */
int health_check(void)
{
	int fd;

	/* V2 startup packet */
	typedef struct {
		int len;		/* startup packet length */
		StartupPacket_v2 sp;
	} MySp;
	MySp mysp;
	char kind;

	memset(&mysp, 0, sizeof(mysp));
	mysp.len = htonl(296);
	mysp.sp.protoVersion = htonl(PROTO_MAJOR_V2 << 16);
	strcpy(mysp.sp.database, "template1");
 	strncpy(mysp.sp.user, pool_config.health_check_user, sizeof(mysp.sp.user) - 1);
	*mysp.sp.options = '\0';
	*mysp.sp.unused = '\0';
	*mysp.sp.tty = '\0';

	if (*pool_config.current_backend_host_name == '\0')
		fd = connect_unix_domain_socket(0);
	else
		fd = connect_inet_domain_socket(0);

	if (fd < 0)
	{
		pool_error("health check failed. master %s at port %d is down",
				   pool_config.current_backend_host_name,
				   pool_config.current_backend_port);
		return -1;
	}

	if (write(fd, &mysp, sizeof(mysp)) < 0)
	{
		pool_error("health check failed during write. master %s at port %d is down",
				   pool_config.current_backend_host_name,
				   pool_config.current_backend_port);
		close(fd);
		return -1;
	}

	read(fd, &kind, 1);

	if (write(fd, "X", 1) < 0)
	{
		pool_error("health check failed during write. master %s at port %d is down",
				   pool_config.current_backend_host_name,
				   pool_config.current_backend_port);
		close(fd);
		return -1;
	}

	close(fd);

	if (!DUAL_MODE)
		return 0;

	if (*pool_config.secondary_backend_host_name == '\0')
		fd = connect_unix_domain_socket(1);
	else
		fd = connect_inet_domain_socket(1);

	if (fd < 0)
	{
		pool_error("health check failed. secondary %s at port %d is down",
				   pool_config.secondary_backend_host_name,
				   pool_config.secondary_backend_port);
		return -2;
	}

	if (write(fd, &mysp, sizeof(mysp)) < 0)
	{
		pool_error("health check failed during write. secondary %s at port %d is down",
				   pool_config.secondary_backend_host_name,
				   pool_config.secondary_backend_port);
		close(fd);
		return -2;
	}

	read(fd, &kind, 1);

	if (write(fd, "X", 1) < 0)
	{
		pool_error("health check failed during write. secondary %s at port %d is down",
				   pool_config.secondary_backend_host_name,
				   pool_config.secondary_backend_port);
		close(fd);
		return -2;
	}

	close(fd);

	return 0;
}