This commit is contained in:
zj
2026-02-03 15:18:43 +08:00
parent 5862588fd1
commit dd51a10239
5 changed files with 480 additions and 143 deletions

View File

@@ -73,8 +73,14 @@ class SystemInfoManager:
add_path_recursive(dev['children'])
add_path_recursive(devices)
return devices
except subprocess.CalledProcessError as e:
logger.error(f"获取块设备信息失败: {e.stderr.strip()}")
return []
except json.JSONDecodeError as e:
logger.error(f"解析 lsblk JSON 输出失败: {e}")
return []
except Exception as e:
logger.error(f"获取块设备信息失败: {e}")
logger.error(f"获取块设备信息失败 (未知错误): {e}")
return []
def _find_device_by_path_recursive(self, dev_list, target_path):
@@ -199,40 +205,12 @@ class SystemInfoManager:
logger.debug(f"get_mountpoint_for_device: 未能获取到 {original_device_path} 的挂载点。")
return None
def get_mdadm_arrays(self):
def _parse_mdadm_detail_output(self, output, device_path):
"""
获取 mdadm RAID 阵列信息
解析 mdadm --detail 命令的输出
"""
cmd = ["mdadm", "--detail", "--scan"]
try:
stdout, _ = self._run_command(cmd)
arrays = []
for line in stdout.splitlines():
if line.startswith("ARRAY"):
parts = line.split(' ')
array_path = parts[1] # e.g., /dev/md0 or /dev/md/new_raid
# Use mdadm --detail for more specific info
detail_cmd = ["mdadm", "--detail", array_path]
detail_stdout, _ = self._run_command(detail_cmd)
array_info = self._parse_mdadm_detail(detail_stdout, array_path)
arrays.append(array_info)
return arrays
except subprocess.CalledProcessError as e:
if "No arrays found" in e.stderr or "No arrays found" in e.stdout: # mdadm --detail --scan might exit 1 if no arrays
logger.info("未找到任何RAID阵列。")
return []
logger.error(f"获取RAID阵列信息失败: {e}")
return []
except Exception as e:
logger.error(f"获取RAID阵列信息失败: {e}")
return []
def _parse_mdadm_detail(self, detail_output, array_path):
"""
解析 mdadm --detail 的输出。
"""
info = {
'device': array_path,
array_info = {
'device': device_path, # Default to input path, will be updated by canonical_device_path
'level': 'N/A',
'state': 'N/A',
'array_size': 'N/A',
@@ -241,46 +219,202 @@ class SystemInfoManager:
'spare_devices': 'N/A',
'total_devices': 'N/A',
'uuid': 'N/A',
'name': 'N/A',
'name': os.path.basename(device_path), # Default name, will be overridden
'chunk_size': 'N/A',
'member_devices': []
}
member_pattern = re.compile(r'^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.+?)\s+(/dev/.+)$')
for line in detail_output.splitlines():
if "Raid Level :" in line:
info['level'] = line.split(':')[-1].strip()
elif "Array Size :" in line:
info['array_size'] = line.split(':')[-1].strip()
elif "State :" in line:
info['state'] = line.split(':')[-1].strip()
elif "Active Devices :" in line:
info['active_devices'] = line.split(':')[-1].strip()
elif "Failed Devices :" in line:
info['failed_devices'] = line.split(':')[-1].strip()
elif "Spare Devices :" in line:
info['spare_devices'] = line.split(':')[-1].strip()
elif "Total Devices :" in line:
info['total_devices'] = line.split(':')[-1].strip()
elif "UUID :" in line:
info['uuid'] = line.split(':')[-1].strip()
elif "Name :" in line:
info['name'] = line.split(':')[-1].strip()
elif "Chunk Size :" in line:
info['chunk_size'] = line.split(':')[-1].strip()
# 首先,尝试从 mdadm --detail 输出的第一行获取规范的设备路径
device_path_header_match = re.match(r'^(?P<canonical_path>/dev/md\d+):', output)
if device_path_header_match:
array_info['device'] = device_path_header_match.group('canonical_path')
array_info['name'] = os.path.basename(array_info['device']) # 根据规范路径更新默认名称
# Member devices
match = member_pattern.match(line)
if match:
member_info = {
'number': match.group(1),
'major': match.group(2),
'minor': match.group(3),
'raid_device': match.group(4),
'device_path': match.group(5)
}
info['member_devices'].append(member_info)
return info
# 逐行解析键值对
for line in output.splitlines():
line = line.strip()
if not line:
continue
# 尝试匹配 "Key : Value" 格式
kv_match = re.match(r'^(?P<key>[A-Za-z ]+)\s*:\s*(?P<value>.+)', line)
if kv_match:
key = kv_match.group('key').strip().lower().replace(' ', '_')
value = kv_match.group('value').strip()
if key == 'raid_level':
array_info['level'] = value
elif key == 'state':
array_info['state'] = value
elif key == 'array_size':
array_info['array_size'] = value
elif key == 'uuid':
array_info['uuid'] = value
elif key == 'raid_devices':
array_info['total_devices'] = value
elif key == 'active_devices':
array_info['active_devices'] = value
elif key == 'failed_devices':
array_info['failed_devices'] = value
elif key == 'spare_devices':
array_info['spare_devices'] = value
elif key == 'name':
# 只取名字的第一部分,忽略括号内的额外信息
array_info['name'] = value.split(' ')[0]
elif key == 'chunk_size':
array_info['chunk_size'] = value
# 成员设备解析 (独立于键值对,因为它有固定格式)
member_pattern = re.match(r'^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([^\s]+(?:\s+[^\s]+)*)\s+(/dev/\S+)$', line)
if member_pattern:
array_info['member_devices'].append({
'number': member_pattern.group(1),
'major': member_pattern.group(2),
'minor': member_pattern.group(3),
'raid_device': member_pattern.group(4),
'state': member_pattern.group(5).strip(),
'device_path': member_pattern.group(6)
})
# 最终状态标准化
if array_info['state'] and 'active' in array_info['state'].lower():
array_info['state'] = array_info['state'].replace('active', 'Active')
elif array_info['state'] == 'clean':
array_info['state'] = 'Active, Clean'
elif array_info['state'] == 'N/A': # 如果未明确找到状态,则回退到推断
if "clean" in output.lower() and "active" in output.lower():
array_info['state'] = "Active, Clean"
elif "degraded" in output.lower():
array_info['state'] = "Degraded"
elif "inactive" in output.lower() or "stopped" in output.lower():
array_info['state'] = "Stopped"
return array_info
def get_mdadm_arrays(self):
"""
获取所有 RAID 阵列的信息,包括活动的和已停止的。
"""
all_arrays_info = {} # 使用 UUID 作为键,存储阵列的详细信息
# 1. 获取活动的 RAID 阵列信息 (通过 mdadm --detail --scan 和 /proc/mdstat)
active_md_devices = []
# 从 mdadm --detail --scan 获取
try:
stdout_scan, stderr_scan = self._run_command(["mdadm", "--detail", "--scan"], check_output=True)
for line in stdout_scan.splitlines():
if line.startswith("ARRAY"):
match = re.match(r'ARRAY\s+(\S+)(?:\s+\S+=\S+)*\s+UUID=([0-9a-f:]+)', line)
if match:
dev_path = match.group(1)
if dev_path not in active_md_devices:
active_md_devices.append(dev_path)
except subprocess.CalledProcessError as e:
if "No arrays found" not in e.stderr and "No arrays found" not in e.stdout:
logger.warning(f"执行 mdadm --detail --scan 失败: {e.stderr.strip()}")
except Exception as e:
logger.warning(f"处理 mdadm --detail --scan 输出时发生错误: {e}")
# 从 /proc/mdstat 获取 (补充可能未被 --scan 报告的活动阵列)
try:
with open("/proc/mdstat", "r") as f:
mdstat_content = f.read()
for line in mdstat_content.splitlines():
if line.startswith("md") and "active" in line:
device_name_match = re.match(r'^(md\d+)\s+:', line)
if device_name_match:
dev_path = f"/dev/{device_name_match.group(1)}"
if dev_path not in active_md_devices:
active_md_devices.append(dev_path)
except FileNotFoundError:
logger.debug("/proc/mdstat not found. Cannot check active arrays from /proc/mdstat.")
except Exception as e:
logger.error(f"Error reading /proc/mdstat: {e}")
# 现在,对每个找到的活动 MD 设备获取其详细信息
for device_path in active_md_devices:
try:
# 解析符号链接以获取规范路径,例如 /dev/md/0 -> /dev/md0
canonical_device_path = self._get_actual_md_device_path(device_path)
if not canonical_device_path:
canonical_device_path = device_path # 如果解析失败,使用原始路径作为回退
detail_stdout, detail_stderr = self._run_command(["mdadm", "--detail", canonical_device_path], check_output=True)
array_info = self._parse_mdadm_detail_output(detail_stdout, canonical_device_path)
if array_info and array_info.get('uuid') and array_info.get('device'):
# _parse_mdadm_detail_output 现在会更新 array_info['device'] 为规范路径
# 使用 UUID 作为键,如果同一个阵列有多个表示,只保留一个(通常是活动的)
all_arrays_info[array_info['uuid']] = array_info
else:
logger.warning(f"无法从 mdadm --detail {canonical_device_path} 输出中解析 RAID 阵列信息: {detail_stdout[:100]}...")
except subprocess.CalledProcessError as e:
logger.warning(f"获取 RAID 阵列 {device_path} 详细信息失败: {e.stderr.strip()}")
except Exception as e:
logger.warning(f"处理 RAID 阵列 {device_path} 详细信息时发生错误: {e}")
# 2. 从 /etc/mdadm.conf 获取配置的 RAID 阵列信息 (可能包含已停止的)
mdadm_conf_paths = ["/etc/mdadm/mdadm.conf", "/etc/mdadm.conf"]
found_conf = False
for mdadm_conf_path in mdadm_conf_paths:
if os.path.exists(mdadm_conf_path):
found_conf = True
try:
with open(mdadm_conf_path, 'r') as f:
for line in f:
line = line.strip()
if line.startswith("ARRAY"):
match_base = re.match(r'ARRAY\s+(\S+)\s*(.*)', line)
if match_base:
device_path = match_base.group(1)
rest_of_line = match_base.group(2)
uuid = 'N/A'
name = os.path.basename(device_path) # Default name
uuid_match_conf = re.search(r'UUID=([0-9a-f:]+)', rest_of_line)
if uuid_match_conf:
uuid = uuid_match_conf.group(1)
name_match_conf = re.search(r'NAME=(\S+)', rest_of_line)
if name_match_conf:
name = name_match_conf.group(1)
if uuid != 'N/A': # 只有成功提取到 UUID 才添加
# 只有当此 UUID 对应的阵列尚未被识别为活动状态时,才添加为停止状态
if uuid not in all_arrays_info:
all_arrays_info[uuid] = {
'device': device_path,
'uuid': uuid,
'name': name,
'level': 'Unknown',
'state': 'Stopped (Configured)',
'array_size': 'N/A',
'active_devices': 'N/A',
'failed_devices': 'N/A',
'spare_devices': 'N/A',
'total_devices': 'N/A',
'chunk_size': 'N/A',
'member_devices': []
}
else:
logger.warning(f"无法从 mdadm.conf 行 '{line}' 中提取 UUID。")
else:
logger.warning(f"无法解析 mdadm.conf 中的 ARRAY 行: '{line}'")
except Exception as e:
logger.warning(f"读取或解析 {mdadm_conf_path} 失败: {e}")
break # 找到并处理了一个配置文件就退出循环
if not found_conf:
logger.info(f"未找到 mdadm 配置文件。")
# 返回所有阵列的列表
# 排序:活动阵列在前,然后是停止的
sorted_arrays = sorted(all_arrays_info.values(), key=lambda x: (x.get('state') != 'Active', x.get('device')))
return sorted_arrays
def get_lvm_info(self):
"""
@@ -290,7 +424,7 @@ class SystemInfoManager:
# Get PVs
try:
stdout, _ = self._run_command(["pvs", "--reportformat", "json"])
stdout, stderr = self._run_command(["pvs", "--reportformat", "json"])
data = json.loads(stdout)
if 'report' in data and data['report']:
for pv_data in data['report'][0].get('pv', []):
@@ -307,13 +441,15 @@ class SystemInfoManager:
if "No physical volume found" in e.stderr or "No physical volumes found" in e.stdout:
logger.info("未找到任何LVM物理卷。")
else:
logger.error(f"获取LVM物理卷信息失败: {e}")
logger.error(f"获取LVM物理卷信息失败: {e.stderr.strip()}")
except json.JSONDecodeError as e:
logger.error(f"解析LVM物理卷JSON输出失败: {e}")
except Exception as e:
logger.error(f"获取LVM物理卷信息失败: {e}")
logger.error(f"获取LVM物理卷信息失败 (未知错误): {e}")
# Get VGs
try:
stdout, _ = self._run_command(["vgs", "--reportformat", "json"])
stdout, stderr = self._run_command(["vgs", "--reportformat", "json"])
data = json.loads(stdout)
if 'report' in data and data['report']:
for vg_data in data['report'][0].get('vg', []):
@@ -332,14 +468,16 @@ class SystemInfoManager:
if "No volume group found" in e.stderr or "No volume groups found" in e.stdout:
logger.info("未找到任何LVM卷组。")
else:
logger.error(f"获取LVM卷组信息失败: {e}")
logger.error(f"获取LVM卷组信息失败: {e.stderr.strip()}")
except json.JSONDecodeError as e:
logger.error(f"解析LVM卷组JSON输出失败: {e}")
except Exception as e:
logger.error(f"获取LVM卷组信息失败: {e}")
logger.error(f"获取LVM卷组信息失败 (未知错误): {e}")
# Get LVs (MODIFIED: added -o lv_path)
try:
# 明确请求 lv_path因为默认的 --reportformat json 不包含它
stdout, _ = self._run_command(["lvs", "-o", "lv_name,vg_name,lv_uuid,lv_size,lv_attr,origin,snap_percent,lv_path", "--reportformat", "json"])
stdout, stderr = self._run_command(["lvs", "-o", "lv_name,vg_name,lv_uuid,lv_size,lv_attr,origin,snap_percent,lv_path", "--reportformat", "json"])
data = json.loads(stdout)
if 'report' in data and data['report']:
for lv_data in data['report'][0].get('lv', []):
@@ -357,9 +495,11 @@ class SystemInfoManager:
if "No logical volume found" in e.stderr or "No logical volumes found" in e.stdout:
logger.info("未找到任何LVM逻辑卷。")
else:
logger.error(f"获取LVM逻辑卷信息失败: {e}")
logger.error(f"获取LVM逻辑卷信息失败: {e.stderr.strip()}")
except json.JSONDecodeError as e:
logger.error(f"解析LVM逻辑卷JSON输出失败: {e}")
except Exception as e:
logger.error(f"获取LVM逻辑卷信息失败: {e}")
logger.error(f"获取LVM逻辑卷信息失败 (未知错误): {e}")
return lvm_info
@@ -430,6 +570,10 @@ class SystemInfoManager:
logger.warning(f"传入 _get_actual_md_device_path 的 array_path 不是字符串: {array_path} (类型: {type(array_path)})")
return None
# 如果已经是规范的 /dev/mdX 路径,直接返回
if re.match(r'^/dev/md\d+$', array_path):
return array_path
if os.path.exists(array_path):
try:
# os.path.realpath 会解析符号链接,例如 /dev/md/new_raid -> /dev/md127
@@ -546,3 +690,69 @@ class SystemInfoManager:
# 5. 如果仍然没有找到,返回 None
logger.debug(f"get_device_details_by_path: 未能获取到 {original_device_path} 的任何详情。")
return None
def delete_raid_array_config(self, uuid):
"""
从 mdadm.conf 文件中删除指定 UUID 的 RAID 阵列配置条目。
:param uuid: 要删除的 RAID 阵列的 UUID。
:return: True 如果成功删除或未找到条目False 如果发生错误。
:raises Exception: 如果删除失败。
"""
logger.info(f"尝试从 mdadm.conf 中删除 UUID 为 {uuid} 的 RAID 阵列配置。")
mdadm_conf_paths = ["/etc/mdadm/mdadm.conf", "/etc/mdadm.conf"]
target_conf_path = None
# 找到存在的 mdadm.conf 文件
for path in mdadm_conf_paths:
if os.path.exists(path):
target_conf_path = path
break
if not target_conf_path:
logger.warning("未找到 mdadm 配置文件,无法删除配置条目。")
raise FileNotFoundError("mdadm 配置文件未找到。")
original_lines = []
try:
with open(target_conf_path, 'r') as f:
original_lines = f.readlines()
except Exception as e:
logger.error(f"读取 mdadm 配置文件 {target_conf_path} 失败: {e}")
raise Exception(f"读取 mdadm 配置文件失败: {e}")
new_lines = []
entry_found = False
for line in original_lines:
stripped_line = line.strip()
if stripped_line.startswith("ARRAY"):
# 尝试匹配 UUID
uuid_match = re.search(r'UUID=([0-9a-f:]+)', stripped_line)
if uuid_match and uuid_match.group(1) == uuid:
logger.debug(f"找到并跳过 UUID 为 {uuid} 的配置行: {stripped_line}")
entry_found = True
continue # 跳过此行,即删除
new_lines.append(line)
if not entry_found:
logger.warning(f"在 mdadm.conf 中未找到 UUID 为 {uuid} 的 RAID 阵列配置条目。")
# 即使未找到,也不视为错误,因为可能已经被手动删除或从未写入
return True
# 将修改后的内容写回文件 (需要 root 权限)
try:
# 使用临时文件进行原子写入,防止数据损坏
temp_file_path = f"{target_conf_path}.tmp"
with open(temp_file_path, 'w') as f:
f.writelines(new_lines)
# 替换原文件
self._run_command(["mv", temp_file_path, target_conf_path], root_privilege=True)
logger.info(f"成功从 {target_conf_path} 中删除 UUID 为 {uuid} 的 RAID 阵列配置。")
return True
except subprocess.CalledProcessError as e:
logger.error(f"删除 mdadm 配置条目失败 (mv 命令错误): {e.stderr.strip()}")
raise Exception(f"删除 mdadm 配置条目失败: {e.stderr.strip()}")
except Exception as e:
logger.error(f"写入 mdadm 配置文件 {target_conf_path} 失败: {e}")
raise Exception(f"写入 mdadm 配置文件失败: {e}")