aboutsummaryrefslogtreecommitdiff
RAID 50 simulation

RAID 50 simulation
with message size of 8 bytes and 6 disks

1. Task

This is a machine translation.1

Each student individually needs to develop an application that simulates the operation of a RAID array at levels 6 and 50 (5+0) with a specified size of the original message and the number of disks. The application performs read and write operations on the message at the specified address (a linear array of strings with indices from 0 to 63). A table with task options is attached to the email, where one "+" symbol indicates one available option. Distribute them among yourselves in such a way that each person gets their own variant. The work must be completed in the form of an executable application file, a report, and an archive with the source code.

The parameters for the task variants are from the table.

  1. Array type: RAID 6 or RAID 50 (5+0). Information about these levels in a simple and accessible form with explanatory images: https://en.wikipedia.org/wiki/Standard_RAID_levels. RAID 6 Arrays must restore data in case of failure of any two disks, RAID 50 arrays – in case of failure of any one disk.
  2. Redundancy calculation: XOR and/or POLY. XOR – calculating the value of a redundancy block using the "exclude or" operation for a pair of blocks. In case of a larger and/or an odd number of blocks messages can use a hierarchical XOR calculation., adding a fixed service value (for example, a set of "1" according to the block size) and any other techniques you choose discretion. POLY – calculating the value of the redundancy block with using polynomial expressions (for example, a pair of polynomials the first level is A-B+C-D+E=X and A+2B-3C+4D-5E=Y for a RAID 6 array of seven disks, where A..E are the blocks that make up the original message, X and Y are redundancy blocks).
  3. Message size: 8, 10, 12, 14 bytes. This is the size of the original (whole) message to be written to the array and read from the array. Message This size is specified by the user when selecting a write operation, and the same size messages are given to the user when selecting a read operation.
  4. Number of disks: 3, 4, 5, 6, 7, 8, 10. This is the total number disks in the array for writing message blocks and redundancy blocks.

Comments on the table.

  1. You can, if you wish, choose a more complex RAID array configuration, such as RAID 60 (6+0), if you’re interested, but this must be согласован with me.
  2. You can, if you wish, choose any other method of calculating redundancy blocks, if you’re interested, but this must be согласован. with me. You also need to be sure that the chosen method allows you to fully restore the original message in case of loss. any two blocks for RAID 6/60 (any message block + any block redundancy, any two message blocks, two redundancy blocks). The hierarchical calculation of XOR is demonstrated by the following example. Let's give a RAID 5 array on five disks and the message 12345678(hex). Then the message blocks will be: 12, 34, 56, 78. We count the XOR separately for the first pair of blocks: 12 XOR 34 = 26, separately for the second pair blocks: 56 XOR 78 = 2E, then count the XOR for these two results: 26 XOR 2E = 08 – we will write this value in the block. redundancy. Now, if we lose any message block (for example, 34), we will restore it. First, let's check which original pair the block is missing from and calculate the XOR of the remaining pair: 56 XOR 78 = 2E, now we count the XOR of our redundancy block with the resulting result: 08 XOR 2E = 26 – got the XOR of the first pair of values, now we find the lost block from this value and the saved one. message block: 26 XOR 12 = 34 — the message block is restored, we can fully reconstruct the original message. Adding a fixed service value can help, for example, if the number of blocks is odd. Let’s say we have a RAID 5 array on four disks and the message is 123456(hex). Then the message blocks will be: 12, 34, 56. You can add a service value, for example, FF as of a fixed “virtual” block and completely repeat the algorithm described above. Or you can do it differently: calculate the XOR for the first pair of message blocks, then calculate the XOR of the resulting value and the remaining message block. That is: 12 XOR 34 = 26, 26 XOR 56 = 70 — this value will be written to the redundancy block.
  3. After analyzing the message size and the number of disks, you can see that the message is not always "divided" into an integer number of blocks. This should not bother you, because you can always adopt rules according to which you will supplement the message block with seniors. zeros so that all blocks have the same size. For example, let given a RAID 6 array on five disks and a 5 byte message (Martin: If we take ASCII, not hex…): 12345(hex). Given that two disks will be used for redundancy when writing the message, we need to divide the original message into three blocks: 12, 34, 5. The last block can be supplemented with a leading zero to get the value 05, which will be written to the disk.
  4. Do not forget that the parity in RAID 5 and 6 arrays, as well as in their derivatives, is distributed. That is, when accessing each next "row", the blocks of messages and redundancy will be They can be arranged in different order. You can use a simple technique: create a placement matrix and select a row of the matrix on based on dividing the address modulo the number of disks. For example, let there will be a RAID 5 array on four disks. For him, the matrix of block placements can be as follows (here BS is a message block, BI is a block redundancy).

Your application can use either of two approaches as disks: text files (one disk is one file, one message block – one line of the file) or a database (one disk - one table, one message block - one table entry) at your discretion. Files and tables must be named

2. Documentation

The exported report can be found at this link.

3. Showcase

A sample session of working with the program is provided; lines with comments start with #.2

# Program start, there are no disk files
INFO:    initializing RAID 50 with XOR on 6 disks with 8 byte messages...
WARNING: found bad disk (missing): disk0
WARNING: found bad disk (missing): disk1
WARNING: found bad disk (missing): disk2
WARNING: found bad disk (missing): disk3
WARNING: found bad disk (missing): disk4
WARNING: found bad disk (missing): disk5
ERROR:   too many bad disks, reinitializing the array with new disks...
# At this point, the disk files already exist.
> 0 asdf
ERROR:   invalid command, must be on of (read, write)
> 0 read asdf
ERROR:   trailing junk after command: asdf
> 0 write
ERROR:   expected 16 hex digits for message, received 0
> 0 write 112233445566778
ERROR:   expected 16 hex digits for message, received 15
> 0 write 11223344556677888
ERROR:   expected 16 hex digits for message, received 17
> 0 write asdf
ERROR:   message contains invalid character `s'
> 0 write -10
ERROR:   message contains invalid character `-'
>
> 0 write 1122334455667788
> 1 write 1122334455667788
> 2 write 1122334455667788
> 0 read
1122334455667788
> 1 read
1122334455667788
> 2 read
1122334455667788
>
# Manualy damaged the disk2 file
> 0 read
WARNING: found bad disk (corrupted): disk2
INFO:    there is just 1 bad disk, recomputing it...
1122334455667788
>
# Manualy damaged the disk4 file
> 1 read
WARNING: found bad disk (corrupted): disk4
INFO:    there is just 1 bad disk, recomputing it...
1122334455667788
>
# Manualy damaged disk0 and disk5 files => we can recover
> 2 read
WARNING: found bad disk (corrupted): disk0
WARNING: found bad disk (corrupted): disk5
INFO:    there are 2 bad disk in separate clusters, recomputing them...
1122334455667788
>
# Manualy damaged disk0 and disk1 files => we can't recover
> 0 read
WARNING: found bad disk (corrupted): disk0
WARNING: found bad disk (corrupted): disk1
ERROR:   too many bad disks, reinitializing the array with new disks...
No data stored!
>
# No message has been recorded at address 0x1F yet
> 1F read
No data stored!
>
# Attempt to access an address outside the allowed range
> 40 read
ERROR:   address not in set [0x00; 0x40)
> AA read
ERROR:   address not in set [0x00; 0x40)
> 100 read
ERROR:   address not in set [0x00; 0x40)
> interrupt

5. Unlicense

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to https://unlicense.org/

Footnotes:

1

Original text:

Каждому студенту индивидуально необходимо разработать приложение, моделирующее работу RAID-массива уровней 6 и 50 (5+0) с заданными размером исходного сообщения и числом дисков. Приложение выполняет операции чтения и записи сообщения по указываемому адресу (линейный массив строк с индексами от 0 до 63). К письму приложена таблица с вариантами заданий, где один символ "+" обозначает один доступный для выбора вариант. Распределите их между собой таким образом, чтобы каждому достался свой вариант. Работа должна быть выполнена в виде исполняемого файла приложения, отчёта, архива с исходным кодом.

Параметры вариантов задания из таблицы.

  1. Тип массива: RAID 6 или RAID 50 (5+0). Информация об этих уровнях в простой и доступной форме с поясняющими изображениями: https://en.wikipedia.org/wiki/Standard_RAID_levels. Массивы RAID 6 должны восстанавливать данные при выходе из строя любых двух дисков, массивы RAID 50 – при выходе из строя любого одного диска.
  2. Подсчёт избыточности: XOR и/или POLY. XOR – подсчёт значения блока избыточности с использованием операции "исключающего или" для пары блоков. В случае большего и/или нечётного количества блоков сообщения можно использовать иерархическое вычисление XOR, добавление фиксированного служебного значения (например, набор "1" соответственно размеру блока) и любые другие приёмы на ваше усмотрение. POLY – подсчёт значения блока избыточности с использованием полиномиальных выражений (например, пара полиномов первого уровня вида A-B+C-D+E=X и A+2B-3C+4D-5E=Y для массива RAID 6 из семи дисков, где A..E – блоки, составляющие исходное сообщение, X и Y – блоки избыточности).
  3. Размер сообщения: 8, 10, 12, 14 байт. Это размер исходного (целого) сообщения для записи на массив и читаемого с массива. Сообщение такого размера указывает пользователь при выборе операции записи и такого же размера сообщения выдаются пользователю при выборе операции чтения.
  4. Количество дисков: 3, 4, 5, 6, 7, 8, 10. Это общее количество дисков в массиве для записи блоков сообщения и блоков избыточности.

Комментарии по таблице.

  1. Вы можете, по желанию, выбрать более сложный вариант массива RAID 60 (6+0), если вам это интересно, но это необходимо согласовать со мной.
  2. Вы можете, по желанию, выбрать любой другой способ подсчёта блоков избыточности, если вам это интересно, но это необходимо согласовать со мной. Также вы должны быть уверены, что выбранный способ позволяет вам полностью восстановить исходное сообщение при потере любых двух блоков для RAID 6/60 (любой блок сообщения + любой блок избыточности, любые два блока сообщения, два блока избыточности). Иерархическое вычисление XOR демонстрируется следующим примером. Пусть дан массив RAID 5 на пяти дисках и сообщение 12345678(hex). Тогда блоки сообщения будут: 12, 34, 56, 78. Считаем XOR отдельно для первой пары блоков: 12 XOR 34 = 26, отдельно – для второй пары блоков: 56 XOR 78 = 2E, затем считаем XOR для этих двух результатов: 26 XOR 2E = 08 – это значение и запишем в блок избыточности. Теперь при потере любого блока сообщения (например, 34) восстановим его. Сначала проверим, из какой исходной пары пропал блок и посчитаем XOR оставшейся пары: 56 XOR 78 = 2E, теперь считаем XOR нашего блока избыточности с полученным результатом: 08 XOR 2E = 26 – получили XOR первой пары значений, теперь находим потерянный блок из этого значения и сохранившегося блока сообщения: 26 XOR 12 = 34 – блок сообщения восстановлен, можем полностью собрать исходное сообщение. Добавление фиксированного служебного значения может помочь, например, если количество блоков нечётное. Пусть дан массив RAID 5 на четырёх дисках сообщение 123456(hex). Тогда блоки сообщения будут: 12, 34, 56. Можно добавить служебное значение, например, FF в качестве фиксированного "виртуального" блока и полностью повторить описанный выше алгоритм. А можно и поступить иначе: вычислять XOR для первой пары блоков сообщения, затем вычислять XOR полученного значения и оставшегося блока сообщения. То есть: 12 XOR 34 = 26, 26 XOR 56 = 70 – это значение и запишем в блок избыточности.
  3. Проанализировав размер сообщения и количество дисков, вы можете увидеть, что сообщение не всегда "делится" на целое число блоков. Это не должно вас смущать, поскольку вы всегда можете принять правила, по которым будете дополнять блок сообщения старшими нулями, чтобы все блоки имели одинаковый размер. Например, пусть дан массив RAID 6 на пяти дисках и сообщение размером 5 байт (Мартин: если брать ascii, а не hex…): 12345(hex). Учитывая, что два диска при записи сообщения будут задействованы под избыточность, нам необходимо разделить исходное сообщение на три блока: 12, 34, 5. Последний блок можно дополнить старшим нулём, чтобы получить значение 05, которое и будет записано на диск.
  4. Не забывайте, что чётность в массивах RAID 5 и 6, как и в производных от них, распределённая. То есть, при обращении к каждой следующей "строке" блоки сообщений и избыточности будут располагаться в разном порядке. Вы можете использовать простой приём: создать матрицу размещений и выбирать строку матрицы на основе деления адреса по модулю от числа дисков. Например, пусть будет массив RAID 5 на четырёх дисках. Для него матрица размещений блоков может быть такой (здесь БС – блок сообщения, БИ – блок избыточности).

В качестве дисков ваше приложение может использовать любой из двух подходов: текстовые файлы (один диск – один файл, один блок сообщения – одна строка файла) или базу данных (один диск – одина таблица, один блок сообщения – одна запись таблицы) на ваше усмотрение. Файлы и таблицы должны быть проименованы как disk0..disk9, файлы должны располагаться в рабочем каталоге приложения и не блокироваться для записи в процессе его работы (чтобы можно было очистить содержимое любого файла или удалить его, моделируя выход диска из строя).

Примеры пользовательских операций (массив RAID 5 на трёх дисках):

> 00 write 3d6c (адрес: 00, операция: запись, сообщение: 3D6C, блок сообщения для записи на диск 0: 3D, блок сообщения для записи на диск 1: 6C, блок избыточности для записи на диск 2 – арифметическая сумма 3В+6С: A9);

> 01 write 519a (адрес: 01, операция: запись, сообщение: 519A, блок сообщения для записи на диск 0: 51, блок избыточности для записи на диск 2 – арифметическая сумма 51+9A: EB, блок сообщения для записи на диск 1: 9A);

… удаляем содержимое файла или таблицы "disk0";

> 00 read (адрес: 00, операция: чтение, диск 0: пусто, диск 1: блок сообщения 6C, диск 2: блок избыточности A9, вычисляем блок сообщения диска 0: A9-6C=3D, собираем сообщение: 3D6C).

Графика, анимации, счётчики – ничего этого не нужно, простое консольное приложение. При использовании базы данных необходимо отдельно приложить файлы сценариев создания таблиц, в качестве диалектов допустимы T-SQL и MySQL.

Date: 2024H1

Author: Martin Michalec

Created: 2026-11-07 Sat 11:37