Projet

Général

Profil

Paste
Télécharger au format
Statistiques
| Branche: | Révision:

root / plugins / system / cpu_linux_multi @ 8589c6df

Historique | Voir | Annoter | Télécharger (11 ko)

1
#! /usr/bin/perl
2
########################################################################
3
# Copyright (c) 2012, Adrien Urban
4
# All rights reserved.
5
# 
6
# Redistribution and use in source and binary forms, with or without
7
# modification, are permitted provided that the following conditions are
8
# met: 
9
# 
10
# 1. Redistributions of source code must retain the above copyright
11
#    notice, this list of conditions and the following disclaimer. 
12
# 2. Redistributions in binary form must reproduce the above copyright
13
#    notice, this list of conditions and the following disclaimer in the
14
#    documentation and/or other materials provided with the
15
#    distribution. 
16
# 
17
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
#
29
########################################################################
30
#                                                                      #
31
#    WARNING    WARNING    WARNING    WARNING    WARNING    WARNING    #
32
#                                                                      #
33
#       This plugin does not work properly with multiple master        #
34
#                                                                      #
35
########################################################################
36
#
37
# multigraph, supersampling, extended cpu information
38
#
39
# require: mpstat (to actually collect the data)
40
#
41
#
42
# ENV (default):
43
#  MUNIN_PLUGSTATE  - pid and cache files gets there
44
#
45
# ENV (user defined):
46
#  MUNIN_UPDATERATE - rate at which to update (default: 1s)
47
#  MUNIN_CACHEFLUSH_RATE - flush data every N batch (default: 1)
48
#  MUNIN_MPSTAT - binary to use as mpstat
49
#
50
#  increase cache flush rate if you have i/o performance issues
51
#  warning: increasing flushrate too much might cause partial write, and
52
#  loss of data. 0 to disable flush
53
#
54
#
55
# Parent graph: cpu usage per core/thread
56
# child graph(1): detailed cpu usage overall
57
# child graph(n): detailed cpu usage per thread
58
#
59
# Known bugs:
60
#
61
#   Multi-Master
62
#     If there are many masters, the data is only sent once. Each master will
63
#     only have part of the data.
64
#
65
#   Everlasting
66
#     The daemon is launched on first config/fetch. A touch of the pidfile is
67
#     done on every following config/fetch. The daemon should check if the
68
#     pidfile is recent (configurable) enough, and stop itself if not.
69
#
70
#   Graph Order
71
#     There is currently (2.0.6) noway to order childgraphs.
72
#
73
#   RRD file
74
#     The master currently (2.0.6) generate rrd file for aggregate values, and
75
#     complains that no data is provided for them (but the graph still works
76
#     fine)
77
#
78

    
79
#%# family=auto
80
#%# capabilities=autoconf
81

    
82
use strict;
83
use warnings;
84

    
85
my $plugin = $0;
86
$plugin =~ s/.*\///;
87

    
88
# quick failsafe
89
if (!defined $ENV{MUNIN_PLUGSTATE}) {
90
	die "This plugin should be run via munin. Try munin-run $plugin\n";
91
}
92

    
93
########################################################################
94
# If you want to change something, it's probably doable here
95
#
96

    
97
# order to display
98
my $fields_order = [
99
	'sys', 'usr', 'nice', 'idle', 'iowait', 'irq', 'soft', 'steal', 'guest',
100
];
101
# order is the order given by mpstat
102
my $fields_info = [
103
	{
104
		name => 'usr',
105
		label => 'usr',
106
		info => "%s time spent in normal programs and daemons",
107
	}, {
108
		name => 'nice',
109
		label => 'nice',
110
		info => "%s time spent in nice(1)d programs and daemons",
111
	}, {
112
		name => 'sys',
113
		label => 'sys',
114
		info => "%s time spent in kernel system activity",
115
	}, {
116
		name => 'iowait',
117
		label => 'iowait',
118
		info => "%s time spent waiting for blocking I/O operations",
119
	}, {
120
		name => 'irq',
121
		label => 'irq',
122
		info => "%s time spent handling interrupts",
123
	}, {
124
		name => 'soft',
125
		label => 'soft',
126
		info => "%s time spent handling software interrupts",
127
	}, {
128
		name => 'steal',
129
		label => 'steal',
130
		info => "%s time spent elsewhere (stolen from us)",
131
	}, {
132
		name => 'guest',
133
		label => 'guest',
134
		info => "%s time spent in a guest operating system",
135
	}, {
136
		name => 'idle',
137
		label => 'idle',
138
		info => "%s time spent idling (waiting to get something to do)",
139
	}
140
];
141

    
142
sub pidfile() { "$ENV{MUNIN_PLUGSTATE}/munin.$plugin.pid" }
143
sub cachefile() { "$ENV{MUNIN_PLUGSTATE}/munin.$plugin.cache" }
144

    
145
sub graph_section() { "system:cpu" };
146
sub graph_name() { "cpu_extended_multi_1s" };
147
sub graph_title() { "CPU usage" };
148
sub graph_title_all() { "Overall CPU usage" };
149
sub graph_title_n($) { "CPU#" . (shift) . " usage" };
150
sub acquire_name() { "<$plugin> collecting information" }
151

    
152
########################################################################
153
# if you need to change something after that line, It should probably be
154
# changed to be configurable above it.
155
#
156

    
157
# mpstat sampling interval
158
my $update_rate = 1;
159
if (defined $ENV{MUNIN_UPDATERATE}) {
160
	if ($ENV{MUNIN_UPDATERATE} =~ /^[1-9][0-9]*$/) {
161
		$update_rate = int($ENV{MUNIN_UPDATERATE});
162
	} else {
163
		print STDERR "Invalid update_rate: $ENV{MUNIN_UPDATERATE}";
164
	}
165
}
166

    
167
my $flush_interval = 1;
168
if (defined $ENV{MUNIN_CACHEFLUSH_RATE}) {
169
	if ($ENV{MUNIN_CACHEFLUSH_RATE} =~ /^[0-9]+$/) {
170
		$update_rate = int($ENV{MUNIN_CACHEFLUSH_RATE});
171
	} else {
172
		print STDERR "Invalid flush rate: $ENV{MUNIN_CACHEFLUSH_RATE}";
173
	}
174
}
175

    
176
my $mpstat = "mpstat";
177
if (defined $ENV{MUNIN_MPSTAT}) {
178
	if (-f $ENV{MUNIN_MPSTAT}) {
179
		print STDERR "MUNIN_STAT: file not found: $ENV{MUNIN_MPSTAT}";
180
	} else {
181
		$mpstat = defined $ENV{MUNIN_MPSTAT};
182
	}
183
}
184

    
185
my $cpu_count_cache = undef;
186
sub cpu_count() {
187
	if (not defined $cpu_count_cache) {
188
               open MPSTAT, "$mpstat -P ALL |" or die "open mpstat|: $!\n";
189
               $cpu_count_cache = 0;
190
               while (<MPSTAT>) {
191
                       chomp;
192
                       my @field = split();
193
                       next unless ($field[1] && ($field[1] =~ /^([0-9]+)$/));
194
                       $cpu_count_cache ++;
195
               }
196
               close(MPSTAT);
197
	}
198
	return $cpu_count_cache;
199
}
200

    
201
sub is_running() {
202
	if (-f pidfile()) {
203
		my $pid = undef;
204
		if (open FILE, "<", pidfile()) {
205
			$pid = <FILE>;
206
			close FILE;
207
			chomp $pid;
208
		}
209
		if ($pid) {
210
			# does not exist ? kill it
211
			if (kill 0, $pid) {
212
				return 1;
213
			}
214
		}
215
 		unlink(pidfile());
216
	}
217
	return 0;
218
}
219

    
220

    
221
# FIXME: should also trap kill sigint and sigterm
222
# FIXME: check pidfile got touched recently
223
sub acquire() {
224
	$0 = acquire_name();
225
	$ARGV = [ '<daemon>' ];
226
	$0 = "<$plugin> collecting information";
227
	open PIDFILE, '>', pidfile() or die "open: @{[ pidfile() ]}: $!\n";
228
	print PIDFILE $$, "\n";
229
	close PIDFILE;
230
	open CACHE, ">>", cachefile() or die "open: @{[ cachefile() ]}: $!\n";
231
	open MPSTAT, "-|", "$mpstat -P ALL $update_rate" or
232
		die "open mpstat|: $!\n";
233
	my $flush_count = 0;
234
	while (<MPSTAT>) {
235
		chomp;
236
		my @field = split();
237
		if (!($field[1] =~ /^(all|[0-9]+)$/)) {
238
			next;
239
		}
240
		$field[0] = $field[1];
241
		$field[1] = time();
242
		print CACHE join(" ", @field), "\n";
243
		if ($flush_interval) {
244
			if ($flush_interval == ++$flush_count) {
245
				CACHE->flush();
246
				$flush_count = 0;
247
			}
248
		}
249
	}
250
	unlink(pidfile());
251
	unlink(cachefile());
252
}
253

    
254
sub run_daemon() {
255
	if (is_running()) {
256
		my $atime;
257
		my $mtime;
258
		$atime = $mtime = time;
259
		utime $atime, $mtime, pidfile();
260
	} else {
261
		if (0 == fork()) {
262
			close(STDIN);
263
			close(STDOUT);
264
			close(STDERR);
265
			open STDIN, "<", "/dev/null";
266
			open STDOUT, ">", "/dev/null";
267
			open STDERR, ">", "/dev/null";
268
			acquire();
269
			exit(0);
270
		}
271
	}
272
}
273

    
274

    
275
sub run_autoconf() {
276
	# in case we have specified args, check the file before that
277
	my $file = $mpstat;
278
	$file =~ s/ .*//;
279
	my $path = `which "$file"`;
280
	if ($path) {
281
		print "yes\n";
282
	} else {
283
		print "no\n";
284
	}
285
}
286

    
287
sub show_config($$$) {
288
	my $i = shift;
289
	my $name = shift;
290
	my $title = shift;
291
	my $graph_order = "graph_order";
292
	for my $field (@$fields_order) {
293
		$graph_order .= " $field";
294
	}
295
	print <<EOF;
296
multigraph @{[ graph_name() ]}.cpu$i
297
graph_title $title
298
graph_vlabel cpu use %
299
graph_scale no
300
update_rate 1
301
graph_data_size custom 1d, 10s for 1w, 1m for 1t, 5m for 1y
302
$graph_order
303
EOF
304
	for my $field (@$fields_info) {
305
		my $style = "STACK";
306
		if ($field->{name} eq $fields_order->[0]) {
307
			$style = "AREA";
308
		}
309
		print <<EOF;
310
$field->{name}.label $field->{label}
311
$field->{name}.draw $style
312
$field->{name}.info @{[ sprintf($field->{info}, $name) ]}
313
$field->{name}.min 0
314
$field->{name}.cdef $field->{name}
315
EOF
316
	}
317
}
318

    
319
sub run_config() {
320
	run_daemon();
321
	my $cpus = cpu_count();
322
	my $graph_order = "graph_order";
323
	my $sub_order = "order cpuall";
324
	for (my $i = 0; $i < $cpus; ++$i) {
325
		$graph_order .= " use$i=@{[ graph_name() ]}.cpu$i.idle";
326
		$sub_order .= " cpu$i";
327
	}
328
# none of those seems to have any effect
329
#domain_$sub_order
330
#node_$sub_order
331
#graph_$sub_order
332
#service_$sub_order
333
#category_$sub_order
334
#group_$sub_order
335

    
336
	print <<EOF;
337
multigraph @{[ graph_name() ]}
338
graph_category @{[ graph_section() ]}
339
graph_title @{[ graph_title() ]}
340
graph_vlabel cpu use %
341
graph_scale no
342
graph_total All CPUs
343
update_rate 1
344
graph_data_size custom 1d, 10s for 1w, 1m for 1t, 5m for 1y
345
$graph_order
346
EOF
347
	my $style="AREA";
348
	for (my $i = 0; $i < $cpus; ++$i) {
349
		print <<EOF;
350
use$i.label CPU#$i
351
use$i.draw $style
352
use$i.cdef 100,use$i,-,${cpus},/
353
EOF
354
		$style = 'STACK';
355
	}
356
	# detailed sub graphs - 1 for all, and 1 per cpu
357
	show_config("all", "all CPU", graph_title_all());
358
	for (my $i = 0; $i < $cpus; ++$i) {
359
		show_config($i, "CPU$i", graph_title_n($i));
360
	}
361
}
362

    
363
sub fetch_showline($) {
364
	my $line = shift;
365
	my $n = 2;
366
	for my $field (@$fields_info) {
367
		print <<EOF;
368
$field->{name}.value $line->[1]:$line->[$n]
369
EOF
370
		++$n;
371
	}
372
}
373
sub run_fetch() {
374
	run_daemon();
375
	if (open CACHE, "+<", cachefile()) {
376
		my $cpus = {};
377
		while (<CACHE>) {
378
			chomp;
379
			my $field = [];
380
			@$field = split(/ /);
381
			if (not defined $cpus->{$field->[0]}) {
382
				$cpus->{$field->[0]} = [];
383
			}
384
			push @{$cpus->{$field->[0]}}, $field;
385
		}
386
		# finished reading ? truncate it right away
387
		truncate CACHE, 0;
388
		close CACHE;
389
		foreach my $cpu (keys %$cpus) {
390
			print <<EOF;
391
multigraph @{[ graph_name() ]}.cpu$cpu
392
EOF
393
			foreach my $line (@{$cpus->{$cpu}}) {
394
				fetch_showline($line);
395
			}
396
		}
397
	}
398
}
399

    
400
my $cmd = 'fetch';
401
if (defined $ARGV[0]) {
402
	$cmd = $ARGV[0];
403
}
404
if ('fetch' eq $cmd) {
405
	run_fetch();
406
} elsif ('config' eq $cmd) {
407
	run_config();
408
} elsif ('autoconf' eq $cmd) {
409
	run_autoconf();
410
} elsif ('daemon' eq $cmd) {
411
	run_daemon();
412
} else {
413
	print STDERR <<EOF;
414
$0: unrecognized command
415

    
416
Usage:
417
	$0 autoconf - check if we have everything we need
418
	$0 config - show plugin configuration
419
	$0 fetch - fetch latest data
420
	$0 daemon - launch daemon
421
EOF
422
	exit(1);
423
}
424
exit(0);
425

    
426
# for Munin Plugin Gallery
427
# graph_category cpu
428