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, $rcid) = @_;
296 my $spooldir = $PMG::MailQueue
::spooldir
;
298 mkdir "$spooldir/cluster/";
299 my $syncdir = "$spooldir/cluster/$rcid";
302 my $cmd = $rsync_command->(
303 $host_name, '--timeout', '10', "[${host_ip}]:$spooldir", $spooldir,
304 '--files-from', $flistname);
306 PVE
::Tools
::run_command
($cmd);
310 my ($host_ip, $host_name, $rcid) = @_;
312 my $spooldir = $PMG::MailQueue
::spooldir
;
314 mkdir "$spooldir/cluster/";
315 my $syncdir = "$spooldir/cluster/$rcid";
318 my $cmd = $rsync_command->(
319 $host_name, '-aq', '--timeout', '10', "[${host_ip}]:$syncdir/", $syncdir);
321 foreach my $incl (('spam/', 'spam/*', 'spam/*/*', 'virus/', 'virus/*', 'virus/*/*')) {
322 push @$cmd, '--include', $incl;
325 push @$cmd, '--exclude', '*';
327 PVE
::Tools
::run_command
($cmd);
330 sub sync_master_quar
{
331 my ($host_ip, $host_name) = @_;
333 my $spooldir = $PMG::MailQueue
::spooldir
;
335 my $syncdir = "$spooldir/cluster/";
338 my $cmd = $rsync_command->(
339 $host_name, '-aq', '--timeout', '10', "[${host_ip}]:$syncdir", $syncdir);
341 PVE
::Tools
::run_command
($cmd);
344 sub sync_config_from_master
{
345 my ($master_name, $master_ip, $noreload) = @_;
348 File
::Path
::remove_tree
($syncdir, {keep_root
=> 1});
350 my $sa_conf_dir = "/etc/mail/spamassassin";
351 my $sa_custom_cf = "custom.cf";
353 my $cmd = $rsync_command->(
355 "[${master_ip}]:$cfgdir/* ${sa_conf_dir}/${sa_custom_cf}",
357 '--exclude', 'master/',
360 '--exclude', 'pmg-api.pem',
361 '--exclude', 'pmg-tls.pem',
364 my $errmsg = "syncing master configuration from '${master_ip}' failed";
365 PVE
::Tools
::run_command
($cmd, errmsg
=> $errmsg);
367 # verify that the remote host is cluster master
368 open (my $fh, '<', "$syncdir/cluster.conf") ||
369 die "unable to open synced cluster.conf - $!\n";
371 my $cinfo = PMG
::ClusterConfig
::read_cluster_conf
('cluster.conf', $fh);
373 if (!$cinfo->{master
} || ($cinfo->{master
}->{ip
} ne $master_ip)) {
374 die "host '$master_ip' is not cluster master\n";
377 my $role = $cinfo->{'local'}->{type
} // '-';
378 die "local node '$cinfo->{local}->{name}' not part of cluster\n"
381 die "local node '$cinfo->{local}->{name}' is new cluster master\n"
382 if $role eq 'master';
384 $cond_commit_synced_file->('cluster.conf');
386 update_ssh_keys
($cinfo); # rewrite ssh keys
388 PMG
::Fetchmail
::update_fetchmail_default
(0); # disable on slave
403 foreach my $filename (@$files) {
404 $cond_commit_synced_file->($filename);
412 foreach my $dir (@$dirs) {
413 my $srcdir = "$syncdir/$dir";
416 my $cmd = ['rsync', '-aq', '--delete-after', "$srcdir/", "$cfgdir/$dir"];
417 PVE
::Tools
::run_command
($cmd);
422 my $force_restart = {};
424 if ($cond_commit_synced_file->($sa_custom_cf, "${sa_conf_dir}/${sa_custom_cf}")) {
425 $force_restart->{'pmg-smtp-filter'} = 1;
428 $cond_commit_synced_file->('pmg.conf');
430 return $force_restart;
433 sub sync_ruledb_from_master
{
434 my ($ldb, $rdb, $ni, $ticket) = @_;
436 my $ruledb = PMG
::RuleDB-
>new($ldb);
437 my $rulecache = PMG
::RuleCache-
>new($ruledb);
439 my $conn = PVE
::APIClient
::LWP-
>new(
441 cookie_name
=> 'PMGAuthCookie',
443 cached_fingerprints
=> {
444 $ni->{fingerprint
} => 1,
447 my $digest = $conn->get("/config/ruledb/digest", {});
449 return if $digest eq $rulecache->{digest
}; # no changes
451 syslog
('info', "detected rule database changes - starting sync from '$ni->{ip}'");
456 $ldb->do("DELETE FROM Rule");
457 $ldb->do("DELETE FROM RuleGroup");
458 $ldb->do("DELETE FROM ObjectGroup");
459 $ldb->do("DELETE FROM Object");
460 $ldb->do("DELETE FROM Attribut");
465 # read a consistent snapshot
466 $rdb->do("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
468 PMG
::DBTools
::copy_table
($ldb, $rdb, "Rule");
469 PMG
::DBTools
::copy_table
($ldb, $rdb, "RuleGroup");
470 PMG
::DBTools
::copy_table
($ldb, $rdb, "ObjectGroup");
471 PMG
::DBTools
::copy_table
($ldb, $rdb, "Object", 'value');
472 PMG
::DBTools
::copy_table
($ldb, $rdb, "Attribut", 'value');
475 $rdb->rollback; # end transaction
481 $ldb->do("SELECT setval('rule_id_seq', max(id)+1) FROM Rule");
482 $ldb->do("SELECT setval('object_id_seq', max(id)+1) FROM Object");
483 $ldb->do("SELECT setval('objectgroup_id_seq', max(id)+1) FROM ObjectGroup");
492 PMG
::DBTools
::reload_ruledb
();
494 syslog
('info', "finished rule database sync from host '$ni->{ip}'");
497 sub sync_quarantine_db
{
498 my ($ldb, $rdb, $ni, $rsynctime_ref) = @_;
500 my $rcid = $ni->{cid
};
502 my $maxmails = 100000;
506 my $ctime = PMG
::DBTools
::get_remote_time
($rdb);
512 PMG
::DBTools
::create_clusterinfo_default
($ldb, $rcid, 'lastid_CMailStore', -1, undef);
514 do { # get new values
518 my $flistname = "/tmp/quarantinefilelist.$$";
523 open(my $flistfh, '>', $flistname) ||
524 die "unable to open file '$flistname' - $!\n";
526 my $lastid = PMG
::DBTools
::read_int_clusterinfo
($ldb, $rcid, 'lastid_CMailStore');
530 my $sth = $rdb->prepare(
531 "SELECT * from CMailstore WHERE cid = ? AND rid > ? " .
532 "ORDER BY cid,rid LIMIT ?");
533 $sth->execute($rcid, $lastid, $maxcount);
538 $maxid = $ref->{rid
};
539 my $filename = $ref->{file
};
540 # skip files generated before cluster was created
541 return if $filename !~ m!^cluster/!;
542 print $flistfh "$filename\n";
545 my $attrs = [qw(cid rid time qtype bytes spamlevel info sender header file)];
546 $count += PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CMailStore', $attrs, $callback);
550 my $starttime = [ gettimeofday
() ];
551 sync_quarantine_files
($ni->{ip
}, $ni->{name
}, $flistname, $rcid);
552 $$rsynctime_ref += tv_interval
($starttime);
557 $sth = $rdb->prepare(
558 "SELECT * from CMSReceivers WHERE " .
559 "CMailStore_CID = ? AND CMailStore_RID > ? " .
560 "AND CMailStore_RID <= ?");
561 $sth->execute($rcid, $lastid, $maxid);
563 $attrs = [qw(cmailstore_cid cmailstore_rid pmail receiver ticketid status mtime)];
564 PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CMSReceivers', $attrs);
566 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $rcid, 'lastid_CMailStore', $maxid);
582 } while (($count >= $maxcount) && ($mscount < $maxmails));
584 PMG
::DBTools
::create_clusterinfo_default
($ldb, $rcid, 'lastmt_CMSReceivers', 0, undef);
586 eval { # synchronize status updates
589 my $lastmt = PMG
::DBTools
::read_int_clusterinfo
($ldb, $rcid, 'lastmt_CMSReceivers');
591 my $sth = $rdb->prepare ("SELECT * from CMSReceivers WHERE mtime >= ? AND status != 'N'");
592 $sth->execute($lastmt);
594 my $update_sth = $ldb->prepare(
595 "UPDATE CMSReceivers SET status = ? WHERE " .
596 "CMailstore_CID = ? AND CMailstore_RID = ? AND TicketID = ?");
597 while (my $ref = $sth->fetchrow_hashref()) {
598 $update_sth->execute($ref->{status
}, $ref->{cmailstore_cid
},
599 $ref->{cmailstore_rid
}, $ref->{ticketid
});
602 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $rcid, 'lastmt_CMSReceivers', $ctime);
614 sub sync_statistic_db
{
615 my ($ldb, $rdb, $ni) = @_;
617 my $rcid = $ni->{cid
};
619 my $maxmails = 100000;
627 PMG
::DBTools
::create_clusterinfo_default
(
628 $ldb, $rcid, 'lastid_CStatistic', -1, undef);
630 do { # get new values
637 my $lastid = PMG
::DBTools
::read_int_clusterinfo
(
638 $ldb, $rcid, 'lastid_CStatistic');
642 my $sth = $rdb->prepare(
643 "SELECT * from CStatistic " .
644 "WHERE cid = ? AND rid > ? " .
645 "ORDER BY cid, rid LIMIT ?");
646 $sth->execute($rcid, $lastid, $maxcount);
651 $maxid = $ref->{rid
};
654 my $attrs = [qw(cid rid time bytes direction spamlevel ptime virusinfo sender)];
655 $count += PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CStatistic', $attrs, $callback);
660 $sth = $rdb->prepare(
661 "SELECT * from CReceivers WHERE " .
662 "CStatistic_CID = ? AND CStatistic_RID > ? AND CStatistic_RID <= ?");
663 $sth->execute($rcid, $lastid, $maxid);
665 $attrs = [qw(cstatistic_cid cstatistic_rid blocked receiver)];
666 PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CReceivers', $attrs);
669 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $rcid, 'lastid_CStatistic', $maxid);
680 } while (($count >= $maxcount) && ($mscount < $maxmails));
685 my $sync_generic_mtime_db = sub {
686 my ($ldb, $rdb, $ni, $table, $selectfunc, $mergefunc) = @_;
688 my $ctime = PMG
::DBTools
::get_remote_time
($rdb);
690 PMG
::DBTools
::create_clusterinfo_default
($ldb, $ni->{cid
}, "lastmt_$table", 0, undef);
692 my $lastmt = PMG
::DBTools
::read_int_clusterinfo
($ldb, $ni->{cid
}, "lastmt_$table");
694 my $sql_cmd = $selectfunc->($ctime, $lastmt);
696 my $sth = $rdb->prepare($sql_cmd);
703 # use transaction to speedup things
704 my $max = 1000; # UPDATE MAX ENTRIES AT ONCE
706 while (my $ref = $sth->fetchrow_hashref()) {
707 $ldb->begin_work if !$count;
709 if (++$count >= $max) {
716 $ldb->commit if $count;
723 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $ni->{cid
}, "lastmt_$table", $ctime);
728 sub sync_localstat_db
{
729 my ($dbh, $rdb, $ni) = @_;
731 my $rcid = $ni->{cid
};
733 my $selectfunc = sub {
734 my ($ctime, $lastmt) = @_;
735 return "SELECT * from LocalStat WHERE mtime >= $lastmt AND cid = $rcid";
738 my $merge_sth = $dbh->prepare(
739 'INSERT INTO LocalStat (Time, RBLCount, PregreetCount, CID, MTime) ' .
740 'VALUES (?, ?, ?, ?, ?) ' .
741 'ON CONFLICT (Time, CID) DO UPDATE SET ' .
742 'RBLCount = excluded.RBLCount, PregreetCount = excluded.PregreetCount, MTime = excluded.MTime');
744 my $mergefunc = sub {
747 $merge_sth->execute($ref->{time}, $ref->{rblcount
}, $ref->{pregreetcount
}, $ref->{cid
}, $ref->{mtime
});
750 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'LocalStat', $selectfunc, $mergefunc);
753 sub sync_greylist_db
{
754 my ($dbh, $rdb, $ni) = @_;
756 my $selectfunc = sub {
757 my ($ctime, $lastmt) = @_;
758 return "SELECT * from CGreylist WHERE extime >= $ctime AND " .
759 "mtime >= $lastmt AND CID != 0";
762 my $merge_sth = $dbh->prepare($PMG::DBTools
::cgreylist_merge_sql
);
763 my $mergefunc = sub {
767 $ref->{ipnet
}, $ref->{host
}, $ref->{sender
}, $ref->{receiver
},
768 $ref->{instance
}, $ref->{rctime
}, $ref->{extime
}, $ref->{delay
},
769 $ref->{blocked
}, $ref->{passed
}, 0, $ref->{cid
});
772 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'CGreylist', $selectfunc, $mergefunc);
775 sub sync_userprefs_db
{
776 my ($dbh, $rdb, $ni) = @_;
778 my $selectfunc = sub {
779 my ($ctime, $lastmt) = @_;
781 return "SELECT * from UserPrefs WHERE mtime >= $lastmt";
784 my $merge_sth = $dbh->prepare(
785 "INSERT INTO UserPrefs (PMail, Name, Data, MTime) " .
786 'VALUES (?, ?, ?, ?) ' .
787 'ON CONFLICT (PMail, Name) DO UPDATE SET ' .
788 # Note: MTime = 0 ==> this is just a copy from somewhere else, not modified
789 'MTime = CASE WHEN excluded.MTime >= UserPrefs.MTime THEN 0 ELSE UserPrefs.MTime END, ' .
790 'Data = CASE WHEN excluded.MTime >= UserPrefs.MTime THEN excluded.Data ELSE UserPrefs.Data END');
792 my $mergefunc = sub {
795 $merge_sth->execute($ref->{pmail
}, $ref->{name
}, $ref->{data
}, $ref->{mtime
});
798 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'UserPrefs', $selectfunc, $mergefunc);
801 sub sync_domainstat_db
{
802 my ($dbh, $rdb, $ni) = @_;
804 my $selectfunc = sub {
805 my ($ctime, $lastmt) = @_;
806 return "SELECT * from DomainStat WHERE mtime >= $lastmt";
809 my $merge_sth = $dbh->prepare(
810 'INSERT INTO Domainstat ' .
811 '(Time,Domain,CountIn,CountOut,BytesIn,BytesOut,VirusIn,VirusOut,SpamIn,SpamOut,' .
812 'BouncesIn,BouncesOut,PTimeSum,Mtime) ' .
813 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' .
814 'ON CONFLICT (Time, Domain) DO UPDATE SET ' .
815 'CountIn = excluded.CountIn, CountOut = excluded.CountOut, ' .
816 'BytesIn = excluded.BytesIn, BytesOut = excluded.BytesOut, ' .
817 'VirusIn = excluded.VirusIn, VirusOut = excluded.VirusOut, ' .
818 'SpamIn = excluded.SpamIn, SpamOut = excluded.SpamOut, ' .
819 'BouncesIn = excluded.BouncesIn, BouncesOut = excluded.BouncesOut, ' .
820 'PTimeSum = excluded.PTimeSum, MTime = excluded.MTime');
822 my $mergefunc = sub {
826 $ref->{time}, $ref->{domain
}, $ref->{countin
}, $ref->{countout
},
827 $ref->{bytesin
}, $ref->{bytesout
},
828 $ref->{virusin
}, $ref->{virusout
}, $ref->{spamin
}, $ref->{spamout
},
829 $ref->{bouncesin
}, $ref->{bouncesout
}, $ref->{ptimesum
}, $ref->{mtime
});
832 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'DomainStat', $selectfunc, $mergefunc);
835 sub sync_dailystat_db
{
836 my ($dbh, $rdb, $ni) = @_;
838 my $selectfunc = sub {
839 my ($ctime, $lastmt) = @_;
840 return "SELECT * from DailyStat WHERE mtime >= $lastmt";
843 my $merge_sth = $dbh->prepare(
844 'INSERT INTO DailyStat ' .
845 '(Time,CountIn,CountOut,BytesIn,BytesOut,VirusIn,VirusOut,SpamIn,SpamOut,' .
846 'BouncesIn,BouncesOut,GreylistCount,SPFCount,RBLCount,PTimeSum,Mtime) ' .
847 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' .
848 'ON CONFLICT (Time) DO UPDATE SET ' .
849 'CountIn = excluded.CountIn, CountOut = excluded.CountOut, ' .
850 'BytesIn = excluded.BytesIn, BytesOut = excluded.BytesOut, ' .
851 'VirusIn = excluded.VirusIn, VirusOut = excluded.VirusOut, ' .
852 'SpamIn = excluded.SpamIn, SpamOut = excluded.SpamOut, ' .
853 'BouncesIn = excluded.BouncesIn, BouncesOut = excluded.BouncesOut, ' .
854 'GreylistCount = excluded.GreylistCount, SPFCount = excluded.SpfCount, ' .
855 'RBLCount = excluded.RBLCount, ' .
856 'PTimeSum = excluded.PTimeSum, MTime = excluded.MTime');
858 my $mergefunc = sub {
862 $ref->{time}, $ref->{countin
}, $ref->{countout
},
863 $ref->{bytesin
}, $ref->{bytesout
},
864 $ref->{virusin
}, $ref->{virusout
}, $ref->{spamin
}, $ref->{spamout
},
865 $ref->{bouncesin
}, $ref->{bouncesout
}, $ref->{greylistcount
},
866 $ref->{spfcount
}, $ref->{rblcount
}, $ref->{ptimesum
}, $ref->{mtime
});
869 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'DailyStat', $selectfunc, $mergefunc);
872 sub sync_virusinfo_db
{
873 my ($dbh, $rdb, $ni) = @_;
875 my $selectfunc = sub {
876 my ($ctime, $lastmt) = @_;
877 return "SELECT * from VirusInfo WHERE mtime >= $lastmt";
880 my $merge_sth = $dbh->prepare(
881 'INSERT INTO VirusInfo (Time,Name,Count,MTime) ' .
882 'VALUES (?,?,?,?) ' .
883 'ON CONFLICT (Time,Name) DO UPDATE SET ' .
884 'Count = excluded.Count , MTime = excluded.MTime');
886 my $mergefunc = sub {
889 $merge_sth->execute($ref->{time}, $ref->{name
}, $ref->{count
}, $ref->{mtime
});
892 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'VirusInfo', $selectfunc, $mergefunc);
895 sub sync_deleted_nodes_from_master
{
896 my ($ldb, $masterdb, $cinfo, $masterni, $rsynctime_ref) = @_;
900 my $cid_hash = {}; # fast lookup
901 foreach my $ni (values %{$cinfo->{ids
}}) {
902 $cid_hash->{$ni->{cid
}} = $ni;
905 my $spooldir = $PMG::MailQueue
::spooldir
;
907 my $maxcid = $cinfo->{master
}->{maxcid
} // 0;
909 for (my $rcid = 1; $rcid <= $maxcid; $rcid++) {
910 next if $cid_hash->{$rcid};
912 my $done_marker = "$spooldir/cluster/$rcid/.synced-deleted-node";
914 next if -f
$done_marker; # already synced
916 syslog
('info', "syncing deleted node $rcid from master '$masterni->{ip}'");
918 my $starttime = [ gettimeofday
() ];
919 sync_spooldir
($masterni->{ip
}, $masterni->{name
}, $rcid);
920 $$rsynctime_ref += tv_interval
($starttime);
923 ip
=> $masterni->{ip
},
924 name
=> $masterni->{name
},
928 sync_quarantine_db
($ldb, $masterdb, $fake_ni);
930 sync_statistic_db
($ldb, $masterdb, $fake_ni);
932 open(my $fh, ">>", $done_marker);