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
24 for disc in listdir("/dev/discs"):
25 path = readlink('/dev/discs/'+disc)
26 devidex = '/dev/discs/'+disc+'/'
27 devidex2 = '/dev'+path[2:]+'/'
28 disc = devidex2+'disc'
29 ret = stat(disc).st_rdev
30 if s_major == major(ret) and s_minor == minor(ret):
31 self.devidex = devidex
32 self.devidex2 = devidex2
33 print "new Harddisk", device, '->', self.devidex, '->', self.devidex2
38 return self.device < ob.device
41 ide_cf = self.device.find("hd") == 0 and self.devidex2.find("host0") == -1 # 7025 specific
42 internal = self.device.find("hd") == 0
52 procfile = tryOpen("/sys/block/"+self.device+"/size")
55 line = procfile.readline()
61 return cap / 1000 * 512 / 1000
67 return "%d.%03d GB" % (cap/1024, cap%1024)
70 if self.device.find("hd") == 0:
71 procfile = tryOpen("/proc/ide/"+self.device+"/model")
74 line = procfile.readline()
77 elif self.device.find("sd") == 0:
78 procfile = tryOpen("/sys/block/"+self.device+"/device/vendor")
81 vendor = procfile.readline().strip()
83 procfile = tryOpen("/sys/block/"+self.device+"/device/model")
84 model = procfile.readline().strip()
85 return vendor+'('+model+')'
87 assert False, "no hdX or sdX"
90 procfile = tryOpen("/proc/mounts")
97 line = procfile.readline()
100 if line.startswith(self.devidex):
101 parts = line.strip().split(" ")
103 stat = statvfs(parts[1])
106 free = stat.f_bfree/1000 * stat.f_bsize/1000
111 def numPartitions(self):
113 idedir = listdir(self.devidex)
117 for filename in idedir:
118 if filename.startswith("disc"):
120 if filename.startswith("part"):
125 procfile = tryOpen("/proc/mounts")
132 for line in procfile:
133 if line.startswith(self.devidex):
135 cmd = ' '.join([cmd, parts[1]])
142 def createPartition(self):
143 cmd = "/sbin/sfdisk -f " + self.devidex + "disc"
144 sfdisk = popen(cmd, "w")
145 sfdisk.write("0,\n;\n;\n;\ny\n")
150 cmd = "/sbin/mkfs.ext3 "
151 if self.diskSize() > 4 * 1024:
152 cmd += "-T largefile "
153 cmd += "-m0 " + self.devidex + "part1"
158 cmd = "/bin/mount -t ext3 " + self.devidex + "part1"
162 def createMovieFolder(self):
164 makedirs(resolveFilename(SCOPE_HDD))
170 # We autocorrect any failures
171 # TODO: we could check if the fs is actually ext3
172 cmd = "/sbin/fsck.ext3 -f -p " + self.devidex + "part1"
176 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")]
178 def initialize(self):
181 if self.createPartition() != 0:
187 if self.mount() != 0:
190 if self.createMovieFolder() != 0:
205 if res != 0 and res != 1:
206 # A sum containing 1 will also include a failure
209 if self.mount() != 0:
214 def getDeviceDir(self):
217 def getDeviceName(self):
218 return self.getDeviceDir() + "disc"
220 # the HDD idle poll daemon.
221 # as some harddrives have a buggy standby timer, we are doing this by hand here.
222 # first, we disable the hardware timer. then, we check every now and then if
223 # any access has been made to the disc. If there has been no access over a specifed time,
224 # we set the hdd into standby.
226 l = open("/sys/block/%s/stat" % self.device).read()
227 nr_read = int(l[:8].strip())
228 nr_write = int(l[4*9:4*9+8].strip())
229 return nr_read, nr_write
232 self.last_access = time.time()
234 self.is_sleeping = False
235 from enigma import eTimer
237 # disable HDD standby timer
238 Console().ePopen(("hdparm", "hdparm", "-S0", (self.devidex + "disc")))
239 self.timer = eTimer()
240 self.timer.callback.append(self.runIdle)
241 self.idle_running = True
242 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
245 if not self.max_idle_time:
249 idle_time = t - self.last_access
251 l = sum(self.readStats())
253 if l != self.last_stat: # access
257 self.is_sleeping = False
259 #print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
260 if idle_time >= self.max_idle_time and not self.is_sleeping:
262 self.is_sleeping = True
265 Console().ePopen(("hdparm", "hdparm", "-y", (self.devidex + "disc")))
267 def setIdleTime(self, idle):
268 self.max_idle_time = idle
269 if self.idle_running:
273 self.timer.start(idle * 250, False) # poll 4 times per period.
275 def isSleeping(self):
276 return self.is_sleeping
279 def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
280 self.mountpoint = mountpoint
281 self.description = description
282 self.force_mounted = force_mounted
283 self.is_hotplug = force_mounted # so far; this might change.
287 return statvfs(self.mountpoint)
292 return s.f_bavail * s.f_bsize
299 return s.f_blocks * s.f_bsize
304 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
305 # TODO: can os.path.ismount be used?
306 if self.force_mounted:
308 procfile = tryOpen("/proc/mounts")
309 for n in procfile.readlines():
310 if n.split(' ')[1] == self.mountpoint:
317 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": "Front USB Slot",
318 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": "Back, upper USB Slot",
319 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": "Back, lower USB Slot",
320 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host1/target1:0:0/1:0:0:0": "DVD Drive",
323 class HarddiskManager:
327 self.partitions = [ ]
329 self.on_partition_list_change = CList()
331 self.enumerateBlockDevices()
333 # currently, this is just an enumeration of what's possible,
334 # this probably has to be changed to support automount stuff.
335 # still, if stuff is mounted into the correct mountpoints by
336 # external tools, everything is fine (until somebody inserts
337 # a second usb stick.)
339 ("/media/hdd", _("Harddisk")),
340 ("/media/card", _("Card")),
341 ("/media/cf", _("Compact Flash")),
342 ("/media/mmc1", _("MMC Card")),
343 ("/media/net", _("Network Mount")),
344 ("/media/ram", _("Ram Disk")),
345 ("/media/usb", _("USB Stick")),
346 ("/", _("Internal Flash"))
350 self.partitions.append(Partition(mountpoint = x[0], description = x[1]))
352 def getBlockDevInfo(self, blockdev):
353 devpath = "/sys/block/" + blockdev
360 removable = bool(int(open(devpath + "/removable").read()))
361 dev = int(open(devpath + "/dev").read().split(':')[0])
362 if dev in [7, 31]: # loop, mtdblock
364 if blockdev[0:2] == 'sr':
366 if blockdev[0:2] == 'hd':
368 media = open("/proc/ide/%s/media" % blockdev).read()
369 if media.find("cdrom") != -1:
373 # check for partitions
375 for partition in listdir(devpath):
376 if partition[0:len(blockdev)] != blockdev:
378 partitions.append(partition)
386 open("/dev/" + blockdev).close()
388 if err.errno == 159: # no medium present
391 return error, blacklisted, removable, is_cdrom, partitions, medium_found
393 def enumerateBlockDevices(self):
394 print "enumerating block devices..."
395 for blockdev in listdir("/sys/block"):
396 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(blockdev)
397 print "found block device '%s':" % blockdev,
399 print "error querying properties"
402 elif not medium_found:
405 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
407 self.addHotplugPartition(blockdev)
408 for part in partitions:
409 self.addHotplugPartition(part)
411 def getAutofsMountpoint(self, device):
412 return "/autofs/%s/" % (device)
414 def addHotplugPartition(self, device, physdev = None):
416 dev, part = self.splitDeviceName(device)
418 physdev = readlink("/sys/block/" + dev + "/device")[5:]
421 print "couldn't determine blockdev physdev for device", device
423 # device is the device name, without /dev
424 # physdev is the physical device path, which we (might) use to determine the userfriendly name
425 description = self.getUserfriendlyDeviceName(device, physdev)
427 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
428 self.partitions.append(p)
429 self.on_partition_list_change("add", p)
431 # see if this is a harddrive
433 if l and device[l-1] not in string.digits:
434 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
435 if not blacklisted and not removable and not is_cdrom and medium_found:
436 self.hdd.append(Harddisk(device))
438 SystemInfo["Harddisk"] = len(self.hdd) > 0
440 def removeHotplugPartition(self, device):
441 mountpoint = self.getAutofsMountpoint(device)
442 for x in self.partitions[:]:
443 if x.mountpoint == mountpoint:
444 self.partitions.remove(x)
445 self.on_partition_list_change("remove", x)
447 if l and device[l-1] not in string.digits:
450 if hdd.device == device:
453 SystemInfo["Harddisk"] = len(self.hdd) > 0
461 hdd = hd.model() + " - " + hd.bus()
464 hdd += " (" + cap + ")"
465 list.append((hdd, hd))
471 def getMountedPartitions(self, onlyhotplug = False):
472 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
473 devs = set([x.device for x in parts])
474 for devname in devs.copy():
477 dev, part = self.splitDeviceName(devname)
478 if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
481 # return all devices which are not removed due to being a wholedisk when a partition exists
482 return [x for x in parts if not x.device or x.device in devs]
484 def splitDeviceName(self, devname):
485 # 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.
489 if p not in string.digits:
491 return dev, part and int(part) or 0
493 def getUserfriendlyDeviceName(self, dev, phys):
494 dev, part = self.splitDeviceName(dev)
495 description = "External Storage %s" % dev
497 description = open("/sys" + phys + "/model").read().strip()
499 print "couldn't read model: ", s
500 for physdevprefix, pdescription in DEVICEDB.items():
501 if phys.startswith(physdevprefix):
502 description = pdescription
504 # not wholedisk and not partition 1
505 if part and part != 1:
506 description += " (Partition %d)" % part
509 harddiskmanager = HarddiskManager()