1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
|
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Wrapper functions around the megacli command."""
import os
import re
from subprocess import PIPE
from subprocess import Popen
import sys
from hardware import detect_utils
SEP_REGEXP = re.compile(r'\s*:\s*')
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Return the path to an executable.
Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(myfile, mode):
return (os.path.exists(myfile) and os.access(myfile, mode)
and not os.path.isdir(myfile))
# If we're given a path with a directory part, look it up directly rather
# than referring to PATH directories. This includes checking relative to
# the current directory, e.g. ./script
if os.path.dirname(cmd):
if _access_check(cmd, mode):
return cmd
return None
if path is None:
path = os.environ.get("PATH", os.defpath)
if not path:
return None
path = path.split(os.pathsep)
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for directory in path:
normdir = os.path.normcase(directory)
if normdir not in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(directory, thefile)
if _access_check(name, mode):
return name
return None
def search_exec(possible_names):
prog_path = None
for prog_name in possible_names:
prog_path = which(prog_name)
if prog_path is not None:
break
return prog_path
def parse_output(output):
"""Parse the output of the megacli command into an associative array."""
res = {}
for line in output.split('\n'):
lis = re.split(SEP_REGEXP, line.strip())
if len(lis) == 2:
if len(lis[1]) > 1 and lis[1][-1] == '.':
lis[1] = lis[1][:-1]
try:
res[lis[0].title().replace(' ', '')] = int(lis[1])
except ValueError:
res[lis[0].title().replace(' ', '')] = lis[1]
return res
def split_parts(sep, output):
"""Split the output string according to the regexp sep."""
regexp = re.compile(sep)
lines = output.split('\n')
idx = []
num = 0
for line in lines:
if regexp.search(line):
idx.append(num)
num = num + 1
arr = []
start = idx[0]
for num in idx[1:]:
arr.append('\n'.join(lines[start:num - 1]))
start = num
arr.append('\n'.join(lines[start:]))
return arr
def run_megacli(*args):
"""Run the megacli command in a subprocess and return the output."""
prog_exec = search_exec(["megacli", "MegaCli", "MegaCli64"])
if prog_exec:
cmd = prog_exec + ' - ' + ' '.join(args)
proc = Popen(cmd, shell=True, stdout=PIPE, universal_newlines=True)
return proc.communicate()[0]
sys.stderr.write('Cannot find megacli on the system\n')
return ""
def run_and_parse(*args):
"""Run the megacli command in a subprocess.
Returns the output as an associative array.
"""
res = run_megacli(*args)
return parse_output(res)
def adp_count():
"""Get the numberof adaptaters."""
arr = run_and_parse('adpCount')
if 'ControllerCount' in arr:
return int(arr['ControllerCount'])
return 0
def adp_all_info(ctrl):
"""Get adaptater info."""
arr = run_and_parse('adpallinfo -a%d' % ctrl)
for key in ('RaidLevelSupported', 'SupportedDrives'):
if key in arr:
arr[key] = arr[key].split(', ')
return arr
def pd_get_num(ctrl):
"""Get the number of physical drives on a controller."""
try:
key = 'NumberOfPhysicalDrivesOnAdapter%d' % ctrl
return run_and_parse('PDGetNum -a%d' % ctrl)[key]
except KeyError:
return 0
def enc_info(ctrl):
"""Get enclosing info on a controller."""
parts = split_parts(' +Enclosure [0-9]+:',
run_megacli('EncInfo -a%d' % ctrl))
all_ = list(map(parse_output, parts))
for entry in all_:
for key in entry.keys():
if re.search(r"Enclosure\d+", key):
entry['Enclosure'] = int(key[len('Enclosure'):])
del entry[key]
break
return all_
def pdinfo(ctrl, encl, disk):
"""Get info about a physical drive on an enclosure and a controller."""
return run_and_parse('pdinfo -PhysDrv[%d:%d] -a%d' % (encl, disk, ctrl))
def ld_get_num(ctrl):
"""Get the number of logical drives on a controller."""
try:
key = 'NumberOfVirtualDrivesConfiguredOnAdapter%d' % ctrl
return run_and_parse('LDGetNum -a%d' % ctrl)[key]
except KeyError:
return 0
def ld_get_info(ctrl, ldrv):
"""Get info about a logical drive on a controller."""
return run_and_parse('LDInfo -L%d -a%d' % (ldrv, ctrl))
def detect():
"""Detect LSI MegaRAID controller configuration."""
hw_lst = []
ctrl_num = adp_count()
if ctrl_num == 0:
return hw_lst
disk_count = 0
global_pdisk_size = 0
for ctrl in range(ctrl_num):
ctrl_info = adp_all_info(ctrl)
for entry in ctrl_info.keys():
hw_lst.append(('megaraid', 'Controller_%d' % ctrl, '%s' % entry,
'%s' % ctrl_info[entry]))
for enc in enc_info(ctrl):
if "Enclosure" in enc.keys():
for key in enc.keys():
ignore_list = ["ExitCode", "Enclosure"]
if key in ignore_list:
continue
hw_lst.append(('megaraid',
'Controller_%d/Enclosure_%s' %
(ctrl, enc["Enclosure"]),
'%s' % key, '%s' % enc[key]))
for slot_num in range(enc['NumberOfSlots']):
disk = 'disk%d' % slot_num
info = pdinfo(ctrl, enc['DeviceId'], slot_num)
# If no PdType, it means that's not a disk
if 'PdType' not in info.keys():
continue
disk_count += 1
hw_lst.append(('pdisk', disk, 'ctrl', str(ctrl_num)))
hw_lst.append(('pdisk', disk, 'type', info['PdType']))
hw_lst.append(('pdisk', disk, 'id',
'%s:%d' % (info['EnclosureDeviceId'],
slot_num)))
disk_size = detect_utils.size_in_gb(
"%s %s" % (info['CoercedSize'].split()[0],
info['CoercedSize'].split()[1]))
global_pdisk_size = global_pdisk_size + float(disk_size)
hw_lst.append(('pdisk', disk, 'size', disk_size))
for key in info.keys():
ignore_list = ['PdType', 'EnclosureDeviceId',
'CoercedSize', 'ExitCode']
if key not in ignore_list:
if "DriveTemperature" in key:
if "C" in str(info[key].split()[0]):
pdisk = info[key].split()[0].split("C")[0]
hw_lst.append(('pdisk', disk, key,
str(pdisk).strip()))
hw_lst.append(('pdisk', disk,
"%s_units" % key,
"Celsius"))
else:
hw_lst.append(('pdisk', disk, key,
str(info[key]).strip()))
elif "InquiryData" in key:
count = 0
for mystring in info[key].split():
hw_lst.append(('pdisk', disk,
"%s[%d]" % (key, count),
str(mystring.strip())))
count = count + 1
else:
hw_lst.append(('pdisk', disk, key,
str(info[key]).strip()))
if global_pdisk_size > 0:
hw_lst.append(('pdisk', 'all', 'size',
"%.2f" % global_pdisk_size))
for ld_num in range(ld_get_num(ctrl)):
disk = 'disk%d' % ld_num
info = ld_get_info(ctrl, ld_num)
ignore_list = ['Size']
for item in info.keys():
if item not in ignore_list:
hw_lst.append(('ldisk', disk, item,
str(info[item])))
if 'Size' in info:
hw_lst.append(('ldisk', disk, 'Size',
detect_utils.size_in_gb(info['Size'])))
hw_lst.append(('disk', 'megaraid', 'count', str(disk_count)))
return hw_lst
|