forked from inteos/pgsql-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgsql-restore.c
2439 lines (2076 loc) · 69.7 KB
/
pgsql-restore.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
/*
* Copyright (c) 2013 by Inteos sp. z o.o.
* All rights reserved. See LICENSE.pgsql for details.
*
* This is a bacula recovery tool for PostgreSQL database. It is designed to work both with
* root (administrator) and database owner (postgres) permissions. Utility will switch its
* permissions to get required functionality.
*/
/*
To perform Point-In-Time-Recovery you need a valid <config.file>
in <config.file>:
#
# Config file for pgsql plugin
#
PGDATA = <pg.data.cluster.path>
PGHOST = <path.to.sockets.directory>
PGPORT = <socket.'port'>
PGSTART = <pg_ctl.command.location.and.options>
PGSTOP = <pg_ctl.command.location.and.options>
CATDB = <catalog.db.name>
CATDBHOST = <catalog.db.host>
CATDBPORT = <catalog.db.port>
CATUSER = <catalog.db.user>
CATPASSWD = <catalog.db.password>
ARCHDEST = <destination.of.archived.wal's.path>
ARCHCLIENT = <name.of.archived.client>
DIRNAME = <director.name>
DIRHOST = <director.address>
DIRPORT = <director.service.port>
DIRPASSWD = <director.connection.password>
and valid bacula console resource in bacula-dir.conf:
#
# Restricted console used for client initiated restore
#
Console {
Name = <name.of.bacula.client>
Password = <console.password>
CommandACL = restore,.filesets,wait
ClientACL = <name.of.bacula.client>
CatalogACL = <bacula.catalog> # it is not pgsql catalog database
WhereACL = "*all*"
JobACL = <job.names.for.pgsql.backup.and.pgsql.archbackup>
PoolACL = <pool.names.of.pgsql.backup.and.pgsql.archbackup>
StorageACL = <bacula.sd.name>
FileSetACL = <fileset.name.of.pgsql.db.backup>,<and.pgsql.archbackup>
}
Next, you have to execute pgsql-restore command:
$ pgsql-restore -c <config.file> [-v][-t <recovery.time> | -x <recovery.xid> ] [-w <where>] restore
Arch restore:
$ pgsql-restore -c <config.file> [-v] wal <name.of.wal> <path.to.restore>
* -c = config file
* -v = verbose
* -t = recovery time point
* -x = recovery transaction point
* -w = where database cluster restore to
*
*/
/* Recomended PostgreSQL recovery procedure we'd like to implement:
1. Stop the postmaster, if it's running.
2. If you have the space to do so, copy the whole cluster data directory and any
tablespaces to a temporary location in case you need them later. Note that this precaution
will require that you have enough free space on your system to hold two copies of your
existing database. If you do not have enough space, you need at the least to copy the
contents of the pg_xlog subdirectory of the cluster data directory, as it may contain logs
which were not archived before the system went down.
3. Clean out all existing files and subdirectories under the cluster data directory and
under the root directories of any tablespaces you are using.
4. Restore the database files from your backup dump. Be careful that they are restored
with the right ownership (the database system user, not root!) and with the right
permissions. If you are using tablespaces, you may want to verify that the symbolic links
in pg_tblspc/ were correctly restored.
5. Remove any files present in pg_xlog/; these came from the backup dump and are therefore
probably obsolete rather than current. If you didn't archive pg_xlog/ at all, then
re-create it, and be sure to re-create the subdirectory pg_xlog/archive_status/ as well.
6. If you had unarchived WAL segment files that you saved in step 2, copy them into
pg_xlog/. (It is best to copy them, not move them, so that you still have the unmodified
files if a problem occurs and you have to start over.)
7. Create a recovery command file recovery.conf in the cluster data directory (see
Recovery Settings). You may also want to temporarily modify pg_hba.conf to prevent ordinary
users from connecting until you are sure the recovery has worked.
8. Start the postmaster. The postmaster will go into recovery mode and proceed to read
through the archived WAL files it needs. Upon completion of the recovery process, the
postmaster will rename recovery.conf to recovery.done (to prevent accidentally re-entering
recovery mode in case of a crash later) and then commence normal database operations.
9. Inspect the contents of the database to ensure you have recovered to where you want to
be. If not, return to step 1. If all is well, let in your users by restoring pg_hba.conf to
normal.
$PGDATA/recovery.conf:
restore_command (string)
recovery_target_time (timestamp) || recovery_target_xid (string)
recovery_target_inclusive (boolean)
bconsole command for archive logs restoration:
* restore file=pgsqlarch:<client-name>/<walfilename> where=<where> done yes
bconsole command for database files restoration:
* .filesets
for every filesets execute
* restore fileset=<$fileset> select
* ls
now we should get which fileset is available, we will verify it, if it will be ok, proceed:
* restore where=<where> fileset=<$fileset> [restoreclient=<client>] [current,before="YYYY-MM-DD HH:MM:SS"] select
now, use "5" => "Select a current backup of the client"
* 5
*
*/
/*
TODO:
* add timeout watchdog thread to check if everything is ok.
* add remote ARCHDEST using SSH/SCP
* prepare a docummentation about plugin
*/
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <libpq-fe.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <libgen.h>
#include <pwd.h>
#include <grp.h>
#include "pgsqllib.h"
#include "utils.h"
/*
* libbac uses its own sscanf implementation which is not compatible with
* libc implementation, unfortunately.
* Usage of bsscanf require format string rewriting.
*/
#ifdef sscanf
#undef sscanf
#endif
#ifdef __cplusplus
extern "C" {
#endif
void inteos_info ( pgsqldata * pdata ){
if ( pdata->verbose || pdata->mode == PGSQL_DB_RESTORE ){
logprg ( LOGINFO, " =============================" );
logprg ( LOGINFO, "| PostgreSQL restore utility. |" );
logprg ( LOGINFO, "| (c) 2013 by Inteos |" );
logprg ( LOGINFO, " =============================" );
}
}
void print_help ( pgsqldata * pdata ){
printf ("Usage: pgsql-restore -c <config.file> [-v] [-t <recovery.time> | -x <recovery.xid> ] [-w <where>] [-r restoreclient] restore\n" );
}
void dbconnect ( pgsqldata * pdata ){
pdata->catdb = catdbconnect ( pdata->paramlist );
if ( ! pdata->catdb ){
abortprg ( pdata, 4, "Problem connecting to catalog database!" );
}
}
void parse_args ( pgsqldata * pdata, int argc, char* argv[] ){
int i;
char * fullconfpath;
if ( argc < 3 ){
/* TODO - add help screen */
print_help ( pdata );
abortprg ( pdata, 1, "Not enough parameters!" );
}
for (i = 1; i < argc; i++) {
// printf ( "%s\n", argv[i] );
if ( !strcmp ( argv[i], "-c" ) ){
/* we have got a custom config file */
fullconfpath = MALLOC ( BUFLEN );
ASSERT_NVAL_RET ( fullconfpath );
realpath ( argv [ i + 1 ], fullconfpath );
pdata->configfile = bstrdup ( fullconfpath );
FREE ( fullconfpath );
i++;
continue;
}
if ( !strcmp ( argv[i], "-t" ) && pdata->pitr == PITR_CURRENT ){
pdata->restorepit = format_btime ( argv [ i + 1 ] );
pdata->pitr = PITR_TIME;
i++;
continue;
}
if ( !strcmp ( argv[i], "-x" ) && pdata->pitr == PITR_CURRENT ){
pdata->restorepit = bstrdup ( argv [ i + 1 ] );
pdata->pitr = PITR_XID;
i++;
continue;
}
if ( !strcmp ( argv[i], "-w" ) ){
pdata->where = bstrdup ( argv [ i + 1 ] );
i++;
continue;
}
if ( !strcmp ( argv[i], "-r" ) ){
pdata->restoreclient = bstrdup ( argv [ i + 1 ] );
i++;
continue;
}
if ( !strcasecmp ( argv[i], "-v" ) ){
pdata->verbose = 1;
continue;
}
if ( !strcasecmp ( argv[i], "restore" ) ){
pdata->mode = PGSQL_DB_RESTORE;
continue;
}
if ( !strcasecmp ( argv[i], "wal" ) ){
pdata->mode = PGSQL_ARCH_RESTORE;
continue;
}
if ( pdata->mode == PGSQL_ARCH_RESTORE && ! pdata->walfilename ){
pdata->walfilename = bstrdup ( argv[i] );
continue;
}
if ( pdata->mode == PGSQL_ARCH_RESTORE && ! pdata->pathtowalfilename ){
pdata->pathtowalfilename = bstrdup ( argv[i] );
break;
}
}
if ( pdata->mode == PGSQL_NONE ){
abortprg ( pdata, 2, "Operation mode [restore,wal] required!" );
}
if ( pdata->mode == PGSQL_ARCH_RESTORE ){
if ( ! pdata->walfilename || ! pdata->pathtowalfilename ){
abortprg ( pdata, 2, "WAL filename and pathname required!" );
}
}
pdata->paramlist = parse_pgsql_conf ( pdata->configfile );
// if ( pdata->mode == PGSQL_DB_RESTORE && ( pdata->pitr != PITR_CURRENT ) ){
//
// }
}
/*
* prints restore configuration data
*/
void print_restore_info ( pgsqldata * pdata )
{
char * buf;
if ( pdata->verbose ){
buf = MALLOC ( BUFLEN );
if ( ! buf ){
abortprg ( pdata, 6, "memory allocation error" );
}
snprintf ( buf, BUFLEN, "CLIENT = %s", search_key ( pdata->paramlist, "ARCHCLIENT" ) );
logprg ( LOGINFO, buf );
snprintf ( buf, BUFLEN, "PGDATA = %s", search_key ( pdata->paramlist, "PGDATA" ) );
logprg ( LOGINFO, buf );
snprintf ( buf, BUFLEN, "PGHOST = %s", search_key ( pdata->paramlist, "PGHOST" ) );
logprg ( LOGINFO, buf );
snprintf ( buf, BUFLEN, "PGPORT = %s", search_key ( pdata->paramlist, "PGPORT" ) );
logprg ( LOGINFO, buf );
switch ( pdata->pitr ){
case PITR_TIME:
case PITR_XID:
snprintf ( buf, BUFLEN, "PITR until %s", pdata->restorepit );
break;
case PITR_CURRENT:
snprintf ( buf, BUFLEN, "PITR until end of WAL data" );
break;
}
logprg ( LOGINFO, buf );
if ( pdata->where ){
snprintf ( buf, BUFLEN, "WHERE = %s", pdata->where );
} else {
snprintf ( buf, BUFLEN, "WHERE = < original location >" );
}
logprg ( LOGINFO, buf );
if ( pdata->restoreclient ){
snprintf ( buf, BUFLEN, "restoreclient = %s", pdata->restoreclient );
logprg ( LOGINFO, buf );
}
FREE ( buf );
}
}
/*
* input:
* pdata->where : search_key ( pdata->paramlist, "PGDATA"
* output:
* 1 - is running
* 0 - is not running
*/
int check_postgres_is_running ( pgsqldata * pdata ){
int pidfd;
int err;
int pid;
int out;
char * pidcont;
char * buf;
int rc = 0;
struct stat st;
buf = MALLOC ( BUFLEN );
if ( ! buf ){
abortprg ( pdata, 6, "memory allocation error" );
}
pidcont = MALLOC ( 64 );
if ( ! pidcont ){
abortprg ( pdata, 6, "memory allocation error" );
}
snprintf ( buf, BUFLEN, "%s/postmaster.pid",
pdata->where ? pdata->where : search_key ( pdata->paramlist, "PGDATA" ) );
err = stat ( buf, &st );
if ( err ){
err = errno;
if ( err == EACCES ){
abortprg ( pdata, 7, "access denied at checking database destination" );
}
}
pidfd = open ( buf, O_RDONLY );
if ( pidfd > 0 ){
/* file exist, check if postmaster is running on that pid, if so
* read contents (pid number encoded as ascii number) */
err = read ( pidfd, pidcont, 64 );
if ( err > 2 ){
/* minimal valid file found, fd no longer needed */
close ( pidfd );
/* check for pid number in the first line of the file */
out = sscanf ( pidcont, "%i\n", &pid );
if ( out == 1 ){
/* valid pid number found, check process existence */
//printf ( "PID %i\n", pid );
/* TODO: add checking for other OS'es then Linux */
snprintf ( buf, BUFLEN, "/proc/%i/status", pid );
pidfd = open ( buf, O_RDONLY );
if ( pidfd > 0 ){
close ( pidfd );
rc = 1;
}
}
}
} else {
if ( pdata->verbose ){
logprg ( LOGINFO, "postmaster should be already down on that cluster, good." );
}
}
FREE ( pidcont );
FREE ( buf );
return rc;
}
/*
* executes a command process with popen call
*
* input:
* pdata - primary data
* command - command to execute
* output:
* stdout/stderr stream into logprg (LOGINFO)
* exitstatus - command exit code
*/
int exec_popen_process ( pgsqldata * pdata, char * command ){
char * buf;
FILE * file;
int out;
char * execommand;
int scnr;
int exitstatus;
const char * EXITSTATUS = " 2>&1;echo \"POPENEXITSTATUS: $?\"";
buf = MALLOC ( BUFLEN );
ASSERT_NVAL_RET_ONE ( buf );
execommand = MALLOC ( strlen ( command ) + strlen ( EXITSTATUS ) + 1 );
execommand [ 0 ] = '\0';
strcat ( execommand, command );
strcat ( execommand, EXITSTATUS );
file = popen ( execommand, "r" );
ASSERT_NVAL_RET_ONE ( file );
while ( ( out = freadline ( file, buf, BUFLEN ) ) > 0 ){
scnr = sscanf ( buf, "POPENEXITSTATUS: %d", &exitstatus );
if ( scnr ){
// printf ( "SSCANF: %i, %d\n", scnr, exitstatus );
break;
} else
if ( pdata->verbose ){
logprg ( LOGINFO, buf );
}
}
pclose ( file );
FREE ( buf );
FREE ( execommand );
return exitstatus;
}
/*
* check an owner of PGDATA directory
* input:
* pdata->paramlist[PGDATA]
* output:
* 0 - on success, uid/gid of PGDATA directory at pgid
* 1 - on error
*/
int get_pgdata_pgugid ( pgsqldata * pdata, pgugid * pgid ){
int err;
struct stat st;
/* Required PGDATA from config file */
err = stat ( pdata->where ? pdata->where : search_key ( pdata->paramlist, "PGDATA" ) , &st );
if ( err ){
return 1;
}
pgid->uid = st.st_uid;
pgid->gid = st.st_gid;
return 0;
}
/*
* shutes down a running postmaster
* input:
* pdata->paramlist
* mode - stoping mode
* output
* 0 - on success
* other - error number from exec_popen
*/
int perform_postmaster_shutdown ( pgsqldata * pdata, char mode ){
int err;
char * pgctlrun;
const char * pgctl;
pgctlrun = MALLOC ( BUFLEN );
ASSERT_NVAL_RET_ONE ( pgctlrun );
/* we re looking for pg_ctl location */
pgctl = search_key ( pdata->paramlist, "PGSTOP" );
if ( !pgctl ){
/* autodetect a pg_ctl and stop options */
pgctl = find_pgctl ( pdata );
ASSERT_NVAL_RET_ONE ( pgctl );
/* biulding a command for instance shutdown in abort mode */
snprintf ( pgctlrun, BUFLEN, "%s stop -s -D \"%s\" -m %c",
pgctl,
pdata->where ? pdata->where : search_key ( pdata->paramlist, "PGDATA" ),
mode );
} else {
/* use a user supplied stop command and options
* building a command for instance shutdown */
snprintf ( pgctlrun, BUFLEN, "%s -D \"%s\" -m %c",
pgctl,
pdata->where ? pdata->where : search_key ( pdata->paramlist, "PGDATA" ),
mode );
}
logprg ( LOGINFO, pgctlrun );
/* exec a required process */
err = exec_popen_process ( pdata, pgctlrun );
return err;
}
/*
* shutdown a running PostgreSQL instance pointed by PGDATA
*/
int shutdown_postmaster ( pgsqldata * pdata ){
pgugid pgid;
uid_t curuid = 0;
// uid_t testuid;
int err;
ASSERT_NVAL_RET_ONE ( pdata );
if ( pdata->verbose ){
int a;
char msg[8] = "x ...";
logprg ( LOGINFO, "shutting down a runing PostgreSQL instance at PGDATA" );
logprg ( LOGINFO, "it is your last chance to interrupt recovery process ..." );
for ( a = 3; a > 0; a-- ){
msg [ 0 ] = '0' + a;
logprg ( LOGINFO, msg );
sleep ( 1 );
}
logprg ( LOGINFO, "OK, as you wish, its' your database ..." );
}
/* save a current permissions */
curuid = geteuid ();
/* dynamic production database owner verification, we use it to shutdown database instance */
err = get_pgdata_pgugid ( pdata, &pgid );
/* switch to pgcluster owner (postgres) */
err = seteuid ( pgid.uid );
ASSERT_VAL_RET_ONE ( err );
//testuid = geteuid ();
/* exec a required process with 'immediate' mode */
err = perform_postmaster_shutdown ( pdata, 'i' );
ASSERT_VAL_RET_ONE ( err );
/* switch to curent user */
err = seteuid ( curuid );
ASSERT_VAL_RET_ONE ( err );
//testuid = geteuid ();
if ( pdata->verbose ){
logprg ( LOGINFO, "shutdown complete" );
}
return 0;
}
/*
*
*/
void read_log_handler ( pgsqldata * pdata, const int msqid, const char * pgctlfifo ){
int fdfifo;
char * buffifo;
char * str;
int outfifo;
/* read log handler */
fdfifo = open ( pgctlfifo, O_RDONLY );
// printf ( "open fifo\n" );
/* buffifo as a postmaster log output buffer */
buffifo = MALLOC ( BUFLEN );
while ( ( outfifo = readline ( fdfifo, buffifo, BUFLEN ) ) > 0 ){
if ( pdata->verbose ) {
printf ( "%s\n", buffifo );
}
/* search for archive recovery completed */
str = strstr ( buffifo, "LOG: archive recovery complete" );
if ( str ){
logprg ( LOGINFO, "RECOVERY COMPLETED!!!" );
pgsql_msg_send ( pdata, msqid, 2, "R. Recovery Completed" );
}
/* search for database shutdown completed */
str = strstr ( buffifo, "LOG: database system is shut down" );
if ( str ){
logprg ( LOGINFO, "Shutdown COMPLETED!!!" );
pgsql_msg_send ( pdata, msqid, 2, "S. Shutdown" );
}
/* search for any error */
str = strstr ( buffifo, "FATAL: " );
//str = strstr ( buffifo, "postgres cannot access" );
if ( str ){
logprg ( LOGINFO, "ERROR!!!" );
pgsql_msg_send ( pdata, msqid, 2, "E. ERROR" );
}
}
close ( fdfifo );
FREE ( buffifo );
}
/*
* input:
* pdata - primary data
* msqid - message queue id
* pgctlfifo - name of log handler fifo
* output:
* pid - forked process pid
*/
int start_read_log_handler ( pgsqldata * pdata, const int msqid, const char * pgctlfifo ){
int pid;
pid = fork ();
if ( pid == 0 ){
// printf ( "Hello from forked process: start_read_log_handler\n" );
/* sleep used for debuging forked process in gdb */
//sleep ( 60 );
/* sync with other process */
pgsql_msg_send ( pdata, msqid, 1, "A. log handler ready" );
/* read log handler */
read_log_handler ( pdata, msqid, pgctlfifo );
/* finish forked process */
exit ( 0 );
} else {
// printf ("PID (start_read_log_handler): %i\n", pid );
}
return pid;
}
/*
* input:
* pgid - uid/gid for switch to
* output:
* 0 - on success
* 1 - on error
*/
int set_user_groups ( const pgugid * pgid ){
passwd * pw;
int err;
gid_t * groups = NULL;
int ngroups = 0;
/* check required uid/gid */
if ( getuid() != pgid->uid || getgid() != pgid->gid ){
/* user switching required */
pw = getpwuid ( pgid->uid );
/* what is a number of suplementary groups of required user */
#ifdef __APPLE__
err = getgrouplist ( pw->pw_name, pgid->gid, (int*)groups, &ngroups );
#else
err = getgrouplist ( pw->pw_name, pgid->gid, groups, &ngroups );
#endif
if ( err == -1 ){
groups = (gid_t *) malloc ( ( ngroups + 1 ) * sizeof ( gid_t ) );
ASSERT_NVAL_RET_ONE ( groups );
}
/* get a suplementary group list */
#ifdef __APPLE__
ngroups = getgrouplist ( pw->pw_name, pgid->gid, (int*)groups, &ngroups);
#else
ngroups = getgrouplist ( pw->pw_name, pgid->gid, groups, &ngroups);
#endif
/* extend possible suplementary groups for user */
err = setgroups ( ngroups, groups );
/* set primary group for process */
err = setgid ( pgid->gid );
/* switch to required user */
err = setuid ( pgid->uid );
// printf ( "switched uid:gid = %i:%i\n", getuid(), getgid() );
FREE ( groups );
}
return 0;
}
/*
* input:
* pdata - primary data
* msqid - message queue id
* pgctlfifo - name of log handler fifo
* output:
* 0 - on success
* 1 - on error
*/
int perform_postmaster_startup_recovery ( pgsqldata * pdata, pgugid * pgid, const int msqid, const char * pgctlfifo ){
char * pgctlrun; // allocated
const char * pgctl;
int pid = 0;
int err;
char * buf; // allocated
int exitstatus;
pgctlrun = MALLOC ( BUFLEN );
ASSERT_NVAL_RET_ONE ( pgctlrun );
/* find a pg_ctl location */
pgctl = search_key ( pdata->paramlist, "PGSTART" );
if ( !pgctl ){
/* autodetect a pg_ctl and start options */
pgctl = find_pgctl ( pdata );
ASSERT_NVAL_RET_ONE ( pgctl );
/* building a command for instance startup */
snprintf ( pgctlrun, BUFLEN, "%s start -l %s -w -s -o \"-c config_file=%s/postgresql.conf -c logging_collector=off\" -D \"%s\"",
pgctl, pgctlfifo,
pdata->where ? pdata->where : search_key ( pdata->paramlist, "PGDATA" ),
pdata->where ? pdata->where : search_key ( pdata->paramlist, "PGDATA" ) );
buf = MALLOC ( BUFLEN );
} else {
/* use a user supplied start command and options
* building a command for instance startup */
snprintf ( pgctlrun, BUFLEN, "%s -w -s -l %s -D \"%s\"",
pgctl,
pgctlfifo,
pdata->where ? pdata->where : search_key ( pdata->paramlist, "PGDATA" ) );
}
logprg ( LOGINFO, pgctlrun );
pid = fork ();
if ( pid == 0 ){
// printf ( "Hello from forked process: perform_postmaster_startup_recovery\n" );
/* sleep used for debuging forked process in gdb */
// sleep ( 60 );
/* sync with read log process */
pgsql_msg_recv ( pdata, msqid, 1, buf );
// printf ( "RECV: %s\n" , buf );
/* switch to pgcluster owner (postgres) and all its groups */
err = set_user_groups ( pgid );
ASSERT_VAL_EXIT_ONE ( err );
/* exec a required process */
err = exec_popen_process ( pdata, pgctlrun );
/* finish forked process */
exit ( err );
} else {
// printf ("PID (perform_postmaster_startup_recovery): %i\n", pid );
waitpid ( pid, (int*)&exitstatus, 0 );
// printf ( "EXITSTATUS: %i\n", exitstatus );
}
/* check if pg_ctl run sucessfully */
if ( ! exitstatus ){
pid = fork ();
if ( pid == 0 ){
// printf ( "Hello from forked process: perform_postmaster_startup_recovery\n" );
/* sleep used for debuging forked process in gdb */
// sleep ( 60 );
/* sync with read log process */
pgsql_msg_recv ( pdata, msqid, 2, buf );
// printf ( "RECV: %s\n" , buf );
if ( buf[0] == 'E' ){
/* error occurred */
return 1;
}
/* switch to pgcluster owner (postgres) */
err = set_user_groups ( pgid );
ASSERT_VAL_RET_ONE ( err );
/* shutdown postgresql */
err = perform_postmaster_shutdown ( pdata, 's' );
/* wait for shutdown to complite */
pgsql_msg_recv ( pdata, msqid, 2, buf );
// printf ( "RECV: %s\n" , buf );
if ( buf[0] == 'E' ){
/* error occurred */
return 1;
}
exit ( err );
} else {
// printf ("PID (perform_postmaster_startup_recovery): %i\n", pid );
waitpid ( pid, (int*)&exitstatus, 0 );
// printf ( "EXITSTATUS: %i\n", exitstatus );
}
}
FREE ( pgctlrun );
FREE ( buf );
return exitstatus;
}
/*
* startup a PostgreSQL instance pointed by PGDATA
*/
int startup_postmaster ( pgsqldata * pdata ){
int msqid;
char * pgctlfifo;
char * unlinkfile;
int err;
int pidfifo;
int exitstatus;
pgugid pgid;
ASSERT_NVAL_RET_ONE ( pdata );
logprg ( LOGINFO, "RECOVERY START!!!" );
if ( pdata->verbose ){
logprg ( LOGINFO, "startup a PostgreSQL instance in Recovery Mode" );
}
/* cleanup some files */
unlinkfile = MALLOC ( PATH_MAX );
ASSERT_NVAL_RET_ONE ( unlinkfile );
snprintf ( unlinkfile, PATH_MAX, "%s/postmaster.pid",
pdata->where ? pdata->where : search_key ( pdata->paramlist, "PGDATA" ) );
unlink ( unlinkfile );
/* dynamic production database owner verification, we use it to startup a database instance */
err = get_pgdata_pgugid ( pdata, &pgid );
/* fifo used for postgres instance log handler located at /tmp/<ARCHCLIENT>.ctl */
pgctlfifo = MALLOC ( BUFLEN );
ASSERT_NVAL_RET_ONE ( pgctlfifo );
snprintf ( pgctlfifo, BUFLEN, "/tmp/%s.ctl", search_key ( pdata->paramlist, "ARCHCLIENT" ) );
/* create a fifo */
unlink ( pgctlfifo );
err = mkfifo ( pgctlfifo, S_IRUSR | S_IWUSR );
ASSERT_VAL_RET_ONE ( err );
chown ( pgctlfifo, pgid.uid, pgid.gid );
/* message queue id */
msqid = pgsql_msg_init ( pdata, 'R' );
/* run a read log handler */
pidfifo = start_read_log_handler ( pdata, msqid, pgctlfifo );
/* execute pg_ctl */
err = perform_postmaster_startup_recovery ( pdata, &pgid, msqid, pgctlfifo );
waitpid ( pidfifo, (int*)&exitstatus, 0 );
// printf ( "EXITSTATUS: %i\n", exitstatus );
pgsql_msg_shutdown ( pdata, msqid );
if ( err ) {
logprg ( LOGERROR, "Recovery failed" );
} else
if ( pdata->verbose ){
logprg ( LOGINFO, "Recovery complete" );
}
return err;
}
/*
*
*/
int copy_unarchived_wals ( pgsqldata * pdata ){
DIR * dirp;
struct dirent * filedir;
char * path;
char * file;
char * dst;
struct stat st;
PGresult * result;
char * sql;
int err;
dbconnect ( pdata );
path = MALLOC ( PATH_MAX );
if ( ! path ){
logprg ( LOGERROR, "out of memeory!" );
return 1;
}
snprintf ( path, PATH_MAX, "%s/pg_xlog",
pdata->where ? pdata->where :
search_key ( pdata->paramlist, "PGDATA" ) );
dirp = opendir ( path );
if ( dirp ){
/* katalog pg_xlog istnieje, sprawdzmy czy są tam jakieś pliki do
* archiwizacji */
if ( pdata->verbose ){
logprg ( LOGINFO, "copying unarchived wal logs" );
}
file = MALLOC ( PATH_MAX );
if ( ! file ){
FREE ( path );
logprg ( LOGERROR, "out of memeory!" );
return 1;
}
dst = MALLOC ( PATH_MAX );
if ( ! dst ){
FREE ( path );
FREE ( file );
logprg ( LOGERROR, "out of memeory!" );
return 1;
}
sql = MALLOC ( SQLLEN );
if ( ! sql ){
FREE ( path );
FREE ( file );
FREE ( dst );
logprg ( LOGERROR, "out of memeory!" );
return 1;
}
while ( (filedir = readdir ( dirp )) ){
if ( strcmp ( filedir->d_name, "." ) != 0 &&
strcmp ( filedir->d_name, ".." ) != 0 ){
/* building a name to check */
snprintf ( file, PATH_MAX, "%s/%s", path, filedir->d_name );
if ( stat ( file, &st ) == 0 && S_ISREG ( st.st_mode ) ){
/* in pg_xlog directory has at least one file, we assume that it is a
* wal file nd we would like to copy it, but we have to check if it was
* previously archived
* TODO: archived wal means status in (1,3,6),
* PGSQL_STATUS_WAL_OK
* others means error or unfinished archiving */
snprintf ( sql, SQLLEN,
"select status from pgsql_archivelogs where client='%s' and \
filename='%s' and status in (%s)",
search_key ( pdata->paramlist, "ARCHCLIENT" ),
filedir->d_name,
PGSQL_STATUS_WAL_OK );
result = PQexec ( pdata->catdb, sql );
if ( PQresultStatus ( result ) != PGRES_TUPLES_OK ){
abortprg ( pdata, 6, "SQL Exec error!" );
}
if ( PQntuples ( result ) ){
/* file was previous archived -> ignoring */
continue;
}
/* insert status in catalog */
snprintf ( sql, SQLLEN,
"insert into pgsql_archivelogs (client, filename, status) \
values ('%s', '%s', '%i')",
search_key ( pdata->paramlist, "ARCHCLIENT" ),
filedir->d_name, PGSQL_STATUS_WAL_ARCH_START );
result = PQexec ( pdata->catdb, sql );
if ( PQresultStatus ( result ) != PGRES_COMMAND_OK ){
abortprg ( pdata, 6, "SQL Exec error!" );
}
/* budujemy nazwę miejsca docelowego kopiowanego pliku */
snprintf ( dst, PATH_MAX, "%s/%s", search_key ( pdata->paramlist, "ARCHDEST" ), filedir->d_name );
/* perform a wal copy */
err = _copy_wal_file ( pdata, file, dst );
/* update status in catalog */
snprintf ( sql, SQLLEN,
"update pgsql_archivelogs set status='%i' where client='%s' and filename='%s'",
/* if err != 0 then copy was unsuccesfull */
err ? PGSQL_STATUS_WAL_ARCH_FAILED : PGSQL_STATUS_WAL_ARCH_FINISH,
search_key ( pdata->paramlist, "ARCHCLIENT" ),
filedir->d_name );
result = PQexec ( pdata->catdb, sql );
if ( PQresultStatus ( result ) != PGRES_COMMAND_OK ){
abortprg ( pdata, 6, "SQL Exec error!" );
}
}
}
}
FREE ( sql );
FREE ( path );
FREE ( file );
closedir ( dirp );
}
/* XXX: czy napewno musimy zamykać połączenie do bazy danych? */
PQfinish ( pdata->catdb );
pdata->catdb = NULL;
return 0;
}
/* funkcja rekursywnie kasująca katalog wraz z zawartością */
int remove_dir ( pgsqldata * pdata, char * dir ){