Главная > Программы Мониторинг SMART HDD во FreeBSD при помощи smartmontoolsSMART очень полезная вещь, и несмотря на то, что некоторые люди утверждают, что порой HDD вылетают с нормальными показаниями SMART, я предпочитаю мониторить статусы SMART HDD. Пара слов, что такое SMART. S.M.A.R.T. (англ. Self Monitoring Analysing and Reporting Technology) - технология оценки состояния жёсткого диска встроенной аппаратурой самодиагностики, а также механизм предсказания времени выхода его из строя. Т.е. ваш HDD умеет сообщать наиболее критичные показатели своей работы, а вы соответственно можете их оценивать и принимать решение – делать ли срочный внеплановый Backup или у вас и вашего жесткого диска итак все хорошо. Мониторинг не является заменой резервным копиям! Это важно и нужно понимать. Ликбез окончен, кому SMART интересен читаем дальше как настроить мониторинг SMART в FreeBSD. Ставим из портов. # cd /usr/ports/sysutils/smartmontools && make install clean Опций у меня никаких не запросило. после установки программа вкратце рассказывает о том, как ее использовать. To check the status of drives, use the following:
/usr/local/sbin/smartctl -a /dev/ad0 for first ATA drive
/usr/local/sbin/smartctl -a /dev/da0 for first SCSI drive
To include drive health information in your daily status reports,
add a line like the following to /etc/periodic.conf:
daily_status_smart_devices="/dev/ad0 /dev/da0"
substituting the appropriate device names for your SMART-capable disks.
To enable drive monitoring, you can use /usr/local/sbin/smartd.
A sample configuration file has been installed as
/usr/local/etc/smartd.conf.sample
Copy this file to /usr/local/etc/smartd.conf and edit appropriately
To have smartd start at boot
echo 'smartd_enable="YES"' >> /etc/rc.conf
===> Installing rc.d startup script()
===> Compressing manual pages for smartmontools-5.38_3
===> Registering installation for smartmontools-5.38_3
===> Cleaning for smartmontools-5.38_3
Ну что же, пробуем диагностику нашего HDD. У меня 1 HDD IDE – /dev/ad0, пишем в консоли # /usr/local/sbin/smartctl -a /dev/ad0 smartctl version 5.38 [i386-portbld-freebsd7.1] Copyright (C) 2002-8 Bruce Allen Home page is http://smartmontools.sourceforge.net/ === START OF INFORMATION SECTION === Model Family: Seagate Barracuda ATA IV family Device Model: ST340016A Serial Number: 3HR2J5Q9 Firmware Version: 7.73 User Capacity: 40 019 582 464 bytes Device is: In smartctl database [for details use: -P show] ATA Version is: 5 ATA Standard is: Exact ATA specification draft version not indicated Local Time is: Mon Apr 20 11:23:08 2009 SMART support is: Available - device has SMART capability. SMART support is: Disabled SMART Disabled. Use option -s with argument 'on' to enable it. Итак, SMART у меня запрещен. Включаем его по подсказке # /usr/local/sbin/smartctl -s on /dev/ad0 smartctl version 5.38 [i386-portbld-freebsd7.1] Copyright (C) 2002-8 Bruce Allen Home page is http://smartmontools.sourceforge.net/ === START OF ENABLE/DISABLE COMMANDS SECTION === SMART Enabled. SMART включился. пробуем снова получить данные о нашем диске # /usr/local/sbin/smartctl -a /dev/ad0 smartctl version 5.38 [i386-portbld-freebsd7.1] Copyright (C) 2002-8 Bruce Allen Home page is http://smartmontools.sourceforge.net/ === START OF INFORMATION SECTION === Model Family: Seagate Barracuda ATA IV family Device Model: ST340016A Serial Number: 3HR2J5Q9 Firmware Version: 7.73 User Capacity: 40 019 582 464 bytes Device is: In smartctl database [for details use: -P show] ATA Version is: 5 ATA Standard is: Exact ATA specification draft version not indicated Local Time is: Mon Apr 20 11:26:31 2009 SMART support is: Available - device has SMART capability. SMART support is: Enabled === START OF READ SMART DATA SECTION === SMART overall-health self-assessment test result: PASSED General SMART Values: Offline data collection status: (0x82) Offline data collection activity was completed without error. Auto Offline Data Collection: Enabled. Self-test execution status: ( 0) The previous self-test routine completed without error or no self-test has ever been run. Total time to complete Offline data collection: ( 422) seconds. Offline data collection capabilities: (0x1b) SMART execute Offline immediate. Auto Offline data collection on/off support. Suspend Offline collection upon new command. Offline surface scan supported. Self-test supported. No Conveyance Self-test supported. No Selective Self-test supported. SMART capabilities: (0x0003) Saves SMART data before entering power-saving mode. Supports SMART auto save timer. Error logging capability: (0x01) Error logging supported. No General Purpose Logging support. Short self-test routine recommended polling time: ( 1) minutes. Extended self-test routine recommended polling time: ( 44) minutes. SMART Attributes Data Structure revision number: 10 Vendor Specific SMART Attributes with Thresholds: ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE 1 Raw_Read_Error_Rate 0x000f 066 056 034 Pre-fail Always - 40186803 3 Spin_Up_Time 0x0003 085 082 000 Pre-fail Always - 0 4 Start_Stop_Count 0x0032 100 100> 020 Old_age Always - 653 5 Reallocated_Sector_Ct 0x0033 100 100 036 Pre-fail Always - 15 7 Seek_Error_Rate 0x000f 079 060 030 Pre-fail Always - 89560973 9 Power_On_Hours 0x0032 093 093 000 Old_age Always - 6676 10 Spin_Retry_Count 0x0013 100 100 097 Pre-fail Always - 0 12 Power_Cycle_Count 0x0032 100 100 020 Old_age Always - 699 194 Temperature_Celsius 0x0022 041 051 000 Old_age Always - 41 195 Hardware_ECC_Recovered 0x001a 066 056 000 Old_age Always - 40186803 197 Current_Pending_Sector 0x0012 100 100 000 Old_age Always - 0 198 Offline_Uncorrectable 0x0010 100 100 000 Old_age Offline - 0 199 UDMA_CRC_Error_Count 0x003e 200 200 000 Old_age Always - 0 200 Multi_Zone_Error_Rate 0x0000 100 253 000 Old_age Offline - 0 202 TA_Increase_Count 0x0032 100 253 000 Old_age Always - 0 SMART Error Log Version: 1 ATA Error Count: 561 (device log contains only the most recent five errors) CR = Command Register [HEX] FR = Features Register [HEX] SC = Sector Count Register [HEX] SN = Sector Number Register [HEX] CL = Cylinder Low Register [HEX] CH = Cylinder High Register [HEX] DH = Device/Head Register [HEX] DC = Device Command Register [HEX] ER = Error register [HEX] ST = Status register [HEX] Powered_Up_Time is measured from power on, and printed as DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes, SS=sec, and sss=millisec. It "wraps" after 49.710 days. Error 561 occurred at disk power-on lifetime: 6670 hours (277 days + 22 hours) When the command that caused the error occurred, the device was active or idle. After command completion occurred, registers were: ER ST SC SN CL CH DH -- -- -- -- -- -- -- 40 51 00 23 a9 d7 f1 Error: UNC at LBA = 0x01d7a923 = 30910755 Commands leading to the command that caused the error were: CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name -- -- -- -- -- -- -- -- ---------------- -------------------- c8 00 08 20 a9 d7 f1 00 01:49:21.927 READ DMA c8 00 80 48 aa d7 f1 00 01:49:21.908 READ DMA c8 00 08 20 a9 d7 f1 00 01:49:18.465 READ DMA c8 00 80 c8 a9 d7 f1 00 01:49:18.449 READ DMA c8 00 08 20 a9 d7 f1 00 01:49:14.943 READ DMA Error 560 occurred at disk power-on lifetime: 6670 hours (277 days + 22 hours) When the command that caused the error occurred, the device was active or idle. After command completion occurred, registers were: ER ST SC SN CL CH DH -- -- -- -- -- -- -- 40 51 00 23 a9 d7 f1 Error: UNC at LBA = 0x01d7a923 = 30910755 Commands leading to the command that caused the error were: CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name -- -- -- -- -- -- -- -- ---------------- -------------------- c8 00 08 20 a9 d7 f1 00 01:49:18.465 READ DMA c8 00 80 c8 a9 d7 f1 00 01:49:18.449 READ DMA c8 00 08 20 a9 d7 f1 00 01:49:14.943 READ DMA c8 00 80 48 a9 d7 f1 00 01:49:14.928 READ DMA c8 00 08 20 a9 d7 f1 00 01:49:11.448 READ DMA Error 559 occurred at disk power-on lifetime: 6670 hours (277 days + 22 hours) When the command that caused the error occurred, the device was active or idle. After command completion occurred, registers were: ER ST SC SN CL CH DH -- -- -- -- -- -- -- 40 51 00 23 a9 d7 f1 Error: UNC at LBA = 0x01d7a923 = 30910755 Commands leading to the command that caused the error were: CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name -- -- -- -- -- -- -- -- ---------------- -------------------- c8 00 08 20 a9 d7 f1 00 01:49:14.943 READ DMA c8 00 80 48 a9 d7 f1 00 01:49:14.928 READ DMA c8 00 08 20 a9 d7 f1 00 01:49:11.448 READ DMA c8 00 20 28 a9 d7 f1 00 01:49:11.439 READ DMA c8 00 08 18 a9 d7 f1 00 01:49:11.427 READ DMA Error 558 occurred at disk power-on lifetime: 6670 hours (277 days + 22 hours) When the command that caused the error occurred, the device was active or idle. After command completion occurred, registers were: ER ST SC SN CL CH DH -- -- -- -- -- -- -- 40 51 00 23 a9 d7 f1 Error: UNC at LBA = 0x01d7a923 = 30910755 Commands leading to the command that caused the error were: CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name -- -- -- -- -- -- -- -- ---------------- -------------------- c8 00 08 20 a9 d7 f1 00 01:49:11.448 READ DMA c8 00 20 28 a9 d7 f1 00 01:49:11.439 READ DMA c8 00 08 18 a9 d7 f1 00 01:49:11.427 READ DMA c8 00 28 20 a9 d7 f1 00 01:49:07.954 READ DMA c8 00 08 10 a9 d7 f1 00 01:49:07.939 READ DMA Error 557 occurred at disk power-on lifetime: 6670 hours (277 days + 22 hours) When the command that caused the error occurred, the device was active or idle. After command completion occurred, registers were: ER ST SC SN CL CH DH -- -- -- -- -- -- -- 40 51 00 23 a9 d7 f1 Error: UNC at LBA = 0x01d7a923 = 30910755 Commands leading to the command that caused the error were: CR FR SC SN CL CH DH DC Powered_Up_Time Command/Feature_Name -- -- -- -- -- -- -- -- ---------------- -------------------- c8 00 28 20 a9 d7 f1 00 01:49:07.954 READ DMA c8 00 08 10 a9 d7 f1 00 01:49:07.939 READ DMA c8 00 30 18 a9 d7 f1 00 01:49:04.469 READ DMA c8 00 08 08 a9 d7 f1 00 01:49:04.457 READ DMA c8 00 38 10 a9 d7 f1 00 01:49:00.992 READ DMA SMART Self-test log structure revision number 1 No self-tests have been logged. [To run self-tests, use: smartctl -t] Device does not support Selective Self Tests/Logging данных существенно больше. А теперь пишем конфиг файл для удобного автоматического мониторинга. # cp /usr/local/etc/smartd.conf.sample /usr/local/etc/smartd.conf правим конфиг, я использую редактор ee – вы используйте ваш любимый редактор. Ниже мой конфиг # ee /usr/local/etc/smartd.conf # опции для наблюдаемых дисков - внизу, перед описанием опций # Пример конфиг файла утилиты мониторинга SMART smartd. Подробности по команде man #smartd.conf. # Сайт программы: http://smartmontools.sourceforge.net # $Id: smartd.conf,v 1.45 2006/11/12 23:39:04 dpgilbert Exp $ # smartd пересчитывает этот конфиг файл при получении сигнала HUP # В данном файле перечислены устройства, которые мониторятся при помощи smartd # каждое устройство на своей отдельной строке. #Символ (#) игнорируется и используется например для написания комментариев # так же можно использовать пробелы или tab для разделения Символ '\' для разбивки длинных #строк. # Опция DEVICESCAN позволяет обнаруживать устройства # ATA и SCSI, и применить к ним ниже перечисленные опции. # Большинству пользователей эту опцию лучше ЗАКОММЕНТИРОВАТЬ # и прописать устройства для мониторинга вручную. # DEVICESCAN # Первый ATA/IDE диск. Наблюдаются все параметры, автоматическое сохранение атрибутов # и запуск короткого теста самодиагностики каждый день между 2-3 ночи, и запуск полного #теста в субботу (Saturdays) между 3-4 часами ночи. #/dev/hda -a -o on -S on -s (S/../.././02|L/../../6/03) # Наблюдение за статусом SMART, вести лог ошибок ATA, лог самодиагностики, наблюдать за #всеми атрибутами # кроме параметра 194 (температура) #/dev/hdb -H -l error -l selftest -t -I 194 # Отследижвать все параметры кроме температуры (194), # но отслеживать изменения температуры на величину >= 4 градуса Цельсия, # Сообщать о температуре >= 45 градусов Цельсия и изменении значения Reallocated_Sector_Ct #(5). (Очень важный параметр, показывает, сколько на диске переназначенных секторов. #Исправный накопитель имеет raw-значение, равное 0. Если вы значение более 50 - явные #проблемы и диск необходимо заменить. # Отправлять e-mail сообщение на про сбои или когда температура >= 55 градусов Цельсия. #/dev/hdc -a -I 194 -W 4,45,55 -R 5 -m admin@hotfreebsd.ru # Очень тихая проверка. Сообщает только статус здоровья SMART. Если есть сбои, то отправить #e-mail по указанному адресу #/dev/hdc -H -C 0 -U 0 -m admin@hotfreebsd.ru #Первые 2 SCSI диска. Контроль всех параметров SMART, которые может извлечь smartd # Запуск расширенной самодиагностики в среду между 6-7 часами вечера, так же в #воскресенье 1-2 часа ночи #/dev/sda -d scsi -s L/../../3/18 #/dev/sdb -d scsi -s L/../../7/01 # Наблюдение за 4 ATA дисками, которые подключены через 3ware 6/7/8000 контроллер #используя 3w-xxxx драйвер. Запуск полного теста в воскресенье между 1-2, 2-3, 3-4, # и 4-5 часами ночью. # NOTE: starting with the Linux 2.6 kernel series, the /dev/sdX interface # is DEPRECATED. Use the /dev/tweN character device interface instead. # For example /dev/twe0, /dev/twe1, and so on. #/dev/sdc -d 3ware,0 -a -s L/../../7/01 #/dev/sdc -d 3ware,1 -a -s L/../../7/02 #/dev/sdc -d 3ware,2 -a -s L/../../7/03 #/dev/sdc -d 3ware,3 -a -s L/../../7/04 # ниже был еще ряд примеров, см. родной конфиг если нужно /usr/local/etc/smartd.conf все #довольно просто # Наблюдение за моими дисками фактически из примера в начале # IDE диск # Наблюдаются все параметры, автоматическое сохранение атрибутов # и запуск короткого теста самодиагностики каждый день между 2-3 ночи, и запуск полного # теста в субботу между 3-4 часами ночи, а так же отправлять уведомление по почте # так же мониторим Reallocated_Sector_Ct и сообщаем, если температура 45 градусов Цельсия, #это информационное сообщение, 55 градусов - критическое положение дел /dev/ad0 -a -I 194 -W 4,45,55 -R 5 -m admin@hotfreebsd.ru -o on -S on -s (S/../.././02|L/../../6/03) # В заключение опции для мониторинга, которые можно использовать в этом конфигурационном файле. # Для подробностей см man smartd.conf # # -d задать тип устройства: ata, scsi, marvell, removable, 3ware,N, hpt,L/M/N # -T задать тип допустимых отклонений : normal, permissive # -o VAL включить/выключить автоматические автономные тесты (on/off) # -S VAL включить/выключить атрибуты автосохранения (on/off) # -n MODE Без проверок. MODE может принимать значения: never, sleep, standby, idle # -H Наблюдать за статусом SMART, сообщать о возникших проблемах # -l TYPE Наблюдение за логом SMART. Значения: error, selftest # -f Наблюдение за отказами в любых значениях 'Usage' атрибутов # -m ADD Отправить предупреждение по e-mail для опций -H, -l error, -l selftest, и -f # -M TYPE Изменить способы отправки e-mail предупреждений (подробнее в ман) # -s REGE Начать самотестирование когда тип/дата соответствуют регулярному выражению (смотри ман) # -p Сообщать об изменениях в атрибутах 'Prefailure' # -u Сообщать об изменениях в атрибутах 'Usage' # -t Равнозначно опциям -p и -u # -r ID Так же сообщать Raw значение атрибута ID включая -p, -u или -t # -R ID Отслеживать изменения в ID Raw значения включая -p, -u или -t # -i ID Игнорировать значения ID для -f опции # -I ID Игнорировать значения ID для -p, -u или -t опций # -C ID Сообщать о том, что текущий (счетчик ждущих секторов) Pending Sector count не равен 0 # -U ID Сообщать если (счетчик неисправленных секторов) Uncorrectable count не равен 0 # -W D,I,C Наблюдение за температурой D)ifference , I)nformal limit, C)ritical limit # -v N,ST измененить метку для параметра N (смотри ман) # -a по умолчанию: эквивалентно параметрам -H -f -t -l error -l selftest -C 197 -U 198 # -F TYPE для ошибок в прошивке. Значение одно из: none, samsung # -P TYPE Представление специфических устройств: use, ignore, show, showall # Значение ID в интервале 1 <= ID <= 255 # за исключением -C и -U, где ID = 0 turns them off. # Все -d, -m и -M опции применяются только к ATA дискам # If the test string DEVICESCAN is the first uncommented text # then smartd will scan for devices /dev/hd[a-l] and /dev/sd[a-z] # DEVICESCAN may be followed by any desired Directives. Теперь настроим логирование # ee /etc/syslog.conf в этот файл нужно добавить строки # Мониторинг SMART
local2.* /var/log/smartd.log
Причем по непонятной причине у меня при добавлении этих строк в конец файла ничего не работало, так что стоит эти строки поставить в вышеуказанный файлик повыше. Создаем файл для записи логов # touch /var/log/smartd.log так же правим # ee /etc/rc.conf добавив в него строки # мониторинг SMART
smartd_enable="YES"
smartd_flags="-l local2 --interval=500"
–interval=500 это частота опроса в секундах можно поставить чаще или реже, как хотите перезапускаем syslog # killall -1 syslogd запускаем наше наблюдение # /usr/local/etc/rc.d/smartd start Starting smartd. Проверяем в списке процессов # ps -ax | grep smartd 4310 ?? I 0:00,01 /usr/local/sbin/smartd -p /var/run/smartd.pid -l local2 --interval=500 все хорошо, наблюдение ведется, поглядим лог # cat /var/log/smartd.log Apr 20 13:47:36 myserver smartd[1089]: smartd version 5.38 [i386-portbld-freebsd7.1] Copyright (C) 2002-8 Bruce Allen Apr 20 13:47:36 myserver smartd[1089]: Home page is http://smartmontools.sourceforge.net/ Apr 20 13:47:36 myserver smartd[1089]: Opened configuration file /usr/local/etc/smartd.conf Apr 20 13:47:36 myserver smartd[1089]: Configuration file /usr/local/etc/smartd.conf parsed. Apr 20 13:47:36 myserver smartd[1089]: Device: /dev/ad0, opened Apr 20 13:47:36 myserver smartd[1089]: Device: /dev/ad0, found in smartd database. Apr 20 13:47:36 myserver smartd[1089]: Device: /dev/ad0, enabled SMART Attribute Autosave. Apr 20 13:47:36 myserver smartd[1089]: Device: /dev/ad0, enabled SMART Automatic Offline Testing. Apr 20 13:47:36 myserver smartd[1089]: Device: /dev/ad0, is SMART capable. Adding to "monitor" list. Apr 20 13:47:36 myserver smartd[1089]: Monitoring 1 ATA and 0 SCSI devices Apr 20 13:47:36 myserver smartd[1091]: smartd has fork()ed into background mode. New PID=1091. Apr 20 13:47:36 myserver smartd[1091]: file /var/run/smartd.pid written containing PID 1091 Через некоторое время смотрим лог еще раз Apr 20 13:52:36 myserver smartd[1091]: Device: /dev/ad0, SMART Usage Attribute: 194 Temperature_Celsius changed from 41 to 42
изменилась температура HDD. Если будут ошибки, то придет электронная почта на указанный адрес. Можно сразу и проверить, я например указал в конфиге запись /dev/ad0 -a -I 194 -W 4,35,40 -R 5 -m admin@hotfreebsd.ru -o on -S on -s (S/../.././02|L/../../6/03)
т.е. слежение за температурой от 35 до 45 градусов, так как текущая температура диска выше, мы точно должны
получить алерт по почте, и перезапустил smartd
# /usr/local/etc/rc.d/smartd restart Stopping smartd. Starting smartd. и чуть погодя получил письмо This email was generated by the smartd daemon running on:
host name: myserver.hotfreebsd.ru
DNS domain: hotfreebsd.ru
NIS domain:
The following warning / error was logged by the smartd daemon:
Device: /dev/ad0, Temperature 43 Celsius reached critical limit of 40 Celsius (Min/Max 43/43 )
For details see host's SYSLOG (default: /var/log/messages).
You can also use the smartctl utility for further investigation.
No additional email messages about this problem will be sent.
Так же для определения что важно, а что нет советую почитать
Атрибуты SMART</a>Полная таблица всех возможных атрибутов SMART выглядит следующим образом в помощь заметке
Главная > Программы |