1 from os import system, listdir, statvfs, popen, makedirs, stat, major, minor, path, access
3 from Tools.Directories import SCOPE_HDD, resolveFilename, fileExists
5 from Tools.CList import CList
6 from SystemInfo import SystemInfo
8 from Components.Console import Console
13 rdev = stat(path).st_rdev
14 return (major(rdev),minor(rdev))
16 def readFile(filename):
18 data = file.read().strip()
24 mounts = open("/proc/mounts", 'r')
26 print "[Harddisk] Failed to open /proc/mounts", ex
28 result = [line.strip().split(' ') for line in mounts]
30 # Spaces are encoded as \040 in mounts
31 item[1] = item[1].replace('\\040', ' ')
35 cmd = 'sfdisk --version'
36 lines = popen(cmd).readlines()
38 if l.find("sfdisk from util-linux") != -1:
39 ver = l.split()[-1].strip()
44 ver = '.'.join(vs[:2])
48 print "[CheckSfdiskVer] check parted version Failed!"
52 def enableUdevEvent(enable = True):
54 option = '--start-exec-queue'
56 option = '--stop-exec-queue'
57 cmd = "udevadm control %s" % option
65 def __init__(self, device):
68 if access("/dev/.udev", 0):
69 self.type = DEVTYPE_UDEV
70 elif access("/dev/.devfsd", 0):
71 self.type = DEVTYPE_DEVFS
73 print "Unable to determine structure of /dev"
75 self.max_idle_time = 0
76 self.idle_running = False
81 self.mount_path = None
82 self.mount_device = None
83 self.phys_path = path.realpath(self.sysfsPath('device'))
85 if self.type == DEVTYPE_UDEV:
86 self.dev_path = '/dev/' + self.device
87 self.disk_path = self.dev_path
89 elif self.type == DEVTYPE_DEVFS:
90 tmp = readFile(self.sysfsPath('dev')).split(':')
93 for disc in listdir("/dev/discs"):
94 dev_path = path.realpath('/dev/discs/' + disc)
95 disk_path = dev_path + '/disc'
97 rdev = stat(disk_path).st_rdev
100 if s_major == major(rdev) and s_minor == minor(rdev):
101 self.dev_path = dev_path
102 self.disk_path = disk_path
105 print "new Harddisk", self.device, '->', self.dev_path, '->', self.disk_path
108 def __lt__(self, ob):
109 return self.device < ob.device
111 def partitionPath(self, n):
112 if self.type == DEVTYPE_UDEV:
113 return self.dev_path + n
114 elif self.type == DEVTYPE_DEVFS:
115 return self.dev_path + '/part' + n
117 def sysfsPath(self, filename):
118 return path.realpath('/sys/block/' + self.device + '/' + filename)
123 self.timer.callback.remove(self.runIdle)
127 if self.type == DEVTYPE_UDEV:
128 ide_cf = False # FIXME
129 elif self.type == DEVTYPE_DEVFS:
130 ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
132 internal = "pci" in self.phys_path
135 ret = "External (CF)"
144 line = readFile(self.sysfsPath('size'))
146 harddiskmanager.removeHotplugPartition(self.device)
147 print "error remove",self.device
153 return cap / 1000 * 512 / 1000
156 cap = self.diskSize()
159 return "%d.%03d GB" % (cap/1000, cap%1000)
163 if self.device[:2] == "hd":
164 return readFile('/proc/ide/' + self.device + '/model')
165 elif self.device[:2] == "sd":
166 vendor = readFile(self.sysfsPath('device/vendor'))
167 model = readFile(self.sysfsPath('device/model'))
168 return vendor + '(' + model + ')'
170 assert False, "no hdX or sdX"
172 harddiskmanager.removeHotplugPartition(self.device)
173 print "error remove",self.device
178 mounts = open("/proc/mounts")
182 lines = mounts.readlines()
186 parts = line.strip().split(" ")
187 real_path = path.realpath(parts[0])
188 if not real_path[-1].isdigit():
191 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
192 stat = statvfs(parts[1])
193 return stat.f_bfree/1000 * stat.f_bsize/1000
198 def numPartitions(self):
200 if self.type == DEVTYPE_UDEV:
202 devdir = listdir('/dev')
205 for filename in devdir:
206 if filename.startswith(self.device):
209 elif self.type == DEVTYPE_DEVFS:
211 idedir = listdir(self.dev_path)
214 for filename in idedir:
215 if filename.startswith("disc"):
217 if filename.startswith("part"):
221 def mountDevice(self):
222 for parts in getProcMounts():
223 if path.realpath(parts[0]).startswith(self.dev_path):
224 self.mount_device = parts[0]
225 self.mount_path = parts[1]
229 if self.mount_path is None:
230 return self.mountDevice()
231 return self.mount_path
235 mounts = open("/proc/mounts")
239 lines = mounts.readlines()
245 parts = line.strip().split(" ")
246 real_path = path.realpath(parts[0])
247 if not real_path[-1].isdigit():
250 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
251 cmd = ' ' . join([cmd, parts[1]])
260 def checkPartionPath(self, path):
262 for i in range(1,10):
263 if os.path.exists(path):
268 def updatePartition(self):
269 sfdiskVer = CheckSfdiskVer()
270 if sfdiskVer < 2.26: # sfdisk -R option is deprecated at sfdiskVer >= 2.26
271 cmd = 'sfdisk -R %s; sleep 5' % (self.disk_path)
272 elif path.exists('/usr/sbin/partprobe'):
273 cmd = 'partprobe %s; sleep 5' % (self.disk_path)
274 elif path.exists('/usr/sbin/partx'):
275 cmd = 'partx -u %s' % (self.disk_path)
284 def createPartition(self):
285 def CheckPartedVer():
286 cmd = 'parted --version'
287 lines = popen(cmd).readlines()
289 if l.find("parted (GNU parted)") != -1:
290 ver = l.split()[3].strip()
295 print "[CheckPartedVer] check parted version Failed!"
299 disk_size = self.diskSize()
301 if disk_size > 2.2 * 1000 * 1000: # if 2.2 TB
303 partedVer = CheckPartedVer()
304 if partedVer >= 2.1: # align option is supported in version 2.1 or later
305 setAlign = "--align optimal"
306 cmd = 'parted %s %s --script mklabel gpt mkpart disk ext2 0%% 100%%' % ( setAlign, self.disk_path )
309 sfdiskVer = CheckSfdiskVer()
310 if sfdiskVer <= 2.21:
311 cmd = 'printf "8,\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS ' + self.disk_path
313 cmd = 'printf "8,\nquit\nY\n" | sfdisk -f -uS ' + self.disk_path
318 if not self.checkPartionPath(self.partitionPath("1")):
319 print "no exist : ", self.partitionPath("1")
325 if self.diskSize() > 4 * 1024:
326 cmd += "-T largefile "
327 cmd += "-m0 -O dir_index " + self.partitionPath("1")
334 fstab = open("/etc/fstab")
338 lines = fstab.readlines()
344 parts = line.strip().split(" ")
345 real_path = path.realpath(parts[0])
346 if not real_path[-1].isdigit():
349 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
350 mount_point = parts[0]
355 if mount_point is None:
358 cmd = "mount -t ext3 " + mount_point
365 if self.createMovieFolder() != 0:
370 def createMovieFolder(self):
372 if not fileExists("/hdd", 0):
373 print "not found /hdd"
374 system("ln -s /media/hdd /hdd")
376 makedirs(resolveFilename(SCOPE_HDD))
382 # We autocorrect any failures
383 # TODO: we could check if the fs is actually ext3
384 cmd = "fsck.ext3 -f -p " + self.partitionPath("1")
388 def killPartition(self, n):
389 part = self.partitionPath(n)
392 cmd = 'dd bs=512 count=3 if=/dev/zero of=' + part
400 errorList = [ _("Everything is fine"), _("Creating partition failed"), _("Mkfs failed"), _("Mount failed"), _("Create movie folder failed"), _("Fsck failed"), _("Please Reboot"), _("Filesystem contains uncorrectable errors"), _("Unmount failed"), _("partx failed")]
402 def initialize(self):
403 enableUdevEvent(False)
406 # Udev tries to mount the partition immediately if there is an
407 # old filesystem on it when fdisk reloads the partition table.
408 # To prevent that, we overwrite the first 3 sectors of the
409 # partition, if the partition existed before. That's enough for
411 self.killPartition("1")
413 if self.updatePartition() != 0:
416 elif self.createPartition() != 0:
419 elif self.updatePartition() != 0:
422 elif self.mkfs() != 0:
428 enableUdevEvent(True)
441 if res != 0 and res != 1:
442 # A sum containing 1 will also include a failure
445 if self.mount() != 0:
450 def getDeviceDir(self):
453 def getDeviceName(self):
454 return self.disk_path
456 # the HDD idle poll daemon.
457 # as some harddrives have a buggy standby timer, we are doing this by hand here.
458 # first, we disable the hardware timer. then, we check every now and then if
459 # any access has been made to the disc. If there has been no access over a specifed time,
460 # we set the hdd into standby.
463 l = open("/sys/block/%s/stat" % self.device).read()
466 (nr_read, _, _, _, nr_write) = l.split()[:5]
467 return int(nr_read), int(nr_write)
470 self.last_access = time.time()
472 self.is_sleeping = False
473 from enigma import eTimer
475 # disable HDD standby timer
476 Console().ePopen(("hdparm", "hdparm", "-S0", self.disk_path))
477 self.timer = eTimer()
478 self.timer.callback.append(self.runIdle)
479 self.idle_running = True
480 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
483 if not self.max_idle_time:
487 idle_time = t - self.last_access
489 stats = self.readStats()
494 print "nr_read", stats[0], "nr_write", stats[1]
496 print "sum", l, "prev_sum", self.last_stat
498 if l != self.last_stat and l >= 0: # access
499 print "hdd was accessed since previous check!"
503 self.is_sleeping = False
507 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
508 if idle_time >= self.max_idle_time and not self.is_sleeping:
510 self.is_sleeping = True
513 Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
515 def setIdleTime(self, idle):
516 self.max_idle_time = idle
517 if self.idle_running:
521 self.timer.start(idle * 100, False) # poll 10 times per period.
523 def isSleeping(self):
524 return self.is_sleeping
527 def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
528 self.mountpoint = mountpoint
529 self.description = description
530 self.force_mounted = force_mounted
531 self.is_hotplug = force_mounted # so far; this might change.
535 return statvfs(self.mountpoint)
540 return s.f_bavail * s.f_bsize
547 return s.f_blocks * s.f_bsize
552 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
553 # TODO: can os.path.ismount be used?
554 if self.force_mounted:
558 mounts = open("/proc/mounts")
562 lines = mounts.readlines()
566 if line.split(' ')[1] == self.mountpoint:
573 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("DVD Drive"),
574 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("DVD Drive"),
575 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host3/target3:0:0/3:0:0:0": _("DVD Drive"),
588 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
589 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": _("Back, upper USB Slot"),
590 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": _("Back, lower USB Slot"),
591 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
592 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/": _("Internal USB Slot"),
593 "/devices/platform/brcm-ohci-1.1/usb4/4-1/4-1:1.0/": _("Internal USB Slot"),
597 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": "Upper USB Slot",
598 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": "Lower USB Slot",
602 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "CF Card Slot", #hdc
603 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
607 class HarddiskManager:
611 self.partitions = [ ]
612 self.devices_scanned_on_init = [ ]
614 self.on_partition_list_change = CList()
616 self.enumerateBlockDevices()
618 # currently, this is just an enumeration of what's possible,
619 # this probably has to be changed to support automount stuff.
620 # still, if stuff is mounted into the correct mountpoints by
621 # external tools, everything is fine (until somebody inserts
622 # a second usb stick.)
624 ("/media/hdd", _("Harddisk")),
625 ("/media/card", _("Card")),
626 ("/media/cf", _("Compact Flash")),
627 ("/media/mmc1", _("MMC Card")),
628 ("/media/net", _("Network Mount")),
629 ("/media/ram", _("Ram Disk")),
630 ("/media/usb", _("USB Stick")),
631 ("/", _("Internal Flash"))
634 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
636 def getBlockDevInfo(self, blockdev):
637 devpath = "/sys/block/" + blockdev
644 removable = bool(int(readFile(devpath + "/removable")))
645 dev = int(readFile(devpath + "/dev").split(':')[0])
646 if dev in (7, 31, 179): # loop, mtdblock, mmcblock
648 if blockdev[0:2] == 'sr':
650 if blockdev[0:2] == 'hd':
652 media = readFile("/proc/ide/%s/media" % blockdev)
657 # check for partitions
659 for partition in listdir(devpath):
660 if partition[0:len(blockdev)] != blockdev:
662 partitions.append(partition)
670 open("/dev/" + blockdev).close()
672 if err.errno == 159: # no medium present
675 return error, blacklisted, removable, is_cdrom, partitions, medium_found
677 def enumerateBlockDevices(self):
678 print "enumerating block devices..."
679 for blockdev in listdir("/sys/block"):
680 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.addHotplugPartition(blockdev)
681 if not error and not blacklisted:
683 for part in partitions:
684 self.addHotplugPartition(part)
685 self.devices_scanned_on_init.append((blockdev, removable, is_cdrom, medium_found))
687 def getAutofsMountpoint(self, device):
688 return "/autofs/%s/" % (device)
691 def is_hard_mounted(self, device):
692 mounts = file('/proc/mounts').read().split('\n')
694 if x.find('/autofs') == -1 and x.find(device) != -1:
698 def getMountpoint(self, device):
699 dev = "/dev/%s" % device
700 for item in getProcMounts():
701 if item[0] == dev and item[1].find('/autofs') == -1:
705 def addHotplugPartition(self, device, physdev = None):
707 dev, part = self.splitDeviceName(device)
709 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
712 print "couldn't determine blockdev physdev for device", device
714 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
715 print "found block device '%s':" % device,
721 print "error querying properties"
722 elif not medium_found:
725 print "ok, removable=%s, cdrom=%s, partitions=%s" % (removable, is_cdrom, partitions)
729 # see if this is a harddrive
730 if not device[l-1].isdigit() and not removable and not is_cdrom:
731 self.hdd.append(Harddisk(device))
733 SystemInfo["Harddisk"] = len(self.hdd) > 0
735 if not removable or medium_found:
736 # device is the device name, without /dev
737 # physdev is the physical device path, which we (might) use to determine the userfriendly name
738 description = self.getUserfriendlyDeviceName(device, physdev)
739 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
740 self.partitions.append(p)
741 self.on_partition_list_change("add", p)
743 return error, blacklisted, removable, is_cdrom, partitions, medium_found
745 def removeHotplugPartition(self, device):
746 for x in self.partitions[:]:
747 if x.device == device:
748 self.partitions.remove(x)
750 self.on_partition_list_change("remove", x)
752 if l and not device[l-1].isdigit():
754 if hdd.device == device:
758 SystemInfo["Harddisk"] = len(self.hdd) > 0
768 hdd = hd.model() + " - " + hd.bus()
771 hdd += " (" + cap + ")"
772 list.append((hdd, hd))
778 def getMountedPartitions(self, onlyhotplug = False):
779 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted() and x.mountpoint]
780 devs = set([x.device for x in parts])
781 for devname in devs.copy():
784 dev, part = self.splitDeviceName(devname)
785 if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
788 # remove duplicate device
789 no_force_mounted_list = [x.mountpoint for x in self.partitions if not x.force_mounted]
792 mp = self.getMountpoint(x.device)
793 if mp and mp in no_force_mounted_list:
794 devs.remove(x.device)
796 # return all devices which are not removed due to being a wholedisk when a partition exists
797 return [x for x in parts if not x.device or x.device in devs]
799 def getLabelFromDevName(self, dev):
802 data = os.popen("e2label %s" % dev).read().strip()
810 def splitDeviceName(self, devname):
811 # this works for: sdaX, hdaX, sr0 (which is in fact dev="sr0", part=""). It doesn't work for other names like mtdblock3, but they are blacklisted anyway.
817 return dev, part and int(part) or 0
819 def getUserfriendlyDeviceName(self, dev, phys):
820 label = self.getLabelFromDevName("/dev/" + dev)
821 dev, part = self.splitDeviceName(dev)
822 description = "External Storage %s" % dev
823 have_model_descr = False
827 have_model_descr = True
830 description = readFile("/sys" + phys + "/model")
831 have_model_descr = True
833 print "couldn't read model: ", s
834 from Tools.HardwareInfo import HardwareInfo
835 if dev.find('sr') == 0 and dev[2].isdigit():
836 devicedb = DEVICEDB_SR
839 for physdevprefix, pdescription in devicedb.get(HardwareInfo().device_name,{}).items():
840 if phys.startswith(physdevprefix):
842 description = pdescription + ' - ' + description
844 description = pdescription
845 # not wholedisk and not partition 1
846 if part and part != 1:
847 description += " (Partition %d)" % part
850 def addMountedPartition(self, device, desc):
851 already_mounted = False
852 for x in self.partitions[:]:
853 if x.mountpoint == device:
854 already_mounted = True
855 if not already_mounted:
856 self.partitions.append(Partition(mountpoint = device, description = desc))
858 def removeMountedPartition(self, mountpoint):
859 for x in self.partitions[:]:
860 if x.mountpoint == mountpoint:
861 self.partitions.remove(x)
862 self.on_partition_list_change("remove", x)
864 harddiskmanager = HarddiskManager()