DVDBurn fix capacity report for full dual layer media in Media Toolbox
[enigma2.git] / lib / python / Components / Harddisk.py
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
5 import time
6 from Components.Console import Console
7
8 def readFile(filename):
9         file = open(filename)
10         data = file.read().strip()
11         file.close()
12         return data
13
14 class Harddisk:
15         DEVTYPE_UDEV = 0
16         DEVTYPE_DEVFS = 1
17
18         def __init__(self, device):
19                 self.device = device
20
21                 if access("/dev/.udev", 0):
22                         self.type = self.DEVTYPE_UDEV
23                 elif access("/dev/.devfsd", 0):
24                         self.type = self.DEVTYPE_DEVFS
25                 else:
26                         print "Unable to determine structure of /dev"
27
28                 self.max_idle_time = 0
29                 self.idle_running = False
30                 self.timer = None
31
32                 self.dev_path = ''
33                 self.disk_path = ''
34                 self.phys_path = path.realpath(self.sysfsPath('device'))
35
36                 if self.type == self.DEVTYPE_UDEV:
37                         self.dev_path = '/dev/' + self.device
38                         self.disk_path = self.dev_path
39
40                 elif self.type == self.DEVTYPE_DEVFS:
41                         tmp = readFile(self.sysfsPath('dev')).split(':')
42                         s_major = int(tmp[0])
43                         s_minor = int(tmp[1])
44                         for disc in listdir("/dev/discs"):
45                                 dev_path = path.realpath('/dev/discs/' + disc)
46                                 disk_path = dev_path + '/disc'
47                                 try:
48                                         rdev = stat(disk_path).st_rdev
49                                 except OSError:
50                                         continue
51                                 if s_major == major(rdev) and s_minor == minor(rdev):
52                                         self.dev_path = dev_path
53                                         self.disk_path = disk_path
54                                         break
55
56                 print "new Harddisk", self.device, '->', self.dev_path, '->', self.disk_path
57                 self.startIdle()
58
59         def __lt__(self, ob):
60                 return self.device < ob.device
61
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
67
68         def sysfsPath(self, filename):
69                 return path.realpath('/sys/block/' + self.device + '/' + filename)
70
71         def stop(self):
72                 if self.timer:
73                         self.timer.stop()
74                         self.timer.callback.remove(self.runIdle)
75
76         def bus(self):
77                 # CF (7025 specific)
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
82
83                 internal = "pci" in self.phys_path
84
85                 if ide_cf:
86                         ret = "External (CF)"
87                 elif internal:
88                         ret = "Internal"
89                 else:
90                         ret = "External"
91                 return ret
92
93         def diskSize(self):
94                 line = readFile(self.sysfsPath('size'))
95                 try:
96                         cap = int(line)
97                 except:
98                         return 0;
99                 return cap / 1000 * 512 / 1000
100
101         def capacity(self):
102                 cap = self.diskSize()
103                 if cap == 0:
104                         return ""
105                 return "%d.%03d GB" % (cap/1000, cap%1000)
106
107         def model(self):
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 + ')'
114                 else:
115                         assert False, "no hdX or sdX"
116
117         def free(self):
118                 try:
119                         mounts = open("/proc/mounts")
120                 except IOError:
121                         return -1
122
123                 lines = mounts.readlines()
124                 mounts.close()
125
126                 for line in lines:
127                         parts = line.strip().split(" ")
128                         if path.realpath(parts[0]).startswith(self.dev_path):
129                                 try:
130                                         stat = statvfs(parts[1])
131                                 except OSError:
132                                         continue
133                                 return stat.f_bfree/1000 * stat.f_bsize/1000
134
135                 return -1
136
137         def numPartitions(self):
138                 numPart = -1
139                 if self.type == self.DEVTYPE_UDEV:
140                         try:
141                                 devdir = listdir('/dev')
142                         except OSError:
143                                 return -1
144                         for filename in devdir:
145                                 if filename.startswith(self.device):
146                                         numPart += 1
147
148                 elif self.type == self.DEVTYPE_DEVFS:
149                         try:
150                                 idedir = listdir(self.dev_path)
151                         except OSError:
152                                 return -1
153                         for filename in idedir:
154                                 if filename.startswith("disc"):
155                                         numPart += 1
156                                 if filename.startswith("part"):
157                                         numPart += 1
158                 return numPart
159
160         def unmount(self):
161                 try:
162                         mounts = open("/proc/mounts")
163                 except IOError:
164                         return -1
165
166                 lines = mounts.readlines()
167                 mounts.close()
168
169                 cmd = "/bin/umount"
170
171                 for line in lines:
172                         parts = line.strip().split(" ")
173                         if path.realpath(parts[0]).startswith(self.dev_path):
174                                 cmd = ' ' . join([cmd, parts[1]])
175
176                 res = system(cmd)
177                 return (res >> 8)
178
179         def createPartition(self):
180                 cmd = 'printf "0,\n;\n;\n;\ny\n" | /sbin/sfdisk -f ' + self.disk_path
181                 res = system(cmd)
182                 return (res >> 8)
183
184         def mkfs(self):
185                 cmd = "/sbin/mkfs.ext3 "
186                 if self.diskSize() > 4 * 1024:
187                         cmd += "-T largefile "
188                 cmd += "-m0 -O dir_index " + self.partitionPath("1")
189                 res = system(cmd)
190                 return (res >> 8)
191
192         def mount(self):
193                 try:
194                         fstab = open("/etc/fstab")
195                 except IOError:
196                         return -1
197
198                 lines = fstab.readlines()
199                 fstab.close()
200
201                 res = -1
202                 for line in lines:
203                         parts = line.strip().split(" ")
204                         if path.realpath(parts[0]) == self.partitionPath("1"):
205                                 cmd = "/bin/mount -t ext3 " + parts[0]
206                                 res = system(cmd)
207                                 break
208
209                 return (res >> 8)
210
211         def createMovieFolder(self):
212                 try:
213                         makedirs(resolveFilename(SCOPE_HDD))
214                 except OSError:
215                         return -1
216                 return 0
217
218         def fsck(self):
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")
222                 res = system(cmd)
223                 return (res >> 8)
224
225         def killPartition(self, n):
226                 part = self.partitionPath(n)
227
228                 if access(part, 0):
229                         cmd = '/bin/dd bs=512 count=3 if=/dev/zero of=' + part
230                         res = system(cmd)
231                 else:
232                         res = 0
233
234                 return (res >> 8)
235
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")]
237
238         def initialize(self):
239                 self.unmount()
240
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
245                 # ext3 at least.
246                 self.killPartition("1")
247
248                 if self.createPartition() != 0:
249                         return -1
250
251                 if self.mkfs() != 0:
252                         return -2
253
254                 if self.mount() != 0:
255                         return -3
256
257                 if self.createMovieFolder() != 0:
258                         return -4
259
260                 return 0
261
262         def check(self):
263                 self.unmount()
264
265                 res = self.fsck()
266                 if res & 2 == 2:
267                         return -6
268
269                 if res & 4 == 4:
270                         return -7
271
272                 if res != 0 and res != 1:
273                         # A sum containing 1 will also include a failure
274                         return -5
275
276                 if self.mount() != 0:
277                         return -3
278
279                 return 0
280
281         def getDeviceDir(self):
282                 return self.dev_path
283
284         def getDeviceName(self):
285                 return self.disk_path
286
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.
292         def readStats(self):
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)
296
297         def startIdle(self):
298                 self.last_access = time.time()
299                 self.last_stat = 0
300                 self.is_sleeping = False
301                 from enigma import eTimer
302
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
309
310         def runIdle(self):
311                 if not self.max_idle_time:
312                         return
313                 t = time.time()
314
315                 idle_time = t - self.last_access
316
317                 stats = self.readStats()
318                 print "nr_read", stats[0], "nr_write", stats[1]
319                 l = sum(stats)
320                 print "sum", l, "prev_sum", self.last_stat
321
322                 if l != self.last_stat: # access
323                         print "hdd was accessed since previous check!"
324                         self.last_stat = l
325                         self.last_access = t
326                         idle_time = 0
327                         self.is_sleeping = False
328                 else:
329                         print "hdd IDLE!"
330
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:
333                         self.setSleep()
334                         self.is_sleeping = True
335
336         def setSleep(self):
337                 Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
338
339         def setIdleTime(self, idle):
340                 self.max_idle_time = idle
341                 if self.idle_running:
342                         if not idle:
343                                 self.timer.stop()
344                         else:
345                                 self.timer.start(idle * 100, False)  # poll 10 times per period.
346
347         def isSleeping(self):
348                 return self.is_sleeping
349
350 class Partition:
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.
356                 self.device = device
357
358         def stat(self):
359                 return statvfs(self.mountpoint)
360
361         def free(self):
362                 try:
363                         s = self.stat()
364                         return s.f_bavail * s.f_bsize
365                 except OSError:
366                         return None
367
368         def total(self):
369                 try:
370                         s = self.stat()
371                         return s.f_blocks * s.f_bsize
372                 except OSError:
373                         return None
374
375         def mounted(self):
376                 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
377                 # TODO: can os.path.ismount be used?
378                 if self.force_mounted:
379                         return True
380
381                 try:
382                         mounts = open("/proc/mounts")
383                 except IOError:
384                         return False
385
386                 lines = mounts.readlines()
387                 mounts.close()
388
389                 for line in lines:
390                         if line.split(' ')[1] == self.mountpoint:
391                                 return True
392                 return False
393
394 DEVICEDB =  \
395         {"dm8000":
396                 {
397                         # dm8000:
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",
402                 },
403         "dm800":
404         {
405                 # dm800:
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",
408         },
409         "dm7025":
410         {
411                 # dm7025:
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"
414         }
415         }
416
417 class HarddiskManager:
418         def __init__(self):
419                 self.hdd = [ ]
420                 self.cd = ""
421                 self.partitions = [ ]
422
423                 self.on_partition_list_change = CList()
424
425                 self.enumerateBlockDevices()
426
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.)
432                 p = [
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"))
441                                 ]
442
443                 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
444
445         def getBlockDevInfo(self, blockdev):
446                 devpath = "/sys/block/" + blockdev
447                 error = False
448                 removable = False
449                 blacklisted = False
450                 is_cdrom = False
451                 partitions = []
452                 try:
453                         removable = bool(int(readFile(devpath + "/removable")))
454                         dev = int(readFile(devpath + "/dev").split(':')[0])
455                         if dev in (7, 31): # loop, mtdblock
456                                 blacklisted = True
457                         if blockdev[0:2] == 'sr':
458                                 is_cdrom = True
459                         if blockdev[0:2] == 'hd':
460                                 try:
461                                         media = readFile("/proc/ide/%s/media" % blockdev)
462                                         if "cdrom" in media:
463                                                 is_cdrom = True
464                                 except IOError:
465                                         error = True
466                         # check for partitions
467                         if not is_cdrom:
468                                 for partition in listdir(devpath):
469                                         if partition[0:len(blockdev)] != blockdev:
470                                                 continue
471                                         partitions.append(partition)
472                         else:
473                                 self.cd = blockdev
474                 except IOError:
475                         error = True
476                 # check for medium
477                 medium_found = True
478                 try:
479                         open("/dev/" + blockdev).close()
480                 except IOError, err:
481                         if err.errno == 159: # no medium present
482                                 medium_found = False
483
484                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
485
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, 
491                         if error:
492                                 print "error querying properties"
493                         elif blacklisted:
494                                 print "blacklisted"
495                         elif not medium_found:
496                                 print "no medium"
497                         else:
498                                 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
499
500                                 self.addHotplugPartition(blockdev)
501                                 for part in partitions:
502                                         self.addHotplugPartition(part)
503
504         def getAutofsMountpoint(self, device):
505                 return "/autofs/%s/" % (device)
506
507         def addHotplugPartition(self, device, physdev = None):
508                 if not physdev:
509                         dev, part = self.splitDeviceName(device)
510                         try:
511                                 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
512                         except OSError:
513                                 physdev = dev
514                                 print "couldn't determine blockdev physdev for device", device
515
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)
519
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)
523
524                 # see if this is a harddrive
525                 l = len(device)
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))
530                                 self.hdd.sort()
531                                 SystemInfo["Harddisk"] = len(self.hdd) > 0
532
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)
539                 l = len(device)
540                 if l and not device[l-1].isdigit():
541                         for hdd in self.hdd:
542                                 if hdd.device == device:
543                                         hdd.stop()
544                                         self.hdd.remove(hdd)
545                                         break
546                         SystemInfo["Harddisk"] = len(self.hdd) > 0
547
548         def HDDCount(self):
549                 return len(self.hdd)
550
551         def HDDList(self):
552                 list = [ ]
553                 for hd in self.hdd:
554                         hdd = hd.model() + " - " + hd.bus()
555                         cap = hd.capacity()
556                         if cap != "":
557                                 hdd += " (" + cap + ")"
558                         list.append((hdd, hd))
559                 return list
560
561         def getCD(self):
562                 return self.cd
563
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():
568                         if not devname:
569                                 continue
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
572                                 devs.remove(dev)
573
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]
576
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.
579                 dev = devname[:3]
580                 part = devname[3:]
581                 for p in part:
582                         if not p.isdigit():
583                                 return devname, 0
584                 return dev, part and int(part) or 0
585
586         def getUserfriendlyDeviceName(self, dev, phys):
587                 dev, part = self.splitDeviceName(dev)
588                 description = "External Storage %s" % dev
589                 try:
590                         description = readFile("/sys" + phys + "/model")
591                 except IOError, s:
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
597
598                 # not wholedisk and not partition 1
599                 if part and part != 1:
600                         description += " (Partition %d)" % part
601                 return description
602
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))
610
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)
616
617 harddiskmanager = HarddiskManager()