-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.c
2037 lines (1756 loc) · 46.3 KB
/
main.c
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
/* -*-pgsql-c-*- */
/*
* $Header: /cvsroot/pgpool/pgpool-II/main.c,v 1.56 2009/12/06 12:55:08 t-ishii Exp $
*
* pgpool: a language independent connection pool server for PostgreSQL
* written by Tatsuo Ishii
*
* Copyright (c) 2003-2009 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 <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/time.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"
#include "parser/pool_memory.h"
#include "parser/pool_string.h"
/*
* Process pending signal actions.
*/
#define CHECK_REQUEST \
do { \
if (wakeup_request) \
{ \
wakeup_children(); \
wakeup_request = 0; \
} \
if (failover_request) \
{ \
failover(); \
failover_request = 0; \
} \
if (sigchld_request) \
{ \
reaper(); \
} \
if (reload_config_request) \
{ \
reload_config(); \
reload_config_request = 0; \
} \
} while (0)
#define PGPOOLMAXLITSENQUEUELENGTH 10000
static void daemonize(void);
static int read_pid_file(void);
static void write_pid_file(void);
static int read_status_file(void);
static int write_statusd_file(void);
static pid_t pcp_fork_a_child(int unix_fd, int inet_fd, char *pcp_conf_file);
static pid_t fork_a_child(int unix_fd, int inet_fd, int id);
static int create_unix_domain_socket(struct sockaddr_un un_addr_tmp);
static int create_inet_domain_socket(const char *hostname, const int port);
static void myexit(int code);
static void failover(void);
static void reaper(void);
static void wakeup_children(void);
static void reload_config(void);
static int pool_pause(struct timeval *timeout);
static void pool_sleep(unsigned int second);
static void kill_all_children(int sig);
static int get_next_master_node(void);
static RETSIGTYPE exit_handler(int sig);
static RETSIGTYPE reap_handler(int sig);
static RETSIGTYPE failover_handler(int sig);
static RETSIGTYPE reload_config_handler(int sig);
static RETSIGTYPE health_check_timer_handler(int sig);
static RETSIGTYPE wakeup_handler(int sig);
static void usage(void);
static void show_version(void);
static void stop_me(void);
static int trigger_failover_command(int node, const char *command_line);
static struct sockaddr_un un_addr; /* unix domain socket path */
static struct sockaddr_un pcp_un_addr; /* unix domain socket path for PCP */
ProcessInfo *pids; /* shmem child pid table */
/*
* shmem connection info table
* this is a two dimension array. i.e.:
* con_info[pool_config->num_init_children][pool_config->max_pool]
*/
ConnectionInfo *con_info;
static int unix_fd; /* unix domain socket fd */
static int inet_fd; /* inet domain socket fd */
static int pcp_pid; /* pid for child process handling PCP */
static int pcp_unix_fd; /* unix domain socket fd for PCP (not used) */
static int pcp_inet_fd; /* inet domain socket fd for PCP */
static char pcp_conf_file[POOLMAXPATHLEN+1]; /* path for pcp.conf */
static char conf_file[POOLMAXPATHLEN+1];
static char hba_file[POOLMAXPATHLEN+1];
static int exiting = 0; /* non 0 if I'm exiting */
static int switching = 0; /* non 0 if I'm fail overing or degenerating */
#ifdef NOT_USED
static int degenerated = 0; /* set non 0 if already degenerated */
#endif
static int clear_cache = 0; /* non 0 if clear chache option (-c) is given */
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) */
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 volatile sig_atomic_t health_check_timer_expired; /* non 0 if health check timer expired */
POOL_REQUEST_INFO *Req_info; /* request info area in shared memory */
volatile sig_atomic_t *InRecovery; /* non 0 if recovery is started */
volatile sig_atomic_t reload_config_request = 0;
static volatile sig_atomic_t failover_request = 0;
static volatile sig_atomic_t sigchld_request = 0;
static volatile sig_atomic_t wakeup_request = 0;
static int pipe_fds[2]; /* for delivering signals */
int my_proc_id;
static BackendStatusRecord backend_rec; /* Backend status record */
int myargc;
char **myargv;
/*
* pgpool main program
*/
int main(int argc, char **argv)
{
int opt;
int i;
int pid;
int size;
int retrycnt;
int sys_retrycnt;
myargc = argc;
myargv = argv;
snprintf(conf_file, sizeof(conf_file), "%s/%s", DEFAULT_CONFIGDIR, POOL_CONF_FILE_NAME);
snprintf(pcp_conf_file, sizeof(pcp_conf_file), "%s/%s", DEFAULT_CONFIGDIR, PCP_PASSWD_FILE_NAME);
snprintf(hba_file, sizeof(hba_file), "%s/%s", DEFAULT_CONFIGDIR, HBA_CONF_FILE_NAME);
while ((opt = getopt(argc, argv, "a:cdf:F:hm:nv")) != -1)
{
switch (opt)
{
case 'a': /* specify hba configuration file */
if (!optarg)
{
usage();
exit(1);
}
strncpy(hba_file, optarg, sizeof(hba_file));
break;
case 'c': /* clear cache option */
clear_cache = 1;
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 'F': /* specify PCP password file */
if (!optarg)
{
usage();
exit(1);
}
strncpy(pcp_conf_file, optarg, sizeof(pcp_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 'v':
show_version();
exit(0);
default:
usage();
exit(1);
}
}
mypid = getpid();
if (pool_init_config())
exit(1);
if (pool_get_config(conf_file, INIT_CONFIG))
{
pool_error("Unable to get configuration. Exiting...");
exit(1);
}
if (pool_config->enable_pool_hba)
load_hba(hba_file);
/*
* If a non-switch argument remains, then it should be either "reload" or "stop".
*/
if (optind == (argc - 1))
{
if (!strcmp(argv[optind], "reload"))
{
pid_t pid;
pid = read_pid_file();
if (pid < 0)
{
pool_error("could not read pid file");
pool_shmem_exit(1);
exit(1);
}
if (kill(pid, SIGHUP) == -1)
{
pool_error("could not reload configuration file pid: %d. reason: %s", pid, strerror(errno));
pool_shmem_exit(1);
exit(1);
}
pool_shmem_exit(0);
exit(0);
}
if (!strcmp(argv[optind], "stop"))
{
stop_me();
pool_shmem_exit(0);
exit(0);
}
else
{
usage();
pool_shmem_exit(1);
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();
if (pool_semaphore_create(MAX_NUM_SEMAPHORES))
{
pool_error("Unable to create semaphores. Exiting...");
pool_shmem_exit(1);
exit(1);
}
/*
* Restore previous backend status if possible
*/
read_status_file();
/* clear cache */
if (clear_cache && pool_config->enable_query_cache && SYSDB_STATUS == CON_UP)
{
Interval interval[1];
interval[0].quantity = 0;
interval[0].unit = second;
pool_clear_cache_by_time(interval, 1);
}
/* 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(un_addr);
/* create inet domain socket if any */
if (pool_config->listen_addresses[0])
{
inet_fd = create_inet_domain_socket(pool_config->listen_addresses, pool_config->port);
}
size = pool_config->num_init_children * pool_config->max_pool * sizeof(ConnectionInfo);
con_info = pool_shared_memory_create(size);
if (con_info == NULL)
{
pool_error("failed to allocate connection informations");
myexit(1);
}
memset(con_info, 0, size);
size = pool_config->num_init_children * (sizeof(ProcessInfo));
pids = pool_shared_memory_create(size);
if (pids == NULL)
{
pool_error("failed to allocate pids");
myexit(1);
}
memset(pids, 0, size);
for (i = 0; i < pool_config->num_init_children; i++)
{
pids[i].connection_info = &con_info[i * pool_config->max_pool];
}
/* create fail over/switch over event area */
Req_info = pool_shared_memory_create(sizeof(POOL_REQUEST_INFO));
if (Req_info == NULL)
{
pool_error("failed to allocate Req_info");
myexit(1);
}
/* initialize Req_info */
Req_info->kind = NODE_UP_REQUEST;
memset(Req_info->node_id, -1, sizeof(int) * MAX_NUM_BACKENDS);
Req_info->master_node_id = get_next_master_node();
Req_info->conn_counter = 0;
InRecovery = pool_shared_memory_create(sizeof(int));
if (InRecovery == NULL)
{
pool_error("failed to allocate InRecovery");
myexit(1);
}
*InRecovery = 0;
/*
* We need to block signal here. Otherwise child might send some
* signals, for example SIGUSR1(fail over). Children will inherit
* signal blocking but they do unblock signals at the very beginning
* of process. So this is harmless.
*/
POOL_SETMASK(&BlockSig);
/* fork the children */
for (i=0;i<pool_config->num_init_children;i++)
{
pids[i].pid = fork_a_child(unix_fd, inet_fd, i);
pids[i].start_time = time(NULL);
}
/* set up signal handlers */
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, wakeup_handler);
pool_signal(SIGHUP, reload_config_handler);
/* create pipe for delivering event */
if (pipe(pipe_fds) < 0)
{
pool_error("failed to create pipe");
myexit(1);
}
pool_log("pgpool successfully started");
/* fork a child for PCP handling */
snprintf(pcp_un_addr.sun_path, sizeof(pcp_un_addr.sun_path), "%s/.s.PGSQL.%d",
pool_config->pcp_socket_dir,
pool_config->pcp_port);
pcp_unix_fd = create_unix_domain_socket(pcp_un_addr);
/* maybe change "*" to pool_config->pcp_listen_addresses */
pcp_inet_fd = create_inet_domain_socket("*", pool_config->pcp_port);
pcp_pid = pcp_fork_a_child(pcp_unix_fd, pcp_inet_fd, pcp_conf_file);
retrycnt = 0; /* reset health check retry counter */
sys_retrycnt = 0; /* reset SystemDB health check retry counter */
/*
* This is the main loop
*/
for (;;)
{
CHECK_REQUEST;
/* do we need health checking for PostgreSQL? */
if (pool_config->health_check_period > 0)
{
int sts;
int sys_sts = 0;
unsigned int sleep_time;
if (retrycnt == 0)
{
pool_debug("starting health checking");
}
else
{
pool_debug("retrying %d th health checking", retrycnt);
}
if (pool_config->health_check_timeout > 0)
{
/*
* set health checker timeout. we want to detect
* communication 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 (pool_config->parallel_mode || pool_config->enable_query_cache)
sys_sts = system_db_health_check();
if ((sts > 0 || sys_sts < 0) && (errno != EINTR || (errno == EINTR && health_check_timer_expired)))
{
if (sts > 0)
{
sts--;
if (!pool_config->parallel_mode)
{
pool_log("set %d th backend down status", sts);
Req_info->kind = NODE_DOWN_REQUEST;
Req_info->node_id[0] = sts;
failover();
/* need to distribute this info to children */
}
else
{
retrycnt++;
pool_signal(SIGALRM, SIG_IGN); /* Cancel timer */
if (retrycnt > NUM_BACKENDS)
{
/* retry count over */
pool_log("set %d th backend down status", sts);
Req_info->kind = NODE_DOWN_REQUEST;
Req_info->node_id[0] = sts;
failover();
retrycnt = 0;
}
else
{
/* continue to retry */
sleep_time = pool_config->health_check_period/NUM_BACKENDS;
pool_debug("retry sleep time: %d seconds", sleep_time);
pool_sleep(sleep_time);
continue;
}
}
}
if (sys_sts < 0)
{
sys_retrycnt++;
pool_signal(SIGALRM, SIG_IGN);
if (sys_retrycnt > NUM_BACKENDS)
{
pool_log("set SystemDB down status");
SYSDB_STATUS = CON_DOWN;
sys_retrycnt = 0;
}
else if (sts == 0) /* goes to sleep only when SystemDB alone was down */
{
sleep_time = pool_config->health_check_period/NUM_BACKENDS;
pool_debug("retry sleep time: %d seconds", sleep_time);
pool_sleep(sleep_time);
continue;
}
}
}
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;
}
}
}
pool_shmem_exit(0);
}
static void show_version(void)
{
fprintf(stderr, "%s version %s (%s)\n", PACKAGE, VERSION, PGPOOLVERSION);
}
static void usage(void)
{
fprintf(stderr, "%s version %s (%s),\n", PACKAGE, VERSION, PGPOOLVERSION);
fprintf(stderr, " a generic connection pool/replication/load balance server for PostgreSQL\n\n");
fprintf(stderr, "Usage:\n");
fprintf(stderr, " pgpool [ -c] [ -f CONFIG_FILE ] [ -F PCP_CONFIG_FILE ] [ -a HBA_CONFIG_FILE ]\n");
fprintf(stderr, " [ -n ] [ -d ]\n");
fprintf(stderr, " pgpool [ -f CONFIG_FILE ] [ -F PCP_CONFIG_FILE ] [ -a HBA_CONFIG_FILE ]\n");
fprintf(stderr, " [ -m SHUTDOWN-MODE ] stop\n");
fprintf(stderr, " pgpool [ -f CONFIG_FILE ] [ -F PCP_CONFIG_FILE ] [ -a HBA_CONFIG_FILE ] reload\n\n");
fprintf(stderr, "Common options:\n");
fprintf(stderr, " -a HBA_CONFIG_FILE Sets the path to the pool_hba.conf configuration file\n");
fprintf(stderr, " (default: %s/%s)\n",DEFAULT_CONFIGDIR, HBA_CONF_FILE_NAME);
fprintf(stderr, " -f CONFIG_FILE Sets the path to the pgpool.conf configuration file\n");
fprintf(stderr, " (default: %s/%s)\n",DEFAULT_CONFIGDIR, POOL_CONF_FILE_NAME);
fprintf(stderr, " -F PCP_CONFIG_FILE Sets the path to the pcp.conf configuration file\n");
fprintf(stderr, " (default: %s/%s)\n",DEFAULT_CONFIGDIR, PCP_PASSWD_FILE_NAME);
fprintf(stderr, " -h Prints this help\n\n");
fprintf(stderr, "Start options:\n");
fprintf(stderr, " -c Clears query cache (enable_query_cache must be on)\n");
fprintf(stderr, " -n Don't run in daemon mode, does not detach control tty\n");
fprintf(stderr, " -d Debug mode\n\n");
fprintf(stderr, "Stop options:\n");
fprintf(stderr, " -m SHUTDOWN-MODE Can be \"smart\", \"fast\", or \"immediate\"\n\n");
fprintf(stderr, "Shutdown modes are:\n");
fprintf(stderr, " smart quit after all clients have disconnected\n");
fprintf(stderr, " fast quit directly, with proper shutdown\n");
fprintf(stderr, " immediate quit without complete shutdown; will lead to recovery on restart\n");
}
/*
* detach control ttys
*/
static void daemonize(void)
{
int i;
pid_t pid;
int fdlimit;
pid = fork();
if (pid == (pid_t) -1)
{
pool_error("fork() failed. reason: %s", strerror(errno));
pool_shmem_exit(1);
exit(1);
return; /* not reached */
}
else if (pid > 0)
{ /* parent */
pool_shmem_exit(0);
exit(0);
}
#ifdef HAVE_SETSID
if (setsid() < 0)
{
pool_error("setsid() failed. reason:%s", strerror(errno));
pool_shmem_exit(1);
exit(1);
}
#endif
mypid = getpid();
chdir("/");
i = open("/dev/null", O_RDWR);
dup2(i, 0);
dup2(i, 1);
dup2(i, 2);
fdlimit = sysconf(_SC_OPEN_MAX);
for (i = 3; i < fdlimit; i++)
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");
pool_shmem_exit(1);
exit(1);
}
if (kill(pid, stop_sig) == -1)
{
pool_error("could not stop pid: %d. reason: %s", pid, strerror(errno));
pool_shmem_exit(1);
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");
}
/*
* read the pid file
*/
static int read_pid_file(void)
{
FILE *fd;
char pidbuf[128];
fd = fopen(pool_config->pid_file_name, "r");
if (!fd)
{
return -1;
}
if (fread(pidbuf, 1, sizeof(pidbuf), fd) <= 0)
{
pool_error("could not read pid file as %s. reason: %s",
pool_config->pid_file_name, strerror(errno));
fclose(fd);
return -1;
}
fclose(fd);
return(atoi(pidbuf));
}
/*
* write the pid file
*/
static void write_pid_file(void)
{
FILE *fd;
char pidbuf[128];
fd = fopen(pool_config->pid_file_name, "w");
if (!fd)
{
pool_error("could not open pid file as %s. reason: %s",
pool_config->pid_file_name, strerror(errno));
pool_shmem_exit(1);
exit(1);
}
snprintf(pidbuf, sizeof(pidbuf), "%d", (int)getpid());
fwrite(pidbuf, strlen(pidbuf)+1, 1, fd);
if (fclose(fd))
{
pool_error("could not write pid file as %s. reason: %s",
pool_config->pid_file_name, strerror(errno));
pool_shmem_exit(1);
exit(1);
}
}
/*
* Read the status file
*/
static int read_status_file(void)
{
FILE *fd;
char fnamebuf[POOLMAXPATHLEN];
int i;
snprintf(fnamebuf, sizeof(fnamebuf), "%s/%s", pool_config->logdir, STATUS_FILE_NAME);
fd = fopen(fnamebuf, "r");
if (!fd)
{
pool_log("Backend status file %s does not exist", fnamebuf);
return -1;
}
if (fread(&backend_rec, 1, sizeof(backend_rec), fd) <= 0)
{
pool_error("Could not read backend status file as %s. reason: %s",
fnamebuf, strerror(errno));
fclose(fd);
return -1;
}
fclose(fd);
for (i=0;i< pool_config->backend_desc->num_backends;i++)
{
if (backend_rec.status[i] == CON_DOWN)
BACKEND_INFO(i).backend_status = CON_DOWN;
else
BACKEND_INFO(i).backend_status = CON_CONNECT_WAIT;
}
return 0;
}
/*
* Write the pid file
*/
static int write_status_file(void)
{
FILE *fd;
char fnamebuf[POOLMAXPATHLEN];
int i;
snprintf(fnamebuf, sizeof(fnamebuf), "%s/%s", pool_config->logdir, STATUS_FILE_NAME);
fd = fopen(fnamebuf, "w");
if (!fd)
{
pool_error("Could not open status file %s", fnamebuf);
return -1;
}
memset(&backend_rec, 0, sizeof(backend_rec));
for (i=0;i< pool_config->backend_desc->num_backends;i++)
{
backend_rec.status[i] = BACKEND_INFO(i).backend_status;
}
if (fwrite(&backend_rec, 1, sizeof(backend_rec), fd) <= 0)
{
pool_error("Could not write backend status file as %s. reason: %s",
fnamebuf, strerror(errno));
fclose(fd);
return -1;
}
fclose(fd);
return 0;
}
/*
* fork a child for PCP
*/
pid_t pcp_fork_a_child(int unix_fd, int inet_fd, char *pcp_conf_file)
{
pid_t pid;
pid = fork();
if (pid == 0)
{
close(pipe_fds[0]);
close(pipe_fds[1]);
myargv = save_ps_display_args(myargc, myargv);
/* call PCP child main */
POOL_SETMASK(&UnBlockSig);
reload_config_request = 0;
pcp_do_child(unix_fd, inet_fd, pcp_conf_file);
}
else if (pid == -1)
{
pool_error("fork() failed. reason: %s", strerror(errno));
myexit(1);
}
return pid;
}
/*
* fork a child
*/
pid_t fork_a_child(int unix_fd, int inet_fd, int id)
{
pid_t pid;
pid = fork();
if (pid == 0)
{
/* Before we unconditionally closed pipe_fds[0] and pipe_fds[1]
* here, which is apparently wrong since in the start up of
* pgpool, pipe(2) is not called yet and it mistakenly closes
* fd 0. Now we check the fd > 0 before close(), expecting
* pipe returns fds greater than 0. Note that we cannot
* unconditionally remove close(2) calls since fork_a_child()
* may be called *after* pgpool starting up.
*/
if (pipe_fds[0] > 0)
{
close(pipe_fds[0]);
close(pipe_fds[1]);
}
myargv = save_ps_display_args(myargc, myargv);
/* call child main */
POOL_SETMASK(&UnBlockSig);
reload_config_request = 0;
my_proc_id = id;
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, const int port)
{
struct sockaddr_in addr;
int fd;
int status;
int one = 1;
int len;
int backlog;
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(port);
len = sizeof(struct sockaddr_in);
status = bind(fd, (struct sockaddr *)&addr, len);
if (status == -1)
{
char *host = "", *serv = "";
char hostname[NI_MAXHOST], servname[NI_MAXSERV];
if (getnameinfo((struct sockaddr *) &addr, len, hostname, sizeof(hostname), servname, sizeof(servname), 0) == 0) {
host = hostname;
serv = servname;
}
pool_error("bind(%s:%s) failed. reason: %s", host, serv, strerror(errno));
myexit(1);
}
backlog = pool_config->num_init_children * 2;
if (backlog > PGPOOLMAXLITSENQUEUELENGTH)
backlog = PGPOOLMAXLITSENQUEUELENGTH;
status = listen(fd, backlog);
if (status < 0)
{
pool_error("listen() failed. reason: %s", strerror(errno));
myexit(1);
}
return fd;
}
/*
* create UNIX domain socket