forked from commandprompt/PITRTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_standby
executable file
·660 lines (604 loc) · 28.2 KB
/
cmd_standby
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
#!/usr/bin/python
#
#
# cmd_standby copyright command prompt inc
#
#
# $Id$
"""
License
Copyright Command Prompt, Inc.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose, without fee, and without a written agreement
is hereby granted, provided that the above copyright notice and this
paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL COMMAND PROMPT, INC BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
EVEN IF COMMAND PROMPT, INC HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
COMMAND PROMPT, INC SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN
"AS IS" BASIS, AND COMMAND PROMPT, INC HAS NO OBLIGATIONS TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""
import os
import shutil
import sys
import re
from sys import *
from os import system
from cmd_worker import CMDWorker
from time import sleep
argslist = (("-A", "--action", dict(dest="pgctl_action", action="store", help="Start/Stop PostgreSQL", metavar="start|stop|stop_basebackup")),
("-B", "--basebackup", dict(dest="base_backup", action="store_true", help="Start a base backup", metavar="FILE")),
("-C", "--config", dict(dest="configfilename", action="store", help="Name of the archiver config file", metavar="FILE", default='cmd_standby.ini')),
("-F", "--failover", dict(dest="failover", action="store", help="Value is arbitrary 3 digit number. It is simply a safeguard measure and you could use -F999 or -F372 etc.", metavar="VALUE")),
("-I", "--dbinit", dict(dest="dbinit", action="store_true", help="Use before -B", metavar="FILE")),
("-P", "--ping", dict(dest="ping_check", action="store_true", help="Is my master alive?", metavar="FILE")),
("-R", "--recovertotime", dict(dest="recovertotime", action="store", help="To restore to a specific point in time", metavar="TIMESTAMP")),
("-S", "--standby", dict(dest="standby", action="store_true", help="Enter standby mode", metavar="FILE")))
classdict = (('pgversion', 's', None),
('ssh', 's', None),
('rsync', 's', None),
('rsync_flags', 's', ""),
('pg_ctl', 's', None),
('r_psql', 's', None),
('pg_standby', 's', None),
('pg_archivecleanup', 's', None),
('master_public_ip', 's', None),
('master_local_ip', 's', ""),
('user', 's', None),
('debug', 'b', False),
('ssh_debug', 'b', False),
('port', 'i', None),
('ssh_timeout', 'i', None),
('archivedir', 's', None),
('pgdata', 's', None),
('postgresql_conf', 's', ""),
('pg_hba_conf', 's', ""),
('postgresql_conf_failover', 's', ""),
('pg_hba.conf_failover', 's', ""),
('no_copy_conf', 'b', False),
('recovery_conf', 's', ""),
('logfile', 's', ""),
('action_failover', 's', ""),
('numarchives', 'i', None),
('use_streaming_replication', 'b', False),
('trigger_file', 's', ""),
('repl_db_user', 's', 'postgres'),
('repl_db_password', 's', ""),
('sslmode', 's', 'prefer'),
('notify_ok', 's', None),
('notify_warning', 's', None),
('notify_critical', 's', None))
class RsyncFailure(Exception):
""" Class to propagate rsync exceptions"""
pass
class SSHFailure(Exception):
""" Class to propagate SSH errors, i.e. wrong password """
pass
class RemoteNoData(Exception):
""" Class to propagate errors when remote host returns empty data """
pass
class CMDStandby(CMDWorker):
# Validate the command line
# XXX: replace those parser.error with exceptions in the future
# for now, they seem to be fine, cause they only happen in the very
# beginning, when to resources are allocated yet.
@staticmethod
def command_line_check_func(parser, options):
if options.configfilename == None:
parser.error("option -C is required")
if options.recovertotime and not (options.failover == '999'):
parser.error("option -R requires open -F999")
if options.pgctl_action:
valid_action = ['start', 'stop', 'stop_basebackup', 'start_basebackup']
if options.pgctl_action not in valid_action:
parser.error("option -A requires one of start, stop, stop_basebackup or start_basebackup")
# Let's make sure executables can be reached
def check_config_func(self, options):
pathvars = [self.ssh, self.rsync, self.pg_ctl, self.postgresql_conf, self.pg_hba_conf, self.archivedir]
if not self.use_streaming_replication:
pathvars.extend([self.pg_standby])
else:
pathvars.extend([self.pg_archivecleanup])
if options.recovertotime:
raise Exception('CONFIG: Unable to use recovery_target_time with streaming replication')
for element in pathvars:
try:
if element != self.archivedir:
os.stat("%s" % (str(element)))
else:
# make a new directory if archivedir doesn't exist.
if not os.access(element, os.R_OK | os.W_OK | os.X_OK):
os.makedirs(element, 0700)
except OSError, e:
raise Exception("CONFIG: can't stat %s %s" % (str(element), str(e)))
if options.failover:
# check that the configuration files are all set.
if not self.postgresql_conf_failover or not self.pg_hba_conf_failover:
raise Exception("CONFIG: failover is requested but postgresql_conf_failover and/or pg_hba.conf_failover are not set, exiting")
else:
for f in (self.postgresql_conf_failover, self.pg_hba_conf_failover):
if not os.access(f, os.F_OK | os.R_OK):
raise Exception("CONFIG: unable to read the failover file %s", str(f))
#
# Create pg_xlog dir if missing, follow symlink if present
# XXX: change os.stat to os.access
def check_pgxlog_path_func(self):
pg_xlog_dir = "%s/%s" % (str(self.pgdata), str('pg_xlog'))
success = False
try:
pg_xlog_dir = os.path.realpath(pg_xlog_dir)
# XXX: we might be able to stat the directory, but still get the
# undersired permissions (i.e no write access).
os.stat(pg_xlog_dir)
success = True
except:
try:
if self.debug:
print "creating pg_xlog directory: %s" % (pg_xlog_dir)
os.makedirs(pg_xlog_dir, 0700)
except OSError, e:
print "ERROR: %s" % (str(e))
print "HINT: You may have permission problems"
print "Make sure that %s has the ability to create the directory %s" % ((str(self.user), (str(pg_xlog_dir))))
except Exception, e:
print "ERROR:", e
else:
success = True
return success
def set_rsync_options(self):
self.rsync_flags = "-al %s --delete " % (self.rsync_flags)
if self.debug:
self.rsync_flags += '-v --stats '
def set_pg_standby_options(self):
self.pg_standby_flags = '-s5 -w0 -c '
if self.debug:
self.pg_standby_flags += '-d '
if self.pgversion == '8.2':
self.pg_standby_args = "%%f %%p -k%s " % (self.numarchives)
else:
self.pg_standby_args = "%f %p %r "
def set_connect_and_copy_options(self, options):
# Yes the odd counted " is needed because of the way we have to quote within the command
# There may be a better way to do this, but I got tired of fighting.
ssh_connect = """%s %s %s@%s """ % (self.ssh, self.ssh_flags, self.user, self.master_public_ip)
psql_connect = """ "%s -A -t -U%s -p%s -dpostgres """ % (self.r_psql, self.user, self.port)
if self.master_local_ip:
psql_connect += '-h%s ' % (self.master_local_ip,)
self.copy_dirs = "%s %s --exclude=pg_log/ --exclude=pg_xlog/ --exclude=postgresql.conf --exclude=pg_hba.conf --exclude=postmaster.pid -e ssh %s@%s:" % (self.rsync, self.rsync_flags, self.user, self.master_public_ip)
self.ssh_psql = ssh_connect + psql_connect
self.pgctl_base = "%s -D %s " % (self.pg_ctl, self.pgdata)
if self.no_copy_conf:
# we don't copy configuration files to the data directory, instead,
# set command-line options to get them from their pristine locations
if not options.failover:
pg_conf = self.postgresql_conf
pg_hba_conf = self.pg_hba_conf
else:
pg_conf = self.postgresql_conf_failover
pg_hba_conf = self.pg_hba_conf_failover
# XXX: pg_ctl is sensitive to the order of -c options:
# config_file always go first, additional '-o' options doesn't work,
# so both postgresql.conf and pg_hba.conf should be in a single -o.
config_file_opts = ""
if pg_conf and os.access(pg_conf, os.F_OK | os.R_OK):
config_file_opts += "-c config_file=%s " % (pg_conf,)
if pg_hba_conf and os.access(pg_hba_conf, os.F_OK | os.R_OK):
config_file_opts += "-c hba_file=%s " % (pg_hba_conf,)
if config_file_opts:
self.pgctl_base += "-o \"%s\"" % (config_file_opts,)
if self.logfile:
self.pgctl_base += "-l \"%s\" " % (self.logfile,)
def set_recovery_options(self, options):
# set more sane value for trigger and recovery files now that we know
# pgdata value:
if self.trigger_file == "":
self.trigger_file = "%s/cmd_end_recovery" % (self.pgdata,)
if self.recovery_conf == "":
self.recovery_conf = """%s/recovery.conf""" % (self.pgdata,)
# Recovery string for recovery.conf
self.recovery_stopped_file = re.sub(r'recovery.conf$', 'recovery.stopped', self.recovery_conf)
# 3 different recovery_string options:
# no streaming replication and no failover - use pg_standby with restore_command
# SR - include both primary_conninfo and restore_command w/o pg_standby.
# failover - use only resore_command w/o pg_standby.
if self.use_streaming_replication and options.failover != '9999':
restore_command = """'cp %s/%%f "%%p"' """ % (self.archivedir,)
cleanup_string = """'%s %s %%r'""" % (self.pg_archivecleanup, self.archivedir)
primary_conninfo_string = "host=%s port=%s user=%s sslmode=%s " % (self.master_public_ip, self.port, self.repl_db_user, self.sslmode)
# streaming replication and not failover, if password is not supplied
# it's expected to be found in .pgpass or via PGPASSWORD variable.
# see http://www.postgresql.org/docs/current/static/libpq-envars.html
if len(self.repl_db_password) > 0:
primary_conninfo_string += "password=%s " % (self.repl_db_password,)
self.recovery_string = """standby_mode = 'on'\nprimary_conninfo = '%s'\ntrigger_file = '%s'\nrestore_command = %s\narchive_cleanup_command = %s """ % (primary_conninfo_string, self.trigger_file, restore_command, cleanup_string)
elif options.failover == '999':
self.recovery_string = """restore_command = 'cp %s/%%f "%%p"' """ % (self.archivedir,)
if options.recovertotime:
self.recovery_string += """\nrecovery_target_time = '%s' """ % (options.recovertotime,)
else:
self.recovery_string = """restore_command = '%s %s %s %s' """ % (self.pg_standby, self.pg_standby_flags, self.archivedir, self.pg_standby_args)
def set_options(self, options):
""" Wrapper for varions set_ functions """
self.set_ssh_flags()
self.set_rsync_options()
self.set_pg_standby_options()
self.set_connect_and_copy_options(options)
self.set_recovery_options(options)
# Check the master for being alive
def ping_check_func(self):
success = False
try:
output = self.exec_query_on_primary("""'SELECT 1'""", False)
except RemoteNoData, e:
print "ERROR: remote host returned no data for query:", e
except SSHFailure:
print "Received error code 255 from ssh, likely due to the wrong password"
except Exception, e:
print "ERROR:", e
else:
for row in output:
row = row.rstrip('\n')
if self.debug:
print "DEBUG: " + row
if str(row) != "1":
self.notify_external(critical=True, message="no response from master")
else:
success = True
if success:
print "Got response from the master"
else:
print "ERROR: no response from the master"
return success
# TODO: replace popen with subprocess module calls.
def exec_query_on_primary(self, query, emptyok=True):
""" Runs a database query on the primary node and returns the psql output"""
if self.debug:
print 'DEBUG: executing query %s by %s' % (query, self.ssh_psql)
p = os.popen("%s -c %s\"" % (self.ssh_psql, query))
result = p.readlines()
exitstatus = p.close()
if exitstatus:
# check whether ssh has terminated due to an error occurred, likely an incorrect password
if (exitstatus>>8) == 255:
raise SSHFailure
raise Exception("command returned non-zero exit status")
if len(result) == 0 and not emptyok:
raise RemoteNoData(query)
return result
# This function gives us all the non pgdata directories required
# for operation, such as table spaces
def primary_get_tablespace_paths(self):
try:
paths = self.exec_query_on_primary("""'SELECT * FROM cmd_get_data_dirs()'""")
except:
print "ERROR: Unable to get namespace paths"
print "HINT: Did you apply cmd_standby.sql?"
raise
return paths
def primary_get_datadir_path(self):
try:
path = self.exec_query_on_primary("""'SELECT * FROM cmd_get_pgdata() LIMIT 1'""", False)
except RemoteNoData:
print "ERROR: Unable to get namespace paths"
print "HINT: Did you apply cmd_standby.sql?"
raise
return path[0]
# Start a base backup on the master
# First we issue a checkpoint and then a start backup
def start_backup_func(self):
retval = os.system("rm -rf %s/*" % (self.archivedir,))
if retval:
print "WARNING: unable to remove old archives, retval:", retval
output = self.exec_query_on_primary(""" 'checkpoint' """, False)
for row in output:
row = row.rstrip('\n')
if self.debug:
print "DEBUG: " + row
if str(row) != "CHECKPOINT":
print "ERROR: Unable to execute CHECKPOINT"
self.notify_external(critical=True, message="Unable to execute CHECKPOINT")
raise Exception("ERROR: Unable to execute CHECKPOINT")
output = self.exec_query_on_primary(""" 'SELECT cmd_pg_start_backup()' """, False)
for row in output:
row = row.rstrip('\n')
if self.debug:
print "DEBUG: cmd_pg_start_backup: " + row
if str(row) != "1":
raise Exception("ERROR: Unable to start base backup")
def stop_backup_func(self):
"""
Stop base backup. This function catches all incoming exception inside and
indicates errors with return status, unlike other _backup counterparts. The
rationale is that since it's the last call in a function we can avoid an
extra try..catch block.
"""
success = False
try:
output = self.exec_query_on_primary(""" 'SELECT cmd_pg_stop_backup()' """)
except RemoteNoData, e:
print "ERROR: remote host returned no data for query:", e
except SSHFailure:
print "Received error code 255 from ssh, likely due to the wrong password"
except Exception, e:
print "ERROR:", e
else:
for row in output:
row = row.rstrip('\n')
if self.debug:
print "DEBUG: cmd_pg_stop_backup: " + row
if str(row) == "1":
success = True
if not success:
print "ERROR: Unable to stop base backup"
return success
# Simple function to help ensure we have all paths created for postgresql
def dbinit_func(self):
check = standby.check_pgpid_func()
if check == 0:
print "ERROR: Can not execute --dbinit with PG running locally"
return False
# check whether pgdata and tablespace paths exist, create if not.
try:
paths = self.primary_get_tablespace_paths()
paths.insert(0, self.pgdata)
for row in paths:
if self.debug:
print "DEBUG: " + row
row = row.rstrip('\n')
if not os.path.isdir(row):
os.makedirs(row, 0700)
except OSError, e:
print "ERROR: ", e
print "HINT: You may have permission problems"
print "Make sure that %s has the ability to create the directory: " % (self.user, self.pgdata)
except Exception, e:
print "ERROR: ", e
else:
print "Standby is ready"
return True
print "ERROR: Initialization FAILED"
return False
# Takes a base backup of master. This function is tricky because
# there is a possibility of a non 0 exit status even when successful
def base_backup_func(self):
# first, copy tablespaces
paths = self.primary_get_tablespace_paths()
for row in paths:
if self.debug:
print "DEBUG: " + row
row = row.rstrip('\n')
retval = system("%s%s/ %s/" % (self.copy_dirs, row, row))
if retval and retval != 23 and retval != 24: # 23, 24 incomplete or vanished source file.
raise RsyncFailure
# finally, copy over pgdata
master_pgdata = self.primary_get_datadir_path().strip('\n')
# Before, doing the rsync, make sure we cleanup pg_xlog for streaming replication
# XXX: does it makes sense at all, given that we don't copy pg_xlog from master?
if self.use_streaming_replication:
if self.debug:
print "DEBUG: cleaning up " + master_pgdata + "/pg_xlog/ directory before rsync"
os.system("rm -rf " + self.pgdata + "/pg_xlog/*")
retval = system("%s%s/ %s/" % (self.copy_dirs, master_pgdata, self.pgdata))
if retval and retval != 23 and retval != 24:
raise RsyncFailure
# Start postgresql
def start_postgresql_func(self):
retval = system(self.pgctl_base + " start")
if retval:
print "ERROR: Unable to start PostgreSQL"
self.notify_external(warning=True, message="Unable to start PostgreSQL")
return False
# check whether PostgreSQL has already started. Sleep to give it time to write
# the pid file.
sleep(2)
check = standby.check_pgpid_func()
if check != 0:
print "ERROR: PostgreSQL refused to start"
return False
return True
# Stop postgresql
def stop_postgresql_func(self):
retval = system(self.pgctl_base + " -m fast stop")
if retval:
print "ERROR: Unable to stop PostgreSQL"
self.notify_external(critical=True, message="Unable to stop PostgreSQL")
return False
return True
# Writes recovery.conf file to pgdata
def write_recovery_func(self):
try:
file = open(self.recovery_conf, 'w')
file.write('%s' % (self.recovery_string))
file.close()
except Exception, e:
print "ERROR: Unable to write recovery file: %s" % (self.recovery_conf)
self.notify_external(critical=True, message="Unable to write recovery file: %s" % (e,))
raise
# Copies in production slave configurations from storage location to production pgdata location
def copy_conf(self, failover=False):
# return if we opt to set command-line options to read files from
# their original location.
if self.no_copy_conf:
return
if failover:
pg_conf = self.postgresql_conf_failover;
pg_hba_conf = self.pg_hba_conf_failover;
else:
pg_conf = self.postgresql_conf;
pg_hba_conf = self.pg_hba_conf;
for f in (pg_conf, pg_hba_conf):
try:
if f:
if os.access(f, os.F_OK | os.R_OK):
shutil.copy(f, self.pgdata)
else:
print "WARNING: %s is inaccessible" % (f,)
except Exception:
print "ERROR: Unable to copy configuration files: %s" % (f,)
raise
# Standby function, we need to write the recovery configuration
# and start postgresql
def standby_func(self):
result = False
check = standby.check_pgpid_func()
if check == 0:
print "ERROR: Can not enter standby mode if PG is already running"
return False
try:
self.write_recovery_func()
except Exception, e:
print "ERROR:", e
else:
self.copy_conf()
result = self.start_postgresql_func()
if not result:
print "ERROR: Unable to enter standby mode"
else:
print "Successfully entered standby mode"
return result
# Function allows you to specify a script to execute on failover
# The script must return 0 to be considered successful
def failover_action_func(self):
if self.action_failover:
retval = system("%s" % (self.action_failover))
if retval:
self.notify_external(critical=True, message="failover action returned non-zero exit code")
return False
else:
print "NOTICE: Statistics are not replicated in warm standy mode."
print "HINT: Execute ANALYZE on your databases"
return True
def run_base_backup(self):
result = False
check = self.check_pgpid_func()
if check == 0:
print "ERROR: Can not take base backup with PG running locally"
else:
try:
self.start_backup_func()
self.base_backup_func()
if self.check_pgxlog_path_func():
result = True
else:
self.notify_external(critical=True, message="unable to access xlog path")
except RsyncFailure:
print
print "WARNING: Failed to get 0 exit status"
print "LOG: Check your rsync errors as this may be harmless"
print "LOG: File vanished: .... is ok"
print
except RemoteNoData, e:
print "ERROR: remote host returned no data for query:", e
except SSHFailure:
print "Received error code 255 from ssh, likely due to the wrong password"
except Exception, e:
print "ERROR:", e
finally:
result = self.stop_backup_func() and result
if result:
print "Base backup finished successfully"
else:
print "Base backup is unsuccessful and should be restarted"
return result
def do_failover(self, options):
success = True
try:
check = self.check_pgpid_func()
# Note: we already check that use_streaming_replication is not issued
# with recovertotime inside check_config_func.
if self.use_streaming_replication:
if check == 0:
# Postgres is running, just touch the trigger file and all should be good.
try:
file = open(self.trigger_file, "w")
file.close()
except:
print "ERROR: Unable to write trigger file: %s" % (self.trigger_file,)
raise
else:
# pgsql is NOT running, and we are trying to failover. Lets try to rename recovery.conf into recovery.stopped and try to start pgsql.
try:
os.rename(self.recovery_conf, self.recovery_stopped_file)
except:
print "ERROR: Unable to rename %s into %s" % (self.recovery_conf, self.recovery_stopped_file)
raise
else:
# XXX: trying to stop the server that does recovery may not work
if check == 0:
self.stop_postgresql_func()
self.write_recovery_func()
# XXX: if it's streaming replication and the server is already running - than it's running with an old set of configuration files.
self.copy_conf(failover=True)
except Exception, e:
print "ERROR:", e
success = False
else:
# try to start PostgreSQL if it's not running
if not self.use_streaming_replication or check != 0:
success = success and self.start_postgresql_func()
if not success:
print "ERROR: Failover FAILED"
else:
print "Failover finished"
# technically, failover has succeeded at this moment, but we still may fail
# at the failover action script. Distinguish that case from failure at failover
success = success and self.failover_action_func()
if success:
self.notify_external(ok=True, message="successfull failover")
return success
if __name__ == '__main__':
# before we do anything, let's just check you we are
if os.geteuid() == 0:
sys.exit("\nBad Mojo... no root access for this script\n")
standby = CMDStandby(classdict)
(options, args) = standby.parse_commandline_arguments(argslist, CMDStandby.command_line_check_func)
configfilename = options.configfilename
base_backup = options.base_backup
setstandby = options.standby
dbinit = options.dbinit
pgctl_action = options.pgctl_action
ping_check = options.ping_check
failover = options.failover
recovertotime = options.recovertotime
try:
cfg_vals = standby.load_configuration_file(configfilename)
# Before we do anything, let's check the configuration
standby.check_config_func(options)
# Configure ssh command-line string, rsync options,
# pg_standy arguments and recovery options.
standby.set_options(options)
except Exception, e:
print "ERROR:", e
sys.exit(2)
success = False
# perform different actions depending on command-line switches
if dbinit:
success = standby.dbinit_func()
elif base_backup:
success = standby.run_base_backup()
# If we want to failover to the latest good transaction
elif options.failover == '999':
success = standby.do_failover(options)
# If we want to enter standby mode
elif setstandby:
success = standby.standby_func()
# If we want to check if we can talk to the master
elif ping_check:
success = standby.ping_check_func()
# If we want to start or stop postgresql on the slave
elif pgctl_action == 'start':
self.copy_conf()
success = standby.start_postgresql_func()
elif pgctl_action == 'stop':
success = standby.stop_postgresql_func()
elif pgctl_action == 'stop_basebackup':
success = standby.stop_backup_func()
if success:
sys.exit(0)
else:
sys.exit(1)