8 use Time
::HiRes qw
(gettimeofday tv_interval
);
13 use PVE
::APIClient
::LWP
;
18 use PMG
::ClusterConfig
;
25 my ($nodename, $noerr) = @_;
27 my $cinfo = PMG
::ClusterConfig-
>new();
29 foreach my $entry (values %{$cinfo->{ids
}}) {
30 if ($entry->{name
} eq $nodename) {
31 my $ip = $entry->{ip
};
32 return $ip if !wantarray;
33 my $family = PVE
::Tools
::get_host_address_family
($ip);
34 return ($ip, $family);
38 # fallback: try to get IP by other means
39 return PVE
::Network
::get_ip_from_hostname
($nodename, $noerr);
45 $cinfo = PMG
::ClusterConfig-
>new() if !$cinfo;
47 return $cinfo->{master
}->{name
} if defined($cinfo->{master
});
52 sub read_local_ssl_cert_fingerprint
{
53 my $cert_path = "/etc/pmg/pmg-api.pem";
57 my $bio = Net
::SSLeay
::BIO_new_file
($cert_path, 'r');
58 $cert = Net
::SSLeay
::PEM_read_bio_X509
($bio);
59 Net
::SSLeay
::BIO_free
($bio);
62 die "unable to read certificate '$cert_path' - $err\n";
65 if (!defined($cert)) {
66 die "unable to read certificate '$cert_path' - got empty value\n";
71 $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
74 die "unable to get fingerprint for '$cert_path' - $err\n";
77 if (!defined($fp) || $fp eq '') {
78 die "unable to get fingerprint for '$cert_path' - got empty value\n";
84 my $hostrsapubkey_fn = '/etc/ssh/ssh_host_rsa_key.pub';
85 my $rootrsakey_fn = '/root/.ssh/id_rsa';
86 my $rootrsapubkey_fn = '/root/.ssh/id_rsa.pub';
88 sub read_local_cluster_info
{
92 my $hostrsapubkey = PVE
::Tools
::file_read_firstline
($hostrsapubkey_fn);
93 $hostrsapubkey =~ s/^.*ssh-rsa\s+//i;
94 $hostrsapubkey =~ s/\s+root\@\S+\s*$//i;
96 die "unable to parse ${hostrsapubkey_fn}\n"
97 if $hostrsapubkey !~ m/^[A-Za-z0-9\.\/\
+]{200,}$/;
99 my $nodename = PVE
::INotify
::nodename
();
101 $res->{name
} = $nodename;
103 $res->{ip
} = PVE
::Network
::get_ip_from_hostname
($nodename);
105 $res->{hostrsapubkey
} = $hostrsapubkey;
107 if (! -f
$rootrsapubkey_fn) {
108 unlink $rootrsakey_fn;
109 my $cmd = ['ssh-keygen', '-t', 'rsa', '-N', '', '-b', '2048',
110 '-f', $rootrsakey_fn];
111 PMG
::Utils
::run_silent_cmd
($cmd);
114 my $rootrsapubkey = PVE
::Tools
::file_read_firstline
($rootrsapubkey_fn);
115 $rootrsapubkey =~ s/^.*ssh-rsa\s+//i;
116 $rootrsapubkey =~ s/\s+root\@\S+\s*$//i;
118 die "unable to parse ${rootrsapubkey_fn}\n"
119 if $rootrsapubkey !~ m/^[A-Za-z0-9\.\/\
+]{200,}$/;
121 $res->{rootrsapubkey
} = $rootrsapubkey;
123 $res->{fingerprint
} = read_local_ssl_cert_fingerprint
();
128 # X509 Certificate cache helper
130 my $cert_cache_nodes = {};
131 my $cert_cache_timestamp = time();
132 my $cert_cache_fingerprints = {};
134 sub update_cert_cache
{
136 $cert_cache_timestamp = time();
138 $cert_cache_fingerprints = {};
139 $cert_cache_nodes = {};
141 my $cinfo = PMG
::ClusterConfig-
>new();
143 foreach my $entry (values %{$cinfo->{ids
}}) {
144 my $node = $entry->{name
};
145 my $fp = $entry->{fingerprint
};
147 $cert_cache_fingerprints->{$fp} = 1;
148 $cert_cache_nodes->{$node} = $fp;
153 # load and cache cert fingerprint once
154 sub initialize_cert_cache
{
158 if defined($node) && !defined($cert_cache_nodes->{$node});
161 sub check_cert_fingerprint
{
164 # clear cache every 30 minutes at least
165 update_cert_cache
() if time() - $cert_cache_timestamp >= 60*30;
167 # get fingerprint of server certificate
170 $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
172 return 0 if $@ || !defined($fp) || $fp eq ''; # error
175 for my $expected (keys %$cert_cache_fingerprints) {
176 return 1 if $fp eq $expected;
181 return 1 if $check->();
183 # clear cache and retry at most once every minute
184 if (time() - $cert_cache_timestamp >= 60) {
185 syslog
('info', "Could not verify remote node certificate '$fp' with list of pinned certificates, refreshing cache");
193 my $sshglobalknownhosts = "/etc/ssh/ssh_known_hosts2";
194 my $rootsshauthkeys = "/root/.ssh/authorized_keys";
195 my $ssh_rsa_id = "/root/.ssh/id_rsa.pub";
197 sub update_ssh_keys
{
203 foreach my $node (values %{$cinfo->{ids
}}) {
204 $data .= "$node->{ip} ssh-rsa $node->{hostrsapubkey}\n";
205 $data .= "$node->{name} ssh-rsa $node->{hostrsapubkey}\n";
208 $old = PVE
::Tools
::file_get_contents
($sshglobalknownhosts, 1024*1024)
209 if -f
$sshglobalknownhosts;
211 PVE
::Tools
::file_set_contents
($sshglobalknownhosts, $data)
218 if (-f
$ssh_rsa_id) {
219 my $pub = PVE
::Tools
::file_get_contents
($ssh_rsa_id);
224 foreach my $node (values %{$cinfo->{ids
}}) {
225 $data .= "ssh-rsa $node->{rootrsapubkey} root\@$node->{name}\n";
228 if (-f
$rootsshauthkeys) {
229 my $mykey = PVE
::Tools
::file_get_contents
($rootsshauthkeys, 128*1024);
236 my @lines = split(/\n/, $data);
237 foreach my $line (@lines) {
238 if ($line !~ /^#/ && $line =~ m/(^|\s)ssh-(rsa|dsa)\s+(\S+)\s+\S+$/) {
239 next if $vhash->{$3}++;
241 $newdata .= "$line\n";
244 $old = PVE
::Tools
::file_get_contents
($rootsshauthkeys, 1024*1024)
245 if -f
$rootsshauthkeys;
247 PVE
::Tools
::file_set_contents
($rootsshauthkeys, $newdata, 0600)
251 my $cfgdir = '/etc/pmg';
252 my $syncdir = "$cfgdir/master";
254 my $cond_commit_synced_file = sub {
255 my ($filename, $dstfn) = @_;
257 $dstfn = "$cfgdir/$filename" if !defined($dstfn);
258 my $srcfn = "$syncdir/$filename";
265 my $new = PVE
::Tools
::file_get_contents
($srcfn, 1024*1024);
268 my $old = PVE
::Tools
::file_get_contents
($dstfn, 1024*1024);
269 return 0 if $new eq $old;
272 # set mtime (touch) to avoid time drift problems
273 utime(undef, undef, $srcfn);
275 rename($srcfn, $dstfn) ||
276 die "cond_rename_file '$filename' failed - $!\n";
278 print STDERR
"updated $dstfn\n";
283 my $rsync_command = sub {
284 my ($host_key_alias, @args) = @_;
286 my $ssh_cmd = '--rsh=ssh -l root -o BatchMode=yes';
287 $ssh_cmd .= " -o HostKeyAlias=${host_key_alias}" if $host_key_alias;
289 my $cmd = ['rsync', $ssh_cmd, '-q', @args];
294 sub sync_quarantine_files
{
295 my ($host_ip, $host_name, $flistname, $rcid) = @_;
297 my $spooldir = $PMG::MailQueue
::spooldir
;
299 mkdir "$spooldir/cluster/";
300 my $syncdir = "$spooldir/cluster/$rcid";
303 my $cmd = $rsync_command->(
304 $host_name, '--timeout', '10', "[${host_ip}]:$spooldir", $spooldir,
305 '--files-from', $flistname);
307 PVE
::Tools
::run_command
($cmd);
311 my ($host_ip, $host_name, $rcid) = @_;
313 my $spooldir = $PMG::MailQueue
::spooldir
;
315 mkdir "$spooldir/cluster/";
316 my $syncdir = "$spooldir/cluster/$rcid";
319 my $cmd = $rsync_command->(
320 $host_name, '-aq', '--timeout', '10', "[${host_ip}]:$syncdir/", $syncdir);
322 foreach my $incl (('spam/', 'spam/*', 'spam/*/*', 'virus/', 'virus/*', 'virus/*/*')) {
323 push @$cmd, '--include', $incl;
326 push @$cmd, '--exclude', '*';
328 PVE
::Tools
::run_command
($cmd);
331 sub sync_master_quar
{
332 my ($host_ip, $host_name) = @_;
334 my $spooldir = $PMG::MailQueue
::spooldir
;
336 my $syncdir = "$spooldir/cluster/";
339 my $cmd = $rsync_command->(
340 $host_name, '-aq', '--timeout', '10', "[${host_ip}]:$syncdir", $syncdir);
342 PVE
::Tools
::run_command
($cmd);
345 sub sync_config_from_master
{
346 my ($master_name, $master_ip, $noreload) = @_;
349 File
::Path
::remove_tree
($syncdir, {keep_root
=> 1});
351 my $sa_conf_dir = "/etc/mail/spamassassin";
352 my $sa_custom_cf = "custom.cf";
353 my $sa_rules_cf = "pmg-scores.cf";
355 my $cmd = $rsync_command->(
357 "[${master_ip}]:$cfgdir/* ${sa_conf_dir}/${sa_custom_cf} ${sa_conf_dir}/${sa_rules_cf}",
359 '--exclude', 'master/',
362 '--exclude', 'pmg-api.pem',
363 '--exclude', 'pmg-tls.pem',
366 my $errmsg = "syncing master configuration from '${master_ip}' failed";
367 PVE
::Tools
::run_command
($cmd, errmsg
=> $errmsg);
369 # verify that the remote host is cluster master
370 open (my $fh, '<', "$syncdir/cluster.conf") ||
371 die "unable to open synced cluster.conf - $!\n";
373 my $cinfo = PMG
::ClusterConfig
::read_cluster_conf
('cluster.conf', $fh);
375 if (!$cinfo->{master
} || ($cinfo->{master
}->{ip
} ne $master_ip)) {
376 die "host '$master_ip' is not cluster master\n";
379 my $role = $cinfo->{'local'}->{type
} // '-';
380 die "local node '$cinfo->{local}->{name}' not part of cluster\n"
383 die "local node '$cinfo->{local}->{name}' is new cluster master\n"
384 if $role eq 'master';
386 $cond_commit_synced_file->('cluster.conf');
388 update_ssh_keys
($cinfo); # rewrite ssh keys
390 PMG
::Fetchmail
::update_fetchmail_default
(0); # disable on slave
405 foreach my $filename (@$files) {
406 $cond_commit_synced_file->($filename);
414 foreach my $dir (@$dirs) {
415 my $srcdir = "$syncdir/$dir";
418 my $cmd = ['rsync', '-aq', '--delete-after', "$srcdir/", "$cfgdir/$dir"];
419 PVE
::Tools
::run_command
($cmd);
424 my $force_restart = {};
426 for my $file (($sa_custom_cf, $sa_rules_cf)) {
427 if ($cond_commit_synced_file->($file, "${sa_conf_dir}/${file}")) {
428 $force_restart->{'pmg-smtp-filter'} = 1;
432 $cond_commit_synced_file->('pmg.conf');
434 return $force_restart;
437 sub sync_ruledb_from_master
{
438 my ($ldb, $rdb, $ni, $ticket) = @_;
440 my $ruledb = PMG
::RuleDB-
>new($ldb);
441 my $rulecache = PMG
::RuleCache-
>new($ruledb);
443 my $conn = PVE
::APIClient
::LWP-
>new(
445 cookie_name
=> 'PMGAuthCookie',
447 cached_fingerprints
=> {
448 $ni->{fingerprint
} => 1,
451 my $digest = $conn->get("/config/ruledb/digest", {});
453 return if $digest eq $rulecache->{digest
}; # no changes
455 syslog
('info', "detected rule database changes - starting sync from '$ni->{ip}'");
460 $ldb->do("DELETE FROM Rule");
461 $ldb->do("DELETE FROM RuleGroup");
462 $ldb->do("DELETE FROM ObjectGroup");
463 $ldb->do("DELETE FROM Object");
464 $ldb->do("DELETE FROM Attribut");
469 # read a consistent snapshot
470 $rdb->do("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
472 PMG
::DBTools
::copy_table
($ldb, $rdb, "Rule");
473 PMG
::DBTools
::copy_table
($ldb, $rdb, "RuleGroup");
474 PMG
::DBTools
::copy_table
($ldb, $rdb, "ObjectGroup");
475 PMG
::DBTools
::copy_table
($ldb, $rdb, "Object", 'value');
476 PMG
::DBTools
::copy_table
($ldb, $rdb, "Attribut", 'value');
479 $rdb->rollback; # end transaction
485 $ldb->do("SELECT setval('rule_id_seq', max(id)+1) FROM Rule");
486 $ldb->do("SELECT setval('object_id_seq', max(id)+1) FROM Object");
487 $ldb->do("SELECT setval('objectgroup_id_seq', max(id)+1) FROM ObjectGroup");
496 PMG
::DBTools
::reload_ruledb
();
498 syslog
('info', "finished rule database sync from host '$ni->{ip}'");
501 sub sync_quarantine_db
{
502 my ($ldb, $rdb, $ni, $rsynctime_ref) = @_;
504 my $rcid = $ni->{cid
};
506 my $maxmails = 100000;
510 my $ctime = PMG
::DBTools
::get_remote_time
($rdb);
516 PMG
::DBTools
::create_clusterinfo_default
($ldb, $rcid, 'lastid_CMailStore', -1, undef);
518 do { # get new values
522 my $flistname = "/tmp/quarantinefilelist.$$";
527 open(my $flistfh, '>', $flistname) ||
528 die "unable to open file '$flistname' - $!\n";
530 my $lastid = PMG
::DBTools
::read_int_clusterinfo
($ldb, $rcid, 'lastid_CMailStore');
534 my $sth = $rdb->prepare(
535 "SELECT * from CMailstore WHERE cid = ? AND rid > ? " .
536 "ORDER BY cid,rid LIMIT ?");
537 $sth->execute($rcid, $lastid, $maxcount);
542 $maxid = $ref->{rid
};
543 my $filename = $ref->{file
};
544 # skip files generated before cluster was created
545 return if $filename !~ m!^cluster/!;
546 print $flistfh "$filename\n";
549 my $attrs = [qw(cid rid time qtype bytes spamlevel info sender header file)];
550 $count += PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CMailStore', $attrs, $callback);
554 my $starttime = [ gettimeofday
() ];
555 sync_quarantine_files
($ni->{ip
}, $ni->{name
}, $flistname, $rcid);
556 $$rsynctime_ref += tv_interval
($starttime);
561 $sth = $rdb->prepare(
562 "SELECT * from CMSReceivers WHERE " .
563 "CMailStore_CID = ? AND CMailStore_RID > ? " .
564 "AND CMailStore_RID <= ?");
565 $sth->execute($rcid, $lastid, $maxid);
567 $attrs = [qw(cmailstore_cid cmailstore_rid pmail receiver ticketid status mtime)];
568 PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CMSReceivers', $attrs);
570 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $rcid, 'lastid_CMailStore', $maxid);
586 } while (($count >= $maxcount) && ($mscount < $maxmails));
588 PMG
::DBTools
::create_clusterinfo_default
($ldb, $rcid, 'lastmt_CMSReceivers', 0, undef);
590 eval { # synchronize status updates
593 my $lastmt = PMG
::DBTools
::read_int_clusterinfo
($ldb, $rcid, 'lastmt_CMSReceivers');
595 my $sth = $rdb->prepare ("SELECT * from CMSReceivers WHERE mtime >= ? AND status != 'N'");
596 $sth->execute($lastmt);
598 my $update_sth = $ldb->prepare(
599 "UPDATE CMSReceivers SET status = ? WHERE " .
600 "CMailstore_CID = ? AND CMailstore_RID = ? AND TicketID = ?");
601 while (my $ref = $sth->fetchrow_hashref()) {
602 $update_sth->execute($ref->{status
}, $ref->{cmailstore_cid
},
603 $ref->{cmailstore_rid
}, $ref->{ticketid
});
606 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $rcid, 'lastmt_CMSReceivers', $ctime);
618 sub sync_statistic_db
{
619 my ($ldb, $rdb, $ni) = @_;
621 my $rcid = $ni->{cid
};
623 my $maxmails = 100000;
631 PMG
::DBTools
::create_clusterinfo_default
(
632 $ldb, $rcid, 'lastid_CStatistic', -1, undef);
634 do { # get new values
641 my $lastid = PMG
::DBTools
::read_int_clusterinfo
(
642 $ldb, $rcid, 'lastid_CStatistic');
646 my $sth = $rdb->prepare(
647 "SELECT * from CStatistic " .
648 "WHERE cid = ? AND rid > ? " .
649 "ORDER BY cid, rid LIMIT ?");
650 $sth->execute($rcid, $lastid, $maxcount);
655 $maxid = $ref->{rid
};
658 my $attrs = [qw(cid rid time bytes direction spamlevel ptime virusinfo sender)];
659 $count += PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CStatistic', $attrs, $callback);
664 $sth = $rdb->prepare(
665 "SELECT * from CReceivers WHERE " .
666 "CStatistic_CID = ? AND CStatistic_RID > ? AND CStatistic_RID <= ?");
667 $sth->execute($rcid, $lastid, $maxid);
669 $attrs = [qw(cstatistic_cid cstatistic_rid blocked receiver)];
670 PMG
::DBTools
::copy_selected_data
($ldb, $sth, 'CReceivers', $attrs);
673 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $rcid, 'lastid_CStatistic', $maxid);
684 } while (($count >= $maxcount) && ($mscount < $maxmails));
689 my $sync_generic_mtime_db = sub {
690 my ($ldb, $rdb, $ni, $table, $selectfunc, $mergefunc) = @_;
692 my $ctime = PMG
::DBTools
::get_remote_time
($rdb);
694 PMG
::DBTools
::create_clusterinfo_default
($ldb, $ni->{cid
}, "lastmt_$table", 0, undef);
696 my $lastmt = PMG
::DBTools
::read_int_clusterinfo
($ldb, $ni->{cid
}, "lastmt_$table");
698 my $sql_cmd = $selectfunc->($ctime, $lastmt);
700 my $sth = $rdb->prepare($sql_cmd);
707 # use transaction to speedup things
708 my $max = 1000; # UPDATE MAX ENTRIES AT ONCE
710 while (my $ref = $sth->fetchrow_hashref()) {
711 $ldb->begin_work if !$count;
713 if (++$count >= $max) {
720 $ldb->commit if $count;
727 PMG
::DBTools
::write_maxint_clusterinfo
($ldb, $ni->{cid
}, "lastmt_$table", $ctime);
732 sub sync_localstat_db
{
733 my ($dbh, $rdb, $ni) = @_;
735 my $rcid = $ni->{cid
};
737 my $selectfunc = sub {
738 my ($ctime, $lastmt) = @_;
739 return "SELECT * from LocalStat WHERE mtime >= $lastmt AND cid = $rcid";
742 my $merge_sth = $dbh->prepare(
743 'INSERT INTO LocalStat (Time, RBLCount, PregreetCount, CID, MTime) ' .
744 'VALUES (?, ?, ?, ?, ?) ' .
745 'ON CONFLICT (Time, CID) DO UPDATE SET ' .
746 'RBLCount = excluded.RBLCount, PregreetCount = excluded.PregreetCount, MTime = excluded.MTime');
748 my $mergefunc = sub {
751 $merge_sth->execute($ref->{time}, $ref->{rblcount
}, $ref->{pregreetcount
}, $ref->{cid
}, $ref->{mtime
});
754 return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'LocalStat', $selectfunc, $mergefunc);
757 sub sync_greylist_db
{
758 my ($dbh, $rdb, $ni) = @_;
760 my $selectfunc = sub {
761 my ($ctime, $lastmt) = @_;
762 return "SELECT * from CGreylist WHERE extime >= $ctime AND " .
763 "mtime >= $lastmt AND CID != 0";
766 # FIXME: drop Host column with PMG 7.0
767 my $merge_sth = $dbh->prepare(PMG
::DBTools
::cgreylist_merge_sql
());
768 my $mergefunc = sub {
771 my $ipnet = $ref->{ipnet
};
772 $ipnet .= '.0/24' if $ipnet !~ /\
/\d+$/;
774 $ipnet, 0, $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 (?, ?, ?, ?) ' .
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
}, $ref->{mtime
});
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);