[prev in list] [next in list] [prev in thread] [next in thread] 

List:       postgresql-general
Subject:    Re: Monitoring logical replication
From:       Shaheed Haque <shaheedhaque () gmail ! com>
Date:       2024-01-30 11:27:04
Message-ID: CAHAc2jeDbVLz4UON4e-UdYA+5JCzrVZYN99E0SDk9FRgZWXu+Q () mail ! gmail ! com
[Download RAW message or body]

This is great, thank you for posting. I'm currently a subcontinent or two
away from my dev env, but will compare your approach with mine (you are
using some facilities of psql I'm not familiar with). At least you have
confirmed that LSNs are the place to start.

Thanks again, Shaheed


On Tue, 30 Jan 2024, 05:15 Klaus Darilion, <klaus.mailinglists@pernau.at>
wrote:

> Hi Saheed!
> 
> I monitor our replication this way:
> 
> 1. Every 10 seconds i fetch the current LSN and write it into a table,
> next with the current timestamp. Further I fetch confirmend LSNs from
> the replication slots and delete old entries in lsn2data table.
> 
> calculate_logical_replication_lag.php:
> 
> <?php
> 
> $path = realpath(dirname(__FILE__) . "/../inc");
> set_include_path($path . PATH_SEPARATOR . get_include_path());
> 
> require_once('config.php');
> $config_int['syslogprefix'] = basename(__FILE__);
> require_once('logging.php');
> 
> $dbuser="replication_lag_user";
> $dbpass="XXXXXXXXXXXXXXXXXXXX";
> if (!$dbconn = pg_pconnect('host='.$config_int['dbhost'].'
> dbname='.$config_int['dbname'].' user='.$dbuser.' password='.$dbpass)) {
> print "Sorry, database connection failed";
> exit;
> }
> 
> $accuracy = 10; // in seconds
> 
> //
> // Preparations:
> //
> // CREATE TABLE lsn2data(
> //    lsn pg_lsn PRIMARY KEY,
> //    seen timestamp NOT NULL DEFAULT NOW()
> // );
> // CREATE ROLE replication_lag_user WITH LOGIN PASSWORD
> 'XXXXXXXXXXXXXXXXXXX';
> // GRANT ALL ON TABLE lsn2data TO replication_lag_user;
> //
> // CREATE OR REPLACE FUNCTION get_replication_lag() RETURNS TABLE
> (subscriber name, lag bigint) AS
> // $BODY$
> // DECLARE
> //     subscriber name;
> // BEGIN
> //     FOR subscriber IN
> //         SELECT slot_name FROM pg_replication_slots
> //     LOOP
> //         RETURN QUERY SELECT slot_name, EXTRACT(EPOCH FROM
> NOW()-seen)::bigint lag from lsn2data,pg_replication_slots WHERE
> slot_name=subscriber AND lsn < confirmed_flush_lsn ORDER BY lsn DESC
> LIMIT 1;
> //     END LOOP;
> //     RETURN;
> // END
> // $BODY$
> // LANGUAGE plpgsql;
> //
> while (1) {
> $dbq = pg_query("INSERT INTO lsn2data (lsn) VALUES
> (pg_current_wal_lsn())");
> if ($dbq === FALSE) {
> mylog(LOG_ERROR, "SQL query error:
> ".pg_last_error()."\n");
> exit(1);
> }
> 
> $dbq = pg_query("DELETE FROM lsn2data WHERE lsn < (".
> "SELECT lsn FROM lsn2data WHERE lsn < (".
> "SELECT confirmed_flush_lsn FROM
> pg_replication_slots ORDER BY confirmed_flush_lsn ASC LIMIT 1".
> ") ORDER BY lsn DESC LIMIT 1".
> ")"
> );
> if ($dbq === FALSE) {
> mylog(LOG_ERROR, "SQL query error:
> ".pg_last_error()."\n");
> exit(1);
> }
> sleep($accuracy);
> }
> 
> 2. I graph the replications lags (converted from LSN to seconds) in my
> check_mk monitoring:
> 
> #!/bin/bash
> 
> #
> # Managed by Puppet:
> modules/base/files/monitoring/check_logical_replication_lag.sh
> #
> # Check the logical replication lag and export performance data for each
> subscriber
> #
> 
> # exit on error
> #set -e
> 
> #Make sure this script only runs one at a time
> (
> 
> ME=$0
> MEBASE=`basename $0`
> 
> mylog () {
> echo "$MEBASE: $1"
> logger -t "$MEBASE" "$1"
> }
> 
> flock -x -w 1 200
> if [ $? != "0" ]; then
> #echo "ERROR: $0 is already running ... exit"
> logger -t "$MEBASE" "ERROR: $0 is already running ... exit"
> exit 1
> fi
> 
> # Do stuff
> 
> # Variablen fuer Monitoring
> CMK_SPOOLDIR=/var/lib/check_mk_agent/spool
> CMK_NAME=$MEBASE
> CMK_SPOOLFILE=600_`basename ${CMK_NAME}`.txt
> CMK_HEADER="<<<local>>>"
> TMP_FILE="/tmp/logical_replication_lag.csv"
> 
> # Schwellwerte
> warn=300
> crit=600
> 
> final_output="$CMK_HEADER\nP $CMK_NAME "
> 
> # move to a directory where user postgresl may reside (sudo)
> cd /tmp
> 
> # Lag auslesen. Waehrend dem initialen aufsynchen eines Subscribers gibt
> es temporaere Subscriptions, mit dem Namen reg_xxx1-pid-sync-pid.
> # Damit diese nicht getrackt werden gibt es die huebsche LIKE Clause.
> rm -f "$TMP_FILE"
> sudo -u postgres psql regdns -c "COPY (SELECT subscriber,lag FROM
> get_replication_lag() WHERE subscriber LIKE '%\_____' ORDER BY 2 DESC)
> TO '$TMP_FILE' With CSV" 2>&1> /dev/null
> LC=$(sudo -u postgres psql -t regdns -c "SELECT count(*) FROM
> get_replication_lag();" | tr -d ' ')
> 
> if [ $LC == "0" ]; then
> echo -e "$CMK_HEADER\n0 $CMK_NAME - No Slaves with Replication
> found - maybe we are a slave?" > $CMK_SPOOLDIR/$CMK_SPOOLFILE
> exit 0;
> fi
> 
> grep $(hostname | cut -d '-' -f2) "$TMP_FILE" > /dev/null
> if [ $? != "0" ]; then
> echo -e "$CMK_HEADER\n2 $CMK_NAME - Postgres Output does not
> seem valid. Please check script $ME and output in $TMP_FILE" >
> $CMK_SPOOLDIR/$CMK_SPOOLFILE
> exit 1;
> fi
> 
> # CSV in Array einlesen
> IFS=$'\n' read -d '' -r -a input_file < "$TMP_FILE"
> 
> # Auswerten
> maxlag=0
> for i in "${input_file[@]}"; do
> node=`echo $i | awk -F  "," '{print $1}' | tr -- _ -`
> lag=`echo $i | awk -F  "," '{print $2}'`
> final_output="$final_output$node=$lag;$warn;$crit|"
> #
> 
> https://unix.stackexchange.com/questions/186663/is-there-a-unix-command-that-gives-the-minimum-maximum-of-two-numbers
>  maxlag=$(( maxlag > lag ? maxlag : lag ))
> done
> final_output="${final_output}max-lag=$maxlag;$warn;$crit"
> 
> # Letztes Pipe Zeichen rausschneiden
> #final_output=`echo $final_output | rev | cut -c 2- | rev`
> 
> # Spool File schreiben
> echo -e $final_output > $CMK_SPOOLDIR/$CMK_SPOOLFILE
> logger -t "$MEBASE" "$final_output"
> 
> 
> ) 200>/tmp/`basename $0`.exclusivelock
> 
> 
> 3. During initial sync I check the status on the subscriber. Once it has
> synced all tables of the publication, it will send me an email.
> #
> # Managed by Puppet:
> modules/pdns/templates/check_pglogical_subscription.sh.erb
> #
> 
> #
> # This script checks and eventually creates the subscription, and wait
> until the initial sync is finished
> #
> 
> PUB=regdns2020_pub
> SLEEP=5
> PREFIX=check_pglogical_subscription.sh
> NUMTAB=175
> 
> SECONDS=0
> date
> while true; do
> echo "SELECT * from pg_subscription;" | sudo -u postgres psql -t
> regdns | grep -q $PUB
> if [ $? -eq 0 ]; then
> echo "OK: Host is subscribed to '$PUB'. Checking for
> table count ..."
> break
> fi
> echo "ERROR: Host is not subscribed to '$PUB'. Subscribing to
> master ..."
> logger -t $PREFIX "ERROR: Host is not subscribed to '$PUB'.
> Subscribing to master ..."
> echo "CREATE SUBSCRIPTION `hostname -s|tr -- - _` CONNECTION
> 'host=XXXXX dbname=XXXX user=XXXXX password=XXXXXX PUBLICATION
> regdns2020_pub;" | sudo -u postgres psql regdns && touch
> /etc/regdns.schema_subscription.created
> echo "Re-Checking in $SLEEP seconds ..."
> logger -t $PREFIX "Re-Checking in $SLEEP seconds ..."
> sleep $SLEEP
> done
> 
> while true; do
> COUNT=$(echo "SELECT count(*) from pg_subscription_rel;" | sudo
> -u postgres psql -t regdns | head -1 | xargs)
> if [ $COUNT -eq $NUMTAB ]; then
> echo "OK: Subscription '$PUB' contains $NUMTAB tables -
> that is OK. Checking for initial-sync status ..."
> logger -t $PREFIX "OK: Subscription '$PUB' contains
> $NUMTAB tables - that is OK. Checking for initial-sync status ..."
> break
> fi
> echo "ERROR: Subscription '$PUB' contains $COUNT tables, but
> should contain $NUMTAB table. Re-Checking in $SLEEP seconds ..."
> logger -t $PREFIX  "ERROR: Subscription '$PUB' contains $COUNT
> tables, but should contain $NUMTAB table. Re-Checking in $SLEEP seconds
> ..."
> sleep $SLEEP
> done
> 
> while true; do
> COUNTFIN=$(echo "SELECT count(*) from pg_subscription_rel WHERE
> srsubstate='r';" | sudo -u postgres psql -t regdns | head -1 | xargs)
> if [ $COUNTFIN -eq $NUMTAB ]; then
> echo "OK: Initial sync of $COUNTFIN/$NUMTAB tables
> finished in $SECONDS seconds."
> logger -t $PREFIX "OK: Initial sync of $COUNTFIN/$NUMTAB
> tables finished in $SECONDS seconds."
> echo "OK: Initial sync of $COUNTFIN/$NUMTAB tables
> finished in $SECONDS seconds." | mailx -s "$HOST $SECONDS seconds to
> subscribe" -- root
> break
> fi
> echo "PROGRESS: Initial sync of $COUNTFIN/$NUMTAB tables
> finished. Re-Checking in $SLEEP seconds ..."
> logger -t $PREFIX  "PROGRESS: Initial sync of $COUNTFIN/$NUMTAB
> tables finished. Re-Checking in $SLEEP seconds ..."
> sleep $SLEEP
> done
> 
> 
> 
> regards
> Klaus
> 
> 
> 
> 
> Am 2023-10-07 17:31, schrieb Shaheed Haque:
> > Hi,
> > 
> > I've been playing with logical replication (currently on PG14),
> > specifically in an AWS RDS Postgres context, but NOT using AWS' own
> > replication tooling. I'm generally familiar with the challenges of
> > distributed systems (such causality, time synchronisation etc), but
> > not especially familiar with PG.
> > 
> > In looking at how to tell how a given subscriber has caught up with
> > its publisher, there is plenty of advice around the Web, for example
> > 
> https://dba.stackexchange.com/questions/314324/monitor-logical-replication-using-lsn
>                 
> .
> > Like this example, much advice ends up talking about using separate
> > queries on the publisher and the subscriber to compare LSNs. First, (I
> > think) I understand the core difficulty that comparing LSNs is
> > inherently racy, but given that, I'm a bit unclear as to why a single
> > query on the publisher is not enough...IIUC:
> > 
> > * Changes sent from the publisher to the subscriber are identified
> by
> > LSN.
> > * The publisher knows it's own current latest LSN
> > (pg_current_wal_lsn()), but this seems not to be exposed at the
> > subscriber.
> > * The subscriber knows what it has applied locally and even tells
> the
> > publisher (pg_stat_subscription.latest_end_lsn), but it does not seem
> > to be exposed at the publisher.
> > 
> > Have I missed something? Is there a way to track the LSN delta (given
> > that this is known to be racy) just by querying one end?
> > 
> > Second, how do folk "know" when replication is "done". For example, if
> > the two LSNs continued to match for 1 * replication lag? Or N *
> > replication lag? What would be a plausible N?
> > 
> > Third, as we know when logical replication is started, the initial
> > table state is captured in a snapshot, and sent across using COPY
> > TABLE under the covers. Now, let's say that the publisher is idle
> > (i.e. no SQL writes to the user's schema...obviously pg_catalog might
> > change as replication is configured and enabled) and that the
> > replication starts with the publisher as LSN_start. How could one know
> > when the copying is done:
> > 
> > * I initially assumed that the publisher's LSN would not change
> from
> > LSN_start, but as the copying proceeds, I see that it DOES change
> > (presumably because there are updates happening to pg_catalog, such as
> > the temporary slots coming and going).
> > * Is there some kind of singleton state on either publisher or
> > subscriber that could be checked to know? (At the moment, I am
> > counting the records in all copied tables).
> > 
> > I realise that the knowledge that the publisher is "idle" is a special
> > case, but right now, my test for being "done" is:
> > 
> > * Number of records in copied tables matches AND the publisher's
> > pg_stat_subscription matches the subscriber's
> > pg_stat_subscription.latest_end_lsn.
> > 
> > Plus or minus the bit about replication lag, is there a better way?
> > 
> > Thanks, Shaheed
> 


[Attachment #3 (text/html)]

<div dir="auto"><div>This is great, thank you for posting. I&#39;m currently a \
subcontinent or two away from my dev env, but will compare your approach with mine \
(you are using some facilities of psql I&#39;m not familiar with). At least you have \
confirmed that LSNs are the place to start.  </div><div dir="auto"><br></div><div \
dir="auto">Thanks again, Shaheed</div><div dir="auto"><br><br><div \
class="gmail_quote" dir="auto"><div dir="ltr" class="gmail_attr">On Tue, 30 Jan 2024, \
05:15 Klaus Darilion, &lt;<a \
href="mailto:klaus.mailinglists@pernau.at">klaus.mailinglists@pernau.at</a>&gt; \
wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 \
.8ex;border-left:1px #ccc solid;padding-left:1ex">Hi Saheed!<br> <br>
I monitor our replication this way:<br>
<br>
1. Every 10 seconds i fetch the current LSN and write it into a table, <br>
next with the current timestamp. Further I fetch confirmend LSNs from <br>
the replication slots and delete old entries in lsn2data table.<br>
<br>
calculate_logical_replication_lag.php:<br>
<br>
&lt;?php<br>
<br>
$path = realpath(dirname(__FILE__) . &quot;/../inc&quot;);<br>
set_include_path($path . PATH_SEPARATOR . get_include_path());<br>
<br>
require_once(&#39;config.php&#39;);<br>
$config_int[&#39;syslogprefix&#39;] = basename(__FILE__);<br>
require_once(&#39;logging.php&#39;);<br>
<br>
$dbuser=&quot;replication_lag_user&quot;;<br>
$dbpass=&quot;XXXXXXXXXXXXXXXXXXXX&quot;;<br>
if (!$dbconn = pg_pconnect(&#39;host=&#39;.$config_int[&#39;dbhost&#39;].&#39; <br>
dbname=&#39;.$config_int[&#39;dbname&#39;].&#39; user=&#39;.$dbuser.&#39; \
password=&#39;.$dbpass)) {<br>  print &quot;Sorry, database connection \
failed&quot;;<br>  exit;<br>
}<br>
<br>
$accuracy = 10; // in seconds<br>
<br>
//<br>
// Preparations:<br>
//<br>
// CREATE TABLE lsn2data(<br>
//      lsn pg_lsn PRIMARY KEY,<br>
//      seen timestamp NOT NULL DEFAULT NOW()<br>
// );<br>
// CREATE ROLE replication_lag_user WITH LOGIN PASSWORD <br>
&#39;XXXXXXXXXXXXXXXXXXX&#39;;<br>
// GRANT ALL ON TABLE lsn2data TO replication_lag_user;<br>
//<br>
// CREATE OR REPLACE FUNCTION get_replication_lag() RETURNS TABLE <br>
(subscriber name, lag bigint) AS<br>
// $BODY$<br>
// DECLARE<br>
//        subscriber name;<br>
// BEGIN<br>
//        FOR subscriber IN<br>
//              SELECT slot_name FROM pg_replication_slots<br>
//        LOOP<br>
//              RETURN QUERY SELECT slot_name, EXTRACT(EPOCH FROM <br>
NOW()-seen)::bigint lag from lsn2data,pg_replication_slots WHERE <br>
slot_name=subscriber AND lsn &lt; confirmed_flush_lsn ORDER BY lsn DESC <br>
LIMIT 1;<br>
//        END LOOP;<br>
//        RETURN;<br>
// END<br>
// $BODY$<br>
// LANGUAGE plpgsql;<br>
//<br>
while (1) {<br>
              $dbq = pg_query(&quot;INSERT INTO lsn2data (lsn) VALUES <br>
(pg_current_wal_lsn())&quot;);<br>
              if ($dbq === FALSE) {<br>
                          mylog(LOG_ERROR, &quot;SQL query error: <br>
&quot;.pg_last_error().&quot;\n&quot;);<br>
                          exit(1);<br>
              }<br>
<br>
              $dbq = pg_query(&quot;DELETE FROM lsn2data WHERE lsn &lt; (&quot;.<br>
                                         &quot;SELECT lsn FROM lsn2data WHERE lsn \
                &lt; (&quot;.<br>
                                            &quot;SELECT confirmed_flush_lsn FROM \
<br> pg_replication_slots ORDER BY confirmed_flush_lsn ASC LIMIT 1&quot;.<br>
                                         &quot;) ORDER BY lsn DESC LIMIT 1&quot;.<br>
                                      &quot;)&quot;<br>
              );<br>
              if ($dbq === FALSE) {<br>
                          mylog(LOG_ERROR, &quot;SQL query error: <br>
&quot;.pg_last_error().&quot;\n&quot;);<br>
                          exit(1);<br>
              }<br>
              sleep($accuracy);<br>
}<br>
<br>
2. I graph the replications lags (converted from LSN to seconds) in my <br>
check_mk monitoring:<br>
<br>
#!/bin/bash<br>
<br>
#<br>
# Managed by Puppet: <br>
modules/base/files/monitoring/check_logical_replication_lag.sh<br>
#<br>
# Check the logical replication lag and export performance data for each <br>
subscriber<br>
#<br>
<br>
# exit on error<br>
#set -e<br>
<br>
#Make sure this script only runs one at a time<br>
(<br>
<br>
     ME=$0<br>
     MEBASE=`basename $0`<br>
<br>
     mylog () {<br>
        echo &quot;$MEBASE: $1&quot;<br>
        logger -t &quot;$MEBASE&quot; &quot;$1&quot;<br>
     }<br>
<br>
     flock -x -w 1 200<br>
     if [ $? != &quot;0&quot; ]; then<br>
        #echo &quot;ERROR: $0 is already running ... exit&quot;<br>
        logger -t &quot;$MEBASE&quot; &quot;ERROR: $0 is already running ... \
exit&quot;<br>  exit 1<br>
     fi<br>
<br>
     # Do stuff<br>
<br>
# Variablen fuer Monitoring<br>
CMK_SPOOLDIR=/var/lib/check_mk_agent/spool<br>
CMK_NAME=$MEBASE<br>
CMK_SPOOLFILE=600_`basename ${CMK_NAME}`.txt<br>
CMK_HEADER=&quot;&lt;&lt;&lt;local&gt;&gt;&gt;&quot;<br>
TMP_FILE=&quot;/tmp/logical_replication_lag.csv&quot;<br>
<br>
# Schwellwerte<br>
warn=300<br>
crit=600<br>
<br>
final_output=&quot;$CMK_HEADER\nP $CMK_NAME &quot;<br>
<br>
# move to a directory where user postgresl may reside (sudo)<br>
cd /tmp<br>
<br>
# Lag auslesen. Waehrend dem initialen aufsynchen eines Subscribers gibt <br>
es temporaere Subscriptions, mit dem Namen reg_xxx1-pid-sync-pid.<br>
# Damit diese nicht getrackt werden gibt es die huebsche LIKE Clause.<br>
rm -f &quot;$TMP_FILE&quot;<br>
sudo -u postgres psql regdns -c &quot;COPY (SELECT subscriber,lag FROM <br>
get_replication_lag() WHERE subscriber LIKE &#39;%\_____&#39; ORDER BY 2 DESC) <br>
TO &#39;$TMP_FILE&#39; With CSV&quot; 2&gt;&amp;1&gt; /dev/null<br>
LC=$(sudo -u postgres psql -t regdns -c &quot;SELECT count(*) FROM <br>
get_replication_lag();&quot; | tr -d &#39; &#39;)<br>
<br>
if [ $LC == &quot;0&quot; ]; then<br>
              echo -e &quot;$CMK_HEADER\n0 $CMK_NAME - No Slaves with Replication \
<br> found - maybe we are a slave?&quot; &gt; $CMK_SPOOLDIR/$CMK_SPOOLFILE<br>
              exit 0;<br>
fi<br>
<br>
grep $(hostname | cut -d &#39;-&#39; -f2) &quot;$TMP_FILE&quot; &gt; /dev/null<br>
if [ $? != &quot;0&quot; ]; then<br>
              echo -e &quot;$CMK_HEADER\n2 $CMK_NAME - Postgres Output does not <br>
seem valid. Please check script $ME and output in $TMP_FILE&quot; &gt; <br>
$CMK_SPOOLDIR/$CMK_SPOOLFILE<br>
              exit 1;<br>
fi<br>
<br>
# CSV in Array einlesen<br>
IFS=$&#39;\n&#39; read -d &#39;&#39; -r -a input_file &lt; &quot;$TMP_FILE&quot;<br>
<br>
# Auswerten<br>
maxlag=0<br>
for i in &quot;${input_file[@]}&quot;; do<br>
              node=`echo $i | awk -F   &quot;,&quot; &#39;{print $1}&#39; | tr -- _ \
                -`<br>
              lag=`echo $i | awk -F   &quot;,&quot; &#39;{print $2}&#39;`<br>
              final_output=&quot;$final_output$node=$lag;$warn;$crit|&quot;<br>
              # <br>
<a href="https://unix.stackexchange.com/questions/186663/is-there-a-unix-command-that-gives-the-minimum-maximum-of-two-numbers" \
rel="noreferrer noreferrer" \
target="_blank">https://unix.stackexchange.com/questions/186663/is-there-a-unix-command-that-gives-the-minimum-maximum-of-two-numbers</a><br>
  maxlag=$(( maxlag &gt; lag ? maxlag : lag ))<br>
done<br>
final_output=&quot;${final_output}max-lag=$maxlag;$warn;$crit&quot;<br>
<br>
# Letztes Pipe Zeichen rausschneiden<br>
#final_output=`echo $final_output | rev | cut -c 2- | rev`<br>
<br>
# Spool File schreiben<br>
echo -e $final_output &gt; $CMK_SPOOLDIR/$CMK_SPOOLFILE<br>
logger -t &quot;$MEBASE&quot; &quot;$final_output&quot;<br>
<br>
<br>
) 200&gt;/tmp/`basename $0`.exclusivelock<br>
<br>
<br>
3. During initial sync I check the status on the subscriber. Once it has <br>
synced all tables of the publication, it will send me an email.<br>
#<br>
# Managed by Puppet: <br>
modules/pdns/templates/check_pglogical_subscription.sh.erb<br>
#<br>
<br>
#<br>
# This script checks and eventually creates the subscription, and wait <br>
until the initial sync is finished<br>
#<br>
<br>
PUB=regdns2020_pub<br>
SLEEP=5<br>
PREFIX=check_pglogical_subscription.sh<br>
NUMTAB=175<br>
<br>
SECONDS=0<br>
date<br>
while true; do<br>
              echo &quot;SELECT * from pg_subscription;&quot; | sudo -u postgres psql \
-t <br> regdns | grep -q $PUB<br>
              if [ $? -eq 0 ]; then<br>
                          echo &quot;OK: Host is subscribed to &#39;$PUB&#39;. \
Checking for <br> table count ...&quot;<br>
                          break<br>
              fi<br>
              echo &quot;ERROR: Host is not subscribed to &#39;$PUB&#39;. Subscribing \
to <br> master ...&quot;<br>
              logger -t $PREFIX &quot;ERROR: Host is not subscribed to \
&#39;$PUB&#39;. <br> Subscribing to master ...&quot;<br>
              echo &quot;CREATE SUBSCRIPTION `hostname -s|tr -- - _` CONNECTION <br>
&#39;host=XXXXX dbname=XXXX user=XXXXX password=XXXXXX PUBLICATION <br>
regdns2020_pub;&quot; | sudo -u postgres psql regdns &amp;&amp; touch <br>
/etc/regdns.schema_subscription.created<br>
              echo &quot;Re-Checking in $SLEEP seconds ...&quot;<br>
              logger -t $PREFIX &quot;Re-Checking in $SLEEP seconds ...&quot;<br>
              sleep $SLEEP<br>
done<br>
<br>
while true; do<br>
              COUNT=$(echo &quot;SELECT count(*) from pg_subscription_rel;&quot; | \
                sudo <br>
-u postgres psql -t regdns | head -1 | xargs)<br>
              if [ $COUNT -eq $NUMTAB ]; then<br>
                          echo &quot;OK: Subscription &#39;$PUB&#39; contains $NUMTAB \
tables - <br> that is OK. Checking for initial-sync status ...&quot;<br>
                          logger -t $PREFIX &quot;OK: Subscription &#39;$PUB&#39; \
contains <br> $NUMTAB tables - that is OK. Checking for initial-sync status \
...&quot;<br>  break<br>
              fi<br>
              echo &quot;ERROR: Subscription &#39;$PUB&#39; contains $COUNT tables, \
but <br> should contain $NUMTAB table. Re-Checking in $SLEEP seconds ...&quot;<br>
              logger -t $PREFIX   &quot;ERROR: Subscription &#39;$PUB&#39; contains \
$COUNT <br> tables, but should contain $NUMTAB table. Re-Checking in $SLEEP seconds \
                <br>
...&quot;<br>
              sleep $SLEEP<br>
done<br>
<br>
while true; do<br>
              COUNTFIN=$(echo &quot;SELECT count(*) from pg_subscription_rel WHERE \
<br> srsubstate=&#39;r&#39;;&quot; | sudo -u postgres psql -t regdns | head -1 | \
xargs)<br>  if [ $COUNTFIN -eq $NUMTAB ]; then<br>
                          echo &quot;OK: Initial sync of $COUNTFIN/$NUMTAB tables \
<br> finished in $SECONDS seconds.&quot;<br>
                          logger -t $PREFIX &quot;OK: Initial sync of \
$COUNTFIN/$NUMTAB <br> tables finished in $SECONDS seconds.&quot;<br>
                          echo &quot;OK: Initial sync of $COUNTFIN/$NUMTAB tables \
<br> finished in $SECONDS seconds.&quot; | mailx -s &quot;$HOST $SECONDS seconds to \
<br> subscribe&quot; -- root<br>
                          break<br>
              fi<br>
              echo &quot;PROGRESS: Initial sync of $COUNTFIN/$NUMTAB tables <br>
finished. Re-Checking in $SLEEP seconds ...&quot;<br>
              logger -t $PREFIX   &quot;PROGRESS: Initial sync of $COUNTFIN/$NUMTAB \
<br> tables finished. Re-Checking in $SLEEP seconds ...&quot;<br>
              sleep $SLEEP<br>
done<br>
<br>
<br>
<br>
regards<br>
Klaus<br>
<br>
<br>
<br>
<br>
Am 2023-10-07 17:31, schrieb Shaheed Haque:<br>
&gt; Hi,<br>
&gt; <br>
&gt; I&#39;ve been playing with logical replication (currently on PG14),<br>
&gt; specifically in an AWS RDS Postgres context, but NOT using AWS&#39; own<br>
&gt; replication tooling. I&#39;m generally familiar with the challenges of<br>
&gt; distributed systems (such causality, time synchronisation etc), but<br>
&gt; not especially familiar with PG.<br>
&gt; <br>
&gt; In looking at how to tell how a given subscriber has caught up with<br>
&gt; its publisher, there is plenty of advice around the Web, for example<br>
&gt; <a href="https://dba.stackexchange.com/questions/314324/monitor-logical-replication-using-lsn" \
rel="noreferrer noreferrer" \
target="_blank">https://dba.stackexchange.com/questions/314324/monitor-logical-replication-using-lsn</a>.<br>
 &gt; Like this example, much advice ends up talking about using separate<br>
&gt; queries on the publisher and the subscriber to compare LSNs. First, (I<br>
&gt; think) I understand the core difficulty that comparing LSNs is<br>
&gt; inherently racy, but given that, I&#39;m a bit unclear as to why a single<br>
&gt; query on the publisher is not enough...IIUC:<br>
&gt; <br>
&gt;           * Changes sent from the publisher to the subscriber are identified \
by<br> &gt; LSN.<br>
&gt;           * The publisher knows it&#39;s own current latest LSN<br>
&gt; (pg_current_wal_lsn()), but this seems not to be exposed at the<br>
&gt; subscriber.<br>
&gt;           * The subscriber knows what it has applied locally and even tells \
the<br> &gt; publisher (pg_stat_subscription.latest_end_lsn), but it does not \
seem<br> &gt; to be exposed at the publisher.<br>
&gt; <br>
&gt; Have I missed something? Is there a way to track the LSN delta (given<br>
&gt; that this is known to be racy) just by querying one end?<br>
&gt; <br>
&gt; Second, how do folk &quot;know&quot; when replication is &quot;done&quot;. For \
example, if<br> &gt; the two LSNs continued to match for 1 * replication lag? Or N \
*<br> &gt; replication lag? What would be a plausible N?<br>
&gt; <br>
&gt; Third, as we know when logical replication is started, the initial<br>
&gt; table state is captured in a snapshot, and sent across using COPY<br>
&gt; TABLE under the covers. Now, let&#39;s say that the publisher is idle<br>
&gt; (i.e. no SQL writes to the user&#39;s schema...obviously pg_catalog might<br>
&gt; change as replication is configured and enabled) and that the<br>
&gt; replication starts with the publisher as LSN_start. How could one know<br>
&gt; when the copying is done:<br>
&gt; <br>
&gt;           * I initially assumed that the publisher&#39;s LSN would not change \
from<br> &gt; LSN_start, but as the copying proceeds, I see that it DOES change<br>
&gt; (presumably because there are updates happening to pg_catalog, such as<br>
&gt; the temporary slots coming and going).<br>
&gt;           * Is there some kind of singleton state on either publisher or<br>
&gt; subscriber that could be checked to know? (At the moment, I am<br>
&gt; counting the records in all copied tables).<br>
&gt; <br>
&gt; I realise that the knowledge that the publisher is &quot;idle&quot; is a \
special<br> &gt; case, but right now, my test for being &quot;done&quot; is:<br>
&gt; <br>
&gt;           * Number of records in copied tables matches AND the \
publisher&#39;s<br> &gt; pg_stat_subscription matches the subscriber&#39;s<br>
&gt; pg_stat_subscription.latest_end_lsn.<br>
&gt; <br>
&gt; Plus or minus the bit about replication lag, is there a better way?<br>
&gt; <br>
&gt; Thanks, Shaheed<br>
</blockquote></div></div></div>



[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic