Debian Codegraph @

bin/amavisd-nanny

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/perl -T
2 # SPDX-License-Identifier: BSD-2-Clause
3
4 #------------------------------------------------------------------------------
5 # This is amavisd-nanny, a program to show the status
6 # and keep an eye on the health of child processes in amavis.
7 #
8 # Author: Mark Martinec <[email protected]>
9 #
10 # Copyright (c) 2004-2014, Mark Martinec
11 # All rights reserved.
12 #
13 # Redistribution and use in source and binary forms, with or without
14 # modification, are permitted provided that the following conditions
15 # are met:
16 # 1. Redistributions of source code must retain the above copyright notice,
17 # this list of conditions and the following disclaimer.
18 # 2. Redistributions in binary form must reproduce the above copyright notice,
19 # this list of conditions and the following disclaimer in the documentation
20 # and/or other materials provided with the distribution.
21 #
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
26 # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 # POSSIBILITY OF SUCH DAMAGE.
33 #
34 # The views and conclusions contained in the software and documentation are
35 # those of the authors and should not be interpreted as representing official
36 # policies, either expressed or implied, of the Jozef Stefan Institute.
37
38 # (the above license is the 2-clause BSD license, also known as
39 # a "Simplified BSD License", and pertains to this program only)
40 #
41 # Patches and problem reports are welcome.
42 # The latest version of this program is available at:
43 # http://www.ijs.si/software/amavisd/
44 #------------------------------------------------------------------------------
45
46 use strict;
47 use re 'taint';
48 use warnings;
49 no warnings 'uninitialized';
50
51 use Errno qw(ESRCH ENOENT);
52 use POSIX qw(strftime);
53 use Time::HiRes ();
54 use BerkeleyDB;
55
56 use vars qw($VERSION); $VERSION = 1.401;
57
58 my($idlettl) = 3*60*60; # idle children are sent a SIGTERM
59 # after this many seconds
60 my($activettl) = 10*60; # stuck active children are sent a SIGTERM
61 # after this many seconds
62
63 my($dbfile) = 'nanny.db';
64 my($db_home) = # DB databases directory
•65 defined $ENV{'AMAVISD_DB_HOME'} ? $ENV{'AMAVISD_DB_HOME'} : '/var/lib/amavis/db';
66 my($wakeuptime) = 2; # -w, sleep time in seconds, may be fractional
67 my($repeatcount); # -c, repeat count (when defined)
68
69 sub fmt_age($$$) {
70 my($t,$state_bar,$idling) = @_;
71 $t = int($t);
72 my($char) = $idling ? '.' : '=';
73 my($bar_l) = $idling ? $t : length($state_bar);
74 my($bar) = substr( ($char x 9 . ':') x 3 . $char x 5, 0,$bar_l);
75 if (!$idling) {
76 $state_bar = substr($state_bar,0,length($bar)-2) . substr($state_bar,-1,1)
77 . '>' if length($state_bar) > length($bar);
78 for my $j (0 .. length($bar)-1) {
79 substr($bar,$j,1) = substr($state_bar,$j,1)
80 if substr($bar,$j,1) eq '=' && substr($state_bar,$j,1) ne ' ';
81 }
82 }
83 my($s) = $t % 60; $t = int($t/60);
84 my($m) = $t % 60; $t = int($t/60);
85 my($h) = $t % 24; $t = int($t/24);
86 my($d) = $t;
87 my($str) = sprintf("%d:%02d:%02d", $h,$m,$s);
88 $str = (!$d ? " " : sprintf("%dd",$d)) . $str;
89 $str . ' ' . $bar;
90 };
91
92 # main program starts here
93 my($normal_termination) = 0;
94 $SIG{INT} = sub { die "\n" }; # do the END code block when interrupted
95 while (@ARGV) {
96 my($opt) = shift @ARGV;
97 my($val) = shift @ARGV;
98 if ($opt eq '-w' && $val =~ /^\+?\d+(?:\.\d*)?\z/) { $wakeuptime = $val }
99 elsif ($opt eq '-c' && $val =~ /^[+-]?\d+\z/) { $repeatcount = $val }
100 else {
101 print <<'EOD';
102 States legend:
103 A accepted a connection
104 b begin with a protocol for accepting a request
105 m 'MAIL FROM' smtp command started a new transaction in the same session
106 d transferring data from MTA to amavisd
107 = content checking just started
108 G generating and verifying unique mail_id
109 D decoding of mail parts
110 V virus scanning
111 S spam scanning
112 P pen pals database lookup and updates
113 r preparing results
114 Q quarantining and preparing/sending notifications
115 F forwarding mail to MTA
116 . content checking just finished
117 sp space indicates idle (elapsed bar is showing dots)
118
119 EOD
120 die "Usage: $0 [-c <count>] [-w <wait-interval>]\n";
121 }
122 }
123 print <<'EOD';
124 process-id task-id elapsed in elapsed-bar (dots indicate idle)
125 or state idle or busy
126 EOD
127
128 my(%waittime); # associative array on pid
129 my($env,$db,$old_db_inode,@dbstat,$cursor);
130 my(%proc_last_timestamp, %proc_state_bars);
131 for (;;) {
132 last if defined $repeatcount && $repeatcount <= 0;
133 @dbstat = stat("$db_home/$dbfile");
134 my($errn) = @dbstat ? 0 : 0+$!;
135 $errn==0 || $errn==ENOENT or die "stat $db_home/$dbfile: $!";
136 if (defined $db && $old_db_inode != $dbstat[1]) {
137 $db->db_close==0 or die "BDB db_close error: $BerkeleyDB::Error $!";
138 undef $db;
139 printf STDERR ("Reopening nanny database %s/%s\n", $db_home,$dbfile);
140 }
141 if (!defined $db && $errn==0) {
142 $old_db_inode = $dbstat[1];
143 $env = BerkeleyDB::Env->new(
144 -Home => $db_home, -Flags => DB_INIT_CDB | DB_INIT_MPOOL,
145 -ErrFile => \*STDOUT, -Verbose => 1);
146 defined $env or die "BDB no env: $BerkeleyDB::Error $!";
147 $db = BerkeleyDB::Hash->new(-Filename => $dbfile, -Env => $env);
148 defined $db or die "BDB no dbN 1: $BerkeleyDB::Error $!";
149 }
150 $| = 0;
151 my(%proc_timestamp, %proc_state, %proc_task_id);
152 my($stat,$key,$val); my($now);
153 my($eval_stat,$interrupt); $interrupt = '';
154 if (!defined $db) {
155 printf STDERR ("No nanny database %s/%s; waiting...\n",
156 $db_home,$dbfile);
157 } else {
158 $repeatcount-- if defined $repeatcount && $repeatcount > 0;
159 print "\n";
160 my($h1) = sub { $interrupt = $_[0] };
161 local(@SIG{qw(INT HUP TERM TSTP QUIT ALRM USR1 USR2)}) = ($h1) x 8;
162 eval {
163 $cursor = $db->db_cursor; # obtain read lock
164 defined $cursor or die "db_cursor error: $BerkeleyDB::Error";
165 $now = Time::HiRes::time; local($1,$2);
166 my($now_utc_iso8601) = strftime("%Y%m%dT%H%M%S",gmtime(int($now)));
167 while ( ($stat=$cursor->c_get($key,$val,DB_NEXT)) == 0 ) {
168 if ($val !~ /^(\d+(?:\.\d*)?) (.*?) *\z/s) {
169 print STDERR "Bad db entry: $key, $val\n";
170 } else {
171 $proc_timestamp{$key} = $1; my($task_id) = $2;
172 $proc_state{$key} = $1 if $task_id =~ s/^([^0-9])//;
173 $proc_task_id{$key} = $task_id;
174 if (!exists $proc_state_bars{$key}) { # new process appeared
175 $proc_last_timestamp{$key} = $proc_timestamp{$key};
176 $proc_state_bars{$key} = '';
177 }
178 }
179 }
180 $stat==DB_NOTFOUND or die "c_get: $BerkeleyDB::Error $!";
181 $cursor->c_close==0 or die "c_close error: $BerkeleyDB::Error";
182 $cursor = undef;
183 };
184 my($eval_stat) = $@;
185 if (defined $db) {
186 $cursor->c_close if defined $cursor; # unlock, ignoring status
187 $cursor = undef;
188 }
189 }
190 if ($interrupt ne '') { kill($interrupt,$$) } # resignal, ignoring status
191 elsif ($eval_stat ne '') { chomp($eval_stat); die "BDB $eval_stat\n" }
192 for my $key (keys(%proc_state_bars)) { # remove old entries
193 if (!exists($proc_timestamp{$key})) {
194 delete $proc_timestamp{$key};
195 delete $proc_task_id{$key};
196 delete $proc_state_bars{$key};
197 }
198 }
199 my(@to_be_removed,@killed);
200 for my $pid (sort {$a<=>$b} keys %proc_timestamp) {
201 $proc_state{$pid} = ' ' if $proc_state{$pid} eq '';
202 my($idling) = $proc_task_id{$pid} eq '' &&
203 $proc_state{$pid} =~ /^[. ]?\z/s;
204 my($age) = $now - $proc_timestamp{$pid};
205 if ($idling) { $proc_state_bars{$pid} = '' }
206 else {
207 $proc_state_bars{$pid} = ''
208 if $proc_timestamp{$pid} ne $proc_last_timestamp{$pid};
209 my($len) = int($age+0.5);
210 $len = 1 if $len < 1;
211 my($str) = $proc_state_bars{$pid};
212 if ($len > length($str)) { # replicate last character to desired size
213 my($ch) = $str eq '' ? '=' : substr($str,-1,1);
214 $str .= $ch x ($len - length($str));
215 }
216 substr($str,$len-1,1) = $proc_state{$pid};
217 $proc_state_bars{$pid} = $str;
218 }
219 $proc_last_timestamp{$pid} = $proc_timestamp{$pid};
220 my($ttl) = $idling ? $idlettl : $activettl;
221 my($n) = kill(0,$pid); # test if the process is still there
222 if ($n == 0 && $! != ESRCH) {
223 die "Can't check the process $pid: $!";
224 } elsif ($n == 0) { # ESRCH means there is no such process
225 printf STDERR ("PID %s: %-11s went away %s\n",
226 $pid, $proc_task_id{$pid} || $proc_state{$pid},
227 fmt_age($age, $proc_state_bars{$pid}, $idling) );
228 push(@to_be_removed, $pid);
229 } elsif ($age <= $ttl) { # all ok
230 printf STDERR ("PID %s: %-11s %s\n",
231 $pid, $proc_task_id{$pid} || $proc_state{$pid},
232 fmt_age($age, $proc_state_bars{$pid}, $idling) );
233 } else { # send a SIGTERM
234 printf STDERR ("PID %s: %-11s terminated %s\n",
235 $pid, $proc_task_id{$pid} || $proc_state{$pid},
236 fmt_age($age, $proc_state_bars{$pid}, $idling) );
237 if (kill('TERM',$pid) || $! == ESRCH) { push(@killed,$pid) }
238 else { warn "Can't SIGTERM $pid: $!" }
239 }
240 }
241 if (@to_be_removed) {
242 local($SIG{'INT'}) = 'IGNORE';
243 $cursor = $db->db_cursor(DB_WRITECURSOR); # obtain a write lock
244 defined $cursor or die "BDB db_cursor error: $BerkeleyDB::Error";
245 for my $key (@to_be_removed) {
246 my($val); my($stat) = $cursor->c_get($key,$val,DB_SET);
247 $stat==0 || $stat==DB_NOTFOUND
248 or die "BDB c_get: $BerkeleyDB::Error, $!.";
249 if ($stat==0) { # remove existing entry
250 $cursor->c_del==0 or die "BDB c_del: $BerkeleyDB::Error, $!.";
251 }
252 }
253 $cursor->c_close==0 or die "BDB c_close error: $BerkeleyDB::Error";
254 $cursor = undef;
255 }
256 my($delay) = 1; # seconds
257 while (@killed) {
258 Time::HiRes::sleep($delay); $delay = 2;
259 for my $pid (@killed) {
260 $waittime{$pid}++;
261 printf STDERR ("PID %s: sending SIGKILL in %d s\n",
262 $pid, 30-$waittime{$pid});
263 if ($waittime{$pid} > 30) { # send a SIGKILL
264 kill('KILL',$pid) or $! == ESRCH or warn "Can't SIGKILL $pid: $!";
265 $waittime{$pid} = 0;
266 } elsif (kill(0,$pid)) { # process is still there
267 } elsif ($! != ESRCH) { # problem?
268 warn "Can't check process $pid: $!";
269 } else { # no longer around
270 printf STDERR ("PID %s: %-11s successfully killed\n", $pid);
271 delete($waittime{$pid});
272 $pid = undef;
273 }
274 }
275 @killed = grep {defined} @killed;
276 printf STDERR ("Waiting for the process to terminate: %s\n",
277 join(', ',@killed)) if @killed;
278 }
279 $| = 1;
280 last if defined $repeatcount && $repeatcount <= 0;
281 Time::HiRes::sleep($wakeuptime) if $wakeuptime > 0;
282 } # forever
283 $normal_termination = 1;
284
285 END {
286 if (defined $db) {
287 $cursor->c_close if defined $cursor; # ignoring status
288 $db->db_close==0 or die "BDB db_close error: $BerkeleyDB::Error $!";
289 }
290 print STDERR "exited\n" if !$normal_termination;
291 }