-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckshutdown
executable file
·337 lines (293 loc) · 9.44 KB
/
checkshutdown
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/env perl
use strict;
use warnings;
use 5.12.0;
use DateTime;
use DateTime::Duration;
use DateTime::Format::Strptime;
use Getopt::Long qw( GetOptions );
use List::MoreUtils qw( uniq );
use Net::Address::IP::Local;
use Transmission::Client;
my %opt = (
help => 0,
statefile => '/tmp/checkshutdown.state',
syslog => 0,
);
my %check_table = (
apache => {
help => 'Check for recent apache requests',
code => sub {
my $last_access = last_apache_access('/var/log/apache2/access.log');
return unless defined $last_access;
my $now = DateTime->now->epoch;
my $age = $now - $last_access->epoch;
my $max_age = 3 * 60;
if ($age < $max_age) {
return "Apache access $age seconds ago within $max_age seconds";
}
return;
},
},
console_user => {
help => 'Check is a user is logged in at the console',
code => sub {
return 'console user is active'
unless grep { /mythwelcome/ } `ps ax`;
return;
},
},
mythshutdown => {
help => 'Check if MythTV is busy',
code => sub {
my $exit = system(qw( mythshutdown -q --status ));
return sprintf('mythshutdown status 0x%02x', $exit >> 8)
if $exit > 0;
return; # 0 = shutdown ok, -1 = didn't run
},
},
checklivetv => {
help => 'Check if a TV tuner is in use',
code => sub {
my $output = `checklivetv`;
my $exitcode = $? >> 8;
# print $exitcode . "\n";
return 'error connecting to backend'
if $exitcode eq 1;
return 'TV tuner in use'
if $output ne "not recording\n";
return;
},
},
sabnzbd => {
help => 'Check if SABnzbd is busy',
code => sub {
use JSON::XS qw( decode_json );
my $host = '127.0.0.1';
my $port = 8080;
my $key = 'b46d9626617568fadbbcbd07220feb56';
my $uri_queue = "http://$host:$port/sabnzbd/api?mode=queue\\&output=json\\&apikey=$key";
my $sab_queue = eval { decode_json(`curl -s $uri_queue`)->{queue} };
#die("curl $uri failed: $@") unless $sab;
my $uri_history = "http://$host:$port/sabnzbd/api?mode=history\\&output=json\\&apikey=$key";
my $sab_history = eval { decode_json(`curl -s $uri_history`)->{history} };
my $last_status = "Completed";
if ($sab_history && $sab_history->{noofslots} > 0) {
$last_status = $sab_history->{slots}[0]->{status};
}
my @last_status_ok = qw(Completed Failed);
my $status_ok = grep{$_ eq $last_status} @last_status_ok;
## check that queue is not downloading and last element of history is Completed or Failed
my $sab_busy = ($sab_queue && ($sab_queue->{status} eq 'Downloading')) || !$status_ok;
return "SABnzbd is busy" if $sab_busy;
return;
},
},
nzbget => {
help => 'Check if NZBGet is busy',
code => sub {
use JSON::XS qw( decode_json );
my $host = '127.0.0.1';
my $port = 6789;
my $uri_status = "http://$host:$port/jsonrpc/status";
## check that server is in standby
my $raw_json = `curl -s $uri_status`;
return "Could not connect to NZBGet" if (length ($raw_json) == 0);
my $status = decode_json($raw_json)->{result};
my $standby = $status->{ServerStandBy};
my $postjobs = $status->{PostJobCount};
return "NZBGet is busy" if $standby ne "1" or $postjobs ne "0";
return;
},
},
airsonic => {
help => 'Check if airsonic is in use',
code => sub{
use JSON::XS qw( decode_json );
my $host = '127.0.0.1';
my $port = '4040/airsonic';
my $user = 'tom';
my $salt = 'ThisIsMySalt';
my $hash = '09670bd7d8afbe4f810a8e311e09dc82';
my $version = '1.15.0';
my $uri = "http://$host:$port/rest/getNowPlaying?u=$user&s=$salt&t=$hash&v=$version&c=status&f=json";
my $raw_json = `curl -s '$uri'`;
return "Could not connect to Airsonic" if (length ($raw_json) == 0);
my $status = decode_json($raw_json)->{'subsonic-response'};
return if (!$status->{nowPlaying} or !$status->{nowPlaying}->{entry});
for my $entry (@{$status->{nowPlaying}->{entry}}) {
return "Airsonic is in use" if $entry->{minutesAgo} < 10;
}
return;
},
},
ssh_sessions => {
help => 'Check for users logged in by ssh',
code => sub {
my $active_ssh_sessions = scalar check_remote_connections(22);
return "$active_ssh_sessions active ssh sessions"
if $active_ssh_sessions > 0;
return;
},
},
samba_sessions => {
help => 'Check for samba connections',
code => sub {
my $active_smb_sessions = scalar check_remote_connections(445);
return "$active_smb_sessions active samba sessions"
if $active_smb_sessions > 0;
return;
},
},
remote_mythtv => {
help => 'Check for remote mythtv clients connected on port 6543',
code => sub {
my $count_mythtv_sessions = scalar uniq check_remote_connections(6543);
return $count_mythtv_sessions . " remote mythtv clients"
if $count_mythtv_sessions > 0;
return;
},
},
emby => {
help => 'Check if emby is in use',
code => sub {
my $exit = system(qw(checkemby)) >> 8;
return sprintf('emby busy')
if $exit == 1;
return;
},
},
xbmc => {
help => 'Check if XBMC is running',
code => sub {
return 'XBMC is running'
if grep { m</usr/bin/xbmc> } `ps ax`;
return;
},
},
uptime => {
help => 'Check is system has been up long enough',
code => sub {
my $minimum_minutes = 5;
open(my $fh, '<', '/proc/uptime') or return;
my $line = <$fh>;
my ($uptime) = split(/\s+/, $line);
return "up for less than $minimum_minutes minutes"
unless $uptime > $minimum_minutes * 60;
return;
},
},
running_tasks => {
help => 'Check there are no tasks queued in task spooler',
code => sub {
my $socket = "TS_SOCKET=/tmp/socket-ts.1002";
my $jobcount = `${socket} tsp -l | wc -l`;
return if $jobcount == 1;
my $linecount = `${socket} tsp -i | grep "Time running" | wc -l`;
return 'Tasks running in task spooler'
unless $linecount == 0;
return;
}
}
);
my @default_checks = qw(
nzbget
ssh_sessions
samba_sessions
emby
running_tasks
);
my $opt_ok = GetOptions(
'help|h|?' => \$opt{help},
'syslog|s' => \$opt{syslog},
);
if ($opt{help} || !$opt_ok) {
usage();
}
exit main(@ARGV);
sub main {
my @checks = @_ ? @_ : @default_checks;
my $ok_to_shutdown = 1;
my @msgs;
for my $name (@checks) {
my $check = $check_table{$name};
if (!$check) {
diag("Unknown check: $name");
next;
}
my $msg = $check->{code}->();
$ok_to_shutdown = 0 if $msg;
push(@msgs, $msg) if $msg;
$msg ||= 'OK';
logit(sprintf("%-16s$msg", "$name")) unless $opt{syslog};
}
if ($opt{syslog}) {
my $prev_state = load_state();
my $new_state = $ok_to_shutdown ? 'all clear for shutdown' : 'busy: ' . join(', ', @msgs);
if ($prev_state ne $new_state) {
# logit($new_state);
save_state($new_state);
}
}
else {
# logit($ok_to_shutdown ? 'all clear for shutdown' : 'not shutting down');
}
return $ok_to_shutdown ? 0 : 1;
}
sub usage {
my $msg = "usage: $0 [--syslog] [check [checks...]]\n\nchecks:\n";
for my $name (sort keys %check_table) {
my $check = $check_table{$name};
$msg .= sprintf"\t%-16s%s\n", $name, $check->{help};
}
die $msg;
}
sub diag {
logit('info: ', @_);
return;
}
sub load_state {
open(my $fh, '<', $opt{statefile}) or return "";
my $state = <$fh> || "";
chomp $state;
return $state;
}
sub save_state {
my ($state) = @_;
open(my $fh, '>', $opt{statefile}) or return;
print {$fh} $state, "\n";
}
sub logit {
if ($opt{syslog}) {
system(qw( logger -p local0.info -t ), "checkshutdown[$$]", @_);
}
else {
say join(' ', @_);
}
}
sub last_apache_access {
my ($filename) = @_;
open my $fh, '<', $filename or (
warn("Opening $filename: $!"), return
);
# 23/Sep/2012:14:54:34 +1000
use DateTime::Format::Strptime;
my $parser = DateTime::Format::Strptime->new(
pattern => '%e/%b/%Y:%H:%M:%S %z',
);
my $dt;
while (<$fh>) {
$dt = $1 if /\[(.*?)\]/;
}
return unless defined $dt;
return $parser->parse_datetime($dt);
}
sub check_remote_connections {
my ($port) = @_;
my $localip = Net::Address::IP::Local->public_ipv4;
$localip =~ s/\./\\./g;
my $localip_regex = "(127\\.0\\.0|$localip:)";
my $command = "netstat -n | awk '\$4~/:$port/ && \$5!~/$localip_regex/ && \$6 == \"ESTABLISHED\" {split(\$5,a,\":\"); print a[1]}'";
my @outp = `$command`;
return @outp;
}