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()
22 mounts = open("/proc/mounts", 'r')
24 print "[Harddisk] Failed to open /proc/mounts", ex
26 result = [line.strip().split(' ') for line in mounts]
28 # Spaces are encoded as \040 in mounts
29 item[1] = item[1].replace('\\040', ' ')
36 def __init__(self, device):
39 if access("/dev/.udev", 0):
40 self.type = DEVTYPE_UDEV
41 elif access("/dev/.devfsd", 0):
42 self.type = DEVTYPE_DEVFS
44 print "Unable to determine structure of /dev"
46 self.max_idle_time = 0
47 self.idle_running = False
52 self.mount_path = None
53 self.mount_device = None
54 self.phys_path = path.realpath(self.sysfsPath('device'))
56 if self.type == DEVTYPE_UDEV:
57 self.dev_path = '/dev/' + self.device
58 self.disk_path = self.dev_path
60 elif self.type == DEVTYPE_DEVFS:
61 tmp = readFile(self.sysfsPath('dev')).split(':')
64 for disc in listdir("/dev/discs"):
65 dev_path = path.realpath('/dev/discs/' + disc)
66 disk_path = dev_path + '/disc'
68 rdev = stat(disk_path).st_rdev
71 if s_major == major(rdev) and s_minor == minor(rdev):
72 self.dev_path = dev_path
73 self.disk_path = disk_path
76 print "new Harddisk", self.device, '->', self.dev_path, '->', self.disk_path
80 return self.device < ob.device
82 def partitionPath(self, n):
83 if self.type == DEVTYPE_UDEV:
84 return self.dev_path + n
85 elif self.type == DEVTYPE_DEVFS:
86 return self.dev_path + '/part' + n
88 def sysfsPath(self, filename):
89 return path.realpath('/sys/block/' + self.device + '/' + filename)
94 self.timer.callback.remove(self.runIdle)
98 if self.type == DEVTYPE_UDEV:
99 ide_cf = False # FIXME
100 elif self.type == DEVTYPE_DEVFS:
101 ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
103 internal = "pci" in self.phys_path
106 ret = "External (CF)"
115 line = readFile(self.sysfsPath('size'))
117 harddiskmanager.removeHotplugPartition(self.device)
118 print "error remove",self.device
124 return cap / 1000 * 512 / 1000
127 cap = self.diskSize()
130 return "%d.%03d GB" % (cap/1000, cap%1000)
134 if self.device[:2] == "hd":
135 return readFile('/proc/ide/' + self.device + '/model')
136 elif self.device[:2] == "sd":
137 vendor = readFile(self.sysfsPath('device/vendor'))
138 model = readFile(self.sysfsPath('device/model'))
139 return vendor + '(' + model + ')'
141 assert False, "no hdX or sdX"
143 harddiskmanager.removeHotplugPartition(self.device)
144 print "error remove",self.device
149 mounts = open("/proc/mounts")
153 lines = mounts.readlines()
157 parts = line.strip().split(" ")
158 real_path = path.realpath(parts[0])
159 if not real_path[-1].isdigit():
162 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
163 stat = statvfs(parts[1])
164 return stat.f_bfree/1000 * stat.f_bsize/1000
169 def numPartitions(self):
171 if self.type == DEVTYPE_UDEV:
173 devdir = listdir('/dev')
176 for filename in devdir:
177 if filename.startswith(self.device):
180 elif self.type == DEVTYPE_DEVFS:
182 idedir = listdir(self.dev_path)
185 for filename in idedir:
186 if filename.startswith("disc"):
188 if filename.startswith("part"):
192 def mountDevice(self):
193 for parts in getProcMounts():
194 if path.realpath(parts[0]).startswith(self.dev_path):
195 self.mount_device = parts[0]
196 self.mount_path = parts[1]
200 if self.mount_path is None:
201 return self.mountDevice()
202 return self.mount_path
206 mounts = open("/proc/mounts")
210 lines = mounts.readlines()
216 parts = line.strip().split(" ")
217 real_path = path.realpath(parts[0])
218 if not real_path[-1].isdigit():
221 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
222 cmd = ' ' . join([cmd, parts[1]])
230 def checkPartionPath(self, path):
232 for i in range(1,10):
233 if os.path.exists(path):
238 def createPartition(self):
239 def CheckPartedVer():
240 cmd = 'parted --version'
241 lines = popen(cmd).readlines()
243 if l.find("parted (GNU parted)") != -1:
244 ver = l.split()[3].strip()
249 print "[CheckPartedVer] check parted version Failed!"
253 disk_size = self.diskSize()
255 if disk_size > 2.2 * 1000 * 1000: # if 2.2 TB
257 partedVer = CheckPartedVer()
258 if partedVer >= 2.1: # align option is supported in version 2.1 or later
259 setAlign = "--align optimal"
260 cmd = 'parted %s %s --script mklabel gpt mkpart disk ext2 0%% 100%%' % ( setAlign, self.disk_path )
263 cmd = 'printf "8,\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS ' + self.disk_path
266 if not self.checkPartionPath(self.partitionPath("1")):
267 print "no exist : ", self.partitionPath("1")
273 if self.diskSize() > 4 * 1024:
274 cmd += "-T largefile "
275 cmd += "-m0 -O dir_index " + self.partitionPath("1")
281 fstab = open("/etc/fstab")
285 lines = fstab.readlines()
290 parts = line.strip().split(" ")
291 real_path = path.realpath(parts[0])
292 if not real_path[-1].isdigit():
295 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
296 cmd = "mount -t ext3 " + parts[0]
304 def createMovieFolder(self):
306 if not fileExists("/hdd", 0):
307 print "not found /hdd"
308 system("ln -s /media/hdd /hdd")
310 makedirs(resolveFilename(SCOPE_HDD))
316 # We autocorrect any failures
317 # TODO: we could check if the fs is actually ext3
318 cmd = "fsck.ext3 -f -p " + self.partitionPath("1")
322 def killPartition(self, n):
323 part = self.partitionPath(n)
326 cmd = 'dd bs=512 count=3 if=/dev/zero of=' + part
333 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")]
335 def initialize(self):
338 # Udev tries to mount the partition immediately if there is an
339 # old filesystem on it when fdisk reloads the partition table.
340 # To prevent that, we overwrite the first 3 sectors of the
341 # partition, if the partition existed before. That's enough for
343 self.killPartition("1")
345 if self.createPartition() != 0:
351 if self.mount() != 0:
354 if self.createMovieFolder() != 0:
369 if res != 0 and res != 1:
370 # A sum containing 1 will also include a failure
373 if self.mount() != 0:
378 def getDeviceDir(self):
381 def getDeviceName(self):
382 return self.disk_path
384 # the HDD idle poll daemon.
385 # as some harddrives have a buggy standby timer, we are doing this by hand here.
386 # first, we disable the hardware timer. then, we check every now and then if
387 # any access has been made to the disc. If there has been no access over a specifed time,
388 # we set the hdd into standby.
391 l = open("/sys/block/%s/stat" % self.device).read()
394 (nr_read, _, _, _, nr_write) = l.split()[:5]
395 return int(nr_read), int(nr_write)
398 self.last_access = time.time()
400 self.is_sleeping = False
401 from enigma import eTimer
403 # disable HDD standby timer
404 Console().ePopen(("hdparm", "hdparm", "-S0", self.disk_path))
405 self.timer = eTimer()
406 self.timer.callback.append(self.runIdle)
407 self.idle_running = True
408 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
411 if not self.max_idle_time:
415 idle_time = t - self.last_access
417 stats = self.readStats()
422 print "nr_read", stats[0], "nr_write", stats[1]
424 print "sum", l, "prev_sum", self.last_stat
426 if l != self.last_stat and l >= 0: # access
427 print "hdd was accessed since previous check!"
431 self.is_sleeping = False
435 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
436 if idle_time >= self.max_idle_time and not self.is_sleeping:
438 self.is_sleeping = True
441 Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
443 def setIdleTime(self, idle):
444 self.max_idle_time = idle
445 if self.idle_running:
449 self.timer.start(idle * 100, False) # poll 10 times per period.
451 def isSleeping(self):
452 return self.is_sleeping
455 def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
456 self.mountpoint = mountpoint
457 self.description = description
458 self.force_mounted = force_mounted
459 self.is_hotplug = force_mounted # so far; this might change.
463 return statvfs(self.mountpoint)
468 return s.f_bavail * s.f_bsize
475 return s.f_blocks * s.f_bsize
480 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
481 # TODO: can os.path.ismount be used?
482 if self.force_mounted:
486 mounts = open("/proc/mounts")
490 lines = mounts.readlines()
494 if line.split(' ')[1] == self.mountpoint:
501 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("DVD Drive"),
502 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("DVD Drive"),
503 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host3/target3:0:0/3:0:0:0": _("DVD Drive"),
516 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
517 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": _("Back, upper USB Slot"),
518 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": _("Back, lower USB Slot"),
519 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
520 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/": _("Internal USB Slot"),
521 "/devices/platform/brcm-ohci-1.1/usb4/4-1/4-1:1.0/": _("Internal USB Slot"),
525 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": "Upper USB Slot",
526 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": "Lower USB Slot",
530 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "CF Card Slot", #hdc
531 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
535 class HarddiskManager:
539 self.partitions = [ ]
540 self.devices_scanned_on_init = [ ]
542 self.on_partition_list_change = CList()
544 self.enumerateBlockDevices()
546 # currently, this is just an enumeration of what's possible,
547 # this probably has to be changed to support automount stuff.
548 # still, if stuff is mounted into the correct mountpoints by
549 # external tools, everything is fine (until somebody inserts
550 # a second usb stick.)
552 ("/media/hdd", _("Harddisk")),
553 ("/media/card", _("Card")),
554 ("/media/cf", _("Compact Flash")),
555 ("/media/mmc1", _("MMC Card")),
556 ("/media/net", _("Network Mount")),
557 ("/media/ram", _("Ram Disk")),
558 ("/media/usb", _("USB Stick")),
559 ("/", _("Internal Flash"))
562 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
564 def getBlockDevInfo(self, blockdev):
565 devpath = "/sys/block/" + blockdev
572 removable = bool(int(readFile(devpath + "/removable")))
573 dev = int(readFile(devpath + "/dev").split(':')[0])
574 if dev in (7, 31): # loop, mtdblock
576 if blockdev[0:2] == 'sr':
578 if blockdev[0:2] == 'hd':
580 media = readFile("/proc/ide/%s/media" % blockdev)
585 # check for partitions
587 for partition in listdir(devpath):
588 if partition[0:len(blockdev)] != blockdev:
590 partitions.append(partition)
598 open("/dev/" + blockdev).close()
600 if err.errno == 159: # no medium present
603 return error, blacklisted, removable, is_cdrom, partitions, medium_found
605 def enumerateBlockDevices(self):
606 print "enumerating block devices..."
607 for blockdev in listdir("/sys/block"):
608 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.addHotplugPartition(blockdev)
609 if not error and not blacklisted:
611 for part in partitions:
612 self.addHotplugPartition(part)
613 self.devices_scanned_on_init.append((blockdev, removable, is_cdrom, medium_found))
615 def getAutofsMountpoint(self, device):
616 return "/autofs/%s/" % (device)
619 def is_hard_mounted(self, device):
620 mounts = file('/proc/mounts').read().split('\n')
622 if x.find('/autofs') == -1 and x.find(device) != -1:
626 def addHotplugPartition(self, device, physdev = None):
628 dev, part = self.splitDeviceName(device)
630 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
633 print "couldn't determine blockdev physdev for device", device
635 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
636 print "found block device '%s':" % device,
642 print "error querying properties"
643 elif not medium_found:
646 print "ok, removable=%s, cdrom=%s, partitions=%s" % (removable, is_cdrom, partitions)
650 # see if this is a harddrive
651 if not device[l-1].isdigit() and not removable and not is_cdrom:
652 self.hdd.append(Harddisk(device))
654 SystemInfo["Harddisk"] = len(self.hdd) > 0
656 if (not removable or medium_found) and not self.is_hard_mounted(device):
657 # device is the device name, without /dev
658 # physdev is the physical device path, which we (might) use to determine the userfriendly name
659 description = self.getUserfriendlyDeviceName(device, physdev)
660 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
661 self.partitions.append(p)
662 self.on_partition_list_change("add", p)
664 return error, blacklisted, removable, is_cdrom, partitions, medium_found
666 def removeHotplugPartition(self, device):
667 mountpoint = self.getAutofsMountpoint(device)
668 for x in self.partitions[:]:
669 if x.mountpoint == mountpoint:
670 self.partitions.remove(x)
671 self.on_partition_list_change("remove", x)
673 if l and not device[l-1].isdigit():
675 if hdd.device == device:
679 SystemInfo["Harddisk"] = len(self.hdd) > 0
689 hdd = hd.model() + " - " + hd.bus()
692 hdd += " (" + cap + ")"
693 list.append((hdd, hd))
699 def getMountedPartitions(self, onlyhotplug = False):
700 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
701 devs = set([x.device for x in parts])
702 for devname in devs.copy():
705 dev, part = self.splitDeviceName(devname)
706 if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
709 # return all devices which are not removed due to being a wholedisk when a partition exists
710 return [x for x in parts if not x.device or x.device in devs]
712 def splitDeviceName(self, devname):
713 # 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.
719 return dev, part and int(part) or 0
721 def getUserfriendlyDeviceName(self, dev, phys):
722 dev, part = self.splitDeviceName(dev)
723 description = "External Storage %s" % dev
724 have_model_descr = False
726 description = readFile("/sys" + phys + "/model")
727 have_model_descr = True
729 print "couldn't read model: ", s
730 from Tools.HardwareInfo import HardwareInfo
731 if dev.find('sr') == 0 and dev[2].isdigit():
732 devicedb = DEVICEDB_SR
735 for physdevprefix, pdescription in devicedb.get(HardwareInfo().device_name,{}).items():
736 if phys.startswith(physdevprefix):
738 description = pdescription + ' - ' + description
740 description = pdescription
741 # not wholedisk and not partition 1
742 if part and part != 1:
743 description += " (Partition %d)" % part
746 def addMountedPartition(self, device, desc):
747 already_mounted = False
748 for x in self.partitions[:]:
749 if x.mountpoint == device:
750 already_mounted = True
751 if not already_mounted:
752 self.partitions.append(Partition(mountpoint = device, description = desc))
754 def removeMountedPartition(self, mountpoint):
755 for x in self.partitions[:]:
756 if x.mountpoint == mountpoint:
757 self.partitions.remove(x)
758 self.on_partition_list_change("remove", x)
760 harddiskmanager = HarddiskManager()