PHP: Parse /proc/mdstat

Step-by-Step descriptions of how to do things.
Post Reply
User avatar
peter_b
Chatterbox
Posts: 383
Joined: Tue Nov 12, 2013 2:05 am

PHP: Parse /proc/mdstat

Post by peter_b »

Here's a small code snippet I've hacked together, which parses /proc/mdstat into an array structure:

Code: Select all

/**
 * This function reads and parses the /proc/mdstat file and returns an
 * array with the information about the status, disks, etc. per
 * kernel MD-RAID.
 */
function read_mdstat($mdstat_file="/proc/mdstat")
{
    $mdstat_array = null;
    $mdstat_raw = file_get_contents($mdstat_file);

    $mdstat_array['raw'] = $mdstat_raw;

    // Let's get one line per md-array:
    preg_match_all("/md\d : .*/", $mdstat_raw, $mdstat_raids);
    foreach ($mdstat_raids[0] as $index=>$mdstat_raid)
    {
        // Gather data from the mdstat lines:
        preg_match("/md\d : (active|xxx)? raid([0156])? (.*)/", $mdstat_raid, $md_raid);
        preg_match_all("/(sd[a-z]{1,2})\d*\[(\d{1,2})\](\(([FS])\)){0,1}/", $md_raid[3], $md_disks);

        $raid_disks = array();
        foreach ($md_disks[1] as $index2=>$md_disk)
        {
            $disk_index = ($md_disks[2][$index2]) +1;
            $raid_disks[$disk_index] = array(
                'device_name' => $md_disk,
                'status' => $md_disks[3][$index2],
            );
        }
        ksort($raid_disks); // Sort by keys

        // Let's map:
        $md_name = $mdstat_raids[1][$index];
        $mdstat_array[$md_name]['status'] = $md_raid[1];
        $mdstat_array[$md_name]['raid_level'] = $md_raid[2];
        $mdstat_array[$md_name]['disks'] = $raid_disks;
    }

    ksort($mdstat_array);
    return $mdstat_array;
}
The print_r($mdstat_array) output would look something like this:

Code: Select all

[md0] => Array
        (
            [status] => active
            [raid_level] => 1
            [disks] => Array
                (
                    [1] => Array
                        (
                            [device_name] => sdat
                            [status] => 
                        )

                    [2] => Array
                        (
                            [device_name] => sdau
                            [status] => (F)
                        )

                )

        )
Post Reply