Stupid Simple Python Script For Working With System vs ZFS Disks

Submitted by gpmidi on Thu, 10/10/2019 - 09:42

This script helps identify what disks are in use (or not in use) by ZFS. It's a stupid-simple python 3 script that requires only 'sh'. You can get that via 'pip3 install sh'. 

#!/usr/bin/python3
import re
from sh import zpool,lsblk,ls
from pprint import pprint

print("Finding all disks")
sdisks = str(lsblk('-d').stdout)
# sdbl  67:240  0   7.3T  0 disk
alldisks = re.findall(r'(sd[a-z]+)\s+\d+:\d+\s+\d+\s+(.*?)\s+\d+\s+disk',sdisks,re.MULTILINE)
print("Found %d disks on system"%len(alldisks))

print("Finding ZFS disks")
status=str(zpool.status("-LP").stdout)
zdisks=re.findall(r'(/dev/sd[a-z]+)(\d)',status)
print("Found %d ZFS disks"%len(zdisks))

print("Finding disk IDs")
byidstr=str(ls('-alh','/dev/disk/by-id').stdout)
#print(byidstr)
# wwn-0x50014ee25f323abe -> ../../sdu
byidlst=re.findall(r'\s+([a-zA-Z0-9\-_]+) -> ../../([a-z]+)',byidstr,re.M)
print("Found %d ID mappings"%len(byidlst))
byid={}
for alias,partial in byidlst:
        full='/dev/%s'%partial
        if full not in byid:
                byid[full]=[]
        byid[full].append("/dev/disk/by-id/%s"%alias)

print("Mathing")
disks={}
for partial,size in alldisks:
        full='/dev/%s'%partial
        disks[full]=dict(size=size,aliases=byid.get(full,None))

for pth,part in zdisks:
        assert pth in disks, "Expected the disk to exist in the system disks"
        dk = disks[pth]
        dk[int(part)]='ZFS'

print("All disks")
pprint(disks)

print("Unused disks: ")
for pth,info in disks.items():
        if "ZFS" not in info.values():
                print("Found: %s"%pth)
                pprint(info)

        
print("Done")

Tags