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
11 rdev = stat(path).st_rdev
12 return (major(rdev),minor(rdev))
14 def readFile(filename):
16 data = file.read().strip()
24 def __init__(self, device):
27 if access("/dev/.udev", 0):
28 self.type = DEVTYPE_UDEV
29 elif access("/dev/.devfsd", 0):
30 self.type = DEVTYPE_DEVFS
32 print "Unable to determine structure of /dev"
34 self.max_idle_time = 0
35 self.idle_running = False
40 self.phys_path = path.realpath(self.sysfsPath('device'))
42 if self.type == DEVTYPE_UDEV:
43 self.dev_path = '/dev/' + self.device
44 self.disk_path = self.dev_path
46 elif self.type == DEVTYPE_DEVFS:
47 tmp = readFile(self.sysfsPath('dev')).split(':')
50 for disc in listdir("/dev/discs"):
51 dev_path = path.realpath('/dev/discs/' + disc)
52 disk_path = dev_path + '/disc'
54 rdev = stat(disk_path).st_rdev
57 if s_major == major(rdev) and s_minor == minor(rdev):
58 self.dev_path = dev_path
59 self.disk_path = disk_path
62 print "new Harddisk", self.device, '->', self.dev_path, '->', self.disk_path
66 return self.device < ob.device
68 def partitionPath(self, n):
69 if self.type == DEVTYPE_UDEV:
70 return self.dev_path + n
71 elif self.type == DEVTYPE_DEVFS:
72 return self.dev_path + '/part' + n
74 def sysfsPath(self, filename):
75 return path.realpath('/sys/block/' + self.device + '/' + filename)
80 self.timer.callback.remove(self.runIdle)
84 if self.type == DEVTYPE_UDEV:
85 ide_cf = False # FIXME
86 elif self.type == DEVTYPE_DEVFS:
87 ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
89 internal = "pci" in self.phys_path
102 line = readFile(self.sysfsPath('size'))
104 harddiskmanager.removeHotplugPartition(self.device)
105 print "error remove",self.device
111 return cap / 1000 * 512 / 1000
114 cap = self.diskSize()
117 return "%d.%03d GB" % (cap/1000, cap%1000)
122 if self.device[:2] == "hd":
123 return readFile('/proc/ide/' + self.device + '/model')
124 elif self.device[:2] == "sd":
125 vendor = readFile(self.sysfsPath('device/vendor'))
126 model = readFile(self.sysfsPath('device/model'))
127 return vendor + '(' + model + ')'
129 assert False, "no hdX or sdX"
131 harddiskmanager.removeHotplugPartition(self.device)
132 print "error remove",self.device
137 mounts = open("/proc/mounts")
141 lines = mounts.readlines()
145 parts = line.strip().split(" ")
146 real_path = path.realpath(parts[0])
147 if not real_path[-1].isdigit():
150 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
151 stat = statvfs(parts[1])
152 return stat.f_bfree/1000 * stat.f_bsize/1000
157 def numPartitions(self):
159 if self.type == DEVTYPE_UDEV:
161 devdir = listdir('/dev')
164 for filename in devdir:
165 if filename.startswith(self.device):
168 elif self.type == DEVTYPE_DEVFS:
170 idedir = listdir(self.dev_path)
173 for filename in idedir:
174 if filename.startswith("disc"):
176 if filename.startswith("part"):
182 mounts = open("/proc/mounts")
186 lines = mounts.readlines()
192 parts = line.strip().split(" ")
193 real_path = path.realpath(parts[0])
194 if not real_path[-1].isdigit():
197 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
198 cmd = ' ' . join([cmd, parts[1]])
206 def createPartition(self):
207 cmd = 'printf "0,\n;\n;\n;\ny\n" | sfdisk -f ' + self.disk_path
213 if self.diskSize() > 4 * 1024:
214 cmd += "-T largefile "
215 cmd += "-m0 -O dir_index " + self.partitionPath("1")
221 fstab = open("/etc/fstab")
225 lines = fstab.readlines()
230 parts = line.strip().split(" ")
231 real_path = path.realpath(parts[0])
232 if not real_path[-1].isdigit():
235 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
236 cmd = "mount -t ext3 " + parts[0]
244 def createMovieFolder(self):
247 if not fileExists("/hdd", 0):
248 print "not found /hdd"
249 system("ln -s /media/hdd /hdd")
251 makedirs(resolveFilename(SCOPE_HDD))
257 # We autocorrect any failures
258 # TODO: we could check if the fs is actually ext3
259 cmd = "fsck.ext3 -f -p " + self.partitionPath("1")
263 def killPartition(self, n):
264 part = self.partitionPath(n)
267 cmd = 'dd bs=512 count=3 if=/dev/zero of=' + part
274 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")]
276 def initialize(self):
279 # Udev tries to mount the partition immediately if there is an
280 # old filesystem on it when fdisk reloads the partition table.
281 # To prevent that, we overwrite the first 3 sectors of the
282 # partition, if the partition existed before. That's enough for
284 self.killPartition("1")
286 if self.createPartition() != 0:
292 if self.mount() != 0:
295 if self.createMovieFolder() != 0:
310 if res != 0 and res != 1:
311 # A sum containing 1 will also include a failure
314 if self.mount() != 0:
319 def getDeviceDir(self):
322 def getDeviceName(self):
323 return self.disk_path
325 # the HDD idle poll daemon.
326 # as some harddrives have a buggy standby timer, we are doing this by hand here.
327 # first, we disable the hardware timer. then, we check every now and then if
328 # any access has been made to the disc. If there has been no access over a specifed time,
329 # we set the hdd into standby.
332 l = open("/sys/block/%s/stat" % self.device).read()
335 (nr_read, _, _, _, nr_write) = l.split()[:5]
336 return int(nr_read), int(nr_write)
339 self.last_access = time.time()
341 self.is_sleeping = False
342 from enigma import eTimer
344 # disable HDD standby timer
345 Console().ePopen(("hdparm", "hdparm", "-S0", self.disk_path))
346 self.timer = eTimer()
347 self.timer.callback.append(self.runIdle)
348 self.idle_running = True
349 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
352 if not self.max_idle_time:
356 idle_time = t - self.last_access
358 stats = self.readStats()
363 print "nr_read", stats[0], "nr_write", stats[1]
365 print "sum", l, "prev_sum", self.last_stat
367 if l != self.last_stat and l >= 0: # access
368 print "hdd was accessed since previous check!"
372 self.is_sleeping = False
376 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
377 if idle_time >= self.max_idle_time and not self.is_sleeping:
379 self.is_sleeping = True
382 Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
384 def setIdleTime(self, idle):
385 self.max_idle_time = idle
386 if self.idle_running:
390 self.timer.start(idle * 100, False) # poll 10 times per period.
392 def isSleeping(self):
393 return self.is_sleeping
396 def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
397 self.mountpoint = mountpoint
398 self.description = description
399 self.force_mounted = force_mounted
400 self.is_hotplug = force_mounted # so far; this might change.
404 return statvfs(self.mountpoint)
409 return s.f_bavail * s.f_bsize
416 return s.f_blocks * s.f_bsize
421 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
422 # TODO: can os.path.ismount be used?
423 if self.force_mounted:
427 mounts = open("/proc/mounts")
431 lines = mounts.readlines()
435 if line.split(' ')[1] == self.mountpoint:
442 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("DVD Drive"),
443 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("DVD Drive"),
444 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host3/target3:0:0/3:0:0:0": _("DVD Drive"),
457 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
458 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": _("Back, upper USB Slot"),
459 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": _("Back, lower USB Slot"),
460 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
461 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/": _("Internal USB Slot"),
462 "/devices/platform/brcm-ohci-1.1/usb4/4-1/4-1:1.0/": _("Internal USB Slot"),
466 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": "Upper USB Slot",
467 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": "Lower USB Slot",
471 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "CF Card Slot", #hdc
472 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
476 class HarddiskManager:
480 self.partitions = [ ]
481 self.devices_scanned_on_init = [ ]
483 self.on_partition_list_change = CList()
485 self.enumerateBlockDevices()
487 # currently, this is just an enumeration of what's possible,
488 # this probably has to be changed to support automount stuff.
489 # still, if stuff is mounted into the correct mountpoints by
490 # external tools, everything is fine (until somebody inserts
491 # a second usb stick.)
493 ("/media/hdd", _("Harddisk")),
494 ("/media/card", _("Card")),
495 ("/media/cf", _("Compact Flash")),
496 ("/media/mmc1", _("MMC Card")),
497 ("/media/net", _("Network Mount")),
498 ("/media/ram", _("Ram Disk")),
499 ("/media/usb", _("USB Stick")),
500 ("/", _("Internal Flash"))
503 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
505 def getBlockDevInfo(self, blockdev):
506 devpath = "/sys/block/" + blockdev
513 removable = bool(int(readFile(devpath + "/removable")))
514 dev = int(readFile(devpath + "/dev").split(':')[0])
515 if dev in (7, 31): # loop, mtdblock
517 if blockdev[0:2] == 'sr':
519 if blockdev[0:2] == 'hd':
521 media = readFile("/proc/ide/%s/media" % blockdev)
526 # check for partitions
528 for partition in listdir(devpath):
529 if partition[0:len(blockdev)] != blockdev:
531 partitions.append(partition)
539 open("/dev/" + blockdev).close()
541 if err.errno == 159: # no medium present
544 return error, blacklisted, removable, is_cdrom, partitions, medium_found
546 def enumerateBlockDevices(self):
547 print "enumerating block devices..."
548 for blockdev in listdir("/sys/block"):
549 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.addHotplugPartition(blockdev)
550 if not error and not blacklisted:
552 for part in partitions:
553 self.addHotplugPartition(part)
554 self.devices_scanned_on_init.append((blockdev, removable, is_cdrom, medium_found))
556 def getAutofsMountpoint(self, device):
557 return "/media/%s/" % (device)
560 def is_hard_mounted(self, device):
561 mounts = file('/proc/mounts').read().split('\n')
563 if x.find('/autofs') == -1 and x.find(device) != -1:
567 def addHotplugPartition(self, device, physdev = None):
569 dev, part = self.splitDeviceName(device)
571 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
574 print "couldn't determine blockdev physdev for device", device
576 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
577 print "found block device '%s':" % device,
583 print "error querying properties"
584 elif not medium_found:
587 print "ok, removable=%s, cdrom=%s, partitions=%s" % (removable, is_cdrom, partitions)
591 # see if this is a harddrive
592 if not device[l-1].isdigit() and not removable and not is_cdrom:
593 self.hdd.append(Harddisk(device))
595 SystemInfo["Harddisk"] = len(self.hdd) > 0
597 if (not removable or medium_found) and not self.is_hard_mounted(device):
598 # device is the device name, without /dev
599 # physdev is the physical device path, which we (might) use to determine the userfriendly name
600 description = self.getUserfriendlyDeviceName(device, physdev)
601 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
602 self.partitions.append(p)
603 self.on_partition_list_change("add", p)
605 return error, blacklisted, removable, is_cdrom, partitions, medium_found
607 def removeHotplugPartition(self, device):
608 mountpoint = self.getAutofsMountpoint(device)
609 for x in self.partitions[:]:
610 if x.mountpoint == mountpoint:
611 self.partitions.remove(x)
612 self.on_partition_list_change("remove", x)
614 if l and not device[l-1].isdigit():
616 if hdd.device == device:
620 SystemInfo["Harddisk"] = len(self.hdd) > 0
631 hdd = hd.model() + " - " + hd.bus()
634 hdd += " (" + cap + ")"
635 list.append((hdd, hd))
641 def getMountedPartitions(self, onlyhotplug = False):
642 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
643 devs = set([x.device for x in parts])
644 for devname in devs.copy():
647 dev, part = self.splitDeviceName(devname)
648 if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
651 # return all devices which are not removed due to being a wholedisk when a partition exists
652 return [x for x in parts if not x.device or x.device in devs]
654 def splitDeviceName(self, devname):
655 # 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.
661 return dev, part and int(part) or 0
663 def getUserfriendlyDeviceName(self, dev, phys):
664 dev, part = self.splitDeviceName(dev)
665 description = "External Storage %s" % dev
666 have_model_descr = False
668 description = readFile("/sys" + phys + "/model")
669 have_model_descr = True
671 print "couldn't read model: ", s
672 from Tools.HardwareInfo import HardwareInfo
673 if dev.find('sr') == 0 and dev[2].isdigit():
674 devicedb = DEVICEDB_SR
677 for physdevprefix, pdescription in devicedb.get(HardwareInfo().device_name,{}).items():
678 if phys.startswith(physdevprefix):
680 description = pdescription + ' - ' + description
682 description = pdescription
683 # not wholedisk and not partition 1
684 if part and part != 1:
685 description += " (Partition %d)" % part
688 def addMountedPartition(self, device, desc):
689 already_mounted = False
690 for x in self.partitions[:]:
691 if x.mountpoint == device:
692 already_mounted = True
693 if not already_mounted:
694 self.partitions.append(Partition(mountpoint = device, description = desc))
696 def removeMountedPartition(self, mountpoint):
697 for x in self.partitions[:]:
698 if x.mountpoint == mountpoint:
699 self.partitions.remove(x)
700 self.on_partition_list_change("remove", x)
702 harddiskmanager = HarddiskManager()