forked from FastVPSEestiOu/storage-system-monitoring
-
Notifications
You must be signed in to change notification settings - Fork 2
/
storage_system_fastvps_monitoring.pl
539 lines (408 loc) · 14.6 KB
/
storage_system_fastvps_monitoring.pl
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
#!/usr/bin/perl
=description
Authors:
Alexander Kaidalov <[email protected]>
Pavel Odintsov <[email protected]>
License: GPLv2
=cut
# TODO
# Добавить выгрузку информации по Физическим Дискам:
# megacli -PDList -Aall
# arcconf getconfig 1 pd
# Перенести исключение ploop на этап идентификации дисковых устройств
# Добавить явно User Agent как у мониторинга, чтобы в случае чего их не лочило
# В случае Adaptec номер контроллера зафикисрован как 1, поддерживается только один контроллер
# В случае Adaptec поддерживается только один логический раздел!!!
use strict;
use warnings;
use LWP::UserAgent;
use JSON;
use Data::Dumper;
# Конфигурация
my $VERSION = "1.0";
# diagnostic utilities
my $ADAPTEC_UTILITY = '/usr/local/bin/arcconf';
my $LSI_UTILITY = '/opt/MegaRAID/MegaCli/MegaCli64';
# API
my $API_URL = 'https://fastcheck24.com/api/server-state/storage';
# Centos && Debian uses same path
my $parted = "LANG=POSIX /sbin/parted";
# Centos && Debian uses same path
my $mdadm = "/sbin/mdadm";
my $sysfs_block_path = '/sys/block';
# Список устройств, которые мы игнорируем из рассмотрения
my @major_blacklist = (
1, # это ram устройства
7, # это loop устройства
182, # это openvz ploop диск
);
# Обанаруживаем все устройства хранения
# Также у нас есть старая версия, работающая исключительно на базе parted: find_disks()
my @disks = find_disks_without_parted();
# Проверим, все ли у нас тулзы для диагностики установлены
check_disk_utilities(@disks);
# Получаем информацию обо всех дисках
@disks = diag_disks(@disks);
my $only_detect_drives = 0;
# Запуск из крона
my $cron_run = 0;
if (scalar @ARGV > 0 and $ARGV[0] eq '--detect') {
$only_detect_drives = 1;
}
if (scalar @ARGV > 0 and $ARGV[0] eq '--cron') {
$cron_run = 1;
}
if ($only_detect_drives) {
for my $storage (@disks) {
# Для обычных дисков понятия статуса нету
if ($storage->{'type'} eq 'hard_disk') {
print "Device $storage->{device_name} with type: $storage->{type} model: $storage->{model} detected\n";
} else {
# а вот для RAID оно вполне определено
print "Device $storage->{device_name} with type: $storage->{type} model: $storage->{model} in state: $storage->{status} detected\n";
}
}
if (scalar @disks == 0) {
print "I can't find any disk devices. I suppose bug on this platform :(";
}
exit (0);
}
if ($cron_run) {
if(!send_disks_results(@disks)) {
print "Failed to send storage monitoring data to FastVPS";
exit(1);
}
}
if (!$only_detect_drives && !$cron_run) {
print "This information was gathered and will be sent to FastVPS:\n";
print "Disks found: " . (scalar @disks) . "\n\n";
for my $storage (@disks) {
print $storage->{device_name} . " is " . $storage->{'type'} . " Diagnostic data:\n";
print $storage->{'diag'} . "\n\n";
}
}
#
# Functions
#
# Функция обнаружения всех дисковых устройств в системе
sub find_disks {
# here we'll save disk => ( info, ... )
my @disks = ();
# get list of disk devices with parted
my @parted_output = `$parted -lms`;
if ($? != 0) {
die "Can't get parted output. Not installed?!";
}
for my $line (@parted_output) {
chomp $line;
# skip empty line
next if $line =~ /^\s/;
next unless $line =~ m#^/dev#;
# После очистки нам приходят лишь строки вида:
# /dev/sda:3597GB:scsi:512:512:gpt:DELL PERC H710P;
# /dev/sda:599GB:scsi:512:512:msdos:Adaptec Device 0;
# /dev/md0:4302MB:md:512:512:loop:Linux Software RAID Array;
# /dev/sdc:1500GB:scsi:512:512:msdos:ATA ST31500341AS;
# Отрезаем точку с запятой в конце
$line =~ s/;$//;
# get fields
my @fields = split ':', $line;
my $device_name = $fields[0];
my $device_size = $fields[1];
my $model = $fields[6];
# Это виртуальные устройства в OpenVZ, их не нужно анализировать
if ($device_name =~ m#/dev/ploop\d+#) {
next;
}
# detect type (raid or disk)
my $type = 'disk';
my $is_raid = '';
# adaptec
if($model =~ m/adaptec/i) {
$model = 'adaptec';
$is_raid = 1;
}
# Linux MD raid (Soft RAID)
if ($device_name =~ m/\/md\d+/) {
$model = 'md';
$is_raid = 1;
}
# LSI (3ware) / DELL PERC (LSI chips also)
if ($model =~ m/lsi/i or $model =~ m/PERC/i) {
$model = 'lsi';
$is_raid = 1;
}
# add to list
my $tmp_disk = {
"device_name" => $device_name,
"size" => $device_size,
"model" => $model,
"type" => ($is_raid ? 'raid' : 'hard_disk'),
};
push @disks, $tmp_disk;
}
return @disks;
}
# Убираем все пробельные символы в конце строки
sub rtrim {
my $string = shift;
$string =~ s/\s+$//g;
return $string;
}
# Получаем путь до устройства по его имени
sub get_device_path {
my $name = shift;
return "/dev/$name";
}
# Получаем major идентификатор блочного устройства в Linux
sub get_major {
my $device_path = shift;
my $rdev = (stat $device_path)[6];
# Это платформо зависимый код!
# https://github.com/quattor/LC/blob/master/src/main/perl/Stat.pm
my $major = ($rdev >> 8) & 0xFF;
return $major;
}
sub in_array {
my ($elem, @array) = @_;
return scalar grep { $elem eq $_ } @array;
}
sub file_get_contents {
my $path = shift;
open my $fl, "<", $path or die "Can't open file";
my $data = join '', <$fl>;
chomp $data;
close $fl;
return $data;
}
# Пробуем получить производителя устройства
sub get_device_vendor {
my $device_name = shift;
my $vendor_path = "$sysfs_block_path/$device_name/device/vendor";
if (-e $vendor_path) {
my $vendor_raw = file_get_contents($vendor_path);
$vendor_raw = lc($vendor_raw);
# remove trailing spaces
$vendor_raw =~ s/\s+$//g;
return $vendor_raw;
} else {
return "unknown";
}
}
# Получаем модуль устройства
sub get_device_model {
my $device_name = shift;
my $model_path = "$sysfs_block_path/$device_name/device/model";
if (-e $model_path) {
my $model_raw = file_get_contents($model_path);
$model_raw = lc($model_raw);
# remove trailing spaces
$model_raw =~ s/\s+$//g;
return $model_raw;
} else {
return "unknown";
}
}
sub get_device_size {
my $device_name = shift;
my $size_path = "$sysfs_block_path/$device_name/size";
if (-e $size_path) {
my $size_in_blocks = file_get_contents($size_path);
# Переводим в байты
my $size_in_bytes = $size_in_blocks << 9;
my $size_in_gbytes = int($size_in_bytes/1024**3);
return "${size_in_gbytes}GB";
} else {
return "unknown";
}
}
# Обнаруживаем дисковые устройства без использования внешнего parted
# Используются идеи из кода util-linux-2.24, lsblk
sub find_disks_without_parted {
opendir my $block_devices, $sysfs_block_path or die "Can't open path $sysfs_block_path";
my @disks = ();
while (my $block_device = readdir($block_devices)) {
# skip . and ..
if ($block_device =~ m/^\.+$/) {
next;
}
# skip device mapper fake devices
if ($block_device =~ m/^dm-\d+/) {
next;
}
# Также исключаем из рассмотрения служебные не физические устройства по номеру major
my $major = get_major(get_device_path($block_device));
if (in_array($major, @major_blacklist)) {
next;
}
my $vendor = get_device_vendor($block_device);
my $model = get_device_model($block_device);
# Код ниже ожидает вот в таком виде
$model = "$vendor $model";
my $device_size = get_device_size($block_device);
my $device_name = get_device_path($block_device);
# detect type (raid or disk)
my $type = 'disk';
my $is_raid = '';
my $raid_level = '';
# adaptec
if($model =~ m/adaptec/i) {
$model = 'adaptec';
$is_raid = 1;
}
# Linux MD raid (Soft RAID)
if ($device_name =~ m/\/md\d+/) {
$model = 'md';
$is_raid = 1;
$raid_level = file_get_contents("/sys/block/$block_device/md/level");
}
# LSI (3ware) / DELL PERC (LSI chips also)
if ($model =~ m/lsi/i or $model =~ m/PERC/i) {
$model = 'lsi';
$is_raid = 1;
}
# add to list
my $tmp_disk = {
"device_name" => $device_name,
"size" => $device_size,
"model" => $model,
"type" => ($is_raid ? 'raid' : 'hard_disk'),
};
push @disks, $tmp_disk;
}
return @disks;
}
# Check diagnostic utilities availability
sub check_disk_utilities {
my (@disks) = @_;
my $adaptec_needed = 0;
my $lsi_needed = 0;
my $mdadm_needed = 0;
for my $storage (@disks) {
# Adaptec
if ($storage->{model} eq "adaptec") {
$adaptec_needed = 1;
}
# LSI
if ($storage->{model} eq "lsi") {
$lsi_needed = 1;
}
if ($storage->{model} eq "md") {
$mdadm_needed = 1;
}
}
if ($adaptec_needed) {
die "Adaptec utility not found. Please, install Adaptech raid management utility into " . $ADAPTEC_UTILITY . "\n" unless -e $ADAPTEC_UTILITY;
}
if ($lsi_needed) {
die "Megacli not found. Please, install LSI MegaCli raid management utility into " . $LSI_UTILITY . " (symlink if needed)\n" unless -e $LSI_UTILITY
}
if ($mdadm_needed) {
die "mdadm not found. Please, install mdadm" unless -e $mdadm;
}
}
# Извлекает из единого блока данных состояние логического устройства Adaptec
sub extract_adaptec_status {
my $data = shift;
my @data_as_array = split "\n", $data;
my $status = 'unknown';
for my $line (@data_as_array) {
chomp $line;
if ($line =~ /^\s+Status of logical device\s+:\s+(\w+)$/i) {
$status = lc(rtrim($1));
}
}
return $status;
}
sub extract_lsi_status {
my $data = shift;
my @data_as_array = split "\n", $data;
my $status = 'unknown';
for my $line (@data_as_array) {
chomp $line;
if ($line =~ /^State\s+:\s+(\w+)/i) {
$status = lc(rtrim($1));
}
}
return $status;
}
# Извлекат из единого блока выдачи состояние массива
sub extract_mdadm_raid_status {
my $data = shift;
my @data_as_array = split "\n", $data;
my $status = 'unknown';
for my $line (@data_as_array) {
chomp $line;
if ($line =~ /^\s+State\s+:\s+(.+)$/) {
$status = lc(rtrim($1));
}
}
return $status;
}
# Run disgnostic utility for each disk
sub diag_disks {
my (@disks) = @_;
my @result_disks = ();
foreach my $storage (@disks) {
my $device_name = $storage->{device_name};
my $type = $storage->{type};
my $model = $storage->{model};
my $res = '';
my $cmd = '';
# где можем, выцепляем состояние массива, актуально в первую очередь для RAID массивов
my $storage_status = 'undefined';
if ($type eq 'raid') {
# adaptec
if ($model eq "adaptec") {
$cmd = $ADAPTEC_UTILITY . " getconfig 1 ld";
$res = `$cmd 2>&1`;
$storage_status = extract_adaptec_status($res);
}
# md
if ($model eq "md") {
$cmd = "$mdadm --detail $device_name";
$res = `$cmd 2>&1`;
# попытаемся извлечь состояние массива
$storage_status = extract_mdadm_raid_status($res);
}
# lsi (3ware)
if($model eq "lsi") {
# it may be run with -L<num> for specific logical drive
$cmd = $LSI_UTILITY . " -LDInfo -Lall -Aall";
$res = `$cmd 2>&1`;
$storage_status = extract_lsi_status($res);
}
} elsif ($type eq 'hard_disk') {
$cmd = "smartctl --all $device_name";
$res = `$cmd 2>&1`;
} else {
warn "Unexpected type";
$cmd = '';
}
$storage->{'status'} = $storage_status;
$storage->{'diag'} = $res;
push @result_disks, $storage;
}
return @result_disks;
}
# Send disks diag results
sub send_disks_results {
my (@disks) = @_;
my $request_data = [
'storage_devices' => \@disks,
'version' => $VERSION,
];
# get result
my $ua = LWP::UserAgent->new();
#$ua->agent("FastVPS disk monitoring version $VERSION");
# Allow redirects for POST requests
push @{ $ua->requests_redirectable }, 'POST';
my $res = $ua->post($API_URL, Content => encode_json($request_data) );
if ($res->is_success) {
#print "Data sent successfully\n";
exit 0;
} else {
warn "Can't sent data to collector: " . $res->status_line . "\n";
exit 1;
}
}