summaryrefslogtreecommitdiff
path: root/bin/icli
blob: 3b2a7a36e539b77eddd1fd5509651cf97afb2b39 (plain)
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
#!/usr/bin/env perl
## Copyright © 2010 by Daniel Friesel <derf@finalrewind.org>
## License: WTFPL <http://sam.zoy.org/wtfpl>
##   0. You just DO WHAT THE FUCK YOU WANT TO.
use autodie;
use strict;
use warnings;
use 5.010;

use Date::Format;
use Getopt::Long qw/:config bundling/;
use Term::ANSIColor;

my $VERSION = '0.2';

my ($cache, $config, $data, $extra);
my $config_file = '/var/cache/icinga/objects.cache';
my $status_file = '/var/lib/icinga/status.dat';
my $rw_file     = '/var/lib/icinga/rw/icinga.cmd';
my $context;
my $colours = 1;
my $short = 0;
my $list_type = 's';
my $verbosity = 1;
my $recheck = 0;
my (@for_hosts, @for_groups, @for_services, @list_hosts, @list_services);
my @filters;

sub have_host {
	my ($host) = @_;
	if ($list_type eq 's') {
		return exists $data->{services}->{$host};
	}
	else {
		return exists $data->{hosts}->{$host};
	}
}

sub have_service {
	my ($host, $service) = @_;

	foreach my $s (@{$data->{services}->{$host}}) {
		if ($s->{service_description} eq $service) {
			return 1;
		}
	}
	return 0;
}

sub have_service_multi {
	my ($host, @services) = @_;

	foreach my $s (@services) {
		if (have_service($host, $s)) {
			return 1;
		}
	}
	return 0;
}

sub with_colour {
	my ($text, $colour) = @_;
	if ($colours) {
		return colored($text, $colour);
	}
	else {
		return $text;
	}
}

sub pretty_date {
	my ($unix) = @_;
	return time2str('%Y-%m-%d %H:%M:%S', $unix);
}

sub check_is_soft {
	my ($x) = @_;

	return ($x->{'last_hard_state'} != $x->{'current_state'});
}


sub filter_generic {
	my ($x) = @_;
	my $filters_unfulfilled = @filters;

	if ($short and not $x->{'current_state'}) {
		return 0;
	}

	foreach my $f (@filters) {
		if (
			($f eq  'A' and     $x->{'problem_has_been_acknowledged'}) or
			($f eq '!A' and not $x->{'problem_has_been_acknowledged'}) or
			($f eq  'F' and     $x->{'is_flapping'}) or
			($f eq '!F' and not $x->{'is_flapping'}) or
			($f eq  'P' and     $x->{'passive_checks_enabled'}
			            and not $x->{'active_checks_enabled'}) or
			($f eq '!P' and     $x->{'active_checks_enabled'}) or
			($f eq  'S' and     check_is_soft($x)) or
			($f eq '!S' and not check_is_soft($x)) or
			($f eq  'o' and     $x->{'current_state'} == 0) or
			($f eq '!o' and     $x->{'current_state'} != 0) or
			($f eq  'w' and     $x->{'current_state'} == 1) or
			($f eq '!w' and     $x->{'current_state'} != 1) or
			($f eq  'c' and     $x->{'current_state'} == 2) or
			($f eq '!c' and     $x->{'current_state'} != 2) or
			($f eq  'u' and     $x->{'current_state'} == 3) or
			($f eq '!u' and     $x->{'current_state'} != 3) or
			($f eq  'd' and     $x->{'current_state'} == 1) or
			($f eq '!d' and     $x->{'current_state'} != 1) or
			($f eq  'x' and     $x->{'current_state'} == 2) or
			($f eq '!x' and     $x->{'current_state'} != 2) or

			0 # Terminator to ease adding new lines
		) {
			$filters_unfulfilled--;
		}
	}

	if ($filters_unfulfilled) {
		return 0;
	}

	return 1;
}

sub filter_host {
	my ($h) = @_;

	if (not filter_generic($h)) {
		return 0;
	}

	return 1;
}

sub filter_service {
	my ($s) = @_;

	if (not filter_generic($s)) {
		return 0;
	}

	if (@list_services and not ($s->{'service_description'} ~~
			[@list_services])) {
		return 0;
	}

	return 1;
}

sub read_objects_line {
	my ($line, $ref) = @_;

	if ($line =~ / ^ (?:define \s )? (?<context> \w+) \s+ { /x) {
		$context = $+{context};
	}
	elsif ($line =~ / ^ \t (?<key> [^=\t]+ ) [=\t] (?<value> .*) $ /x) {
		$cache->{$+{key}} = $+{value};
	}
	elsif ($line =~ / ^ \t } $ /x) {
		given ($context) {
			when (['info', 'programstatus']) {
				${$ref}->{$context} = $cache;
			}
			when ('hoststatus') {
				${$ref}->{hosts}->{$cache->{host_name}} = $cache;
			}
			when ('servicestatus') {
				push(@{${$ref}->{services}->{$cache->{host_name}}}, $cache);
			}
			when ('contactstatus') {
				push(@{${$ref}->{contacts}}, $cache);
			}
			when ('hostdowntime') {
				push(@{${$ref}->{downtimes}}, $cache);
			}
			when ('hostgroup') {
				${$ref}->{hostgroups}->{$cache->{hostgroup_name}} = $cache;
			}
			when('servicegroup') {
				${$ref}->{servicegroups}->{$cache->{servicegroup_name}} = $cache;
			}
			when ('hostcomment') {
				# TODO
			}
			when ('servicecomment') {
				# TODO
			}
			when ([qw[
				timeperiod command contactgroup contact host service
				servicedependency
				]])
			{
				# skipped for now
			}
			default {
				warn("Unknown field in $status_file: $context\n");
			}
		}
		$cache = undef;
	}
}

sub read_objects {
	my ($file, $ref) = @_;

	open(my $fh, '<', $file);
	while (my $line = <$fh>) {
		chomp($line);
		read_objects_line($line, $ref);
	}
	close($fh);
}

sub enhance_status {
	HOST: for my $h (keys %{$data->{services}}) {
		for my $s (@{$data->{services}->{$h}}) {
			if ($s->{current_state} != 0) {
				$extra->{$h}->{service_problem} = 1;
				next HOST;
			}
		}
	}
}

sub service_state {
	my ($checked, $digit) = @_;

	if (not $checked) {
		return 'PENDING ';
	}

	given ($digit) {
		when(0) { return with_colour('   OK   ', 'black on_green' ) }
		when(1) { return with_colour(' WARNING', 'black on_yellow') }
		when(2) { return with_colour('CRITICAL', 'white on_red'   ) }
		when(3) { return with_colour(' UNKNOWN', 'white on_blue'  ) }
		default { die("Unknown service state: $digit\n") }
	}
}

sub host_state {
	my ($checked, $digit) = @_;

	if (not $checked) {
		return '  PENDING  ';
	}

	given($digit) {
		when(0) { return with_colour('    OK     ', 'black on_green') }
		when(1) { return with_colour('   DOWN    ', 'white on_red'  ) }
		when(2) { return with_colour('UNREACHABLE', 'white on_blue' ) }
		default { die("Unknown host state: $digit\n") }
	}
}

sub display_queue {
	my @queue = map  { $_->[0] }
	            sort { $a->[1] <=> $b->[1] }
	            map  { [$_, $_->{next_check}] }
	                 (values %{$data->{hosts}},
	                  map { @{$_} } values %{$data->{services}});

	@queue = grep { $_->{host_name} ~~ \@list_hosts } @queue;

	if (@list_services) {
		@queue = grep { $_->{service_description} ~~ \@list_services } @queue;
	}

	printf(
		"%-25.25s  %-20.20s  %-19s  %-19s\n",
		'Host',
		'Service',
		'Last Check',
		'Next Check',
	);

	for my $e (@queue) {

		if ($e->{next_check} == 0) {
			next;
		}

		printf(
			"%-25.25s  %-20.20s  %-19s  %-19s\n",
			$e->{host_name},
			$e->{service_description} // q{},
			pretty_date($e->{last_check}),
			pretty_date($e->{next_check}),
		);
	}
}

sub display_downtime {
	my ($d) = @_;
	my $v = $verbosity;

	printf('%-27.27s', $d->{'host_name'});

	if ($v >= 3) {
		printf(
			' %s %-10.10s',
			pretty_date($d->{'entry_time'}),
			$d->{'author'},
		);
	}
	if ($v >= 2) {
		printf(' %-30.30s', $d->{'comment'});
	}
	printf(
		' %s %s',
		pretty_date($d->{'start_time'}),
		pretty_date($d->{'end_time'}),
	);
	if ($v >= 2) {
		print ($d->{'fixed'} ? ' Fixed' : ' Flexi');
	}

	print "\n";
}


sub display_service {
	my ($s) = @_;

	my $v = $verbosity;
	my $flags = q{};

	printf("%-20.20s", $s->{service_description});

	if ($v >= 2) {
		if ($s->{'problem_has_been_acknowledged'}) {
			$flags .= 'A';
		}
		if ($s->{'is_flapping'}) {
			$flags .= 'F';
		}
		if ($s->{'active_checks_enabled'} == 0 and
				$s->{'passive_checks_enabled'} == 1) {
			$flags .= 'P';
		}
		if (not ($s->{'active_checks_enabled'} or
				$s->{'passive_checks_enabled'})) {
			$flags .= '!';
		}

		printf(" %s%-3s%s", color('bold'), $flags, color('reset'));
	}

	printf(" %s"     , service_state($s->{'has_been_checked'}, $s->{'current_state'}));

	if ($v >= 2) {
		printf(' %d/%d', $s->{'current_attempt'}, $s->{'max_attempts'});
	}

	printf(" %s\n", $s->{'plugin_output'});
}

sub display_host_services {
	my ($host, $all) = @_;
	my @services;

	@services = grep { filter_service($_) } @{$data->{'services'}->{$host}};

	if ($all and @services) {
		say "\n$host";
	}

	foreach my $service (@services) {

		if ($all) {
			print "\t";
		}

		display_service($service);
	}
}

sub display_host_single {
	my ($host) = @_;
	my $h = $data->{hosts}->{$host};
	my $v = $verbosity;

	printf("%-32.32s", $h->{'host_name'});
	printf(" %s", host_state($h->{'has_been_checked'}, $h->{'current_state'}));

	if ($v >= 2) {
		printf(" %d/%d", $h->{'current_attempt'}, $h->{'max_attempts'});
	}

	printf(" %s\n", $h->{'plugin_output'});
}

sub display_host {
	my ($host, $all) = @_;

	if ($list_type eq 'h') {
		display_host_single($host);
	}
	else {
		display_host_services($host, $all);
	}
}

sub dispatch_command {
	my $str = join(';', @_);

	open(my $cmd_fh, '>', $rw_file);
	printf $cmd_fh (
		"[%d] %s",
		time(),
		$str,
	);
	close($cmd_fh);
}


sub recheck_host_all {
	my ($host) = @_;

	dispatch_command('SCHEDULE_HOST_SVC_CHECKS', $host, time());
	say "Scheduled check of * on '$host'";
}

sub recheck_service {
	my ($host, $service) = @_;

	if (have_service($host, $service)) {
		dispatch_command('SCHEDULE_SVC_CHECK', $host, $service,
			time());
		say "Scheduled check of '$service' on '$host'";
	}
}

GetOptions(
	'c|config=s'      => \$config_file,
	'C|no-colours'    => sub { $colours = 0 },
	'f|status-file=s' => \$status_file,
	'F|rw-file=s'     => \$rw_file,
	'g|hostgroup=s'   => sub { push(@for_groups, split(/,/, $_[1])) },
	'h|host=s'        => sub { push(@for_hosts, split(/,/, $_[1])) },
	'l|list=s'        => sub { $list_type = substr($_[1], 0, 1) },
	'r|recheck'       => sub { $recheck = 1; $list_type = q{} },
	's|service=s'     => sub { push(@for_services, split(/,/, $_[1])) },
	'v|verbose+'      => \$verbosity,
	'V|version'       => sub { say "icli version $VERSION"; exit 0 },
	'x|critical-only' => \$short,
	'z|filter=s'      => sub { push(@filters, split(/,/, $_[1])) },
)
	or die("Please see perldoc -F $0 for help\n");

read_objects($status_file, \$data);
read_objects($config_file, \$config);
enhance_status();

foreach my $host (@for_hosts) {
	if (not exists $data->{services}->{$host}) {
		die("Unknown host: ${host}\n");
	}
}

@list_hosts    = @for_hosts;
@list_services = @for_services;

foreach my $group (@for_groups) {
	if (not exists $config->{'hostgroups'}->{$group}) {
		die("Unknown hostgroup: ${group}\n");
	}
	foreach my $host (split/,/, $config->{'hostgroups'}->{$group}->{'members'}) {
		if (not grep { $_ eq $host } @list_hosts) {
			push(@list_hosts, $host);
		}
	}
}

if (@list_hosts == 0) {
	@list_hosts = sort keys %{$data->{services}};
}

if (@list_services) {
	@list_hosts = grep { have_service_multi($_, @list_services) } @list_hosts;
}

if ($list_type eq 'h') {
	@list_hosts = grep { filter_host($data->{'hosts'}->{$_}) } @list_hosts;
}

if ($list_type ~~ [qw[s h]]) {
	foreach my $host (@list_hosts) {
		display_host($host, (@list_hosts > 1));
	}
}
elsif ($list_type eq 'q') {
	display_queue();
}
elsif ($list_type eq 'd') {
	foreach my $downtime (@{$data->{downtimes}}) {
		display_downtime($downtime);
	}
}
elsif ($recheck) {
	foreach my $host (@list_hosts) {
		if (not @list_services) {
			recheck_host_all($host);
		}
		else {
			foreach my $service (@list_services) {
				recheck_service($host, $service);
			}
		}
	}
}
else {
	die("See perldoc -F $0\n");
}

__END__

=head1 NAME

B<icli> - Icinga Command Line Interface

=head1 SYNOPSIS

B<icli> [B<-x>] [B<-h> I<hosts>] [B<-g> I<hostgroups>] [B<-s> I<services>]
[B<-c> I<config>] [B<-C>] [B<-f> I<status-file>]
[B<-r>|B<-lh>|B<-ls>|B<-lq>|B<-ld>]

=head1 DESCRIPTION

B<icli> is a command line interface to Icinga. By default it lists all
services and their states.

=head1 OPTIONS

=over

=item B<-c>|B<--config> I<config>

Read config from I<file> instead of the default
F</var/cache/icinga/objects.cache>

=item B<-C>|B<--no-colours>

Disable colours in output

=item B<-f>|B<--status-file> I<file>

Read the status from I<file> instead of the default
F</var/lib/icinga/status.dat>

=item B<-F>|B<--rw-file> I<file>

Use I<file> as external commands file. Default:
F</var/lib/icinga/rw/icinga.cmd>

=item B<-g>|B<--hostgroup> I<hostgroup>

Limit selection to hosts in I<hostgroup> (comma separated list)

=item B<-h>|B<--host> I<hosts>

Limit selection to I<hosts> (comma separated list)

=item B<-l>|B<--list> B<downtimes>|B<hosts>|B<services>|B<queue>

List either services (the default) or hosts.
Note that only the first character of the argument is checked, so C<< icli
-lh >>, C<< icli -ls >> etc. are also fine.

=item B<-r>|B<--recheck>

Schedule an immediate recheck of all selected services

=item B<-s>|B<--service> I<services>

Limit selection to I<services> (comma separated lists).  Can be combined with
B<-h>/B<-g> to further narrow down the selection, but may also be used
stand-alone.

=item B<-x>|B<--short>

Only show services which are not OK

=item B<-v>|B<--verbose>

Increase output verbosity

=item B<-V>|B<--version>

Show version information

=item B<-z>|B<--filter> I<expression>

comma separated list of filters, only shows services for which all filters
match.  See L</"FILTER EXPRESSIONS">.

=back

=head1 OUTPUT

=head2 SERVICE LISTING

This is the standard output method. It contains the following:

=over

=item * Service description

=item * -v: Service Flags (B<A>cknowledged, B<F>lapping, B<P>assive, B<!>no
checks)

=item * Service state (ok / warning / critical / unknown)

=item * -v: Current attempt / Max attempts

=item * Plugin output

=back

=head2 HOST LISTING

Enabled with -ld

=over

=item * Host name

=item * Host state (ok / down / unreachable)

=item * -v: Current attempt / Max attempts

=item * Plugin output

=back

=head2 QUEUE LISTING

Enabled with -lq

=over

=item * Host name

=item * Service name

=item * Last check

=item * Next check

=back

=head1 FILTER EXPRESSIONS

Each expression can be negated with an exclamation mark, e.g. "!A" for all
non-acknowledged services.

=over

=item B<A>

Check state has been acknowledged

=item B<F>

Service is flapping between states

=item B<P>

Only passive checks are enabled.  Note that B<!P> simply means that active
checks are enabled, no matter the status of passive checks

=item B<S>

Check state is soft.  For instance, it used to be OK and is now critical, but
has not reached its maximum number and caused a notification yet.  Good to
find (or ignore) service problems which might just be temporary, non-critical
glitches.

=item B<o>

Host/Service state is OK

=item B<w>

Service state is Warning

=item B<c>

Service state is Critical

=item B<u>

Service state is Unknown

=item B<d>

Host state is Down

=item B<x>

Host state is Unreachable

=back

=head1 EXIT STATUS

Zero, unless errors occured.

=head1 CONFIGURATION

None.

=head1 DEPENDENCIES

None, so far.

=head1 BUGS AND LIMITATIONS

This software is in early development stages. So there will probably be quite
a lot.

=head2 REPORTING BUGS

Either via mail to E<lt>derf@finalrewind.orgE<gt> or on
E<lt>http://github.com/derf/icinga-cli/issuesE<gt>.

=head1 EXAMPLES

=over

=item C<< icli -r -s 'APT Updates' >>

Schedule a check of the "APT Updates" service on all hosts having it

=item C<< icli -lq -h aneurysm -g chaosdorf-hosts >>

List check queue for all hosts in the hostgroup "chaosdorf-hosts", plus the
host aneurysm

=back

=head1 AUTHOR

Copyright (C) 2010 by Daniel Friesel E<lt>derf@finalrewind.orgE<gt>

=head1 LICENSE

  0. You just DO WHAT THE FUCK YOU WANT TO.