forked from amarao/sdled
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encled
executable file
·541 lines (487 loc) · 21.2 KB
/
encled
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
#!/usr/bin/env python3
"""
encled - SCSI Enclosure indicators (SES LED) control
"""
import argparse
import logging
import subprocess
import re
import os
import numpy
# default settings
defaults = {
"CLASS": "/sys/class/enclosure/",
"SLOT": None,
"first_slot": 1
}
# define layouts for enclosures
enclosure_layouts = {"sm20": numpy.array([[0, 8, 14, 20],
[0, 7, 13, 19],
[0, 6, 12, 18],
[0, 5, 11, 17],
[2, 4, 10, 16],
[1, 3, 9, 15]]),
"sm24": numpy.array([[6, 12, 18, 24],
[5, 11, 17, 23],
[4, 10, 16, 22],
[3, 9, 15, 21],
[2, 8, 14, 20],
[1, 7, 13, 19]]),
"sm44": numpy.array([[6, 12, 18, 24],
[5, 11, 17, 23],
[4, 10, 16, 22],
[3, 9, 15, 21],
[2, 8, 14, 20],
[1, 7, 13, 19],
[0, 32, 38, 44],
[0, 31, 37, 43],
[0, 30, 36, 42],
[0, 29, 35, 41],
[26, 28, 34, 40],
[25, 27, 33, 39]])}
def error(text):
"""
cancel the operation and exit
:param text:
:return:
"""
logging.error(text)
exit(-1)
def scan_system():
"""
use lsscsi, sg_ses to get an overview of the system
:return:
"""
# first step: use lsscsi to find all enclosures
enclosures = {}
sts, out = subprocess.getstatusoutput("lsscsi -g")
if sts != 0:
error("unable to list scsi devices!")
for line in out.splitlines():
words = line.split()
if words[1] == "enclosu":
enclosures[words[-1]] = {"scsi_tuple": words[0][1:-1]}
# create a mapping between the /dev/sd* devices and sas addresses
sas_dev_sd = {}
dev_sd_scsi = {}
dev_sd_size = {}
sts, out = subprocess.getstatusoutput("lsscsi -t -i -s")
if sts != 0:
error("unable to list scsi devices!")
for line in out.splitlines():
words = line.split()
if words[1] == "disk" and words[2].startswith("sas:"):
sas_dev_sd[words[2].replace("sas:", "")] = words[-3]
dev_sd_scsi[words[-3]] = words[-2]
dev_sd_size[words[-3]] = words[-1]
# loop over all enclosures to find all connected devices
for one_enclosure in enclosures.keys():
# at first count the slots
enc_path = find_path(enclosures[one_enclosure]["scsi_tuple"], -1)
slot_dirs = [one_dir for one_dir in os.listdir(enc_path) if defaults["SLOT"] in one_dir]
enclosures[one_enclosure]["n_slots"] = len(slot_dirs)
# then go through information provided by sg_ses
sts, out = subprocess.getstatusoutput("sg_ses -p 0xa %s" % one_enclosure)
if sts != 0:
error("unable to find connected devices for enclosure %s" % one_enclosure)
lines = out.splitlines()
# the first line is the enclosure name
enclosures[one_enclosure]["description"] = re.sub("\s+", ", ", lines[0].strip())
# then find all disks, they start with "Element index:"
enclosures[one_enclosure]["disks"] = {}
in_device_slots = False
for iline, line in enumerate(lines):
if "Element type: " in line:
in_device_slots = "Array device slot" in line
if not in_device_slots:
continue
if line.strip().startswith("Element index:"):
# find slot number and SAS-Address of this device
current_line = iline+1
new_dev = {"slot": None, "sas_address": None}
while current_line < len(lines) and not "Element index:" in lines[current_line]:
m = re.search("device slot number: (\d+)", lines[current_line])
if m is not None:
new_dev["slot"] = int(m.group(1)) + 1
new_dev["path"] = find_path(enclosures[one_enclosure]["scsi_tuple"], new_dev["slot"])
new_dev["fault"] = int(get_file_content(os.path.join(new_dev["path"], "fault")))
new_dev["locate"] = int(get_file_content(os.path.join(new_dev["path"], "locate")))
new_dev["status"] = get_file_content(os.path.join(new_dev["path"], "status"))
if new_dev["status"] == "not installed":
new_dev["status"] = "NI"
m = re.search("^SAS address: (\w+)", lines[current_line].strip())
if m is not None and m.group(1) != "0x0000000000000000":
new_dev["sas_address"] = m.group(1)
if new_dev["sas_address"] in sas_dev_sd:
new_dev["dev_sd"] = sas_dev_sd[new_dev["sas_address"]]
else:
new_dev["dev_sd"] = "unknown"
if new_dev["dev_sd"] in dev_sd_scsi:
new_dev["scsi_id"] = dev_sd_scsi[new_dev["dev_sd"]]
else:
new_dev["scsi_id"] = "unknown"
if new_dev["dev_sd"] in dev_sd_size:
new_dev["size"] = dev_sd_size[new_dev["dev_sd"]]
else:
new_dev["size"] = "unknown"
current_line += 1
# store the disk by slot, /dev/sd* and scsi_id
enclosures[one_enclosure]["disks"][new_dev["slot"]] = new_dev
if new_dev["sas_address"] is not None:
enclosures[one_enclosure]["disks"][new_dev["dev_sd"]] = new_dev
enclosures[one_enclosure]["disks"][new_dev["scsi_id"]] = new_dev
else:
new_dev["dev_sd"] = ""
new_dev["scsi_id"] = ""
new_dev["size"] = ""
return enclosures
def find_path(enc, slot):
"""
find the full path to the slot folder
:param enc: scsi_tuple of the enclosure
:param slot: number of the slot (starts with 1), use -1 to the the path of the enclosure
:return: full path, or None
"""
if slot == -1:
result = os.path.join(defaults["CLASS"], enc)
if os.path.isdir(result):
return result
else:
return None
if defaults["first_slot"] == 0:
slot -= 1
name = str(slot)
if os.path.isfile(os.path.join(defaults["CLASS"], enc, name, 'type')):
return os.path.join(defaults["CLASS"], enc, name)
for z in range(0, 4):
if os.path.isfile(os.path.join(defaults["CLASS"], enc, defaults["SLOT"] + name, 'type')): # naming type 'Slot 01'
return os.path.join(defaults["CLASS"], enc, defaults["SLOT"] + name)
if os.path.isfile(os.path.join(defaults["CLASS"], enc, name, 'type')): # naming type '001'
return os.path.join(defaults["CLASS"], enc, name)
name = '0' + name # try same name with more zeroes at front
return None
def get_file_content(path):
"""
read the content of a file
:param path:
:return:
"""
try:
with open(path) as f:
return f.read().strip()
except IOError:
error("unable to read file %s" % path)
def find_disk(enclosures, key):
"""
find a disk by a slot, a /dev/sd-name, or a scsi_id
:param enclosures: enclosure structure created by scan_system
:param key: slot, /dev/sd-name, or scsi_id
:return:
"""
for enc_dev in sorted(enclosures.keys()):
one_enc = enclosures[enc_dev]
if key in one_enc["disks"]:
result = one_enc["disks"][key]
result["enclosure"] = enc_dev
return result
return None
def cat_text_blocks(blocks, width=20, lines=4):
"""
take multiline textblocks and concatinate them. Each block is a string with line breaks.
"""
def splitlines(text):
result = text.splitlines()
while len(result) < lines:
result.append("-")
return result
blocks_in_lines = map(lambda x: splitlines(x), blocks)
result = []
for one_block in blocks_in_lines:
for i, line in enumerate(one_block):
if i >= len(result):
result.append("")
if "\033" in line:
result[i] += ("%%-%ds" % (width + 13)) % line
else:
result[i] += ("%%-%ds" % width) % line
return "\n".join(result)
def get_status_block_for_disk(one_disk):
"""
returns a formatted text block for one disk
:param disk: disk-dictionary created by scan_system
:return:
"""
# highlight block by red colored text
if one_disk["locate"] != 0 or one_disk["fault"] != 0:
prefix = "\033[1;31m"
suffix = "\033[0;0m"
else:
prefix = ""
suffix = ""
block = "%sSlot %d: %s%s\n" % (prefix, one_disk["slot"], one_disk["dev_sd"], suffix)
block += "%s%s%s\n" % (prefix, one_disk["scsi_id"], suffix)
if one_disk["status"] != "NI":
block += "%sSize=%s%s\n" % (prefix, one_disk["size"], suffix)
else:
block += "\n"
block += "%sStatus=%s L=%d F=%d%s" % (prefix, one_disk["status"], one_disk["locate"], one_disk["fault"], suffix)
return block
def set_single_disk_led(disk, status):
"""
turn leds for disks on and off
:param disk: the disk-dictionary from scan_system
:param status: "locate", "fault", or "off"
:return:
"""
if status == 'fault':
with open(os.path.join(disk["path"], 'locate'), 'w') as f:
f.write('0')
with open(os.path.join(disk["path"], 'fault'), 'w') as f:
f.write('1')
elif status == 'locate':
with open(os.path.join(disk["path"], 'fault'), 'w') as f:
f.write('0')
with open(os.path.join(disk["path"], 'locate'), 'w') as f:
f.write('1')
elif status == 'off':
with open(os.path.join(disk["path"], 'locate'), 'w') as f:
f.write('0')
with open(os.path.join(disk["path"], 'fault'), 'w') as f:
f.write('0')
else:
error("Wrong status (%s)" % status)
def check_zpool_status():
"""
:return: a dictionary with all disks used within any connected zpool. The key is the device identifier used by
the zpool, the value is the zfs status of the disk.
"""
sts, out = subprocess.getstatusoutput("zpool status")
if sts != 0:
error("unable to check the zfs pool status:\n %s" % out)
# parse the output to get the disk state
result = {}
for line in out.splitlines():
if line.startswith("\t "):
words = line.split()
if len(words) < 5:
continue
result[words[0]] = words[1]
return result
def set_leds(enclosures, arg_disk, status):
"""
set for one or multiple disk the leds
:param enclosures: enclosure structure created by scan_system
:param arg_disk: disk-dictionary
:param status: "locate", "fault", or "off"
:return:
"""
# is the requested operation auto-zpool? check the disk-status with the zpool command
if status == "auto-zpool":
pool_disks_status = check_zpool_status()
for dev_key, dev_status in pool_disks_status.items():
one_disk = find_disk(enclosures, dev_key)
if dev_status != "ONLINE":
set_single_disk_led(one_disk, "fault")
else:
set_single_disk_led(one_disk, "off")
return
# one disk, or everything?
if arg_disk is not None:
set_single_disk_led(arg_disk, status)
return
# loop over all enclosures
for enc_dev in sorted(enclosures.keys()):
one_enc = enclosures[enc_dev]
# loop over all disks
for one_disk_key in one_enc["disks"].keys():
if type(one_disk_key) != int:
continue
set_single_disk_led(one_enc["disks"][one_disk_key], status)
def show_status(enclosures, arg_disk):
"""
create a formatted overview of the status
:param enclosures: enclosure structure created by scan_system
:param arg_disk: disk-dictionary
:return:
"""
# one disk, or everything?
if arg_disk is not None:
print("Enclosure: %s (%s)" % (enclosures[arg_disk["enclosure"]]["description"], arg_disk["enclosure"]))
print(get_status_block_for_disk(arg_disk))
return
# sort enclosures by their /dev/sg-number
enc_devs = enclosures.keys()
enc_devs_sortable = {}
for one_key in enc_devs:
enc_devs_sortable[int(one_key.replace("/dev/sg", ""))] = one_key
# loop over all enclosures
for enc_dev in sorted(enc_devs_sortable.keys()):
enc_dev = enc_devs_sortable[enc_dev]
one_enc = enclosures[enc_dev]
print("\nEnclosure: %s (%s)" % (one_enc["description"], enc_dev))
print("-" * 80)
# create blocks of text for each slot
n_slot = one_enc["n_slots"]
# guess the enclosure type from the number of disks
if n_slot == 20:
enc_type = "sm20"
elif n_slot == 24:
enc_type = "sm24"
else:
enc_type = "sm44"
slot_blocks = numpy.empty(enclosure_layouts[enc_type].shape, dtype="U200")
for slot in range(1,n_slot+1):
if slot in one_enc["disks"]:
slot_blocks[enclosure_layouts[enc_type] == slot] = get_status_block_for_disk(one_enc["disks"][slot])
# arrange the blocks, six per row
rows = slot_blocks.shape[0]
for row in range(0, rows):
print(cat_text_blocks(slot_blocks[row, :]))
print()
def create_device_list(enclosures, args):
"""
create a list of devices usable in other commands
:param enclosures: enclosure structure created by scan_system
:param args: the command line arguments
"""
result = []
vdevs = [[args.vdev_type]]
disk_size = None
disk_number = 0
total_disk_number = 0
def add_one_disk():
# include this disk?
nonlocal disk_number, disk_size, total_disk_number
disk_number += 1
if args.first_disk is not None and disk_number < args.first_disk:
return
if args.last_disk is not None and disk_number > args.last_disk:
return
# has this disk the correct size?
if args.type == "zpool-create":
if args.disk_size is not None and one_enc["disks"][slot]["size"] != args.disk_size:
return
if disk_size is None:
disk_size = one_enc["disks"][slot]["size"]
elif disk_size != one_enc["disks"][slot]["size"]:
error("Disks of different size within the same pool: %s and %s!" % (
disk_size, one_enc["disks"][slot]["size"]))
# create list of devices in proper format
if args.type == "fence-mpath":
result.append("/dev/mapper/%s" % one_enc["disks"][slot]["scsi_id"])
if args.type == "zpool-create":
if len(vdevs[-1]) < args.vdev_size + 1:
vdevs[-1].append(one_enc["disks"][slot]["scsi_id"])
else:
vdevs.append([args.vdev_type, one_enc["disks"][slot]["scsi_id"]])
total_disk_number += 1
# loop over all enclosures
if args.loop_order == "enc":
for enc_dev in sorted(enclosures.keys()):
one_enc = enclosures[enc_dev]
# get the number of slots in this enclosure
n_slot = one_enc["n_slots"]
# loop over all devices
for slot in range(1,n_slot+1):
if slot in one_enc["disks"] and one_enc["disks"][slot]["status"] != "NI":
add_one_disk()
# loop over all slots
elif args.loop_order == "slot":
# find at first the larges number of slots
n_slot_max = 0
for enc_dev in sorted(enclosures.keys()):
n_slot = enclosures[enc_dev]["n_slots"]
if n_slot > n_slot_max:
n_slot_max = n_slot
# now loop over all slots
for slot in range(1, n_slot_max + 1):
# and look into this slot for all enclosures
for enc_dev in sorted(enclosures.keys()):
one_enc = enclosures[enc_dev]
if slot in one_enc["disks"] and one_enc["disks"][slot]["status"] != "NI":
add_one_disk()
# print the final list
if args.type == "fence-mpath":
print(",".join(result))
if args.type == "zpool-create":
# check length of vdevs
for i in range(0, len(vdevs)):
if len(vdevs[i]) != args.vdev_size +1:
error("wrong number of disks in vdev. Use --vdev-size!\nTotal number of disks: %d" % total_disk_number)
vdevs = map(lambda x: " ".join(x), vdevs)
print(" ".join(vdevs))
def check_defaults():
"""
check the default path of slots and enclosures
"""
enclosures = os.listdir(defaults["CLASS"])
entries = os.listdir(os.path.join(defaults["CLASS"], enclosures[0]))
# slots are counted from 0 or from 1?
if "Slot00" in entries or "Slot 00" in entries or "Slot000" in entries or "Slot 000" in entries:
defaults["first_slot"] = 0
# Slot names include space or not
if "Slot01" in entries or "Slot001" in entries:
defaults["SLOT"] = "Slot"
if "Slot 01" in entries or "Slot 001" in entries:
defaults["SLOT"] = "Slot "
def add_enc_disk_args(sp, add_enc=True, add_disk=True):
if add_enc:
sp.add_argument("-e", "--enc", nargs='+', help="the enclosure of interest.")
if add_disk:
sp.add_argument("-d", "--disk", help="the disk of interest.")
sp.add_argument("-s", "--slot", type=int, help="the slot of interest.")
if __name__ == "__main__":
# set default log level
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
# parse command line arguments
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest='action', title='available operations')
sp_status = subparsers.add_parser("status", help="show the status of enclosures or disks")
sp_led = subparsers.add_parser("led", help="turn on/off the leds of a disk")
sp_led.add_argument("status", choices=["locate", "fault", "off", "auto-zpool"], help="select the led to turn on/off.")
sp_list = subparsers.add_parser("list", help="list devices in different formats")
sp_list.add_argument("--type", choices=["zpool-create", "fence-mpath"], required=True, help="select the type of device list to create.")
sp_list.add_argument("--vdev-size", type=int, default=6, help="number of devices within one vdev.")
sp_list.add_argument("--vdev-type", default="raidz2", help="type to use in device list for zpool-create.")
sp_list.add_argument("--first-disk", type=int, help="Number between 1 and the total number of disks. Empty slots don't count as disk.")
sp_list.add_argument("--last-disk", type=int, help="Number between 1 and the total number of disks. Empty slots don't count as disk.")
sp_list.add_argument("--disk-size", help="Size of disk to be included (same format as in status).")
sp_list.add_argument("--loop-order", default="enc", choices=["enc", "slot"], help="the list is created in a loop over all enclosures with a nested loop over all slots (=enc), or in a loop over all slots with a nested loop over all enclosures (=slot).")
add_enc_disk_args(sp_status)
add_enc_disk_args(sp_led)
add_enc_disk_args(sp_list, add_disk=False)
args = parser.parse_args()
# is an operation selected?
if args.action is None:
error("no operation selected!")
# check the default settings
check_defaults()
# scan the system and create a mapping between device names and slots
encs = scan_system()
# check arguments
if args.enc is not None:
encs_filtered = {}
for one_enc in args.enc:
if one_enc not in encs:
error("Enclosure '%s' not found!" % args.enc)
else:
# add this enclosure to filtered list
encs_filtered[one_enc] = encs[one_enc]
encs = encs_filtered
if "disk" in args and args.disk is not None:
disk_dev = find_disk(encs, args.disk)
if disk_dev is None:
error("Disk '%s' not found!" % args.disk)
args.disk = disk_dev
if "slot" in args and args.slot is not None:
disk_dev = find_disk(encs, args.slot)
if disk_dev is None:
error("Slot '%s' not found!" % args.slot)
args.disk = disk_dev
# perform requested operation
if args.action == "status":
show_status(encs, args.disk)
if args.action == "led":
set_leds(encs, args.disk, args.status)
if args.action == "list":
create_device_list(encs, args)