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', ' ')
33 cmd = 'sfdisk --version'
34 lines = popen(cmd).readlines()
36 if l.find("sfdisk from util-linux") != -1:
37 ver = l.split()[-1].strip()
42 ver = '.'.join(vs[:2])
46 print "[CheckSfdiskVer] check parted version Failed!"
50 def enableUdevEvent(enable = True):
52 option = '--start-exec-queue'
54 option = '--stop-exec-queue'
55 cmd = "udevadm control %s" % option
63 def __init__(self, device):
66 if access("/dev/.udev", 0):
67 self.type = DEVTYPE_UDEV
68 elif access("/dev/.devfsd", 0):
69 self.type = DEVTYPE_DEVFS
71 print "Unable to determine structure of /dev"
73 self.max_idle_time = 0
74 self.idle_running = False
79 self.mount_path = None
80 self.mount_device = None
81 self.phys_path = path.realpath(self.sysfsPath('device'))
83 if self.type == DEVTYPE_UDEV:
84 self.dev_path = '/dev/' + self.device
85 self.disk_path = self.dev_path
87 elif self.type == DEVTYPE_DEVFS:
88 tmp = readFile(self.sysfsPath('dev')).split(':')
91 for disc in listdir("/dev/discs"):
92 dev_path = path.realpath('/dev/discs/' + disc)
93 disk_path = dev_path + '/disc'
95 rdev = stat(disk_path).st_rdev
98 if s_major == major(rdev) and s_minor == minor(rdev):
99 self.dev_path = dev_path
100 self.disk_path = disk_path
103 print "new Harddisk", self.device, '->', self.dev_path, '->', self.disk_path
106 def __lt__(self, ob):
107 return self.device < ob.device
109 def partitionPath(self, n):
110 if self.type == DEVTYPE_UDEV:
111 return self.dev_path + n
112 elif self.type == DEVTYPE_DEVFS:
113 return self.dev_path + '/part' + n
115 def sysfsPath(self, filename):
116 return path.realpath('/sys/block/' + self.device + '/' + filename)
121 self.timer.callback.remove(self.runIdle)
125 if self.type == DEVTYPE_UDEV:
126 ide_cf = False # FIXME
127 elif self.type == DEVTYPE_DEVFS:
128 ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
130 internal = "pci" in self.phys_path
133 ret = "External (CF)"
142 line = readFile(self.sysfsPath('size'))
144 harddiskmanager.removeHotplugPartition(self.device)
145 print "error remove",self.device
151 return cap / 1000 * 512 / 1000
154 cap = self.diskSize()
157 return "%d.%03d GB" % (cap/1000, cap%1000)
161 if self.device[:2] == "hd":
162 return readFile('/proc/ide/' + self.device + '/model')
163 elif self.device[:2] == "sd":
164 vendor = readFile(self.sysfsPath('device/vendor'))
165 model = readFile(self.sysfsPath('device/model'))
166 return vendor + '(' + model + ')'
168 assert False, "no hdX or sdX"
170 harddiskmanager.removeHotplugPartition(self.device)
171 print "error remove",self.device
176 mounts = open("/proc/mounts")
180 lines = mounts.readlines()
184 parts = line.strip().split(" ")
185 real_path = path.realpath(parts[0])
186 if not real_path[-1].isdigit():
189 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
190 stat = statvfs(parts[1])
191 return stat.f_bfree/1000 * stat.f_bsize/1000
196 def numPartitions(self):
198 if self.type == DEVTYPE_UDEV:
200 devdir = listdir('/dev')
203 for filename in devdir:
204 if filename.startswith(self.device):
207 elif self.type == DEVTYPE_DEVFS:
209 idedir = listdir(self.dev_path)
212 for filename in idedir:
213 if filename.startswith("disc"):
215 if filename.startswith("part"):
219 def mountDevice(self):
220 for parts in getProcMounts():
221 if path.realpath(parts[0]).startswith(self.dev_path):
222 self.mount_device = parts[0]
223 self.mount_path = parts[1]
227 if self.mount_path is None:
228 return self.mountDevice()
229 return self.mount_path
233 mounts = open("/proc/mounts")
237 lines = mounts.readlines()
243 parts = line.strip().split(" ")
244 real_path = path.realpath(parts[0])
245 if not real_path[-1].isdigit():
248 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
249 cmd = ' ' . join([cmd, parts[1]])
258 def checkPartionPath(self, path):
260 for i in range(1,10):
261 if os.path.exists(path):
266 def updatePartition(self):
267 sfdiskVer = CheckSfdiskVer()
268 if sfdiskVer < 2.26: # sfdisk -R option is deprecated at sfdiskVer >= 2.26
269 cmd = 'sfdisk -R %s; sleep 5' % (self.disk_path)
270 elif path.exists('/usr/sbin/partprobe'):
271 cmd = 'partprobe %s; sleep 5' % (self.disk_path)
272 elif path.exists('/usr/sbin/partx'):
273 cmd = 'partx -u %s' % (self.disk_path)
282 def createPartition(self):
283 def CheckPartedVer():
284 cmd = 'parted --version'
285 lines = popen(cmd).readlines()
287 if l.find("parted (GNU parted)") != -1:
288 ver = l.split()[3].strip()
293 print "[CheckPartedVer] check parted version Failed!"
297 disk_size = self.diskSize()
299 if disk_size > 2.2 * 1000 * 1000: # if 2.2 TB
301 partedVer = CheckPartedVer()
302 if partedVer >= 2.1: # align option is supported in version 2.1 or later
303 setAlign = "--align optimal"
304 cmd = 'parted %s %s --script mklabel gpt mkpart disk ext2 0%% 100%%' % ( setAlign, self.disk_path )
307 sfdiskVer = CheckSfdiskVer()
308 if sfdiskVer <= 2.21:
309 cmd = 'printf "8,\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS ' + self.disk_path
311 cmd = 'printf "8,\nquit\nY\n" | sfdisk -f -uS ' + self.disk_path
316 if not self.checkPartionPath(self.partitionPath("1")):
317 print "no exist : ", self.partitionPath("1")
323 if self.diskSize() > 4 * 1024:
324 cmd += "-T largefile "
325 cmd += "-m0 -O dir_index " + self.partitionPath("1")
332 fstab = open("/etc/fstab")
336 lines = fstab.readlines()
342 parts = line.strip().split(" ")
343 real_path = path.realpath(parts[0])
344 if not real_path[-1].isdigit():
347 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
348 mount_point = parts[0]
353 if mount_point is None:
356 cmd = "mount -t ext3 " + mount_point
363 if self.createMovieFolder() != 0:
368 def createMovieFolder(self):
370 if not fileExists("/hdd", 0):
371 print "not found /hdd"
372 system("ln -s /media/hdd /hdd")
374 makedirs(resolveFilename(SCOPE_HDD))
380 # We autocorrect any failures
381 # TODO: we could check if the fs is actually ext3
382 cmd = "fsck.ext3 -f -p " + self.partitionPath("1")
386 def killPartition(self, n):
387 part = self.partitionPath(n)
390 cmd = 'dd bs=512 count=3 if=/dev/zero of=' + part
398 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"), _("partx failed")]
400 def initialize(self):
401 enableUdevEvent(False)
404 # Udev tries to mount the partition immediately if there is an
405 # old filesystem on it when fdisk reloads the partition table.
406 # To prevent that, we overwrite the first 3 sectors of the
407 # partition, if the partition existed before. That's enough for
409 self.killPartition("1")
411 if self.updatePartition() != 0:
414 elif self.createPartition() != 0:
417 elif self.updatePartition() != 0:
420 elif self.mkfs() != 0:
426 enableUdevEvent(True)
439 if res != 0 and res != 1:
440 # A sum containing 1 will also include a failure
443 if self.mount() != 0:
448 def getDeviceDir(self):
451 def getDeviceName(self):
452 return self.disk_path
454 # the HDD idle poll daemon.
455 # as some harddrives have a buggy standby timer, we are doing this by hand here.
456 # first, we disable the hardware timer. then, we check every now and then if
457 # any access has been made to the disc. If there has been no access over a specifed time,
458 # we set the hdd into standby.
461 l = open("/sys/block/%s/stat" % self.device).read()
464 (nr_read, _, _, _, nr_write) = l.split()[:5]
465 return int(nr_read), int(nr_write)
468 self.last_access = time.time()
470 self.is_sleeping = False
471 from enigma import eTimer
473 # disable HDD standby timer
474 Console().ePopen(("hdparm", "hdparm", "-S0", self.disk_path))
475 self.timer = eTimer()
476 self.timer.callback.append(self.runIdle)
477 self.idle_running = True
478 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
481 if not self.max_idle_time:
485 idle_time = t - self.last_access
487 stats = self.readStats()
492 print "nr_read", stats[0], "nr_write", stats[1]
494 print "sum", l, "prev_sum", self.last_stat
496 if l != self.last_stat and l >= 0: # access
497 print "hdd was accessed since previous check!"
501 self.is_sleeping = False
505 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
506 if idle_time >= self.max_idle_time and not self.is_sleeping:
508 self.is_sleeping = True
511 Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
513 def setIdleTime(self, idle):
514 self.max_idle_time = idle
515 if self.idle_running:
519 self.timer.start(idle * 100, False) # poll 10 times per period.
521 def isSleeping(self):
522 return self.is_sleeping
525 def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
526 self.mountpoint = mountpoint
527 self.description = description
528 self.force_mounted = force_mounted
529 self.is_hotplug = force_mounted # so far; this might change.
533 return statvfs(self.mountpoint)
538 return s.f_bavail * s.f_bsize
545 return s.f_blocks * s.f_bsize
550 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
551 # TODO: can os.path.ismount be used?
552 if self.force_mounted:
556 mounts = open("/proc/mounts")
560 lines = mounts.readlines()
564 if line.split(' ')[1] == self.mountpoint:
571 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("DVD Drive"),
572 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("DVD Drive"),
573 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host3/target3:0:0/3:0:0:0": _("DVD Drive"),
586 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
587 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": _("Back, upper USB Slot"),
588 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": _("Back, lower USB Slot"),
589 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
590 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/": _("Internal USB Slot"),
591 "/devices/platform/brcm-ohci-1.1/usb4/4-1/4-1:1.0/": _("Internal USB Slot"),
595 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": "Upper USB Slot",
596 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": "Lower USB Slot",
600 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "CF Card Slot", #hdc
601 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
605 class HarddiskManager:
609 self.partitions = [ ]
610 self.devices_scanned_on_init = [ ]
612 self.on_partition_list_change = CList()
614 self.enumerateBlockDevices()
616 # currently, this is just an enumeration of what's possible,
617 # this probably has to be changed to support automount stuff.
618 # still, if stuff is mounted into the correct mountpoints by
619 # external tools, everything is fine (until somebody inserts
620 # a second usb stick.)
622 ("/media/hdd", _("Harddisk")),
623 ("/media/card", _("Card")),
624 ("/media/cf", _("Compact Flash")),
625 ("/media/mmc1", _("MMC Card")),
626 ("/media/net", _("Network Mount")),
627 ("/media/ram", _("Ram Disk")),
628 ("/media/usb", _("USB Stick")),
629 ("/", _("Internal Flash"))
632 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
634 def getBlockDevInfo(self, blockdev):
635 devpath = "/sys/block/" + blockdev
642 removable = bool(int(readFile(devpath + "/removable")))
643 dev = int(readFile(devpath + "/dev").split(':')[0])
644 if dev in (7, 31, 179): # loop, mtdblock, mmcblock
646 if blockdev[0:2] == 'sr':
648 if blockdev[0:2] == 'hd':
650 media = readFile("/proc/ide/%s/media" % blockdev)
655 # check for partitions
657 for partition in listdir(devpath):
658 if partition[0:len(blockdev)] != blockdev:
660 partitions.append(partition)
668 open("/dev/" + blockdev).close()
670 if err.errno == 159: # no medium present
673 return error, blacklisted, removable, is_cdrom, partitions, medium_found
675 def enumerateBlockDevices(self):
676 print "enumerating block devices..."
677 for blockdev in listdir("/sys/block"):
678 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.addHotplugPartition(blockdev)
679 if not error and not blacklisted:
681 for part in partitions:
682 self.addHotplugPartition(part)
683 self.devices_scanned_on_init.append((blockdev, removable, is_cdrom, medium_found))
685 def getAutofsMountpoint(self, device):
686 return "/autofs/%s/" % (device)
689 def is_hard_mounted(self, device):
690 mounts = file('/proc/mounts').read().split('\n')
692 if x.find('/autofs') == -1 and x.find(device) != -1:
696 def addHotplugPartition(self, device, physdev = None):
698 dev, part = self.splitDeviceName(device)
700 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
703 print "couldn't determine blockdev physdev for device", device
705 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
706 print "found block device '%s':" % device,
712 print "error querying properties"
713 elif not medium_found:
716 print "ok, removable=%s, cdrom=%s, partitions=%s" % (removable, is_cdrom, partitions)
720 # see if this is a harddrive
721 if not device[l-1].isdigit() and not removable and not is_cdrom:
722 self.hdd.append(Harddisk(device))
724 SystemInfo["Harddisk"] = len(self.hdd) > 0
726 if (not removable or medium_found) and not self.is_hard_mounted(device):
727 # device is the device name, without /dev
728 # physdev is the physical device path, which we (might) use to determine the userfriendly name
729 description = self.getUserfriendlyDeviceName(device, physdev)
730 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
731 self.partitions.append(p)
732 self.on_partition_list_change("add", p)
734 return error, blacklisted, removable, is_cdrom, partitions, medium_found
736 def removeHotplugPartition(self, device):
737 mountpoint = self.getAutofsMountpoint(device)
738 for x in self.partitions[:]:
739 if x.mountpoint == mountpoint:
740 self.partitions.remove(x)
741 self.on_partition_list_change("remove", x)
743 if l and not device[l-1].isdigit():
745 if hdd.device == device:
749 SystemInfo["Harddisk"] = len(self.hdd) > 0
759 hdd = hd.model() + " - " + hd.bus()
762 hdd += " (" + cap + ")"
763 list.append((hdd, hd))
769 def getMountedPartitions(self, onlyhotplug = False):
770 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
771 devs = set([x.device for x in parts])
772 for devname in devs.copy():
775 dev, part = self.splitDeviceName(devname)
776 if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
779 # return all devices which are not removed due to being a wholedisk when a partition exists
780 return [x for x in parts if not x.device or x.device in devs]
782 def splitDeviceName(self, devname):
783 # 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.
789 return dev, part and int(part) or 0
791 def getUserfriendlyDeviceName(self, dev, phys):
792 dev, part = self.splitDeviceName(dev)
793 description = "External Storage %s" % dev
794 have_model_descr = False
796 description = readFile("/sys" + phys + "/model")
797 have_model_descr = True
799 print "couldn't read model: ", s
800 from Tools.HardwareInfo import HardwareInfo
801 if dev.find('sr') == 0 and dev[2].isdigit():
802 devicedb = DEVICEDB_SR
805 for physdevprefix, pdescription in devicedb.get(HardwareInfo().device_name,{}).items():
806 if phys.startswith(physdevprefix):
808 description = pdescription + ' - ' + description
810 description = pdescription
811 # not wholedisk and not partition 1
812 if part and part != 1:
813 description += " (Partition %d)" % part
816 def addMountedPartition(self, device, desc):
817 already_mounted = False
818 for x in self.partitions[:]:
819 if x.mountpoint == device:
820 already_mounted = True
821 if not already_mounted:
822 self.partitions.append(Partition(mountpoint = device, description = desc))
824 def removeMountedPartition(self, mountpoint):
825 for x in self.partitions[:]:
826 if x.mountpoint == mountpoint:
827 self.partitions.remove(x)
828 self.on_partition_list_change("remove", x)
830 harddiskmanager = HarddiskManager()