- Megaraid sas with linux
- Установка MegaRAID
- Использование утилиты MegaCli
- Настройка мониторинга RAID LSI MegaRaid на Linux с помощью Zabbix
- Установка megacli
- CentOS
- Ubuntu
- Использование megacli
- Скрипты для получения состояния дисков
- UserParameter для агента Zabbix
- Настройка сервера Zabbix
- Создание шаблона
- Применение шаблона
- LSI MegaRAID SAS
- 2. Linux kernel drivers
- 3. Management and reporting tools
- 3.1. megactl
- 3.1.1. Quickstart and output example
- 3.1.2. Periodic checks
- 3.2. megaraid-status
- 3.2.1. About megaraid-status
- 3.2.2. Wrapper output example
- 3.3. megacli
- 3.3.1. About megacli
- 3.3.2. Quickstart and output example
- Create a RAID6 array with megacli
- Read Cache, Write Cache, ReadAhead and Battery
- Rebuilding a disk by hand when it doesn’t occur automatically
- Expand an array over an additionnal disk
- 3.3.3. Periodic checks
- Full documentation
- 3.4. megaclisas-status
- 3.4.1. About megaclisas-status
- 3.4.2. Wrapper output example
- 3.4.3. Nagios integration
- 3.5. About /dev/megaraid_sas_ioctl_node
- 4. SMART
- 5. BIOS upgrade from a Linux system
Megaraid sas with linux
Утилита MegaRAID позволяет управлять рейд контроллером из операционной системы. В моем случае я приручаю и устанавливаю на CentOS 6.3. Это не пример но принцип один и для других Linux систем и железа от IBM.
В моем случае было железо производителя IBM:
В долгой переписке с поддержкой IBM, выдали письмо что они поддерживают не все операционные системы, а только Windows, Red Hat, VMware, SUSE Linux, что как раз и говорится в этой статье (http://www-03.ibm.com/systems/info/x86servers/serverproven/compat/us/nos/matrix.shtml). Пришлось обращаться к производителю чипсета, это компания LSI.
Драйвера для ServeRAID M5110, M5110e, M5120, M1115, M1000, M5014, M5015, M5016 M5025, MR10i, MR10ie, MR10il, MR10is, MR10k, MR10M можно скачать по данной ссылке https://www-947.ibm.com/support/entry/myportal/docdisplay?lndocid=MIGR-5073015 или написать запрос в IBM и вам предоставят драйвера. Для входа необходимо зарегистрироваться на сайте IBM.
На сайте производителя я нашел все необходимое ПО и драйвера под ServeRAID M5015 (MegaRAID SAS 9262-8i) под всевозможные операционные системы (Windows, Ubuntu, Sles, FreeBSD, RHEL, Debian, Citrix, CentOS, OEL, OVM).
Установка MegaRAID
Я загрузил полный пакет драйверов и распаковал:
На сервер свой залил только то что пригодилось.
Далее установка. У меня встали только 2 пакета, драйвера и сама утилита MegaCli. Дебаг не понадобился.
Использование утилиты MegaCli
Переходим в каталог утилиты
Вывести всю информацию по Raid контроллеру
Вывести всю информацию по жестким дискам
Вывести информацию по массивам и дискам
Вывести информацию только по массивам
Вывести всю информацию по состояние батареи
Более подробно в инструкции.
Для себя я сделал скрипт по мониторингу MegaRAID и поставил в выполнение крон.
Источник
Настройка мониторинга RAID LSI MegaRaid на Linux с помощью Zabbix
Разберем ситуацию, при которой нам нужно узнать состояние дискового RAID-массива, затем настроить мониторинг данного состояния сервером Zabbix. В качестве операционной системы, под управлением которой работает компьютер с LSI MegaRaid будем использовать Linux.
Установка megacli
Смотреть состояние массива RAID будем с помощью фирменной утилиты megacli.
Для начала, проверим, что на сервере используется контроллер LSI MegaRaid:
lspci -nn | grep -i lsi
02:00.0 RAID bus controller [0104]: LSI Logic / Symbios Logic MegaRAID SAS 2108 [Liberator] [1000:0079] (rev 05)
Разберем процесс установка утилиты на Linux CentOS и Ubuntu.
CentOS
Устанавливаем пакеты для распаковки архивов и загрузки файлов:
yum install unzip wget
Переходим по ссылке download.hetzner.de/tools/LSI/tools/MegaCLI — логин hetzner и пароль download. В открывшемся окне копируем ссылку на нужную версию утилиты, например:
С помощью ссылки скачиваем утилиту на компьютер, на котором будет мониторить состояние контроллера:
wget —user hetzner —password download https://download.hetzner.de/tools/LSI/tools/MegaCLI/8.07.10_MegaCLI_Linux.zip
* в данном примере мы загружаем MegaCLI версии 8.07.10 для Linux. Для прохождения авторизации используем логин и пароль hetzner/download.
* если система вернет ошибку при выполнении команды, устанавливаем wget командой yum install wget.
Распаковываем скачанный архив:
rpm -i 8.07.10_MegaCLI_Linux/Linux\ MegaCLI\ 8.07.10/MegaCli-8.07.10-1.noarch.rpm
* напомню, в данном примере устанавливаем версию 8.07.10.
Создаем ссылку на бинарник:
ln -s /opt/MegaRAID/MegaCli/MegaCli64 /usr/bin/megacli
Проверяем, что утилита работает:
Мы должны получить версию установленного пакета.
Ubuntu
Открываем настройки репозитория:
В самый низ добавляем:
deb http://hwraid.le-vert.net/ubuntu xenial main
* где xenial — выпуск Ubuntu (можно посмотреть командой lsb_release -a).
Обновляем список пакетов:
И устанавливаем megacli:
apt-get install megacli
Проверяем, что утилита работает:
Мы должны получить версию установленного пакета.
Использование megacli
Для работы нам могут быть полезны следующие команды.
1. Посмотреть модели контролера и версию прошивки:
megacli -AdpAllInfo -aAll | grep -E ‘Product Name|Serial No|FW Package Build’
Product Name : RAID Ctrl SAS 6G 5/6 512MB (D2616)
Serial No :
FW Package Build : 12.12.0-0174
2. Состояние дисков:
megacli -PDList -Aall
Enclosure Device ID: 252
Slot Number: 0
Drive’s position: DiskGroup: 2, Span: 0, Arm: 0
Enclosure position: N/A
Device Id: 2
WWN: 50014ee2662dd189
Sequence Number: 2
Media Error Count: 0
Other Error Count: 0
Predictive Failure Count: 0
Last Predictive Failure Event Seq Number: 0
PD Type: SATA
Raw Size: 931.512 GB [0x74706db0 Sectors]
Non Coerced Size: 931.012 GB [0x74606db0 Sectors]
Coerced Size: 931.0 GB [0x74600000 Sectors]
Sector Size: 0
Logical Sector Size: 0
Physical Sector Size: 0
Firmware state: Online, Spun Up
Device Firmware Level: 1A02
Shield Counter: 0
Successful diagnostics completion on : N/A
SAS Address(0): 0x4433221103000000
Connected Port Number: 1(path0)
Inquiry Data: WD-WCC6Y1NURJ0VWDC WD10EZEX-08WN4A0 02.01A 02
FDE Capable: Not Capable
FDE Enable: Disable
Secured: Unsecured
Locked: Unlocked
Needs EKM Attention: No
Foreign State: None
Device Speed: 6.0Gb/s
Link Speed: 6.0Gb/s
Media Type: Hard Disk Device
Drive: Not Certified
Drive Temperature :30C (86.00 F)
PI Eligibility: No
Drive is formatted for PI information: No
PI: No PI
Port-0 :
Port status: Active
Port’s Linkspeed: 6.0Gb/s
Drive has flagged a S.M.A.R.T alert : No
* в данном примере отображено состояние для одного диска. Нам могут быть полезны параметры Firmware state — показывает состояние диска; Drive has flagged a S.M.A.R.T alert — состояние SMART.
Скрипты для получения состояния дисков
В нашем примере мы напишем очень простой скрипт, который будет находить неправильное состояние диска. Если хотя бы один из носителей имеет тревоги по SMART или ошибки в состоянии, скрипт будет возвращать 1. Если проблем нет — 0. Сам скрипт будет написан на bash.
У меня не получилось сделать так, чтобы команда megacli нормально отрабатывала при запуске от zabbix агента, поэтому сам скрипт будет выполняться по крону и результат записывать в отдельный файл, который и будет читать агент заббикса.
Создаем каталог, в который поместим скрипт:
Создаем файл скрипта:
count_errors=`megacli -PDList -Aall | grep -e «S.M.A.R.T alert : Yes» -e «Firmware state: Fail» | wc -l`
if [ $count_errors -gt 0 ]
then
echo 1 > /scripts/scan_result
else
echo 0 > /scripts/scan_result
fi
* это простой скрипт, который получает состояние всех дисков и проверяет, нет ли среди этих состояний тревог от SMART и состояния Failed — результат записывается в переменную count_errors в виде количества найденных проблем. Если значение данной переменной больше 0 (то есть, есть хотя бы одно состояние сбоя), скрипт записывает в файл /scripts/scan_result «1», иначе — «0».
Разрешаем запуск скрипта на выполнение:
chmod +x /scripts/raid_mon_cron.sh
Создадим задание в cron:
* в данном примере мы будем запускать наш скрипт по проверке состояние дисков каждые 5 минут.
Теперь создадим скрипт, который будет запускать zabbix-agent:
* обратите внимание, что скрипт создается в каталоге zabbix-агента. Если в нашей системе его нет, необходима установка — примеры установки для CentOS и Ubuntu.
* все, что делает скрипт — выводит содержимое файла /scripts/scan_result, в котором должно быть либо 0, либо 1.
Разрешаем запуск скрипта на выполнение и зададим владельца zabbix:
chmod 770 /etc/zabbix/zabbix_agentd.d/raid_mon.sh
chown zabbix:zabbix /etc/zabbix/zabbix_agentd.d/raid_mon.sh
Пробуем выполнить скрипты:
В зависимости от ситуации они вернут 0 или 1.
UserParameter для агента Zabbix
Запуск скрипта и передача результата его работы серверу мониторинга выполняется с помощью Zabbix-агента. Для этого необходимо настроить UserParameter.
Открываем настройки агента:
В самый низ добавляем строку:
* в данном случае, мы создаем в zabbix агенте пользовательский параметр с именем raid_mon — при его вызове будет запускаться скрипт /etc/zabbix/zabbix_agentd.d/raid_mon.sh, который мы ранее создали.
systemctl restart zabbix-agent
Если используется SELinux, отключаем его:
sed -i ‘s/^SELINUX=.*/SELINUX=disabled/g’ /etc/selinux/config
Проверяем работу параметра. Для этого с сервера zabbix выполняем команду:
zabbix_get -s 192.168.0.15 -k raid_mon
* в данном примере мы обращаемся к серверу 192.168.0.15 и запускаем пользовательский параметр raid_mon.
В итоге, мы должны получить такой же ответ, который получили, запустив скрипт локально с компьютера, на котором его создали.
Настройка сервера Zabbix
На сервере zabbix необходимо создать шаблон для сканирования дисков с триггером для получения данных от агента на сервере и в случае 1 выводить тревогу. После необходимо добавить данный шаблон для всех узлов, на которых необходим мониторинг дисков.
Создание шаблона
Открываем веб-панель управления Zabbix. Выполним ряд шагов для достижения цели.
1. Переходим в Настройка — Шаблоны:
Справа сверху кликаем по Создать шаблон:
В открывшемся окне называем шаблон, например, Template Scan RAID — добавляем его в группы, например Linux Servers и Windows Servers (нам никто не мешает также сканировать диски на серверах Windows):
Кликаем по Добавить. Будет создан шаблон.
2. В списке шаблонов находим свой и кликаем для его настройки:
Переходим в Группы элементов данных:
Кликаем по Создать группу элементов данных:
Даем название для группы, например, RAID:
. и кликаем по Добавить. Группа элементов создана.
3. Переходим на вкладку Элементы данных и кликаем по Создать элементы данных:
В открывшемся окне даем название для элемента, например, RAID: Status Monitoring — прописываем ключ raid_mon (тот, что задали в UserParameter) — ставим интервал обновления в 5 минут (так как в кроне мы сканируем состояние каждые 5 минут, проверять чаще нет смысла) — выбираем созданную ранее группу элементов данных (RAID):
. и кликаем по Добавить. Элемент данных добавлен.
4. Создаем триггер — для этого переходим на вкладку Триггеры — кликаем по Создать триггер:
Даем название для триггера, например, RAID: Status Error — меняем значение для важности, например, на Высокая — задаем выражение =1 (триггер должен реагировать на значение равное 1):
Нажимаем Добавить.
Шаблон готов и настроен.
Применение шаблона
Теперь можно применить наш шаблон к узлу. Переходим в Настройка — Узлы сети — выбираем узел, на котором создан скрипт для мониторинга дисков — переходим на вкладку Шаблоны и добавляем созданный нами шаблон:
Нажимаем Обновить.
Мониторинг состояния дисков настроен. При возникновении критического состояния мы увидим проблему «RAID: Status Error».
Источник
LSI MegaRAID SAS
MegaRAID SAS is the current high-end RAID controllers series by LSI.
It is fully hardware RAIDs controllers supporting RAID5, at least, with SAS or SATA interfaces.
If you’re a looking for information about MegaRAID SCSI connectors, please look at LSIMegaRAID instead.
All theses card can be used with stock Linux kernel which includes a working driver.
It’s quite new and thus, may be missing in some not-up-to-date distributions.
There is currently no known opensource tool for theses cards.
Some old MegaRAID SAS can be used with megactl, but none of current cards works.
However LSI provide megacli, a proprietary management command line utility which is rather hard to use.
2. Linux kernel drivers
Driver | Supported cards |
megaraid_sas | LSI MegaRAID SAS |
megaraid_sas is part of mainstream Linux kernel and should be available in all current distributions.
However, please that most of old distributions won’t have this driver.
If your card use megaraid_mm or megaraid_mbox driver, please look at LSIMegaRAID instead.
Some lspci -nn output examples:
- 02:0e.0 RAID bus controller [0104]: Dell PowerEdge Expandable RAID controller 5 ![1028:0015]
- 01:00.0 RAID bus controller [0104]: LSI Logic / Symbios Logic MegaRAID SAS 1078 (rev 04) [1000:0060]
- 04:0e.0 RAID bus controller [0104]: LSI Logic / Symbios Logic MegaRAID SAS [1000:0411]
- 03:00.0 RAID bus controller [0104]: LSI Logic / Symbios Logic MegaRAID SAS 2108 [Liberator] [1000:0079] (rev 05)
- 10:00.0 RAID bus controller [0104]: LSI Logic / Symbios Logic MegaRAID SAS TB [1000:005b] (rev 01)
- 01:00.0 RAID bus controller [0104]: LSI Logic / Symbios Logic MegaRAID SAS 2008 [Falcon] [1000:0073] (rev 03) Dell PERC H310 Mini
- 01:00.0 RAID bus controller [0104]: LSI Logic / Symbios Logic MegaRAID SAS 2208 [Thunderbolt] [1000:005b] (rev 05) Dell PERC H710 Mini
3. Management and reporting tools
megactl includes a SAS compliant binary named megasasctl. It seems to work on old card but fails with the new one.
If megasasctl doesn’t work for you, you will have to use the proprietary cli utility from LSI: megaclisas.
For managing the card there are no alternatives to megaclisas.
3.1. megactl
Despites megasasctl doesn’t seem to work with recent cards, you should really give it a try.
3.1.1. Quickstart and output example
Print current controller status:
There are several switches which are interresting:
- -H: Only print lines which are not ok.
If nothing is printer, everything is fine - -B: Ignore batttery problems when running -H.
In fact megasasctl can’t define if your controller has a battery or not.
If you don’t have one, use this parameter.
3.1.2. Periodic checks
You can write your own script around megasasctl to check your adapter status health periodically. However, I already did this for you. See megaraid-status below.
3.2. megaraid-status
3.2.1. About megaraid-status
megaraidsas-status is a wrapper script around megactl with periodics checks.
It is available in the packages repository too.
The packages comes with a python wrapper around megasasctl and an initscript that periodic run this wrapper to check status.
It keeps a file with latest status and thus is able to detect RAID status changes and/or brokeness.
It will log a ligne to syslog when something failed and will send you a mail.
Until arrays are healthy again a reminder will be sent each 2 hours.
3.2.2. Wrapper output example
3.3. megacli
3.3.1. About megacli
megacli is a proprietary tool by LSI which can perform both reporting and management for MegaRAID SAS cards.
However it’s really hard to use because it’s use tones of command line parameters and there’s no documentation.
3.3.2. Quickstart and output example
Get all adapters status and config:
Logical drive 0 on adapter 0 status and type:
Display, disable or enable automatic rebuild on adapter 0:
Get and modify rebuild rate:
Show physical disks from first controller:
We can see that disk 32,1 (enclosure slot = 1) is currently rebuilding (firmware state).
Let’s check this operation progress:
Create a RAID6 array with megacli
Let’s assume we have a server with two MegaRAID SAS cards. The first one is already setup but we have just plugged a disk bays on the second card.
List physical disks on second card (only print enclosure and slots numbers):
Now we have all enclosure and slot number. Let’s create the new array:
Read Cache, Write Cache, ReadAhead and Battery
A quick section about performance tunning.
Let’s enable Read Cache, and always cache data:
Enable disks’ cache:
About ReadAhead: this feature will read more stuff and store in the cache, guessing the system may access it soon.
We’re going to enable an enhanced version of readahead: the adaptative one.
With this option, readahead will only be enabled if the controller receive several access to sequencial sectors. If not, it won’t be used to avoid filling cache with randon useless data (in case of randomly accessed sector).
It seems ADRA is deprecated, current megacli binary doesn’t offer this option anymore. Use regular readahead instead:
Now we’re going to enable write cache. Beware of data loss! Write cache should be enabled ONLY if you have a battery pack on your controller.
Let’s check if we have one and if it’s working fine:
Both adapters have one in this server, let’s enable write cache:
But disable it if the battery went broken or discharged:
Now we can check if everythin and fine and reboot the server (not sure if it’s needed):
References (extracted from Dell OpenManage doc):
Read Policy: The read policies indicate whether or not the controller should read sequential sectors of the logical drive when seeking data.
- Read-Ahead. When using read-ahead policy, the controller reads sequential sectors of the logical drive when seeking data. Read-ahead policy may improve system performance if the data is actually written to sequential sectors of the logical drive.
- No-Read-Ahead. Selecting no-read-ahead policy indicates that the controller should not use read-ahead policy.
- Adaptive Read-Ahead. When using adaptive read-ahead policy, the controller initiates read-ahead only if the two most recent read requests accessed sequential sectors of the disk. If subsequent read requests access random sectors of the disk, the controller reverts to no-read-ahead policy. The controller continues to evaluate whether read requests are accessing sequential sectors of the disk, and can initiate read-ahead if necessary.
Write Policy: The write policies specify whether the controller sends a write-request completion signal as soon as the data is in the cache or after it has been written to disk.
- Write-Back. When using write-back caching, the controller sends a write-request completion signal as soon as the data is in the controller cache but has not yet been written to disk. Write-back caching may provide improved performance since subsequent read requests can more quickly retrieve data from the controller cache than they could from the disk. Write-back caching also entails a data security risk, however, since a system failure could prevent the data from being written to disk even though the controller has sent a write-request completion signal. In this case, data may be lost. Other applications may also experience problems when taking actions that assume the data is available on the disk.
- Write-Through. When using write-through caching, the controller sends a write-request completion signal only after the data is written to the disk. Write-through caching provides better data security than write-back caching, since the system assumes the data is available only after it has been safely written to the disk.
Cache Policy: The Direct I/O and Cache I/O cache policies apply to reads on a specific virtual disk. These settings do not affect the read-ahead policy. The cache policies are as follows:
- Cache I/O. Specifies that all reads are buffered in cache memory.
- Direct I/O. Specifies that reads are not buffered in cache memory. When using direct I/O, data is transferred to the controller cache and the host system simultaneously during a read request. If a subsequent read request requires data from the same data block, it can be read directly from the controller cache. The direct I/O setting does not override the cache policy settings. Direct I/O is also the default setting.
Rebuilding a disk by hand when it doesn’t occur automatically
I noticed that strange behavior on an IBM controller. Unplugging and pluging back a disk from an array doesn’t make the controller rebuild the array with that disk.
Here is what to do:
The disk drive identified as ![252:4] ([enclosureid:slotnumber]) is currently ‘Unconfigured(bad)’.
Make the drive online again:
The controller will now recognise the disk as being a «foreign» one. It means it has detected some RAID informations on it, and thus, considers it as a disk being part of an array that may be imported into current controller configuration.
We will now ask the controller to scan for foreign configuration and drop it:
The disk should now be available for getting back into the array.
Let’s check it:
We now need to figure out how that disk was identified inside the RAID array:
Here is what’s important here:
Span Reference: 0x01 is the number of the array (strip the 0x0 part).
We can see that Physical Disk: 2 has no information, which means the drive is missing.
Now we have all we need to add the disk back into the array.
Get the disk ![252:4] back into array 1, as disk 2:
And finally start rebuilding:
Expand an array over an additionnal disk
Thanks to a co-worker, I have now a quick howto.
Assuming your new unassigned drive is identified as ![252:3] and you have a RAID5 array identified as L0 (See documentation above to figure out how to find this).
Reconfigure the array to add this new drive:
Check operation progress:
3.3.3. Periodic checks
You can write your own script around megacli to check your adapter status health periodically. However, I already did this for you. See megaclisas-status below.
Full documentation
A complete documentation is attached as PDF here: raw-attachment:megacli_user_guide.pdf
3.4. megaclisas-status
3.4.1. About megaclisas-status
megaclisas-status is a wrapper script around megacli that report summarized RAID status with periodic checks feature.
It is available in the packages repository too.
The packages comes with a python wrapper around megacli and an initscript that periodic run this wrapper to check status.
It keeps a file with latest status and thus is able to detect RAID status changes and/or brokeness.
It will log a ligne to syslog when something failed and will send you a mail.
Until arrays are healthy again a reminder will be sent each 2 hours.
3.4.2. Wrapper output example
Another example (I broke the raid by running «megacli -PDOffline -PhysDrv [32:0] -a0»)
The nagios mode (run with —nagios):
The same example but with missing disk rebuilding (ran «megacli -PDRbld -Start -PhysDrv [32:0] -a0» for this example):
A server with two controllers (old script version output, sorry got no such hardware to get a newer example): The first one with a RAID1 array working fine. A second one with a RAID6 arrays of 7 drives with one offline (the array has just been created so it’s under initialization too).
3.4.3. Nagios integration
The script can be called with —nagios parameter. It will force a single line output and will return exit code 0 if all good, or 2 if at least one thing is wrong. It’s the standard nagios expected return code.
You probably want to run the script through NRPE, define the command like this:
In /etc/nagios/nrpe.d/00_check_raid.cfg
You also need a sudo config file, in /etc/sudoers.d/00-check-raid
Then you can expect such monitoring facilities (centreon on-top centreon-engine in this picture):
3.5. About /dev/megaraid_sas_ioctl_node
All theses tools requires this device node to be created.
It has to be done by hand.
Proprietary tools creates the device node at startup.
I made some wrappers around binaries from megactl package to create the node if it doesn’t exist yet.
4. SMART
Finally I found the way to read SMART through these MegaRAID cards. The first thing you’ll have to do is to list IDs of all your physical disks:
Then you can add this kind of lines to /etc/smartd.conf (don’t forget to comment the DEVICESCAN one):
Please note you need a recent version of smartmontools. 5.38 from Debian Lenny won’t work, 5.39.1+svn3124 from Squeeze does.
5. BIOS upgrade from a Linux system
Dell cards can be flashed using firmware-tools.
See http://linux.dell.com/wiki/index.php/Repository/firmware for more informations.
However this will only work on RedHat, CentOS, SuSE and Fedora. Even Ubuntu is listed in the wikipage, LSI card upgrade is not supported.
We use a Fedora 8 nfsroot booted by PXE to update our Dell’s firmware running Debian.
Michael reported a firmware can be flashed using megacli with the following syntax:
I haven’t done it by myself but I sure it works.
Источник