]>
Commit | Line | Data |
---|---|---|
0854fb22 DM |
1 | package PMG::Cluster; |
2 | ||
3 | use strict; | |
4 | use warnings; | |
45e68618 | 5 | use Data::Dumper; |
0854fb22 | 6 | use Socket; |
cfdf6608 | 7 | use File::Path; |
9430b6d4 | 8 | use Time::HiRes qw (gettimeofday tv_interval); |
45e68618 | 9 | |
a7c7cad7 | 10 | use PVE::SafeSyslog; |
0854fb22 DM |
11 | use PVE::Tools; |
12 | use PVE::INotify; | |
0757859a | 13 | use PVE::APIClient::LWP; |
0854fb22 | 14 | |
1fb2ab76 | 15 | use PMG::Utils; |
a7c7cad7 | 16 | use PMG::Config; |
9f67f5b3 | 17 | use PMG::ClusterConfig; |
db303db4 DM |
18 | use PMG::RuleDB; |
19 | use PMG::RuleCache; | |
9430b6d4 | 20 | use PMG::MailQueue; |
0757859a | 21 | use PMG::Fetchmail; |
0854fb22 | 22 | |
8737f93a DM |
23 | sub remote_node_ip { |
24 | my ($nodename, $noerr) = @_; | |
25 | ||
d8782874 | 26 | my $cinfo = PMG::ClusterConfig->new(); |
8737f93a | 27 | |
45e68618 | 28 | foreach my $entry (values %{$cinfo->{ids}}) { |
8737f93a DM |
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); | |
34 | } | |
35 | } | |
36 | ||
37 | # fallback: try to get IP by other means | |
9f67f5b3 | 38 | return PMG::Utils::lookup_node_ip($nodename, $noerr); |
8737f93a DM |
39 | } |
40 | ||
d2e43f9e DM |
41 | sub get_master_node { |
42 | my ($cinfo) = @_; | |
43 | ||
d8782874 | 44 | $cinfo = PMG::ClusterConfig->new() if !$cinfo; |
d2e43f9e DM |
45 | |
46 | return $cinfo->{master}->{name} if defined($cinfo->{master}); | |
47 | ||
48 | return 'localhost'; | |
49 | } | |
50 | ||
cba17aeb DM |
51 | sub read_local_ssl_cert_fingerprint { |
52 | my $cert_path = "/etc/pmg/pmg-api.pem"; | |
0854fb22 | 53 | |
cba17aeb DM |
54 | my $cert; |
55 | eval { | |
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); | |
59 | }; | |
60 | if (my $err = $@) { | |
61 | die "unable to read certificate '$cert_path' - $err\n"; | |
62 | } | |
0854fb22 | 63 | |
cba17aeb DM |
64 | if (!defined($cert)) { |
65 | die "unable to read certificate '$cert_path' - got empty value\n"; | |
66 | } | |
67 | ||
68 | my $fp; | |
69 | eval { | |
70 | $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256'); | |
71 | }; | |
72 | if (my $err = $@) { | |
73 | die "unable to get fingerprint for '$cert_path' - $err\n"; | |
74 | } | |
0854fb22 | 75 | |
cba17aeb DM |
76 | if (!defined($fp) || $fp eq '') { |
77 | die "unable to get fingerprint for '$cert_path' - got empty value\n"; | |
78 | } | |
0854fb22 | 79 | |
cba17aeb DM |
80 | return $fp; |
81 | } | |
0854fb22 | 82 | |
cba17aeb DM |
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'; | |
0854fb22 | 86 | |
cba17aeb DM |
87 | sub read_local_cluster_info { |
88 | ||
89 | my $res = {}; | |
90 | ||
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; | |
94 | ||
95 | die "unable to parse ${hostrsapubkey_fn}\n" | |
96 | if $hostrsapubkey !~ m/^[A-Za-z0-9\.\/\+]{200,}$/; | |
0854fb22 DM |
97 | |
98 | my $nodename = PVE::INotify::nodename(); | |
99 | ||
cba17aeb | 100 | $res->{name} = $nodename; |
0854fb22 | 101 | |
cba17aeb | 102 | $res->{ip} = PMG::Utils::lookup_node_ip($nodename); |
0854fb22 | 103 | |
cba17aeb | 104 | $res->{hostrsapubkey} = $hostrsapubkey; |
0854fb22 | 105 | |
cba17aeb DM |
106 | if (! -f $rootrsapubkey_fn) { |
107 | unlink $rootrsakey_fn; | |
108 | my $cmd = ['ssh-keygen', '-t', 'rsa', '-N', '', '-b', '2048', | |
109 | '-f', $rootrsakey_fn]; | |
1fb2ab76 | 110 | PMG::Utils::run_silent_cmd($cmd); |
cba17aeb DM |
111 | } |
112 | ||
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; | |
116 | ||
117 | die "unable to parse ${rootrsapubkey_fn}\n" | |
118 | if $rootrsapubkey !~ m/^[A-Za-z0-9\.\/\+]{200,}$/; | |
119 | ||
120 | $res->{rootrsapubkey} = $rootrsapubkey; | |
121 | ||
122 | $res->{fingerprint} = read_local_ssl_cert_fingerprint(); | |
123 | ||
124 | return $res; | |
125 | } | |
126 | ||
127 | # X509 Certificate cache helper | |
128 | ||
129 | my $cert_cache_nodes = {}; | |
130 | my $cert_cache_timestamp = time(); | |
131 | my $cert_cache_fingerprints = {}; | |
0854fb22 | 132 | |
cba17aeb | 133 | sub update_cert_cache { |
0854fb22 | 134 | |
cba17aeb DM |
135 | $cert_cache_timestamp = time(); |
136 | ||
137 | $cert_cache_fingerprints = {}; | |
138 | $cert_cache_nodes = {}; | |
139 | ||
d8782874 | 140 | my $cinfo = PMG::ClusterConfig->new(); |
cba17aeb DM |
141 | |
142 | foreach my $entry (values %{$cinfo->{ids}}) { | |
143 | my $node = $entry->{name}; | |
144 | my $fp = $entry->{fingerprint}; | |
145 | if ($node && $fp) { | |
146 | $cert_cache_fingerprints->{$fp} = 1; | |
147 | $cert_cache_nodes->{$node} = $fp; | |
0854fb22 DM |
148 | } |
149 | } | |
150 | } | |
151 | ||
152 | # load and cache cert fingerprint once | |
153 | sub initialize_cert_cache { | |
154 | my ($node) = @_; | |
155 | ||
cba17aeb | 156 | update_cert_cache() |
0854fb22 DM |
157 | if defined($node) && !defined($cert_cache_nodes->{$node}); |
158 | } | |
159 | ||
160 | sub check_cert_fingerprint { | |
161 | my ($cert) = @_; | |
162 | ||
163 | # clear cache every 30 minutes at least | |
cba17aeb | 164 | update_cert_cache() if time() - $cert_cache_timestamp >= 60*30; |
0854fb22 DM |
165 | |
166 | # get fingerprint of server certificate | |
167 | my $fp; | |
168 | eval { | |
169 | $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256'); | |
170 | }; | |
171 | return 0 if $@ || !defined($fp) || $fp eq ''; # error | |
172 | ||
173 | my $check = sub { | |
174 | for my $expected (keys %$cert_cache_fingerprints) { | |
175 | return 1 if $fp eq $expected; | |
176 | } | |
177 | return 0; | |
178 | }; | |
179 | ||
cba17aeb | 180 | return 1 if $check->(); |
0854fb22 DM |
181 | |
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"); | |
185 | update_cert_cache(); | |
cba17aeb | 186 | return $check->(); |
0854fb22 DM |
187 | } |
188 | ||
189 | return 0; | |
190 | } | |
191 | ||
58072364 DM |
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"; | |
195 | ||
196 | sub update_ssh_keys { | |
197 | my ($cinfo) = @_; | |
198 | ||
809dd92a | 199 | my $old = ''; |
58072364 | 200 | my $data = ''; |
809dd92a | 201 | |
58072364 DM |
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"; | |
205 | } | |
206 | ||
809dd92a DM |
207 | $old = PVE::Tools::file_get_contents($sshglobalknownhosts, 1024*1024) |
208 | if -f $sshglobalknownhosts; | |
209 | ||
210 | PVE::Tools::file_set_contents($sshglobalknownhosts, $data) | |
211 | if $old ne $data; | |
58072364 DM |
212 | |
213 | $data = ''; | |
809dd92a | 214 | $old = ''; |
58072364 DM |
215 | |
216 | # always add ourself | |
217 | if (-f $ssh_rsa_id) { | |
218 | my $pub = PVE::Tools::file_get_contents($ssh_rsa_id); | |
219 | chomp($pub); | |
220 | $data .= "$pub\n"; | |
221 | } | |
222 | ||
223 | foreach my $node (values %{$cinfo->{ids}}) { | |
224 | $data .= "ssh-rsa $node->{rootrsapubkey} root\@$node->{name}\n"; | |
225 | } | |
226 | ||
227 | if (-f $rootsshauthkeys) { | |
a7c7cad7 DM |
228 | my $mykey = PVE::Tools::file_get_contents($rootsshauthkeys, 128*1024); |
229 | chomp($mykey); | |
230 | $data .= "$mykey\n"; | |
58072364 DM |
231 | } |
232 | ||
233 | my $newdata = ""; | |
234 | my $vhash = {}; | |
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}++; | |
239 | } | |
240 | $newdata .= "$line\n"; | |
241 | } | |
242 | ||
809dd92a DM |
243 | $old = PVE::Tools::file_get_contents($rootsshauthkeys, 1024*1024) |
244 | if -f $rootsshauthkeys; | |
245 | ||
246 | PVE::Tools::file_set_contents($rootsshauthkeys, $newdata, 0600) | |
247 | if $old ne $newdata; | |
58072364 DM |
248 | } |
249 | ||
a7c7cad7 DM |
250 | my $cfgdir = '/etc/pmg'; |
251 | my $syncdir = "$cfgdir/master"; | |
252 | ||
253 | my $cond_commit_synced_file = sub { | |
254 | my ($filename, $dstfn) = @_; | |
255 | ||
256 | $dstfn = "$cfgdir/$filename" if !defined($dstfn); | |
257 | my $srcfn = "$syncdir/$filename"; | |
258 | ||
259 | if (! -f $srcfn) { | |
260 | unlink $dstfn; | |
261 | return; | |
262 | } | |
263 | ||
264 | my $new = PVE::Tools::file_get_contents($srcfn, 1024*1024); | |
265 | ||
266 | if (-f $dstfn) { | |
267 | my $old = PVE::Tools::file_get_contents($dstfn, 1024*1024); | |
268 | return 0 if $new eq $old; | |
269 | } | |
270 | ||
271 | rename($srcfn, $dstfn) || | |
272 | die "cond_rename_file '$filename' failed - $!\n"; | |
273 | ||
274 | print STDERR "updated $dstfn\n"; | |
275 | ||
276 | return 1; | |
277 | }; | |
278 | ||
c9dae0df DM |
279 | my $rsync_command = sub { |
280 | my ($host_key_alias, @args) = @_; | |
281 | ||
282 | my $ssh_cmd = '--rsh=ssh -l root -o BatchMode=yes'; | |
283 | $ssh_cmd .= " -o HostKeyAlias=${host_key_alias}" if $host_key_alias; | |
284 | ||
285 | my $cmd = ['rsync', $ssh_cmd, '-q', @args]; | |
286 | ||
287 | return $cmd; | |
288 | }; | |
289 | ||
290 | sub sync_quarantine_files { | |
291 | my ($host_ip, $host_name, $flistname) = @_; | |
292 | ||
9430b6d4 DM |
293 | my $spooldir = $PMG::MailQueue::spooldir; |
294 | ||
c9dae0df DM |
295 | my $cmd = $rsync_command->( |
296 | $host_name, '--timeout', '10', "${host_ip}:$spooldir", $spooldir, | |
297 | '--files-from', $flistname); | |
298 | ||
9430b6d4 | 299 | PVE::Tools::run_command($cmd); |
c9dae0df DM |
300 | } |
301 | ||
302 | sub sync_spooldir { | |
303 | my ($host_ip, $host_name, $rcid) = @_; | |
304 | ||
9430b6d4 DM |
305 | my $spooldir = $PMG::MailQueue::spooldir; |
306 | ||
c9dae0df DM |
307 | mkdir "$spooldir/cluster/"; |
308 | my $syncdir = "$spooldir/cluster/$rcid"; | |
309 | mkdir $syncdir; | |
310 | ||
311 | my $cmd = $rsync_command->( | |
312 | $host_name, '-aq', '--timeout', '10', "${host_ip}:$syncdir/", $syncdir); | |
313 | ||
314 | foreach my $incl (('spam/', 'spam/*', 'spam/*/*', 'virus/', 'virus/*', 'virus/*/*')) { | |
315 | push @$cmd, '--include', $incl; | |
316 | } | |
317 | ||
318 | push @$cmd, '--exclude', '*'; | |
319 | ||
320 | PVE::Tools::run_command($cmd); | |
321 | } | |
322 | ||
323 | sub sync_master_quar { | |
324 | my ($host_ip, $host_name) = @_; | |
325 | ||
9430b6d4 DM |
326 | my $spooldir = $PMG::MailQueue::spooldir; |
327 | ||
c9dae0df DM |
328 | my $syncdir = "$spooldir/cluster/"; |
329 | mkdir $syncdir; | |
330 | ||
331 | my $cmd = $rsync_command->( | |
332 | $host_name, '-aq', '--timeout', '10', "${host_ip}:$syncdir", $syncdir); | |
333 | ||
334 | PVE::Tools::run_command($cmd); | |
335 | } | |
336 | ||
58072364 | 337 | sub sync_config_from_master { |
809ae8f4 | 338 | my ($master_name, $master_ip, $noreload) = @_; |
58072364 | 339 | |
58072364 | 340 | mkdir $syncdir; |
a7c7cad7 | 341 | File::Path::remove_tree($syncdir, {keep_root => 1}); |
58072364 | 342 | |
a7c7cad7 DM |
343 | my $sa_conf_dir = "/etc/mail/spamassassin"; |
344 | my $sa_custom_cf = "custom.cf"; | |
58072364 | 345 | |
c9dae0df | 346 | my $cmd = $rsync_command->( |
f4b7112b | 347 | $master_name, '-aq', |
c9dae0df DM |
348 | "${master_ip}:$cfgdir/* ${sa_conf_dir}/${sa_custom_cf}", |
349 | "$syncdir/", | |
f4b7112b | 350 | '--exclude', 'master/', |
c9dae0df DM |
351 | '--exclude', '*~', |
352 | '--exclude', '*.db', | |
353 | '--exclude', 'pmg-api.pem', | |
354 | '--exclude', 'pmg-tls.pem', | |
355 | ); | |
58072364 DM |
356 | |
357 | my $errmsg = "syncing master configuration from '${master_ip}' failed"; | |
358 | PVE::Tools::run_command($cmd, errmsg => $errmsg); | |
a7c7cad7 DM |
359 | |
360 | # verify that the remote host is cluster master | |
361 | open (my $fh, '<', "$syncdir/cluster.conf") || | |
362 | die "unable to open synced cluster.conf - $!\n"; | |
a7c7cad7 | 363 | |
809ae8f4 DM |
364 | my $cinfo = PMG::ClusterConfig::read_cluster_conf('cluster.conf', $fh); |
365 | ||
366 | if (!$cinfo->{master} || ($cinfo->{master}->{ip} ne $master_ip)) { | |
a7c7cad7 DM |
367 | die "host '$master_ip' is not cluster master\n"; |
368 | } | |
369 | ||
809ae8f4 DM |
370 | my $role = $cinfo->{'local'}->{type} // '-'; |
371 | die "local node '$cinfo->{local}->{name}' not part of cluster\n" | |
a7c7cad7 DM |
372 | if $role eq '-'; |
373 | ||
809ae8f4 | 374 | die "local node '$cinfo->{local}->{name}' is new cluster master\n" |
a7c7cad7 DM |
375 | if $role eq 'master'; |
376 | ||
a7c7cad7 | 377 | $cond_commit_synced_file->('cluster.conf'); |
a7c7cad7 | 378 | |
809dd92a DM |
379 | update_ssh_keys($cinfo); # rewrite ssh keys |
380 | ||
0757859a DM |
381 | PMG::Fetchmail::update_fetchmail_default(0); # disable on slave |
382 | ||
a7c7cad7 DM |
383 | my $files = [ |
384 | 'pmg-authkey.key', | |
385 | 'pmg-authkey.pub', | |
386 | 'pmg-csrf.key', | |
387 | 'ldap.conf', | |
388 | 'user.conf', | |
7cac3e28 DM |
389 | 'domains', |
390 | 'mynetworks', | |
391 | 'transport', | |
959aaeba | 392 | 'tls_policy', |
fd6feef4 | 393 | 'fetchmailrc', |
a7c7cad7 DM |
394 | ]; |
395 | ||
396 | foreach my $filename (@$files) { | |
397 | $cond_commit_synced_file->($filename); | |
398 | } | |
399 | ||
0757859a | 400 | |
a7c7cad7 DM |
401 | my $force_restart = {}; |
402 | ||
403 | if ($cond_commit_synced_file->($sa_custom_cf, "${sa_conf_dir}/${sa_custom_cf}")) { | |
404 | $force_restart->{spam} = 1; | |
405 | } | |
406 | ||
407 | $cond_commit_synced_file->('pmg.conf'); | |
f4b7112b DM |
408 | |
409 | # sync user templates files/symlinks (not recursive) | |
410 | my $srcdir = "$syncdir/templates"; | |
411 | if (-d $srcdir) { | |
412 | my $dstdir = "$cfgdir/templates"; | |
413 | mkdir $dstdir; | |
414 | my $names_hash = {}; | |
415 | foreach my $fn (<$srcdir/*>) { | |
416 | next if $fn !~ m|^($srcdir/(.*))$|; | |
417 | $fn = $1; # untaint; | |
418 | my $name = $2; | |
419 | $names_hash->{$name} = 1; | |
420 | my $target = "$dstdir/$name"; | |
421 | if (-f $fn) { | |
422 | $cond_commit_synced_file->("templates/$name", $target); | |
423 | } elsif (-l $fn) { | |
424 | warn "update $target failed - $!\n" if !rename($fn, $target); | |
425 | } | |
426 | } | |
427 | # remove vanished files | |
428 | foreach my $fn (<$dstdir/*>) { | |
429 | next if $fn !~ m|^($dstdir/(.*))$|; | |
430 | $fn = $1; # untaint; | |
431 | my $name = $2; | |
432 | next if $names_hash->{$name}; | |
433 | warn "unlink $fn failed - $!\n" if !unlink($fn); | |
434 | } | |
435 | } | |
58072364 DM |
436 | } |
437 | ||
db303db4 DM |
438 | sub sync_ruledb_from_master { |
439 | my ($ldb, $rdb, $ni, $ticket) = @_; | |
440 | ||
441 | my $ruledb = PMG::RuleDB->new($ldb); | |
442 | my $rulecache = PMG::RuleCache->new($ruledb); | |
443 | ||
444 | my $conn = PVE::APIClient::LWP->new( | |
445 | ticket => $ticket, | |
446 | cookie_name => 'PMGAuthCookie', | |
447 | host => $ni->{ip}, | |
448 | cached_fingerprints => { | |
449 | $ni->{fingerprint} => 1, | |
450 | }); | |
451 | ||
452 | my $digest = $conn->get("/config/ruledb/digest", {}); | |
453 | ||
454 | return if $digest eq $rulecache->{digest}; # no changes | |
455 | ||
456 | syslog('info', "detected rule database changes - starting sync from '$ni->{ip}'"); | |
457 | ||
458 | eval { | |
459 | $ldb->begin_work; | |
460 | ||
461 | $ldb->do("DELETE FROM Rule"); | |
462 | $ldb->do("DELETE FROM RuleGroup"); | |
463 | $ldb->do("DELETE FROM ObjectGroup"); | |
464 | $ldb->do("DELETE FROM Object"); | |
465 | $ldb->do("DELETE FROM Attribut"); | |
466 | ||
467 | eval { | |
468 | $rdb->begin_work; | |
469 | ||
470 | # read a consistent snapshot | |
471 | $rdb->do("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE"); | |
472 | ||
473 | PMG::DBTools::copy_table($ldb, $rdb, "Rule"); | |
474 | PMG::DBTools::copy_table($ldb, $rdb, "RuleGroup"); | |
475 | PMG::DBTools::copy_table($ldb, $rdb, "ObjectGroup"); | |
476 | PMG::DBTools::copy_table($ldb, $rdb, "Object", 'value'); | |
477 | PMG::DBTools::copy_table($ldb, $rdb, "Attribut", 'value'); | |
478 | }; | |
479 | ||
480 | $rdb->rollback; # end transaction | |
481 | ||
482 | die $@ if $@; | |
483 | ||
484 | # update sequences | |
485 | ||
486 | $ldb->do("SELECT setval('rule_id_seq', max(id)+1) FROM Rule"); | |
487 | $ldb->do("SELECT setval('object_id_seq', max(id)+1) FROM Object"); | |
488 | $ldb->do("SELECT setval('objectgroup_id_seq', max(id)+1) FROM ObjectGroup"); | |
489 | ||
490 | $ldb->commit; | |
491 | }; | |
492 | if (my $err = $@) { | |
493 | $ldb->rollback; | |
494 | die $err; | |
495 | } | |
496 | ||
497 | syslog('info', "finished rule database sync from host '$ni->{ip}'"); | |
498 | } | |
499 | ||
9430b6d4 DM |
500 | sub sync_quarantine_db { |
501 | my ($ldb, $rdb, $ni, $rsynctime_ref) = @_; | |
502 | ||
503 | my $rcid = $ni->{cid}; | |
504 | ||
505 | my $maxmails = 100000; | |
506 | ||
507 | my $mscount = 0; | |
508 | ||
509 | my $ctime = PMG::DBTools::get_remote_time($rdb); | |
510 | ||
511 | my $maxcount = 1000; | |
512 | ||
513 | my $count; | |
514 | ||
515 | PMG::DBTools::create_clusterinfo_default($ldb, $rcid, 'lastid_CMailStore', -1, undef); | |
516 | ||
517 | do { # get new values | |
518 | ||
519 | $count = 0; | |
520 | ||
521 | my $flistname = "/tmp/quarantinefilelist.$$"; | |
522 | ||
523 | eval { | |
524 | $ldb->begin_work; | |
525 | ||
526 | open(my $flistfh, '>', $flistname) || | |
527 | die "unable to open file '$flistname' - $!\n"; | |
528 | ||
529 | my $lastid = PMG::DBTools::read_int_clusterinfo($ldb, $rcid, 'lastid_CMailStore'); | |
530 | ||
531 | # sync CMailStore | |
532 | ||
533 | my $sth = $rdb->prepare( | |
534 | "SELECT * from CMailstore WHERE cid = ? AND rid > ? " . | |
535 | "ORDER BY cid,rid LIMIT ?"); | |
536 | $sth->execute($rcid, $lastid, $maxcount); | |
537 | ||
538 | my $maxid; | |
539 | my $callback = sub { | |
540 | my $ref = shift; | |
541 | $maxid = $ref->{rid}; | |
542 | print $flistfh "$ref->{file}\n"; | |
543 | }; | |
544 | ||
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); | |
547 | ||
548 | close($flistfh); | |
549 | ||
550 | my $starttime = [ gettimeofday() ]; | |
551 | sync_quarantine_files($ni->{ip}, $ni->{name}, $flistname); | |
552 | $$rsynctime_ref += tv_interval($starttime); | |
553 | ||
554 | if ($maxid) { | |
555 | # sync CMSReceivers | |
556 | ||
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); | |
562 | ||
39d91358 | 563 | $attrs = [qw(cmailstore_cid cmailstore_rid pmail receiver status mtime)]; |
9430b6d4 DM |
564 | PMG::DBTools::copy_selected_data($ldb, $sth, 'CMSReceivers', $attrs); |
565 | ||
566 | PMG::DBTools::write_maxint_clusterinfo($ldb, $rcid, 'lastid_CMailStore', $maxid); | |
567 | } | |
568 | ||
569 | $ldb->commit; | |
570 | }; | |
571 | my $err = $@; | |
572 | ||
573 | unlink $flistname; | |
574 | ||
575 | if ($err) { | |
576 | $ldb->rollback; | |
577 | die $err; | |
578 | } | |
579 | ||
580 | $mscount += $count; | |
581 | ||
582 | last if $mscount >= $maxmails; | |
583 | ||
584 | } while ($count >= $maxcount); | |
585 | ||
586 | PMG::DBTools::create_clusterinfo_default($ldb, $rcid, 'lastmt_CMSReceivers', 0, undef); | |
587 | ||
588 | eval { # synchronize status updates | |
589 | $ldb->begin_work; | |
590 | ||
591 | my $lastmt = PMG::DBTools::read_int_clusterinfo($ldb, $rcid, 'lastmt_CMSReceivers'); | |
592 | ||
593 | my $sth = $rdb->prepare ("SELECT * from CMSReceivers WHERE mtime >= ? AND status != 'N'"); | |
594 | $sth->execute($lastmt); | |
595 | ||
596 | my $update_sth = $ldb->prepare( | |
597 | "UPDATE CMSReceivers SET status = ? WHERE " . | |
598 | "CMailstore_CID = ? AND CMailstore_RID = ? AND PMail = ?;"); | |
599 | while (my $ref = $sth->fetchrow_hashref()) { | |
600 | $update_sth->execute($ref->{status}, $ref->{cmailstore_cid}, | |
601 | $ref->{cmailstore_rid}, $ref->{pmail}); | |
602 | } | |
603 | ||
604 | PMG::DBTools::write_maxint_clusterinfo($ldb, $rcid, 'lastmt_CMSReceivers', $ctime); | |
605 | ||
606 | $ldb->commit; | |
607 | }; | |
608 | if (my $err = $@) { | |
609 | $ldb->rollback; | |
610 | die $err; | |
611 | } | |
612 | ||
613 | return $mscount; | |
614 | } | |
615 | ||
616 | sub sync_statistic_db { | |
617 | my ($ldb, $rdb, $ni) = @_; | |
618 | ||
619 | my $rcid = $ni->{cid}; | |
620 | ||
621 | my $maxmails = 100000; | |
622 | ||
623 | my $mscount = 0; | |
624 | ||
625 | my $maxcount = 1000; | |
626 | ||
627 | my $count; | |
628 | ||
629 | PMG::DBTools::create_clusterinfo_default( | |
630 | $ldb, $rcid, 'lastid_CStatistic', -1, undef); | |
631 | ||
632 | do { # get new values | |
633 | ||
634 | $count = 0; | |
635 | ||
636 | eval { | |
637 | $ldb->begin_work; | |
638 | ||
639 | my $lastid = PMG::DBTools::read_int_clusterinfo( | |
640 | $ldb, $rcid, 'lastid_CStatistic'); | |
641 | ||
642 | # sync CStatistic | |
643 | ||
644 | my $sth = $rdb->prepare( | |
645 | "SELECT * from CStatistic " . | |
646 | "WHERE cid = ? AND rid > ? " . | |
647 | "ORDER BY cid, rid LIMIT ?"); | |
648 | $sth->execute($rcid, $lastid, $maxcount); | |
649 | ||
650 | my $maxid; | |
651 | my $callback = sub { | |
652 | my $ref = shift; | |
653 | $maxid = $ref->{rid}; | |
654 | }; | |
655 | ||
656 | my $attrs = [qw(cid rid time bytes direction spamlevel ptime virusinfo sender)]; | |
657 | $count += PMG::DBTools::copy_selected_data($ldb, $sth, 'CStatistic', $attrs, $callback); | |
658 | ||
659 | if ($maxid) { | |
660 | # sync CReceivers | |
661 | ||
662 | $sth = $rdb->prepare( | |
663 | "SELECT * from CReceivers WHERE " . | |
664 | "CStatistic_CID = ? AND CStatistic_RID > ? AND CStatistic_RID <= ?"); | |
665 | $sth->execute($rcid, $lastid, $maxid); | |
666 | ||
667 | $attrs = [qw(cstatistic_cid cstatistic_rid blocked receiver)]; | |
668 | PMG::DBTools::copy_selected_data($ldb, $sth, 'CReceivers', $attrs); | |
669 | ||
670 | PMG::DBTools::write_maxint_clusterinfo ($ldb, $rcid, 'lastid_CStatistic', $maxid); | |
671 | } | |
672 | ||
673 | $ldb->commit; | |
674 | }; | |
675 | if (my $err = $@) { | |
676 | $ldb->rollback; | |
677 | die $err; | |
678 | } | |
679 | ||
680 | $mscount += $count; | |
681 | ||
682 | last if $mscount >= $maxmails; | |
683 | ||
684 | } while ($count >= $maxcount); | |
e86b85a3 DM |
685 | |
686 | return $mscount; | |
9430b6d4 DM |
687 | } |
688 | ||
986eec31 | 689 | my $sync_generic_mtime_db = sub { |
9430b6d4 DM |
690 | my ($ldb, $rdb, $ni, $table, $selectfunc, $mergefunc) = @_; |
691 | ||
9430b6d4 DM |
692 | my $ctime = PMG::DBTools::get_remote_time($rdb); |
693 | ||
694 | PMG::DBTools::create_clusterinfo_default($ldb, $ni->{cid}, "lastmt_$table", 0, undef); | |
695 | ||
696 | my $lastmt = PMG::DBTools::read_int_clusterinfo($ldb, $ni->{cid}, "lastmt_$table"); | |
697 | ||
4c93256a | 698 | my $sql_cmd = $selectfunc->($ctime, $lastmt); |
9430b6d4 | 699 | |
4c93256a | 700 | my $sth = $rdb->prepare($sql_cmd); |
9430b6d4 DM |
701 | |
702 | $sth->execute(); | |
703 | ||
986eec31 DM |
704 | my $updates = 0; |
705 | ||
4c93256a DM |
706 | eval { |
707 | # use transaction to speedup things | |
708 | my $max = 1000; # UPDATE MAX ENTRIES AT ONCE | |
4c93256a DM |
709 | my $count = 0; |
710 | while (my $ref = $sth->fetchrow_hashref()) { | |
9d5bdd2a DM |
711 | $ldb->begin_work if !$count; |
712 | $mergefunc->($ref); | |
4c93256a DM |
713 | if (++$count >= $max) { |
714 | $count = 0; | |
715 | $ldb->commit; | |
9430b6d4 | 716 | } |
986eec31 | 717 | $updates++; |
9430b6d4 | 718 | } |
9d5bdd2a DM |
719 | |
720 | $ldb->commit if $count; | |
9430b6d4 | 721 | }; |
4c93256a DM |
722 | if (my $err = $@) { |
723 | $ldb->rollback; | |
724 | die $err; | |
9430b6d4 DM |
725 | } |
726 | ||
9430b6d4 DM |
727 | PMG::DBTools::write_maxint_clusterinfo($ldb, $ni->{cid}, "lastmt_$table", $ctime); |
728 | ||
986eec31 DM |
729 | return $updates; |
730 | }; | |
9430b6d4 | 731 | |
5e1408fd DM |
732 | sub sync_localstat_db { |
733 | my ($dbh, $rdb, $ni) = @_; | |
734 | ||
735 | my $rcid = $ni->{cid}; | |
736 | ||
737 | my $selectfunc = sub { | |
738 | my ($ctime, $lastmt) = @_; | |
739 | return "SELECT * from LocalStat WHERE mtime >= $lastmt AND cid = $rcid"; | |
740 | }; | |
741 | ||
742 | my $merge_sth = $dbh->prepare( | |
ebd19c79 DM |
743 | 'INSERT INTO LocalStat (Time, RBLCount, PregreetCount, CID, MTime) ' . |
744 | 'VALUES (?, ?, ?, ?, ?) ' . | |
5e1408fd | 745 | 'ON CONFLICT (Time, CID) DO UPDATE SET ' . |
ebd19c79 | 746 | 'RBLCount = excluded.RBLCount, PregreetCount = excluded.PregreetCount, MTime = excluded.MTime'); |
5e1408fd DM |
747 | |
748 | my $mergefunc = sub { | |
749 | my ($ref) = @_; | |
750 | ||
ebd19c79 | 751 | $merge_sth->execute($ref->{time}, $ref->{rblcount}, $ref->{pregreetcount}, $ref->{cid}, $ref->{mtime}); |
5e1408fd DM |
752 | }; |
753 | ||
754 | return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'LocalStat', $selectfunc, $mergefunc); | |
755 | } | |
756 | ||
9430b6d4 DM |
757 | sub sync_greylist_db { |
758 | my ($dbh, $rdb, $ni) = @_; | |
759 | ||
760 | my $selectfunc = sub { | |
761 | my ($ctime, $lastmt) = @_; | |
762 | return "SELECT * from CGreylist WHERE extime >= $ctime AND " . | |
763 | "mtime >= $lastmt AND CID != 0"; | |
764 | }; | |
765 | ||
2e049252 | 766 | my $merge_sth = $dbh->prepare($PMG::DBTools::cgreylist_merge_sql); |
9430b6d4 | 767 | my $mergefunc = sub { |
986eec31 | 768 | my ($ref) = @_; |
9430b6d4 | 769 | |
f413f920 DM |
770 | $merge_sth->execute( |
771 | $ref->{ipnet}, $ref->{host}, $ref->{sender}, $ref->{receiver}, | |
772 | $ref->{instance}, $ref->{rctime}, $ref->{extime}, $ref->{delay}, | |
773 | $ref->{blocked}, $ref->{passed}, 0, $ref->{cid}); | |
9430b6d4 DM |
774 | }; |
775 | ||
986eec31 | 776 | return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'CGreylist', $selectfunc, $mergefunc); |
9430b6d4 DM |
777 | } |
778 | ||
779 | sub sync_userprefs_db { | |
780 | my ($dbh, $rdb, $ni) = @_; | |
781 | ||
782 | my $selectfunc = sub { | |
783 | my ($ctime, $lastmt) = @_; | |
784 | ||
785 | return "SELECT * from UserPrefs WHERE mtime >= $lastmt"; | |
786 | }; | |
787 | ||
7d13157e | 788 | my $merge_sth = $dbh->prepare( |
471b05ed | 789 | "INSERT INTO UserPrefs (PMail, Name, Data, MTime) " . |
0527ea1a | 790 | 'VALUES (?, ?, ?, 0) ' . |
471b05ed | 791 | 'ON CONFLICT (PMail, Name) DO UPDATE SET ' . |
dbdf1298 | 792 | # Note: MTime = 0 ==> this is just a copy from somewhere else, not modified |
3a9ffd85 | 793 | 'MTime = CASE WHEN excluded.MTime >= UserPrefs.MTime THEN 0 ELSE UserPrefs.MTime END, ' . |
0527ea1a | 794 | 'Data = CASE WHEN excluded.MTime >= UserPrefs.MTime THEN excluded.Data ELSE UserPrefs.Data END'); |
471b05ed | 795 | |
9430b6d4 | 796 | my $mergefunc = sub { |
986eec31 | 797 | my ($ref) = @_; |
9430b6d4 | 798 | |
7d13157e | 799 | $merge_sth->execute($ref->{pmail}, $ref->{name}, $ref->{data}); |
9430b6d4 DM |
800 | }; |
801 | ||
986eec31 | 802 | return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'UserPrefs', $selectfunc, $mergefunc); |
9430b6d4 DM |
803 | } |
804 | ||
805 | sub sync_domainstat_db { | |
806 | my ($dbh, $rdb, $ni) = @_; | |
807 | ||
808 | my $selectfunc = sub { | |
809 | my ($ctime, $lastmt) = @_; | |
810 | return "SELECT * from DomainStat WHERE mtime >= $lastmt"; | |
811 | }; | |
812 | ||
1c7ea32c DM |
813 | my $merge_sth = $dbh->prepare( |
814 | 'INSERT INTO Domainstat ' . | |
815 | '(Time,Domain,CountIn,CountOut,BytesIn,BytesOut,VirusIn,VirusOut,SpamIn,SpamOut,' . | |
816 | 'BouncesIn,BouncesOut,PTimeSum,Mtime) ' . | |
817 | 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' . | |
818 | 'ON CONFLICT (Time, Domain) DO UPDATE SET ' . | |
819 | 'CountIn = excluded.CountIn, CountOut = excluded.CountOut, ' . | |
820 | 'BytesIn = excluded.BytesIn, BytesOut = excluded.BytesOut, ' . | |
821 | 'VirusIn = excluded.VirusIn, VirusOut = excluded.VirusOut, ' . | |
822 | 'SpamIn = excluded.SpamIn, SpamOut = excluded.SpamOut, ' . | |
823 | 'BouncesIn = excluded.BouncesIn, BouncesOut = excluded.BouncesOut, ' . | |
824 | 'PTimeSum = excluded.PTimeSum, MTime = excluded.MTime'); | |
825 | ||
9430b6d4 | 826 | my $mergefunc = sub { |
986eec31 | 827 | my ($ref) = @_; |
9430b6d4 | 828 | |
1c7ea32c DM |
829 | $merge_sth->execute( |
830 | $ref->{time}, $ref->{domain}, $ref->{countin}, $ref->{countout}, | |
831 | $ref->{bytesin}, $ref->{bytesout}, | |
832 | $ref->{virusin}, $ref->{virusout}, $ref->{spamin}, $ref->{spamout}, | |
833 | $ref->{bouncesin}, $ref->{bouncesout}, $ref->{ptimesum}, $ref->{mtime}); | |
9430b6d4 DM |
834 | }; |
835 | ||
986eec31 | 836 | return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'DomainStat', $selectfunc, $mergefunc); |
9430b6d4 DM |
837 | } |
838 | ||
839 | sub sync_dailystat_db { | |
840 | my ($dbh, $rdb, $ni) = @_; | |
841 | ||
842 | my $selectfunc = sub { | |
843 | my ($ctime, $lastmt) = @_; | |
844 | return "SELECT * from DailyStat WHERE mtime >= $lastmt"; | |
8bf584ae DM |
845 | }; |
846 | ||
847 | my $merge_sth = $dbh->prepare( | |
848 | 'INSERT INTO DailyStat ' . | |
849 | '(Time,CountIn,CountOut,BytesIn,BytesOut,VirusIn,VirusOut,SpamIn,SpamOut,' . | |
850 | 'BouncesIn,BouncesOut,GreylistCount,SPFCount,RBLCount,PTimeSum,Mtime) ' . | |
851 | 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' . | |
852 | 'ON CONFLICT (Time) DO UPDATE SET ' . | |
853 | 'CountIn = excluded.CountIn, CountOut = excluded.CountOut, ' . | |
854 | 'BytesIn = excluded.BytesIn, BytesOut = excluded.BytesOut, ' . | |
855 | 'VirusIn = excluded.VirusIn, VirusOut = excluded.VirusOut, ' . | |
856 | 'SpamIn = excluded.SpamIn, SpamOut = excluded.SpamOut, ' . | |
857 | 'BouncesIn = excluded.BouncesIn, BouncesOut = excluded.BouncesOut, ' . | |
858 | 'GreylistCount = excluded.GreylistCount, SPFCount = excluded.SpfCount, ' . | |
859 | 'RBLCount = excluded.RBLCount, ' . | |
860 | 'PTimeSum = excluded.PTimeSum, MTime = excluded.MTime'); | |
9430b6d4 DM |
861 | |
862 | my $mergefunc = sub { | |
986eec31 | 863 | my ($ref) = @_; |
9430b6d4 | 864 | |
dbdf1298 | 865 | $merge_sth->execute( |
8bf584ae DM |
866 | $ref->{time}, $ref->{countin}, $ref->{countout}, |
867 | $ref->{bytesin}, $ref->{bytesout}, | |
868 | $ref->{virusin}, $ref->{virusout}, $ref->{spamin}, $ref->{spamout}, | |
869 | $ref->{bouncesin}, $ref->{bouncesout}, $ref->{greylistcount}, | |
870 | $ref->{spfcount}, $ref->{rblcount}, $ref->{ptimesum}, $ref->{mtime}); | |
9430b6d4 DM |
871 | }; |
872 | ||
986eec31 | 873 | return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'DailyStat', $selectfunc, $mergefunc); |
9430b6d4 DM |
874 | } |
875 | ||
876 | sub sync_virusinfo_db { | |
877 | my ($dbh, $rdb, $ni) = @_; | |
878 | ||
879 | my $selectfunc = sub { | |
880 | my ($ctime, $lastmt) = @_; | |
881 | return "SELECT * from VirusInfo WHERE mtime >= $lastmt"; | |
882 | }; | |
883 | ||
80615ad6 DM |
884 | my $merge_sth = $dbh->prepare( |
885 | 'INSERT INTO VirusInfo (Time,Name,Count,MTime) ' . | |
886 | 'VALUES (?,?,?,?) ' . | |
887 | 'ON CONFLICT (Time,Name) DO UPDATE SET ' . | |
888 | 'Count = excluded.Count , MTime = excluded.MTime'); | |
889 | ||
9430b6d4 | 890 | my $mergefunc = sub { |
986eec31 | 891 | my ($ref) = @_; |
9430b6d4 | 892 | |
80615ad6 | 893 | $merge_sth->execute($ref->{time}, $ref->{name}, $ref->{count}, $ref->{mtime}); |
9430b6d4 DM |
894 | }; |
895 | ||
986eec31 | 896 | return $sync_generic_mtime_db->($dbh, $rdb, $ni, 'VirusInfo', $selectfunc, $mergefunc); |
9430b6d4 DM |
897 | } |
898 | ||
899 | sub sync_deleted_nodes_from_master { | |
900 | my ($ldb, $masterdb, $cinfo, $masterni, $rsynctime_ref) = @_; | |
901 | ||
902 | my $rsynctime = 0; | |
903 | ||
904 | my $cid_hash = {}; # fast lookup | |
5c6e6eeb | 905 | foreach my $ni (values %{$cinfo->{ids}}) { |
9430b6d4 DM |
906 | $cid_hash->{$ni->{cid}} = $ni; |
907 | } | |
908 | ||
909 | my $spooldir = $PMG::MailQueue::spooldir; | |
910 | ||
5c6e6eeb DM |
911 | my $maxcid = $cinfo->{master}->{maxcid} // 0; |
912 | ||
913 | for (my $rcid = 1; $rcid <= $maxcid; $rcid++) { | |
9430b6d4 DM |
914 | next if $cid_hash->{$rcid}; |
915 | ||
916 | my $done_marker = "$spooldir/cluster/$rcid/.synced-deleted-node"; | |
917 | ||
918 | next if -f $done_marker; # already synced | |
919 | ||
920 | syslog('info', "syncing deleted node $rcid from master '$masterni->{ip}'"); | |
921 | ||
922 | my $starttime = [ gettimeofday() ]; | |
923 | sync_spooldir($masterni->{ip}, $masterni->{name}, $rcid); | |
924 | $$rsynctime_ref += tv_interval($starttime); | |
925 | ||
926 | my $fake_ni = { | |
927 | ip => $masterni->{ip}, | |
928 | name => $masterni->{name}, | |
929 | cid => $rcid, | |
930 | }; | |
931 | ||
932 | sync_quarantine_db($ldb, $masterdb, $fake_ni); | |
933 | ||
934 | sync_statistic_db ($ldb, $masterdb, $fake_ni); | |
935 | ||
936 | open(my $fh, ">>", $done_marker); | |
937 | } | |
938 | } | |
939 | ||
940 | ||
0854fb22 | 941 | 1; |