1 from os import system, listdir, statvfs, popen, makedirs, stat, major, minor, path, access
2 from Tools.Directories import SCOPE_HDD, resolveFilename
3 from Tools.CList import CList
4 from SystemInfo import SystemInfo
6 from Components.Console import Console
8 def readFile(filename):
10 data = file.read().strip()
18 def __init__(self, device):
21 if access("/dev/.udev", 0):
22 self.type = self.DEVTYPE_UDEV
23 elif access("/dev/.devfsd", 0):
24 self.type = self.DEVTYPE_DEVFS
26 print "Unable to determine structure of /dev"
28 self.max_idle_time = 0
29 self.idle_running = False
34 self.phys_path = path.realpath(self.sysfsPath('device'))
36 if self.type == self.DEVTYPE_UDEV:
37 self.dev_path = '/dev/' + self.device
38 self.disk_path = self.dev_path
40 elif self.type == self.DEVTYPE_DEVFS:
41 tmp = readFile(self.sysfsPath('dev')).split(':')
44 for disc in listdir("/dev/discs"):
45 dev_path = path.realpath('/dev/discs/' + disc)
46 disk_path = dev_path + '/disc'
48 rdev = stat(disk_path).st_rdev
51 if s_major == major(rdev) and s_minor == minor(rdev):
52 self.dev_path = dev_path
53 self.disk_path = disk_path
56 print "new Harddisk", self.device, '->', self.dev_path, '->', self.disk_path
60 return self.device < ob.device
62 def partitionPath(self, n):
63 if self.type == self.DEVTYPE_UDEV:
64 return self.dev_path + n
65 elif self.type == self.DEVTYPE_DEVFS:
66 return self.dev_path + '/part' + n
68 def sysfsPath(self, filename):
69 return path.realpath('/sys/block/' + self.device + '/' + filename)
74 self.timer.callback.remove(self.runIdle)
78 if self.type == self.DEVTYPE_UDEV:
79 ide_cf = False # FIXME
80 elif self.type == self.DEVTYPE_DEVFS:
81 ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
83 internal = "pci" in self.phys_path
94 line = readFile(self.sysfsPath('size'))
99 return cap / 1000 * 512 / 1000
102 cap = self.diskSize()
105 return "%d.%03d GB" % (cap/1000, cap%1000)
108 if self.device[:2] == "hd":
109 return readFile('/proc/ide/' + self.device + '/model')
110 elif self.device[:2] == "sd":
111 vendor = readFile(self.sysfsPath('device/vendor'))
112 model = readFile(self.sysfsPath('device/model'))
113 return vendor + '(' + model + ')'
115 assert False, "no hdX or sdX"
119 mounts = open("/proc/mounts")
123 lines = mounts.readlines()
127 parts = line.strip().split(" ")
128 if path.realpath(parts[0]).startswith(self.dev_path):
130 stat = statvfs(parts[1])
133 return stat.f_bfree/1000 * stat.f_bsize/1000
137 def numPartitions(self):
139 if self.type == self.DEVTYPE_UDEV:
141 devdir = listdir('/dev')
144 for filename in devdir:
145 if filename.startswith(self.device):
148 elif self.type == self.DEVTYPE_DEVFS:
150 idedir = listdir(self.dev_path)
153 for filename in idedir:
154 if filename.startswith("disc"):
156 if filename.startswith("part"):
162 mounts = open("/proc/mounts")
166 lines = mounts.readlines()
172 parts = line.strip().split(" ")
173 if path.realpath(parts[0]).startswith(self.dev_path):
174 cmd = ' ' . join([cmd, parts[1]])
179 def createPartition(self):
180 cmd = 'printf "0,\n;\n;\n;\ny\n" | /sbin/sfdisk -f ' + self.disk_path
185 cmd = "/sbin/mkfs.ext3 "
186 if self.diskSize() > 4 * 1024:
187 cmd += "-T largefile "
188 cmd += "-m0 -O dir_index " + self.partitionPath("1")
194 fstab = open("/etc/fstab")
198 lines = fstab.readlines()
203 parts = line.strip().split(" ")
204 if path.realpath(parts[0]) == self.partitionPath("1"):
205 cmd = "/bin/mount -t ext3 " + parts[0]
211 def createMovieFolder(self):
213 makedirs(resolveFilename(SCOPE_HDD))
219 # We autocorrect any failures
220 # TODO: we could check if the fs is actually ext3
221 cmd = "/sbin/fsck.ext3 -f -p " + self.partitionPath("1")
225 def killPartition(self, n):
226 part = self.partitionPath(n)
229 cmd = '/bin/dd bs=512 count=3 if=/dev/zero of=' + part
236 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")]
238 def initialize(self):
241 # Udev tries to mount the partition immediately if there is an
242 # old filesystem on it when fdisk reloads the partition table.
243 # To prevent that, we overwrite the first 3 sectors of the
244 # partition, if the partition existed before. That's enough for
246 self.killPartition("1")
248 if self.createPartition() != 0:
254 if self.mount() != 0:
257 if self.createMovieFolder() != 0:
272 if res != 0 and res != 1:
273 # A sum containing 1 will also include a failure
276 if self.mount() != 0:
281 def getDeviceDir(self):
284 def getDeviceName(self):
285 return self.disk_path
287 # the HDD idle poll daemon.
288 # as some harddrives have a buggy standby timer, we are doing this by hand here.
289 # first, we disable the hardware timer. then, we check every now and then if
290 # any access has been made to the disc. If there has been no access over a specifed time,
291 # we set the hdd into standby.
294 l = open("/sys/block/%s/stat" % self.device).read()
297 (nr_read, _, _, _, nr_write) = l.split()[:5]
298 return int(nr_read), int(nr_write)
301 self.last_access = time.time()
303 self.is_sleeping = False
304 from enigma import eTimer
306 # disable HDD standby timer
307 Console().ePopen(("hdparm", "hdparm", "-S0", self.disk_path))
308 self.timer = eTimer()
309 self.timer.callback.append(self.runIdle)
310 self.idle_running = True
311 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
314 if not self.max_idle_time:
318 idle_time = t - self.last_access
320 stats = self.readStats()
321 print "nr_read", stats[0], "nr_write", stats[1]
323 print "sum", l, "prev_sum", self.last_stat
325 if l != self.last_stat and l >= 0: # access
326 print "hdd was accessed since previous check!"
330 self.is_sleeping = False
334 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
335 if idle_time >= self.max_idle_time and not self.is_sleeping:
337 self.is_sleeping = True
340 Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
342 def setIdleTime(self, idle):
343 self.max_idle_time = idle
344 if self.idle_running:
348 self.timer.start(idle * 100, False) # poll 10 times per period.
350 def isSleeping(self):
351 return self.is_sleeping
354 def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
355 self.mountpoint = mountpoint
356 self.description = description
357 self.force_mounted = force_mounted
358 self.is_hotplug = force_mounted # so far; this might change.
362 return statvfs(self.mountpoint)
367 return s.f_bavail * s.f_bsize
374 return s.f_blocks * s.f_bsize
379 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
380 # TODO: can os.path.ismount be used?
381 if self.force_mounted:
385 mounts = open("/proc/mounts")
389 lines = mounts.readlines()
393 if line.split(' ')[1] == self.mountpoint:
401 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": "Front USB Slot",
402 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": "Back, upper USB Slot",
403 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": "Back, lower USB Slot",
404 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host1/target1:0:0/1:0:0:0": "DVD Drive",
409 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": "Upper USB Slot",
410 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": "Lower USB Slot",
415 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "CF Card Slot", #hdc
416 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
420 class HarddiskManager:
424 self.partitions = [ ]
426 self.on_partition_list_change = CList()
428 self.enumerateBlockDevices()
430 # currently, this is just an enumeration of what's possible,
431 # this probably has to be changed to support automount stuff.
432 # still, if stuff is mounted into the correct mountpoints by
433 # external tools, everything is fine (until somebody inserts
434 # a second usb stick.)
436 ("/media/hdd", _("Harddisk")),
437 ("/media/card", _("Card")),
438 ("/media/cf", _("Compact Flash")),
439 ("/media/mmc1", _("MMC Card")),
440 ("/media/net", _("Network Mount")),
441 ("/media/ram", _("Ram Disk")),
442 ("/media/usb", _("USB Stick")),
443 ("/", _("Internal Flash"))
446 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
448 def getBlockDevInfo(self, blockdev):
449 devpath = "/sys/block/" + blockdev
456 removable = bool(int(readFile(devpath + "/removable")))
457 dev = int(readFile(devpath + "/dev").split(':')[0])
458 if dev in (7, 31): # loop, mtdblock
460 if blockdev[0:2] == 'sr':
462 if blockdev[0:2] == 'hd':
464 media = readFile("/proc/ide/%s/media" % blockdev)
469 # check for partitions
471 for partition in listdir(devpath):
472 if partition[0:len(blockdev)] != blockdev:
474 partitions.append(partition)
482 open("/dev/" + blockdev).close()
484 if err.errno == 159: # no medium present
487 return error, blacklisted, removable, is_cdrom, partitions, medium_found
489 def enumerateBlockDevices(self):
490 print "enumerating block devices..."
491 for blockdev in listdir("/sys/block"):
492 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(blockdev)
493 print "found block device '%s':" % blockdev,
495 print "error querying properties"
498 elif not medium_found:
501 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
503 self.addHotplugPartition(blockdev)
504 for part in partitions:
505 self.addHotplugPartition(part)
507 def getAutofsMountpoint(self, device):
508 return "/autofs/%s/" % (device)
510 def addHotplugPartition(self, device, physdev = None):
512 dev, part = self.splitDeviceName(device)
514 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
517 print "couldn't determine blockdev physdev for device", device
519 # device is the device name, without /dev
520 # physdev is the physical device path, which we (might) use to determine the userfriendly name
521 description = self.getUserfriendlyDeviceName(device, physdev)
523 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
524 self.partitions.append(p)
525 self.on_partition_list_change("add", p)
527 # see if this is a harddrive
529 if l and not device[l-1].isdigit():
530 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
531 if not blacklisted and not removable and not is_cdrom and medium_found:
532 self.hdd.append(Harddisk(device))
534 SystemInfo["Harddisk"] = len(self.hdd) > 0
536 def removeHotplugPartition(self, device):
537 mountpoint = self.getAutofsMountpoint(device)
538 for x in self.partitions[:]:
539 if x.mountpoint == mountpoint:
540 self.partitions.remove(x)
541 self.on_partition_list_change("remove", x)
543 if l and not device[l-1].isdigit():
545 if hdd.device == device:
549 SystemInfo["Harddisk"] = len(self.hdd) > 0
557 hdd = hd.model() + " - " + hd.bus()
560 hdd += " (" + cap + ")"
561 list.append((hdd, hd))
567 def getMountedPartitions(self, onlyhotplug = False):
568 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
569 devs = set([x.device for x in parts])
570 for devname in devs.copy():
573 dev, part = self.splitDeviceName(devname)
574 if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
577 # return all devices which are not removed due to being a wholedisk when a partition exists
578 return [x for x in parts if not x.device or x.device in devs]
580 def splitDeviceName(self, devname):
581 # 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.
587 return dev, part and int(part) or 0
589 def getUserfriendlyDeviceName(self, dev, phys):
590 dev, part = self.splitDeviceName(dev)
591 description = "External Storage %s" % dev
593 description = readFile("/sys" + phys + "/model")
595 print "couldn't read model: ", s
596 from Tools.HardwareInfo import HardwareInfo
597 for physdevprefix, pdescription in DEVICEDB.get(HardwareInfo().device_name,{}).items():
598 if phys.startswith(physdevprefix):
599 description = pdescription
601 # not wholedisk and not partition 1
602 if part and part != 1:
603 description += " (Partition %d)" % part
606 def addMountedPartition(self, device, desc):
607 already_mounted = False
608 for x in self.partitions[:]:
609 if x.mountpoint == device:
610 already_mounted = True
611 if not already_mounted:
612 self.partitions.append(Partition(mountpoint = device, description = desc))
614 def removeMountedPartition(self, mountpoint):
615 for x in self.partitions[:]:
616 if x.mountpoint == mountpoint:
617 self.partitions.remove(x)
618 self.on_partition_list_change("remove", x)
620 harddiskmanager = HarddiskManager()