{"id":1533,"date":"2017-09-24T09:33:01","date_gmt":"2017-09-24T06:33:01","guid":{"rendered":"http:\/\/www.fatihacar.com\/blog\/?p=1533"},"modified":"2019-10-23T16:14:14","modified_gmt":"2019-10-23T13:14:14","slug":"postgresql-hot-standby-streaming-replication-database-installation-and-failover-operations","status":"publish","type":"post","link":"https:\/\/www.fatihacar.com\/blog\/postgresql-hot-standby-streaming-replication-database-installation-and-failover-operations\/","title":{"rendered":"PostgreSQL Hot Standby (Streaming Replication) Database Installation and Failover Operations"},"content":{"rendered":"<p>PostgreSQL has few feature for standby technology. I generally use streaming replication. This is very easy and confident. Streaming replication use a replication user for replication operations.Streaming replication allows a standby server to stay more up-to-date than is possible with file-based log shipping. The standby connects to the primary, which streams WAL records to the standby as they&#8217;re generated, without waiting for the WAL file to be filled.<\/p>\n<p>Streaming replication is asynchronous by default, in which case there is a small delay between committing a transaction in the primary and the changes becoming visible in the standby.<\/p>\n<p>If you use streaming replication without file-based continuous archiving, the server might recycle old WAL segments before the standby has received them. If this occurs, the standby will need to be reinitialized from a new base backup. You can avoid this by setting wal_keep_segments to a value large enough to ensure that WAL segments are not recycled too early, or by configuring a replication slot for the standby. If you set up a WAL archive that&#8217;s accessible from the standby, these solutions are not required, since the standby can always use the archive to catch up provided it retains enough segments.<\/p>\n<p><strong>Test Systems Features<\/strong><\/p>\n<blockquote><p><strong>PG Version :<\/strong> 9.5<br \/>\n<strong>Primary DB IP :<\/strong> 192.168.10.11<br \/>\n<strong>Pimary DB Hostname :<\/strong> pg01<br \/>\n<strong>Hot Standby DB IP :<\/strong> 192.168.10.12<br \/>\n<strong>Host Standby DB Hostname :<\/strong> pg02<br \/>\n<strong>Virtual Service IP :<\/strong> 192.168.10.10<br \/>\n<strong>OS :<\/strong> Centos 7 x64<br \/>\n<strong>Data directory :<\/strong> \/pgdata\/data<br \/>\n<strong>Archive direcytory :<\/strong> \/pgdata\/ARCHIVELOG<\/p><\/blockquote>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-1534\" src=\"http:\/\/www.fatihacar.com\/blog\/resimler\/streaming_replication.png\" alt=\"streaming_replication\" width=\"520\" height=\"293\" srcset=\"https:\/\/www.fatihacar.com\/blog\/resimler\/streaming_replication.png 520w, https:\/\/www.fatihacar.com\/blog\/resimler\/streaming_replication-300x169.png 300w\" sizes=\"auto, (max-width: 520px) 100vw, 520px\" \/><\/p>\n<p><strong>1- Keygen Generate And Copy<\/strong><\/p>\n<blockquote><p>[postgres@pg01 ~] ssh-keygen -t rsa<br \/>\n[postgres@pg02 ~] ssh-keygen -t rsa<br \/>\n[postgres@pg01 ~] ssh-copy-id -i .ssh\/id_rsa.pub postgres@pg02<br \/>\n[postgres@pg02 ~] ssh-copy-id -i .ssh\/id_rsa.pub postgres@pg01<\/p><\/blockquote>\n<p><strong>2- Create Streaming Replication User on Primary DB<\/strong><\/p>\n<blockquote><p>psql# createuser -U postgres -p 5432 repuser -P -c 10 &#8211;replication<\/p><\/blockquote>\n<p><strong>3- Primary DB pg_hba.conf configuratio<\/strong>n<\/p>\n<blockquote><p>[root@pg01 ~] vi \/pgdata\/data\/pg_hba.conf<\/p>\n<p>Add below line<\/p>\n<p>host replication repuser 192.168.10.12\/32 md5<\/p>\n<p>[root@pg01 ~] systemctl reload postgresql.service<\/p><\/blockquote>\n<p><strong>4- Create Archive Directory on Hot Standby Server<\/strong><br \/>\n<!--more--><\/p>\n<blockquote><p>[root@pg02 ~] mkdir -p \/pgdata\/ARCHIVELOG<\/p><\/blockquote>\n<p><strong>5- Postgresql.conf configuration on Primary DB<\/strong><\/p>\n<blockquote><p>[root@pg01 ~] vi \/pgdata\/data\/postgresql.conf<\/p>\n<p>Parameters change like below<\/p>\n<p>listen_addresses = &#8216;192.168.10.10&#8217;<\/p>\n<p>wal_level = hot_standby # minimal, archive, hot_standby, or logical<\/p>\n<p>archive_mode = on # enables archiving; off, on, or always<br \/>\narchive_command = &#8216;rsync -a %p postgres@192.168.10.12:\/pgdata\/ARCHIVELOG\/%f&#8217; # command to use to archive a logfile segment<\/p>\n<p>max_wal_senders = 3 # max number of walsender processes<br \/>\nwal_keep_segments = 1000 # in logfile segments, 16MB each; 0 disables<br \/>\nmax_replication_slots = 4 max number of replication slots # (change requires restart)<\/p>\n<p>[root@pg01 ~] systemctl restart postgresql.service<\/p><\/blockquote>\n<p><strong>6- Base Backup<\/strong><\/p>\n<blockquote><p>You can use pg_basebackup when primary db is start or stop. Stop status is more confident.<\/p>\n<p>[root@pg01 ~] systemctl stop postgresql.service<\/p>\n<p>\/pgdata\/data directory has to be empty on hot standby server. pg_basebackup command will fill up that directory.<\/p>\n<p>[postgres@pg02 ~] \/usr\/pgsql-9.5\/bin\/pg_basebackup -h 192.168.10.10 -D \/pgdata\/data -U repuser -p 5432 -v -P &#8211;xlog-method=stream<\/p><\/blockquote>\n<p><strong>7- Postgresql.conf configuration on Hot Standby Server<\/strong><\/p>\n<blockquote><p>Primary DB configuration has to be disabled with # mark.<\/p>\n<p>#wal_level = hot_standby # minimal, archive, hot_standby, or logical<\/p>\n<p>#archive_mode = on # enables archiving; off, on, or always<br \/>\n#archive_command = &#8216;rsync -a %p postgres@192.168.10.12:\/pgdata\/ARCHIVELOG\/%f&#8217; # command to use to archive a logfile segment<\/p>\n<p>#max_wal_senders = 3 # max number of walsender processes<br \/>\n#wal_keep_segments = 1000 # in logfile segments, 16MB each; 0 disables<br \/>\n#max_replication_slots = 4<\/p>\n<p>listen_addresses = &#8216;*&#8217;<br \/>\nhot_standby = on<\/p><\/blockquote>\n<p><strong>8- Create Recovery.conf file on Hot Standby Server<\/strong><\/p>\n<blockquote><p>[root@pg02 ~] vi \/pgdata\/data\/recovery.conf<\/p>\n<p>restore_command = &#8216;cp \/pgdata\/ARCHIVELOG\/%f %p&#8217; # e.g. &#8216;cp \/mnt\/server\/archivedir\/%f %p&#8217;<br \/>\narchive_cleanup_command = &#8216;\/usr\/pgsql-9.5\/bin\/pg_archivecleanup \/pgdata\/ARCHIVELOG\/%r&#8217;<br \/>\nstandby_mode = on<br \/>\nprimary_conninfo = &#8216;host=192.168.10.10 port=5432 user=repuser password=repuserpass&#8217;<br \/>\ntrigger_file = &#8216;\/pgdata\/data\/failover.uygula&#8217;<\/p>\n<p>If you want to delay to apply committed values. You can use recovery_min_apply_delay parameter in recovery.conf like below.<\/p>\n<p>recovery_min_apply_delay = 5min<\/p>\n<p>This parameter provide 5 minutes delay. When you commit a transaction at primary side, hot standby will apply this transaction 5 minutes later.<\/p><\/blockquote>\n<p><strong>9- Start Hot Standby PostgreSQL Service<\/strong><\/p>\n<blockquote><p>[root@pg02 ~] systemctl start postgresql.service<\/p><\/blockquote>\n<p><strong>10- Test<\/strong><\/p>\n<blockquote><p><strong>Primary DB<\/strong><br \/>\nReplications list<br \/>\npsql# select * from pg_stat_replication ;<\/p>\n<p>Sender process i \u00e7al\u0131\u015f\u0131yor olmal\u0131d\u0131r.<br \/>\nps -ef | grep sender<br \/>\npostgres 18388 18298 0 17:04 ? 00:00:00 postgres: wal sender process repuser 192.168.10.12(33700) streaming 0\/9000348<\/p>\n<p>psql# create table test (name text);<br \/>\npsql# insert into test values(&#8216;Fatih Acar&#8217;);<\/p>\n<p><strong>Hot Standby DB<\/strong><br \/>\nRecovery mode check<br \/>\npsql# select pg_is_in_recovery();<\/p>\n<p>Receiver process check<br \/>\nps -ef | grep receiver<br \/>\npostgres 20936 20919 0 17:04 ? 00:00:00 postgres: wal receiver process streaming 0\/9000268<\/p>\n<p>psql# select * from test;<\/p>\n<p>name<br \/>\n&#8212;&#8212;&#8212;&#8211;<br \/>\nFatih Acar<\/p><\/blockquote>\n<p><strong>Failover Operations<\/strong><\/p>\n<blockquote><p>When Primary DB is down with crash, you have to perform failover operation.<\/p>\n<p><strong>Step 1<\/strong><\/p>\n<p>Create \/pgdata\/data\/failover.uygula file that is wrote in recovery.conf file trigger_file parameter<\/p>\n<p>Hot Standby DB will be primary db (read-write mode) when trigger_file exist.<\/p>\n<p><strong>Step 2<\/strong><\/p>\n<p>Take virtual service IP on Hot Standby Server<\/p>\n<p>ifconfig eth0:0 192.168.10.10 netmask 255.255.255.0<\/p><\/blockquote>\n<p><strong>Failover With Python Script<\/strong><\/p>\n<blockquote>\n<pre>I wrote a python script for failover operation. You can use this script for failover operation.\r\n\r\nYou can download script from <a href=\"http:\/\/www.fatihacar.com\/blog\/resimler\/pg_failover.py_.zip\">pg_failover.py.zip<\/a> and upload your hot standby server.\r\n\r\n\r\nYou have to change parameter for your hot standby server.\r\n\r\n[root@pg02 ~] vi pg_failover.py\r\n\r\n<code>#-*- coding: utf-8 -*-\r\n\r\n############ Script Bilgisi ##########\r\n\r\n# Versiyon \t    : 1\r\n\r\n# Tarih\t\t    : 2016-06-30\r\n\r\n# Gelistirici  \t    : Fatih Acar\r\n\r\n# E-Mail   \t    : fatih@fatihacar.com\r\n\r\n# Aciklama : Bu Script Hot Standby olarak calisan PostgreSQL veritabainin\r\n# primary veritabainda bozulma meydana geldigi durumlarda Hot Standby in \r\n# primary veritabani olarak calismasini saglamaktadir. \r\n\r\n# Anahtar Kelimeler : PostgreSQL Hot Standby Failover, Create Virtual IP, \r\n# Streaming Replication\r\n\r\n############ Kutuphaneler #############\r\n\r\nimport os\r\nimport sys\r\nimport commands\r\nimport datetime\r\n\r\n############# Degiskenler #############\r\n\r\n# Virtual IP parametrelerine PROD veritabaninin Virtual ve Scan IP degerleri yazilmalidir.\r\n\r\ndata_dizini = '\/pgdata\/data'\r\n\r\nfailover_islem_dosyasi= 'failover.uygula'\r\n\r\nhot_standby_ip = '192.168.10.12' # Hot Standby sunucusunun IP adresi\r\n\r\nvirtual_ip = '192.168.10.10' # Bos birakilirsa IP atamasi yapilmaz.\r\n\r\nethernet_adaptor = 'eth0' # Hot Standby sunucusu ethernet adaptor bilgisi\r\n\r\npostgresql_service_name = 'postgresql-masterDB.service' # Hot Standby veritabaninin postgresql service ismi yazilmalidir.\r\n\r\n#######################################\r\n\r\ndef failover_db():\r\n\t\r\n\ttry:\r\n\t\tprint ('\\033[92mSUCCESS : '+data_dizini+'\/'+failover_islem_dosyasi+' dosyasi olusturuluyor..\\033[0m')\r\n\t\tfile = open(''+data_dizini+'\/'+failover_islem_dosyasi,'w')\r\n\t\tfile.write('PostgreSQL Hot Standby Failover islemi icin olusturulmustur !\\n')\r\n        \tfile.write('Lutfen silmeyiniz !\\n')\r\n\t\tfile.write('Tarih : ' +datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\r\n\t\tfile.close()\r\n\t\tos.system('chown postgres.postgres '+data_dizini+'\/'+failover_islem_dosyasi)\r\n\t\tprint ('\\033[92mSUCCESS : '+data_dizini+'\/'+failover_islem_dosyasi+' dosyasi olusturuldu.\\033[0m')\r\n\texcept:\r\n\t\tprint ('\\033[91mERROR : '+data_dizini+'\/'+failover_islem_dosyasi+' dosyasi olusturulamadi !\\033[0m')\r\n\t\r\n\ttry:\r\n\t\tif os.path.isfile(\"\/tmp\/failover_query.sql\"):\r\n\t\t\tprint ('\\033[92mSUCCESS : Failover islemleri basliyor..\\033[0m')\r\n\t\t\tprint ('\\033[92mSUCCESS : PostgreSQL servisi restart ediliyor..\\033[0m')\r\n\t\t\ttry:\r\n\t\t\t\tif(os.system('systemctl restart '+postgresql_service_name)) == 0:\r\n \t\t\t\t\tprint ('\\033[92mSUCCESS :  '+postgresql_service_name+ 'servisi restart edildi.\\033[0m')\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint ('\\033[91mERROR : '+postgresql_service_name+ 'servisi restart edilemedi !\\033[0m')\r\n\t\t\texcept:\r\n\t\t\t\tprint \"\\033[91mERROR : Failover islemleri sirasinda hata alindi.\\033[0m\"\r\n\r\n\texcept:\r\n\t\t\tprint \"\\033[91mERROR : Failover islemleri sirasinda hata alindi.\\033[0m\"\r\n\t\r\n\tprint ('\\033[92mSUCCESS : PostgreSQL servisinin durumu goruntuleniyor. \\033[0m')\r\n\t\r\n\tprint os.system('systemctl status '+postgresql_service_name)\r\n\t\r\n        print ('\\033[93mWARNING : Eger PostgreSQL servis durumu running olarak gozukmediyse failover islem adimlarinda problem meydana gelmistir !\\033[0m')\r\n\r\n\tprint \"\\033[92mSUCCESS : IP alma ve failover islemleri tamamlandi.\\033[0m\"\r\n\r\ndef take_virtual_ip():\r\n\r\n\tprint \"\\033[92mSUCCESS : Virtual IPler aliniyor..\\033[0m\"\r\n\tif virtual_ip &lt;&gt; '':\r\n\t\ttry:\r\n\t\t\tif(os.system('ifconfig '+ethernet_adaptor+':0 ' +virtual_ip+ ' netmask 255.255.255.0')) == 0:\r\n\t\t\t\tprint ('\\033[92mSUCCESS : ' +virtual_ip+ ' alindi.\\033[0m')\r\n\t\t\telse:\r\n\t\t\t\tprint ('\\033[91mERROR : ' +virtual_ip+ ' alinamadi !\\033[0m')\r\n\t\texcept:\r\n\t\t\tprint ('\\033[91mERROR : ' +virtual_ip+ ' alinamadi !\\033[0m')\r\n\telse:\r\n\t\tprint ('\\033[93mWARNING : virtual_ip parametresi bos oldugu icin IP alma islemi yapilmadi !\\033[0m')\r\n\r\n\tprint \"IP adreslerinin son durumu listeleniyor..\"\r\n\tprint os.system('ifconfig')\r\n\tprint \"IP alma islemleri tamamlandi.\"\r\n\r\ndef main():\r\n\r\n\tprint \"\\n\\n ###################### PostgreSQL Hot Standby Failover ###################### \\n\\n\"\r\n\tprint \"DIKKAT ! Bu uygulama PostgreSQL Hot Standby veritabanini PROD veritabani olarak aktif hale getirir ! \\n\"\r\n\tprint \"###### Parametreler ######\\n\"\r\n\tprint ('data_dizini = ' +data_dizini)\r\n\tprint ('failover_islem_dosyasi = ' +failover_islem_dosyasi)\r\n\tprint ('hot_standby_ip = ' +hot_standby_ip)\r\n\tprint ('virtual_ip = ' +virtual_ip)\r\n\tprint ('ethernet_adaptor = ' +ethernet_adaptor)\r\n\tprint ('postgresql_service_name = ' +postgresql_service_name)\r\n\tprint ('\\n#########################\\n')\r\n\tif raw_input(\"Parametreler dogru ise devam etmek icin evet yazip enter tusuna basiniz : \") == 'evet': \r\n\t\t\r\n\t\tsecim1 = raw_input(\"Sadace IP alma islemi icin 1 e, hem IP alma hem de failover islemleri icin 2 ye basiniz : \")\r\n\t\tif secim1 == '1':\r\n                \ttake_virtual_ip()\r\n\t\telif secim1 == '2':\r\n         \t\ttake_virtual_ip()\r\n\r\n\t\t\tprint \"\\033[92mSUCCESS : Failover islemi basliyor..\\n\\033[0m\"\r\n\t\t\t\t\t\t\r\n\t\t\tfailover_db()\r\n\r\n\t\t\tprint ('\\033[93mWARNING : Failover islemlerinin ardindan FULL yedek alinmasi onerilir ! \\033[0m')\r\n\t\telse:\r\n\t\t\tprint \"Virtual IP olusturma ve failover islemleri yapilmadi !\"\r\n\telse:\r\n\t\tprint \"Uygulama calistirilmadan sonlandirildi.\"\r\n\r\nmain()\r\n<\/code> <strong>Execute <\/strong> [root@pg02 ~] python pgfailover.py<\/pre>\n<\/blockquote>\n<p>Source : www.postgresql.org<\/p>\n","protected":false},"excerpt":{"rendered":"<p>PostgreSQL has few feature for standby technology. I generally use streaming replication. This is very easy and confident. Streaming replication use a replication user for replication operations.Streaming replication allows a standby server to stay more up-to-date than is possible with file-based log shipping. The standby connects to the primary, which streams WAL records to the&#8230;<\/p>\n","protected":false},"author":37,"featured_media":1534,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[10],"tags":[14,88,108,109],"class_list":["post-1533","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-administration-postgresql","tag-database-administration","tag-postgresql-administration","tag-postgresql-high-availability","tag-postgresql-hot-standby"],"jetpack_featured_media_url":"https:\/\/www.fatihacar.com\/blog\/resimler\/streaming_replication.png","jetpack_shortlink":"https:\/\/wp.me\/p39NFI-oJ","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/posts\/1533","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/users\/37"}],"replies":[{"embeddable":true,"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/comments?post=1533"}],"version-history":[{"count":21,"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/posts\/1533\/revisions"}],"predecessor-version":[{"id":2582,"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/posts\/1533\/revisions\/2582"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/media\/1534"}],"wp:attachment":[{"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/media?parent=1533"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/categories?post=1533"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.fatihacar.com\/blog\/wp-json\/wp\/v2\/tags?post=1533"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}