1 from os import system, listdir, statvfs, popen, makedirs, readlink, stat, major, minor
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
10 procFile = open(filename)
16 def __init__(self, device):
18 procfile = tryOpen("/sys/block/"+self.device+"/dev")
19 tmp = procfile.readline().split(':')
22 self.max_idle_time = 0
23 self.idle_running = False
25 for disc in listdir("/dev/discs"):
26 path = readlink('/dev/discs/'+disc)
27 devidex = '/dev/discs/'+disc+'/'
28 devidex2 = '/dev'+path[2:]+'/'
29 disc = devidex2+'disc'
30 ret = stat(disc).st_rdev
31 if s_major == major(ret) and s_minor == minor(ret):
32 self.devidex = devidex
33 self.devidex2 = devidex2
34 print "new Harddisk", device, '->', self.devidex, '->', self.devidex2
39 return self.device < ob.device
44 self.timer.callback.remove(self.runIdle)
47 ide_cf = self.device[:2] == "hd" and "host0" not in self.devidex2 # 7025 specific
48 internal = self.device[:2] == "hd"
58 procfile = tryOpen("/sys/block/"+self.device+"/size")
61 line = procfile.readline()
67 return cap / 1000 * 512 / 1000
73 return "%d.%03d GB" % (cap/1000, cap%1000)
76 if self.device[:2] == "hd":
77 procfile = tryOpen("/proc/ide/"+self.device+"/model")
80 line = procfile.readline()
83 elif self.device[:2] == "sd":
84 procfile = tryOpen("/sys/block/"+self.device+"/device/vendor")
87 vendor = procfile.readline().strip()
89 procfile = tryOpen("/sys/block/"+self.device+"/device/model")
90 model = procfile.readline().strip()
91 return vendor+'('+model+')'
93 assert False, "no hdX or sdX"
96 procfile = tryOpen("/proc/mounts")
103 line = procfile.readline()
106 if line.startswith(self.devidex) or line.startswith(self.devidex2):
107 parts = line.strip().split(" ")
109 stat = statvfs(parts[1])
112 free = stat.f_bfree/1000 * stat.f_bsize/1000
117 def numPartitions(self):
119 idedir = listdir(self.devidex)
123 for filename in idedir:
124 if filename.startswith("disc"):
126 if filename.startswith("part"):
131 procfile = tryOpen("/proc/mounts")
138 for line in procfile:
139 if line.startswith(self.devidex) or line.startswith(self.devidex2):
141 cmd = ' '.join([cmd, parts[1]])
148 def createPartition(self):
149 cmd = "/sbin/sfdisk -f " + self.devidex + "disc"
150 sfdisk = popen(cmd, "w")
151 sfdisk.write("0,\n;\n;\n;\ny\n")
156 cmd = "/sbin/mkfs.ext3 "
157 if self.diskSize() > 4 * 1024:
158 cmd += "-T largefile "
159 cmd += "-m0 -O dir_index " + self.devidex + "part1"
165 #we don't know which type of devicename is used in fstab, try both
166 for device in [self.devidex, self.devidex2]:
167 cmd = "/bin/mount -t ext3 " + device + "part1"
174 def createMovieFolder(self):
176 makedirs(resolveFilename(SCOPE_HDD))
182 # We autocorrect any failures
183 # TODO: we could check if the fs is actually ext3
184 cmd = "/sbin/fsck.ext3 -f -p " + self.devidex + "part1"
188 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")]
190 def initialize(self):
193 if self.createPartition() != 0:
199 if self.mount() != 0:
202 if self.createMovieFolder() != 0:
217 if res != 0 and res != 1:
218 # A sum containing 1 will also include a failure
221 if self.mount() != 0:
226 def getDeviceDir(self):
229 def getDeviceName(self):
230 return self.getDeviceDir() + "disc"
232 # the HDD idle poll daemon.
233 # as some harddrives have a buggy standby timer, we are doing this by hand here.
234 # first, we disable the hardware timer. then, we check every now and then if
235 # any access has been made to the disc. If there has been no access over a specifed time,
236 # we set the hdd into standby.
238 l = open("/sys/block/%s/stat" % self.device).read()
239 (nr_read, _, _, _, nr_write) = l.split()[:5]
240 return int(nr_read), int(nr_write)
243 self.last_access = time.time()
245 self.is_sleeping = False
246 from enigma import eTimer
248 # disable HDD standby timer
249 Console().ePopen(("hdparm", "hdparm", "-S0", (self.devidex + "disc")))
250 self.timer = eTimer()
251 self.timer.callback.append(self.runIdle)
252 self.idle_running = True
253 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
256 if not self.max_idle_time:
260 idle_time = t - self.last_access
262 stats = self.readStats()
263 print "nr_read", stats[0], "nr_write", stats[1]
265 print "sum", l, "prev_sum", self.last_stat
267 if l != self.last_stat: # access
268 print "hdd was accessed since previous check!"
272 self.is_sleeping = False
276 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
277 if idle_time >= self.max_idle_time and not self.is_sleeping:
279 self.is_sleeping = True
282 Console().ePopen(("hdparm", "hdparm", "-y", (self.devidex + "disc")))
284 def setIdleTime(self, idle):
285 self.max_idle_time = idle
286 if self.idle_running:
290 self.timer.start(idle * 100, False) # poll 10 times per period.
292 def isSleeping(self):
293 return self.is_sleeping
296 def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
297 self.mountpoint = mountpoint
298 self.description = description
299 self.force_mounted = force_mounted
300 self.is_hotplug = force_mounted # so far; this might change.
304 return statvfs(self.mountpoint)
309 return s.f_bavail * s.f_bsize
316 return s.f_blocks * s.f_bsize
321 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
322 # TODO: can os.path.ismount be used?
323 if self.force_mounted:
325 procfile = tryOpen("/proc/mounts")
326 for n in procfile.readlines():
327 if n.split(' ')[1] == self.mountpoint:
335 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": "Front USB Slot",
336 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": "Back, upper USB Slot",
337 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": "Back, lower USB Slot",
338 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host1/target1:0:0/1:0:0:0": "DVD Drive",
343 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": "Upper USB Slot",
344 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": "Lower USB Slot",
349 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "CF Card Slot", #hdc
350 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
354 class HarddiskManager:
358 self.partitions = [ ]
360 self.on_partition_list_change = CList()
362 self.enumerateBlockDevices()
364 # currently, this is just an enumeration of what's possible,
365 # this probably has to be changed to support automount stuff.
366 # still, if stuff is mounted into the correct mountpoints by
367 # external tools, everything is fine (until somebody inserts
368 # a second usb stick.)
370 ("/media/hdd", _("Harddisk")),
371 ("/media/card", _("Card")),
372 ("/media/cf", _("Compact Flash")),
373 ("/media/mmc1", _("MMC Card")),
374 ("/media/net", _("Network Mount")),
375 ("/media/ram", _("Ram Disk")),
376 ("/media/usb", _("USB Stick")),
377 ("/", _("Internal Flash"))
380 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
382 def getBlockDevInfo(self, blockdev):
383 devpath = "/sys/block/" + blockdev
390 removable = bool(int(open(devpath + "/removable").read()))
391 dev = int(open(devpath + "/dev").read().split(':')[0])
392 if dev in (7, 31): # loop, mtdblock
394 if blockdev[0:2] == 'sr':
396 if blockdev[0:2] == 'hd':
398 media = open("/proc/ide/%s/media" % blockdev).read()
403 # check for partitions
405 for partition in listdir(devpath):
406 if partition[0:len(blockdev)] != blockdev:
408 partitions.append(partition)
416 open("/dev/" + blockdev).close()
418 if err.errno == 159: # no medium present
421 return error, blacklisted, removable, is_cdrom, partitions, medium_found
423 def enumerateBlockDevices(self):
424 print "enumerating block devices..."
425 for blockdev in listdir("/sys/block"):
426 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(blockdev)
427 print "found block device '%s':" % blockdev,
429 print "error querying properties"
432 elif not medium_found:
435 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
437 self.addHotplugPartition(blockdev)
438 for part in partitions:
439 self.addHotplugPartition(part)
441 def getAutofsMountpoint(self, device):
442 return "/autofs/%s/" % (device)
444 def addHotplugPartition(self, device, physdev = None):
446 dev, part = self.splitDeviceName(device)
448 physdev = readlink("/sys/block/" + dev + "/device")[5:]
451 print "couldn't determine blockdev physdev for device", device
453 # device is the device name, without /dev
454 # physdev is the physical device path, which we (might) use to determine the userfriendly name
455 description = self.getUserfriendlyDeviceName(device, physdev)
457 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
458 self.partitions.append(p)
459 self.on_partition_list_change("add", p)
461 # see if this is a harddrive
463 if l and not device[l-1].isdigit():
464 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
465 if not blacklisted and not removable and not is_cdrom and medium_found:
466 self.hdd.append(Harddisk(device))
468 SystemInfo["Harddisk"] = len(self.hdd) > 0
470 def removeHotplugPartition(self, device):
471 mountpoint = self.getAutofsMountpoint(device)
472 for x in self.partitions[:]:
473 if x.mountpoint == mountpoint:
474 self.partitions.remove(x)
475 self.on_partition_list_change("remove", x)
477 if l and not device[l-1].isdigit():
479 if hdd.device == device:
483 SystemInfo["Harddisk"] = len(self.hdd) > 0
491 hdd = hd.model() + " - " + hd.bus()
494 hdd += " (" + cap + ")"
495 list.append((hdd, hd))
501 def getMountedPartitions(self, onlyhotplug = False):
502 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
503 devs = set([x.device for x in parts])
504 for devname in devs.copy():
507 dev, part = self.splitDeviceName(devname)
508 if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
511 # return all devices which are not removed due to being a wholedisk when a partition exists
512 return [x for x in parts if not x.device or x.device in devs]
514 def splitDeviceName(self, devname):
515 # 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.
521 return dev, part and int(part) or 0
523 def getUserfriendlyDeviceName(self, dev, phys):
524 dev, part = self.splitDeviceName(dev)
525 description = "External Storage %s" % dev
527 description = open("/sys" + phys + "/model").read().strip()
529 print "couldn't read model: ", s
530 from Tools.HardwareInfo import HardwareInfo
531 for physdevprefix, pdescription in DEVICEDB.get(HardwareInfo().device_name,{}).items():
532 if phys.startswith(physdevprefix):
533 description = pdescription
535 # not wholedisk and not partition 1
536 if part and part != 1:
537 description += " (Partition %d)" % part
540 def addMountedPartition(self, device, desc):
541 already_mounted = False
542 for x in self.partitions[:]:
543 if x.mountpoint == device:
544 already_mounted = True
545 if not already_mounted:
546 self.partitions.append(Partition(mountpoint = device, description = desc))
548 def removeMountedPartition(self, mountpoint):
549 for x in self.partitions[:]:
550 if x.mountpoint == mountpoint:
551 self.partitions.remove(x)
552 self.on_partition_list_change("remove", x)
554 harddiskmanager = HarddiskManager()