8 use Time
::HiRes qw
(gettimeofday tv_interval
);
13 use PVE
::APIClient
::LWP
;
17 use PMG
::ClusterConfig
;
24 my ($nodename, $noerr) = @_;
26 my $cinfo = PMG
::ClusterConfig-
>new();
28 foreach my $entry (values %{$cinfo->{ids
}}) {
29 if ($entry->{name
} eq $nodename) {
30 my $ip = $entry->{ip
};
31 return $ip if !wantarray;
32 my $family = PVE
::Tools
::get_host_address_family
($ip);
33 return ($ip, $family);
37 # fallback: try to get IP by other means
38 return PMG
::Utils
::lookup_node_ip
($nodename, $noerr);
44 $cinfo = PMG
::ClusterConfig-
>new() if !$cinfo;
46 return $cinfo->{master
}->{name
} if defined($cinfo->{master
});
51 sub read_local_ssl_cert_fingerprint
{
52 my $cert_path = "/etc/pmg/pmg-api.pem";
56 my $bio = Net
::SSLeay
::BIO_new_file
($cert_path, 'r');
57 $cert = Net
::SSLeay
::PEM_read_bio_X509
($bio);
58 Net
::SSLeay
::BIO_free
($bio);
61 die "unable to read certificate '$cert_path' - $err\n";
64 if (!defined($cert)) {
65 die "unable to read certificate '$cert_path' - got empty value\n";
70 $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
73 die "unable to get fingerprint for '$cert_path' - $err\n";
76 if (!defined($fp) || $fp eq '') {
77 die "unable to get fingerprint for '$cert_path' - got empty value\n";
83 my $hostrsapubkey_fn = '/etc/ssh/ssh_host_rsa_key.pub';
84 my $rootrsakey_fn = '/root/.ssh/id_rsa';
85 my $rootrsapubkey_fn = '/root/.ssh/id_rsa.pub';
87 sub read_local_cluster_info
{
91 my $hostrsapubkey = PVE
::Tools
::file_read_firstline
($hostrsapubkey_fn);
92 $hostrsapubkey =~ s/^.*ssh-rsa\s+//i;
93 $hostrsapubkey =~ s/\s+root\@\S+\s*$//i;
95 die "unable to parse ${hostrsapubkey_fn}\n"
96 if $hostrsapubkey !~ m/^[A-Za-z0-9\.\/\
+]{200,}$/;
98 my $nodename = PVE
::INotify
::nodename
();
100 $res->{name
} = $nodename;
102 $res->{ip
} = PMG
::Utils
::lookup_node_ip
($nodename);
104 $res->{hostrsapubkey
} = $hostrsapubkey;
106 if (! -f
$rootrsapubkey_fn) {
107 unlink $rootrsakey_fn;
108 my $cmd = ['ssh-keygen', '-t', 'rsa', '-N', '', '-b', '2048',
109 '-f', $rootrsakey_fn];
110 PMG
::Utils
::run_silent_cmd
($cmd);
113 my $rootrsapubkey = PVE
::Tools
::file_read_firstline
($rootrsapubkey_fn);
114 $rootrsapubkey =~ s/^.*ssh-rsa\s+//i;
115 $rootrsapubkey =~ s/\s+root\@\S+\s*$//i;
117 die "unable to parse ${rootrsapubkey_fn}\n"
118 if $rootrsapubkey !~ m/^[A-Za-z0-9\.\/\
+]{200,}$/;
120 $res->{rootrsapubkey
} = $rootrsapubkey;
122 $res->{fingerprint
} = read_local_ssl_cert_fingerprint
();
127 # X509 Certificate cache helper
129 my $cert_cache_nodes = {};
130 my $cert_cache_timestamp = time();
131 my $cert_cache_fingerprints = {};
133 sub update_cert_cache
{
135 $cert_cache_timestamp = time();
137 $cert_cache_fingerprints = {};
138 $cert_cache_nodes = {};
140 my $cinfo = PMG
::ClusterConfig-
>new();
142 foreach my $entry (values %{$cinfo->{ids
}}) {
143 my $node = $entry->{name
};
144 my $fp = $entry->{fingerprint
};
146 $cert_cache_fingerprints->{$fp} = 1;
147 $cert_cache_nodes->{$node} = $fp;
152 # load and cache cert fingerprint once
153 sub initialize_cert_cache
{
157 if defined($node) && !defined($cert_cache_nodes->{$node});
160 sub check_cert_fingerprint
{
163 # clear cache every 30 minutes at least
164 update_cert_cache
() if time() - $cert_cache_timestamp >= 60*30;
166 # get fingerprint of server certificate
169 $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
171 return 0 if $@ || !defined($fp) || $fp eq ''; # error
174 for my $expected (keys %$cert_cache_fingerprints) {
175 return 1 if $fp eq $expected;
180 return 1 if $check->();
182 # clear cache and retry at most once every minute
183 if (time() - $cert_cache_timestamp >= 60) {
184 syslog
('info', "Could not verify remote node certificate '$fp' with list of pinned certificates, refreshing cache");
192 my $sshglobalknownhosts = "/etc/ssh/ssh_known_hosts2";
193 my $rootsshauthkeys = "/root/.ssh/authorized_keys";
194 my $ssh_rsa_id = "/root/.ssh/id_rsa.pub";
196 sub update_ssh_keys
{
202 foreach my $node (values %{$cinfo->{ids
}}) {
203 $data .= "$node->{ip} ssh-rsa $node->{hostrsapubkey}\n";
204 $data .= "$node->{name} ssh-rsa $node->{hostrsapubkey}\n";
207 $old = PVE
::Tools
::file_get_contents
($sshglobalknownhosts, 1024*1024)
208 if -f
$sshglobalknownhosts;
210 PVE
::Tools
::file_set_contents
($sshglobalknownhosts, $data)
217 if (-f
$ssh_rsa_id) {
218 my $pub = PVE
::Tools
::file_get_contents
($ssh_rsa_id);
223 foreach my $node (values %{$cinfo->{ids
}}) {
224 $data .= "ssh-rsa $node->{rootrsapubkey} root\@$node->{name}\n";
227 if (-f
$rootsshauthkeys) {
228 my $mykey = PVE
::Tools
::file_get_contents
($rootsshauthkeys, 128*1024);
235 my @lines = split(/\n/, $data);
236 foreach my $line (@lines) {
237 if ($line !~ /^#/ && $line =~ m/(^|\s)ssh-(rsa|dsa)\s+(\S+)\s+\S+$/) {
238 next if $vhash->{$3}++;
240 $newdata .= "$line\n";
243 $old = PVE
::Tools
::file_get_contents
($rootsshauthkeys, 1024*1024)
244 if -f
$rootsshauthkeys;
246 PVE
::Tools
::file_set_contents
($rootsshauthkeys, $newdata, 0600)
250 my $cfgdir = '/etc/pmg';
251 my $syncdir = "$cfgdir/master";
253 my $cond_commit_synced_file = sub {
254 my ($filename, $dstfn) = @_;
256 $dstfn = "$cfgdir/$filename" if !defined($dstfn);
257 my $srcfn = "$syncdir/$filename";
264 my $new = PVE
::Tools
::file_get_contents
($srcfn, 1024*1024);
267 my $old = PVE
::Tools
::file_get_contents
($dstfn, 1024*1024);
268 return 0 if $new eq $old;
271 # set mtime (touch) to avoid time drift problems
272 utime(undef, undef, $srcfn);
274 rename($srcfn, $dstfn) ||
275 die "cond_rename_file '$filename' failed - $!\n";
277 print STDERR
"updated $dstfn\n";
282 my $rsync_command = sub {
283 my ($host_key_alias, @args) = @_;
285 my $ssh_cmd = '--rsh=ssh -l root -o BatchMode=yes';
286 $ssh_cmd .= " -o HostKeyAlias=${host_key_alias}" if $host_key_alias;
288 my $cmd = ['rsync', $ssh_cmd, '-q', @args];
293 sub sync_quarantine_files
{
294 my ($host_ip, $host_name, $flistname) = @_;
296 my $spooldir = $PMG::MailQueue
::spooldir
;
298 my $cmd = $rsync_command->(
299 $host_name, '--timeout', '10', "${host_ip}:$spooldir", $spooldir,
300 '--files-from', $flistname);
302 PVE
::Tools
::run_command
($cmd);
306 my ($host_ip, $host_name, $rcid) = @_;
308 my $spooldir = $PMG::MailQueue
::spooldir
;
310 mkdir "$spooldir/cluster/";
311 my $syncdir = "$spooldir/cluster/$rcid";
314 my $cmd = $rsync_command->(
315 $host_name, '-aq', '--timeout', '10', "${host_ip}:$syncdir/", $syncdir);
317 foreach my $incl (('spam/', 'spam/*', 'spam/*/*', 'virus/', 'virus/*', 'virus/*/*')) {
318 push @$cmd, '--include', $incl;
321 push @$cmd, '--exclude', '*';
323 PVE
::Tools
::run_command
($cmd);
326 sub sync_master_quar
{
327 my ($host_ip, $host_name) = @_;
329 my $spooldir = $PMG::MailQueue
::spooldir
;
331 my $syncdir = "$spooldir/cluster/";
334 my $cmd = $rsync_command->(
335 $host_name, '-aq', '--timeout', '10', "${host_ip}:$syncdir", $syncdir);
337 PVE
::Tools
::run_command
($cmd);
340 sub sync_config_from_master
{
341 my ($master_name, $master_ip, $noreload) = @_;
344 File
::Path
::remove_tree
($syncdir, {keep_root
=> 1});
346 my $sa_conf_dir = "/etc/mail/spamassassin";
347 my $sa_custom_cf = "custom.cf";
349 my $cmd = $rsync_command->(
351 "${master_ip}:$cfgdir/* ${sa_conf_dir}/${sa_custom_cf}",
353 '--exclude', 'master/',
356 '--exclude', 'pmg-api.pem',
357 '--exclude', 'pmg-tls.pem',
360 my $errmsg = "syncing master configuration from '${master_ip}' failed";
361 PVE
::Tools
::run_command
($cmd, errmsg
=> $errmsg);
363 # verify that the remote host is cluster master
364 open (my $fh, '<', "$syncdir/cluster.conf") ||
365 die "unable to open synced cluster.conf - $!\n";
367 my $cinfo = PMG
::ClusterConfig
::read_cluster_conf
('cluster.conf', $fh);
369 if (!$cinfo->{master
} || ($cinfo->{master
}->{ip
} ne $master_ip)) {
370 die "host '$master_ip' is not cluster master\n";
373 my $role = $cinfo->{'local'}->{type
} // '-';
374 die "local node '$cinfo->{local}->{name}' not part of cluster\n"
377 die "local node '$cinfo->{local}->{name}' is new cluster master\n"
378 if $role eq 'master';
380 $cond_commit_synced_file->('cluster.conf');
382 update_ssh_keys
($cinfo); # rewrite ssh keys
384 PMG
::Fetchmail
::update_fetchmail_default
(0); # disable on slave
399 foreach my $filename (@$files) {
400 $cond_commit_synced_file->($filename);
404 my $force_restart = {};
406 if ($cond_commit_synced_file->($sa_custom_cf, "${sa_conf_dir}/${sa_custom_cf}")) {
407 $force_restart->{spam
} = 1;
410 $cond_commit_synced_file->('pmg.conf');
412 # sync user templates files/symlinks (not recursive)
413 my $srcdir = "$syncdir/templates";
415 my $dstdir = "$cfgdir/templates";
418 foreach my $fn (<$srcdir/*>) {
419 next if $fn !~ m
|^($srcdir/(.*))$|;
422 $names_hash->{$name} = 1;
423 my $target = "$dstdir/$name";
425 $cond_commit_synced_file->("templates/$name", $target);
427 warn "update $target failed - $!\n" if !rename($fn, $target);
430 # remove vanished files
431 foreach my $fn (<$dstdir/*>) {
432 next if $fn !~ m
|^($dstdir/(.*))$|;
435 next if $names_hash->{$name};
436 warn "unlink $fn failed - $!\n" if !unlink($fn);
441 sub sync_ruledb_from_master
{
442 my ($ldb, $rdb, $ni, $ticket) = @_;
444 my $ruledb = PMG
::RuleDB-
>new($ldb);
445 my $rulecache = PMG
::RuleCache-
>new($ruledb);
447 my $conn = PVE
::APIClient
::LWP-
>new(
449 cookie_name
=> 'PMGAuthCookie',
451 cached_fingerprints
=> {
452 $ni->{fingerprint
} => 1,
455 my $digest = $conn->get("/config/ruledb/digest", {});
457 return if $digest eq $rulecache->{digest
}; # no changes
459 syslog
('info', "detected rule database changes - starting sync from '$ni->{ip}'");
464 $ldb->do("DELETE FROM Rule");
465 $ldb->do("DELETE FROM RuleGroup");
466 $ldb->do("DELETE FROM ObjectGroup");
467 $ldb->do("DELETE FROM Object");
468 $ldb->do("DELETE FROM Attribut");
473 # read a consistent snapshot
474 $rdb->do("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
476 PMG
::DBTools
::copy_table
($ldb, $rdb, "Rule");
477 PMG
::DBTools
::copy_table
($ldb, $rdb, "RuleGroup");
478 PMG
::DBTools
::copy_table
($ldb, $rdb, "ObjectGroup");
479 PMG
::DBTools
::copy_table
($ldb, $rdb, "Object", 'value');
480 PMG
::DBTools
::copy_table
($ldb, $rdb, "Attribut", 'value');
483 $rdb->rollback; # end transaction
489 $ldb->do("SELECT setval('rule_id_seq', max(id)+1) FROM Rule");
490 $ldb->do("SELECT setval('object_id_seq', max(id)+1) FROM Object");
491 $ldb->do("SELECT setval('objectgroup_id_seq', max(id)+1) FROM ObjectGroup");
500 syslog
('info', "finished rule database sync from host '$ni->{ip}'");
503 sub sync_quarantine_db
{
504 my ($ldb, $rdb, $ni, $rsynctime_ref) = @_;
506 my $rcid = $ni->{cid
};
508 my $maxmails = 100000;
512 my $ctime = PMG
::DBTools
::get_remote_time
($rdb);
518 PMG
::DBTools
::create_clusterinfo_default
($ldb, $rcid, 'lastid_CMailStore', -1, undef);
520 do { # get new values
524 my $flistname = "/tmp/quarantinefilelist.$$";
529 open(my $flistfh, '>', $flistname) ||
530 die "unable to open file '$flistname' - $!\n";
532 my $lastid = PMG
::DBTools
::read_int_clusterinfo
($ldb, $rcid, 'lastid_CMailStore');
536 my $sth = $rdb->prepare(
537 "SELECT * from CMailstore WHERE cid = ? AND rid > ? " .
538 "ORDER BY cid,rid LIMIT ?");
539 $sth->execute($rcid, $lastid, $maxcount);
544 $maxid = $ref->{rid
};
545 print $flistfh "$ref->{file}\n";
548 my $attrs = [qw(cid rid time qtype bytes spamlevel info sender header file)];
549 $count += PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CMailStore', $attrs, $callback);
553 my $starttime = [ gettimeofday
() ];
554 sync_quarantine_files
($ni->{ip
}, $ni->{name
}, $flistname);
555 $$rsynctime_ref += tv_interval
($starttime);
560 $sth = $rdb->prepare(
561 "SELECT * from CMSReceivers WHERE " .
562 "CMailStore_CID = ? AND CMailStore_RID > ? " .
563 "AND CMailStore_RID <= ?");
564 $sth->execute($rcid, $lastid, $maxid);
566 $attrs = [qw(cmailstore_cid cmailstore_rid pmail receiver ticketid status mtime)];
567 PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CMSReceivers', $attrs);
569 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $rcid, 'lastid_CMailStore', $maxid);
585 last if $mscount >= $maxmails;
587 } while ($count >= $maxcount);
589 PMG
::DBTools
::create_clusterinfo_default
($ldb, $rcid, 'lastmt_CMSReceivers', 0, undef);
591 eval { # synchronize status updates
594 my $lastmt = PMG
::DBTools
::read_int_clusterinfo
($ldb, $rcid, 'lastmt_CMSReceivers');
596 my $sth = $rdb->prepare ("SELECT * from CMSReceivers WHERE mtime >= ? AND status != 'N'");
597 $sth->execute($lastmt);
599 my $update_sth = $ldb->prepare(
600 "UPDATE CMSReceivers SET status = ? WHERE " .
601 "CMailstore_CID = ? AND CMailstore_RID = ? AND TicketID = ?");
602 while (my $ref = $sth->fetchrow_hashref()) {
603 $update_sth->execute($ref->{status
}, $ref->{cmailstore_cid
},
604 $ref->{cmailstore_rid
}, $ref->{ticketid
});
607 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $rcid, 'lastmt_CMSReceivers', $ctime);
619 sub sync_statistic_db
{
620 my ($ldb, $rdb, $ni) = @_;
622 my $rcid = $ni->{cid
};
624 my $maxmails = 100000;
632 PMG
::DBTools
::create_clusterinfo_default
(
633 $ldb, $rcid, 'lastid_CStatistic', -1, undef);
635 do { # get new values
642 my $lastid = PMG
::DBTools
::read_int_clusterinfo
(
643 $ldb, $rcid, 'lastid_CStatistic');
647 my $sth = $rdb->prepare(
648 "SELECT * from CStatistic " .
649 "WHERE cid = ? AND rid > ? " .
650 "ORDER BY cid, rid LIMIT ?");
651 $sth->execute($rcid, $lastid, $maxcount);
656 $maxid = $ref->{rid
};
659 my $attrs = [qw(cid rid time bytes direction spamlevel ptime virusinfo sender)];
660 $count += PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CStatistic', $attrs, $callback);
665 $sth = $rdb->prepare(
666 "SELECT * from CReceivers WHERE " .
667 "CStatistic_CID = ? AND CStatistic_RID > ? AND CStatistic_RID <= ?");
668 $sth->execute($rcid, $lastid, $maxid);
670 $attrs = [qw(cstatistic_cid cstatistic_rid blocked receiver)];
671 PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CReceivers', $attrs);
673 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $rcid, 'lastid_CStatistic', $maxid);
685 last if $mscount >= $maxmails;
687 } while ($count >= $maxcount);
692 my $sync_generic_mtime_db = sub {
693 my ($ldb, $rdb, $ni, $table, $selectfunc, $mergefunc) = @_;
695 my $ctime = PMG
::DBTools
::get_remote_time
($rdb);
697 PMG
::DBTools
::create_clusterinfo_default
($ldb, $ni->{cid
}, "lastmt_$table", 0, undef);
699 my $lastmt = PMG
::DBTools
::read_int_clusterinfo
($ldb, $ni->{cid
}, "lastmt_$table");
701 my $sql_cmd = $selectfunc->($ctime, $lastmt);
703 my $sth = $rdb->prepare($sql_cmd);
710 # use transaction to speedup things
711 my $max = 1000; # UPDATE MAX ENTRIES AT ONCE
713 while (my $ref = $sth->fetchrow_hashref()) {
714 $ldb->begin_work if !$count;
716 if (++$count >= $max) {
723 $ldb->commit if $count;
730 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $ni->{cid
}, "lastmt_$table", $ctime);
735 sub sync_localstat_db
{
736 my ($dbh, $rdb, $ni) = @_;
738 my $rcid = $ni->{cid
};
740 my $selectfunc = sub {
741 my ($ctime, $lastmt) = @_;
742 return "SELECT * from LocalStat WHERE mtime >= $lastmt AND cid = $rcid";
745 my $merge_sth = $dbh->prepare(
746 'INSERT INTO LocalStat (Time, RBLCount, PregreetCount, CID, MTime) ' .
747 'VALUES (?, ?, ?, ?, ?) ' .
748 'ON CONFLICT (Time, CID) DO UPDATE SET ' .
749 'RBLCount = excluded.RBLCount, PregreetCount = excluded.PregreetCount, MTime = excluded.MTime');
751 my $mergefunc = sub {
754 $merge_sth->execute($ref->{time}, $ref->{rblcount
}, $ref->{pregreetcount
}, $ref->{cid
}, $ref->{mtime
});
757 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'LocalStat', $selectfunc, $mergefunc);
760 sub sync_greylist_db
{
761 my ($dbh, $rdb, $ni) = @_;
763 my $selectfunc = sub {
764 my ($ctime, $lastmt) = @_;
765 return "SELECT * from CGreylist WHERE extime >= $ctime AND " .
766 "mtime >= $lastmt AND CID != 0";
769 my $merge_sth = $dbh->prepare($PMG::DBTools
::cgreylist_merge_sql
);
770 my $mergefunc = sub {
774 $ref->{ipnet
}, $ref->{host
}, $ref->{sender
}, $ref->{receiver
},
775 $ref->{instance
}, $ref->{rctime
}, $ref->{extime
}, $ref->{delay
},
776 $ref->{blocked
}, $ref->{passed
}, 0, $ref->{cid
});
779 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'CGreylist', $selectfunc, $mergefunc);
782 sub sync_userprefs_db
{
783 my ($dbh, $rdb, $ni) = @_;
785 my $selectfunc = sub {
786 my ($ctime, $lastmt) = @_;
788 return "SELECT * from UserPrefs WHERE mtime >= $lastmt";
791 my $merge_sth = $dbh->prepare(
792 "INSERT INTO UserPrefs (PMail, Name, Data, MTime) " .
793 'VALUES (?, ?, ?, 0) ' .
794 'ON CONFLICT (PMail, Name) DO UPDATE SET ' .
795 # Note: MTime = 0 ==> this is just a copy from somewhere else, not modified
796 'MTime = CASE WHEN excluded.MTime >= UserPrefs.MTime THEN 0 ELSE UserPrefs.MTime END, ' .
797 'Data = CASE WHEN excluded.MTime >= UserPrefs.MTime THEN excluded.Data ELSE UserPrefs.Data END');
799 my $mergefunc = sub {
802 $merge_sth->execute($ref->{pmail
}, $ref->{name
}, $ref->{data
});
805 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'UserPrefs', $selectfunc, $mergefunc);
808 sub sync_domainstat_db
{
809 my ($dbh, $rdb, $ni) = @_;
811 my $selectfunc = sub {
812 my ($ctime, $lastmt) = @_;
813 return "SELECT * from DomainStat WHERE mtime >= $lastmt";
816 my $merge_sth = $dbh->prepare(
817 'INSERT INTO Domainstat ' .
818 '(Time,Domain,CountIn,CountOut,BytesIn,BytesOut,VirusIn,VirusOut,SpamIn,SpamOut,' .
819 'BouncesIn,BouncesOut,PTimeSum,Mtime) ' .
820 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' .
821 'ON CONFLICT (Time, Domain) DO UPDATE SET ' .
822 'CountIn = excluded.CountIn, CountOut = excluded.CountOut, ' .
823 'BytesIn = excluded.BytesIn, BytesOut = excluded.BytesOut, ' .
824 'VirusIn = excluded.VirusIn, VirusOut = excluded.VirusOut, ' .
825 'SpamIn = excluded.SpamIn, SpamOut = excluded.SpamOut, ' .
826 'BouncesIn = excluded.BouncesIn, BouncesOut = excluded.BouncesOut, ' .
827 'PTimeSum = excluded.PTimeSum, MTime = excluded.MTime');
829 my $mergefunc = sub {
833 $ref->{time}, $ref->{domain
}, $ref->{countin
}, $ref->{countout
},
834 $ref->{bytesin
}, $ref->{bytesout
},
835 $ref->{virusin
}, $ref->{virusout
}, $ref->{spamin
}, $ref->{spamout
},
836 $ref->{bouncesin
}, $ref->{bouncesout
}, $ref->{ptimesum
}, $ref->{mtime
});
839 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'DomainStat', $selectfunc, $mergefunc);
842 sub sync_dailystat_db
{
843 my ($dbh, $rdb, $ni) = @_;
845 my $selectfunc = sub {
846 my ($ctime, $lastmt) = @_;
847 return "SELECT * from DailyStat WHERE mtime >= $lastmt";
850 my $merge_sth = $dbh->prepare(
851 'INSERT INTO DailyStat ' .
852 '(Time,CountIn,CountOut,BytesIn,BytesOut,VirusIn,VirusOut,SpamIn,SpamOut,' .
853 'BouncesIn,BouncesOut,GreylistCount,SPFCount,RBLCount,PTimeSum,Mtime) ' .
854 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' .
855 'ON CONFLICT (Time) DO UPDATE SET ' .
856 'CountIn = excluded.CountIn, CountOut = excluded.CountOut, ' .
857 'BytesIn = excluded.BytesIn, BytesOut = excluded.BytesOut, ' .
858 'VirusIn = excluded.VirusIn, VirusOut = excluded.VirusOut, ' .
859 'SpamIn = excluded.SpamIn, SpamOut = excluded.SpamOut, ' .
860 'BouncesIn = excluded.BouncesIn, BouncesOut = excluded.BouncesOut, ' .
861 'GreylistCount = excluded.GreylistCount, SPFCount = excluded.SpfCount, ' .
862 'RBLCount = excluded.RBLCount, ' .
863 'PTimeSum = excluded.PTimeSum, MTime = excluded.MTime');
865 my $mergefunc = sub {
869 $ref->{time}, $ref->{countin
}, $ref->{countout
},
870 $ref->{bytesin
}, $ref->{bytesout
},
871 $ref->{virusin
}, $ref->{virusout
}, $ref->{spamin
}, $ref->{spamout
},
872 $ref->{bouncesin
}, $ref->{bouncesout
}, $ref->{greylistcount
},
873 $ref->{spfcount
}, $ref->{rblcount
}, $ref->{ptimesum
}, $ref->{mtime
});
876 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'DailyStat', $selectfunc, $mergefunc);
879 sub sync_virusinfo_db
{
880 my ($dbh, $rdb, $ni) = @_;
882 my $selectfunc = sub {
883 my ($ctime, $lastmt) = @_;
884 return "SELECT * from VirusInfo WHERE mtime >= $lastmt";
887 my $merge_sth = $dbh->prepare(
888 'INSERT INTO VirusInfo (Time,Name,Count,MTime) ' .
889 'VALUES (?,?,?,?) ' .
890 'ON CONFLICT (Time,Name) DO UPDATE SET ' .
891 'Count = excluded.Count , MTime = excluded.MTime');
893 my $mergefunc = sub {
896 $merge_sth->execute($ref->{time}, $ref->{name
}, $ref->{count
}, $ref->{mtime
});
899 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'VirusInfo', $selectfunc, $mergefunc);
902 sub sync_deleted_nodes_from_master
{
903 my ($ldb, $masterdb, $cinfo, $masterni, $rsynctime_ref) = @_;
907 my $cid_hash = {}; # fast lookup
908 foreach my $ni (values %{$cinfo->{ids
}}) {
909 $cid_hash->{$ni->{cid
}} = $ni;
912 my $spooldir = $PMG::MailQueue
::spooldir
;
914 my $maxcid = $cinfo->{master
}->{maxcid
} // 0;
916 for (my $rcid = 1; $rcid <= $maxcid; $rcid++) {
917 next if $cid_hash->{$rcid};
919 my $done_marker = "$spooldir/cluster/$rcid/.synced-deleted-node";
921 next if -f
$done_marker; # already synced
923 syslog
('info', "syncing deleted node $rcid from master '$masterni->{ip}'");
925 my $starttime = [ gettimeofday
() ];
926 sync_spooldir
($masterni->{ip
}, $masterni->{name
}, $rcid);
927 $$rsynctime_ref += tv_interval
($starttime);
930 ip
=> $masterni->{ip
},
931 name
=> $masterni->{name
},
935 sync_quarantine_db
($ldb, $masterdb, $fake_ni);
937 sync_statistic_db
($ldb, $masterdb, $fake_ni);
939 open(my $fh, ">>", $done_marker);