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.
293 l = readFile("/sys/block/%s/stat" % self.device)
294 (nr_read, _, _, _, nr_write) = l.split()[:5]
295 return int(nr_read), int(nr_write)
298 self.last_access = time.time()
300 self.is_sleeping = False
301 from enigma import eTimer
303 # disable HDD standby timer
304 Console().ePopen(("hdparm", "hdparm", "-S0", self.disk_path))
305 self.timer = eTimer()
306 self.timer.callback.append(self.runIdle)
307 self.idle_running = True
308 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
311 if not self.max_idle_time:
315 idle_time = t - self.last_access
317 stats = self.readStats()
318 print "nr_read", stats[0], "nr_write", stats[1]
320 print "sum", l, "prev_sum", self.last_stat
322 if l != self.last_stat: # access
323 print "hdd was accessed since previous check!"
327 self.is_sleeping = False
331 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
332 if idle_time >= self.max_idle_time and not self.is_sleeping:
334 self.is_sleeping = True
337 Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
339 def setIdleTime(self, idle):
340 self.max_idle_time = idle
341 if self.idle_running:
345 self.timer.start(idle * 100, False) # poll 10 times per period.
347 def isSleeping(self):
348 return self.is_sleeping
351 def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
352 self.mountpoint = mountpoint
353 self.description = description
354 self.force_mounted = force_mounted
355 self.is_hotplug = force_mounted # so far; this might change.
359 return statvfs(self.mountpoint)
364 return s.f_bavail * s.f_bsize
371 return s.f_blocks * s.f_bsize
376 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
377 # TODO: can os.path.ismount be used?
378 if self.force_mounted:
382 mounts = open("/proc/mounts")
386 lines = mounts.readlines()
390 if line.split(' ')[1] == self.mountpoint:
398 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": "Front USB Slot",
399 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": "Back, upper USB Slot",
400 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": "Back, lower USB Slot",
401 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host1/target1:0:0/1:0:0:0": "DVD Drive",
406 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": "Upper USB Slot",
407 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": "Lower USB Slot",
412 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "CF Card Slot", #hdc
413 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
417 class HarddiskManager:
421 self.partitions = [ ]
423 self.on_partition_list_change = CList()
425 self.enumerateBlockDevices()
427 # currently, this is just an enumeration of what's possible,
428 # this probably has to be changed to support automount stuff.
429 # still, if stuff is mounted into the correct mountpoints by
430 # external tools, everything is fine (until somebody inserts
431 # a second usb stick.)
433 ("/media/hdd", _("Harddisk")),
434 ("/media/card", _("Card")),
435 ("/media/cf", _("Compact Flash")),
436 ("/media/mmc1", _("MMC Card")),
437 ("/media/net", _("Network Mount")),
438 ("/media/ram", _("Ram Disk")),
439 ("/media/usb", _("USB Stick")),
440 ("/", _("Internal Flash"))
443 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
445 def getBlockDevInfo(self, blockdev):
446 devpath = "/sys/block/" + blockdev
453 removable = bool(int(readFile(devpath + "/removable")))
454 dev = int(readFile(devpath + "/dev").split(':')[0])
455 if dev in (7, 31): # loop, mtdblock
457 if blockdev[0:2] == 'sr':
459 if blockdev[0:2] == 'hd':
461 media = readFile("/proc/ide/%s/media" % blockdev)
466 # check for partitions
468 for partition in listdir(devpath):
469 if partition[0:len(blockdev)] != blockdev:
471 partitions.append(partition)
479 open("/dev/" + blockdev).close()
481 if err.errno == 159: # no medium present
484 return error, blacklisted, removable, is_cdrom, partitions, medium_found
486 def enumerateBlockDevices(self):
487 print "enumerating block devices..."
488 for blockdev in listdir("/sys/block"):
489 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(blockdev)
490 print "found block device '%s':" % blockdev,
492 print "error querying properties"
495 elif not medium_found:
498 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
500 self.addHotplugPartition(blockdev)
501 for part in partitions:
502 self.addHotplugPartition(part)
504 def getAutofsMountpoint(self, device):
505 return "/autofs/%s/" % (device)
507 def addHotplugPartition(self, device, physdev = None):
509 dev, part = self.splitDeviceName(device)
511 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
514 print "couldn't determine blockdev physdev for device", device
516 # device is the device name, without /dev
517 # physdev is the physical device path, which we (might) use to determine the userfriendly name
518 description = self.getUserfriendlyDeviceName(device, physdev)
520 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
521 self.partitions.append(p)
522 self.on_partition_list_change("add", p)
524 # see if this is a harddrive
526 if l and not device[l-1].isdigit():
527 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
528 if not blacklisted and not removable and not is_cdrom and medium_found:
529 self.hdd.append(Harddisk(device))
531 SystemInfo["Harddisk"] = len(self.hdd) > 0
533 def removeHotplugPartition(self, device):
534 mountpoint = self.getAutofsMountpoint(device)
535 for x in self.partitions[:]:
536 if x.mountpoint == mountpoint:
537 self.partitions.remove(x)
538 self.on_partition_list_change("remove", x)
540 if l and not device[l-1].isdigit():
542 if hdd.device == device:
546 SystemInfo["Harddisk"] = len(self.hdd) > 0
554 hdd = hd.model() + " - " + hd.bus()
557 hdd += " (" + cap + ")"
558 list.append((hdd, hd))
564 def getMountedPartitions(self, onlyhotplug = False):
565 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
566 devs = set([x.device for x in parts])
567 for devname in devs.copy():
570 dev, part = self.splitDeviceName(devname)
571 if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
574 # return all devices which are not removed due to being a wholedisk when a partition exists
575 return [x for x in parts if not x.device or x.device in devs]
577 def splitDeviceName(self, devname):
578 # 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.
584 return dev, part and int(part) or 0
586 def getUserfriendlyDeviceName(self, dev, phys):
587 dev, part = self.splitDeviceName(dev)
588 description = "External Storage %s" % dev
590 description = readFile("/sys" + phys + "/model")
592 print "couldn't read model: ", s
593 from Tools.HardwareInfo import HardwareInfo
594 for physdevprefix, pdescription in DEVICEDB.get(HardwareInfo().device_name,{}).items():
595 if phys.startswith(physdevprefix):
596 description = pdescription
598 # not wholedisk and not partition 1
599 if part and part != 1:
600 description += " (Partition %d)" % part
603 def addMountedPartition(self, device, desc):
604 already_mounted = False
605 for x in self.partitions[:]:
606 if x.mountpoint == device:
607 already_mounted = True
608 if not already_mounted:
609 self.partitions.append(Partition(mountpoint = device, description = desc))
611 def removeMountedPartition(self, mountpoint):
612 for x in self.partitions[:]:
613 if x.mountpoint == mountpoint:
614 self.partitions.remove(x)
615 self.on_partition_list_change("remove", x)
617 harddiskmanager = HarddiskManager()