Merge branch 'master' of fraxinas@git.opendreambox.org:/git/enigma2
[enigma2.git] / lib / python / Components / Harddisk.py
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
5 import time
6 from Components.Console import Console
7
8 def tryOpen(filename):
9         try:
10                 procFile = open(filename)
11         except IOError:
12                 return ""
13         return procFile
14
15 class Harddisk:
16         def __init__(self, device):
17                 self.device = device
18                 procfile = tryOpen("/sys/block/"+self.device+"/dev")
19                 tmp = procfile.readline().split(':')
20                 s_major = int(tmp[0])
21                 s_minor = int(tmp[1])
22                 self.max_idle_time = 0
23                 self.idle_running = False
24                 self.timer = None
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
35                                 self.startIdle()
36                                 break
37
38         def __lt__(self, ob):
39                 return self.device < ob.device
40
41         def stop(self):
42                 if self.timer:
43                         self.timer.stop()
44                         self.timer.callback.remove(self.runIdle)
45
46         def bus(self):
47                 ide_cf = self.device[:2] == "hd" and "host0" not in self.devidex2 # 7025 specific
48                 internal = self.device[:2] == "hd"
49                 if ide_cf:
50                         ret = "External (CF)"
51                 elif internal:
52                         ret = "Internal"
53                 else:
54                         ret = "External"
55                 return ret
56
57         def diskSize(self):
58                 procfile = tryOpen("/sys/block/"+self.device+"/size")
59                 if procfile == "":
60                         return 0
61                 line = procfile.readline()
62                 procfile.close()
63                 try:
64                         cap = int(line)
65                 except:
66                         return 0;
67                 return cap / 1000 * 512 / 1000
68
69         def capacity(self):
70                 cap = self.diskSize()
71                 if cap == 0:
72                         return ""
73                 return "%d.%03d GB" % (cap/1024, cap%1024)
74
75         def model(self):
76                 if self.device[:2] == "hd":
77                         procfile = tryOpen("/proc/ide/"+self.device+"/model")
78                         if procfile == "":
79                                 return ""
80                         line = procfile.readline()
81                         procfile.close()
82                         return line.strip()
83                 elif self.device[:2] == "sd":
84                         procfile = tryOpen("/sys/block/"+self.device+"/device/vendor")
85                         if procfile == "":
86                                 return ""
87                         vendor = procfile.readline().strip()
88                         procfile.close()
89                         procfile = tryOpen("/sys/block/"+self.device+"/device/model")
90                         model = procfile.readline().strip()
91                         return vendor+'('+model+')'
92                 else:
93                         assert False, "no hdX or sdX"
94
95         def free(self):
96                 procfile = tryOpen("/proc/mounts")
97                 
98                 if procfile == "":
99                         return -1
100
101                 free = -1
102                 while 1:
103                         line = procfile.readline()
104                         if line == "":
105                                 break
106                         if line.startswith(self.devidex) or line.startswith(self.devidex2):
107                                 parts = line.strip().split(" ")
108                                 try:
109                                         stat = statvfs(parts[1])
110                                 except OSError:
111                                         continue
112                                 free = stat.f_bfree/1000 * stat.f_bsize/1000
113                                 break
114                 procfile.close()
115                 return free
116
117         def numPartitions(self):
118                 try:
119                         idedir = listdir(self.devidex)
120                 except OSError:
121                         return -1
122                 numPart = -1
123                 for filename in idedir:
124                         if filename.startswith("disc"):
125                                 numPart += 1
126                         if filename.startswith("part"):
127                                 numPart += 1
128                 return numPart
129
130         def unmount(self):
131                 procfile = tryOpen("/proc/mounts")
132
133                 if procfile == "":
134                         return -1
135
136                 cmd = "/bin/umount"
137
138                 for line in procfile:
139                         if line.startswith(self.devidex) or line.startswith(self.devidex2):
140                                 parts = line.split()
141                                 cmd = ' '.join([cmd, parts[1]])
142
143                 procfile.close()
144
145                 res = system(cmd)
146                 return (res >> 8)
147
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")
152                 sfdisk.close()
153                 return 0
154
155         def mkfs(self):
156                 cmd = "/sbin/mkfs.ext3 "
157                 if self.diskSize() > 4 * 1024:
158                         cmd += "-T largefile "
159                 cmd += "-m0 " + self.devidex + "part1"
160                 res = system(cmd)
161                 return (res >> 8)
162
163         def mount(self):
164                 cmd = "/bin/mount -t ext3 " + self.devidex + "part1"
165                 res = system(cmd)
166                 return (res >> 8)
167
168         def createMovieFolder(self):
169                 try:
170                         makedirs(resolveFilename(SCOPE_HDD))
171                 except OSError:
172                         return -1
173                 return 0
174
175         def fsck(self):
176                 # We autocorrect any failures
177                 # TODO: we could check if the fs is actually ext3
178                 cmd = "/sbin/fsck.ext3 -f -p " + self.devidex + "part1"
179                 res = system(cmd)
180                 return (res >> 8)
181
182         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")]
183
184         def initialize(self):
185                 self.unmount()
186
187                 if self.createPartition() != 0:
188                         return -1
189
190                 if self.mkfs() != 0:
191                         return -2
192
193                 if self.mount() != 0:
194                         return -3
195
196                 if self.createMovieFolder() != 0:
197                         return -4
198
199                 return 0
200
201         def check(self):
202                 self.unmount()
203
204                 res = self.fsck()
205                 if res & 2 == 2:
206                         return -6
207
208                 if res & 4 == 4:
209                         return -7
210
211                 if res != 0 and res != 1:
212                         # A sum containing 1 will also include a failure
213                         return -5
214
215                 if self.mount() != 0:
216                         return -3
217
218                 return 0
219         
220         def getDeviceDir(self):
221                 return self.devidex
222         
223         def getDeviceName(self):
224                 return self.getDeviceDir() + "disc"
225
226         # the HDD idle poll daemon.
227         # as some harddrives have a buggy standby timer, we are doing this by hand here.
228         # first, we disable the hardware timer. then, we check every now and then if
229         # any access has been made to the disc. If there has been no access over a specifed time,
230         # we set the hdd into standby.
231         def readStats(self):
232                 l = open("/sys/block/%s/stat" % self.device).read()
233                 nr_read = int(l[:8].strip())
234                 nr_write = int(l[4*9:4*9+8].strip())
235                 return nr_read, nr_write
236
237         def startIdle(self):
238                 self.last_access = time.time()
239                 self.last_stat = 0
240                 self.is_sleeping = False
241                 from enigma import eTimer
242
243                 # disable HDD standby timer
244                 Console().ePopen(("hdparm", "hdparm", "-S0", (self.devidex + "disc")))
245                 self.timer = eTimer()
246                 self.timer.callback.append(self.runIdle)
247                 self.idle_running = True
248                 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
249
250         def runIdle(self):
251                 if not self.max_idle_time:
252                         return
253                 t = time.time()
254
255                 idle_time = t - self.last_access
256
257                 stats = self.readStats()
258                 print "nr_read", stats[0], "nr_write", stats[1]
259                 l = sum(stats)
260                 print "sum", l, "prev_sum", self.last_stat
261
262                 if l != self.last_stat: # access
263                         print "hdd was accessed since previous check!"
264                         self.last_stat = l
265                         self.last_access = t
266                         idle_time = 0
267                         self.is_sleeping = False
268                 else:
269                         print "hdd IDLE!"
270
271                 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
272                 if idle_time >= self.max_idle_time and not self.is_sleeping:
273                         self.setSleep()
274                         self.is_sleeping = True
275
276         def setSleep(self):
277                 Console().ePopen(("hdparm", "hdparm", "-y", (self.devidex + "disc")))
278
279         def setIdleTime(self, idle):
280                 self.max_idle_time = idle
281                 if self.idle_running:
282                         if not idle:
283                                 self.timer.stop()
284                         else:
285                                 self.timer.start(idle * 100, False)  # poll 10 times per period.
286
287         def isSleeping(self):
288                 return self.is_sleeping
289
290 class Partition:
291         def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
292                 self.mountpoint = mountpoint
293                 self.description = description
294                 self.force_mounted = force_mounted
295                 self.is_hotplug = force_mounted # so far; this might change.
296                 self.device = device
297
298         def stat(self):
299                 return statvfs(self.mountpoint)
300
301         def free(self):
302                 try:
303                         s = self.stat()
304                         return s.f_bavail * s.f_bsize
305                 except OSError:
306                         return None
307         
308         def total(self):
309                 try:
310                         s = self.stat()
311                         return s.f_blocks * s.f_bsize
312                 except OSError:
313                         return None
314
315         def mounted(self):
316                 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
317                 # TODO: can os.path.ismount be used?
318                 if self.force_mounted:
319                         return True
320                 procfile = tryOpen("/proc/mounts")
321                 for n in procfile.readlines():
322                         if n.split(' ')[1] == self.mountpoint:
323                                 return True
324                 return False
325
326 DEVICEDB =  \
327         {
328                 # dm8000:
329                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": "Front USB Slot",
330                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": "Back, upper USB Slot",
331                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": "Back, lower USB Slot",
332                 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host1/target1:0:0/1:0:0:0": "DVD Drive",
333         }
334
335 class HarddiskManager:
336         def __init__(self):
337                 self.hdd = [ ]
338                 self.cd = ""
339                 self.partitions = [ ]
340                 
341                 self.on_partition_list_change = CList()
342                 
343                 self.enumerateBlockDevices()
344                 
345                 # currently, this is just an enumeration of what's possible,
346                 # this probably has to be changed to support automount stuff.
347                 # still, if stuff is mounted into the correct mountpoints by
348                 # external tools, everything is fine (until somebody inserts 
349                 # a second usb stick.)
350                 p = [
351                                         ("/media/hdd", _("Harddisk")), 
352                                         ("/media/card", _("Card")), 
353                                         ("/media/cf", _("Compact Flash")),
354                                         ("/media/mmc1", _("MMC Card")),
355                                         ("/media/net", _("Network Mount")),
356                                         ("/media/ram", _("Ram Disk")),
357                                         ("/media/usb", _("USB Stick")),
358                                         ("/", _("Internal Flash"))
359                                 ]
360                 
361                 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
362
363         def getBlockDevInfo(self, blockdev):
364                 devpath = "/sys/block/" + blockdev
365                 error = False
366                 removable = False
367                 blacklisted = False
368                 is_cdrom = False
369                 partitions = []
370                 try:
371                         removable = bool(int(open(devpath + "/removable").read()))
372                         dev = int(open(devpath + "/dev").read().split(':')[0])
373                         if dev in (7, 31): # loop, mtdblock
374                                 blacklisted = True
375                         if blockdev[0:2] == 'sr':
376                                 is_cdrom = True
377                         if blockdev[0:2] == 'hd':
378                                 try:
379                                         media = open("/proc/ide/%s/media" % blockdev).read()
380                                         if "cdrom" in media:
381                                                 is_cdrom = True
382                                 except IOError:
383                                         error = True
384                         # check for partitions
385                         if not is_cdrom:
386                                 for partition in listdir(devpath):
387                                         if partition[0:len(blockdev)] != blockdev:
388                                                 continue
389                                         partitions.append(partition)
390                         else:
391                                 self.cd = blockdev
392                 except IOError:
393                         error = True
394                 # check for medium
395                 medium_found = True
396                 try:
397                         open("/dev/" + blockdev).close()
398                 except IOError, err:
399                         if err.errno == 159: # no medium present
400                                 medium_found = False
401                         
402                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
403
404         def enumerateBlockDevices(self):
405                 print "enumerating block devices..."
406                 for blockdev in listdir("/sys/block"):
407                         error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(blockdev)
408                         print "found block device '%s':" % blockdev, 
409                         if error:
410                                 print "error querying properties"
411                         elif blacklisted:
412                                 print "blacklisted"
413                         elif not medium_found:
414                                 print "no medium"
415                         else:
416                                 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
417
418                                 self.addHotplugPartition(blockdev)
419                                 for part in partitions:
420                                         self.addHotplugPartition(part)
421
422         def getAutofsMountpoint(self, device):
423                 return "/autofs/%s/" % (device)
424
425         def addHotplugPartition(self, device, physdev = None):
426                 if not physdev:
427                         dev, part = self.splitDeviceName(device)
428                         try:
429                                 physdev = readlink("/sys/block/" + dev + "/device")[5:]
430                         except OSError:
431                                 physdev = dev
432                                 print "couldn't determine blockdev physdev for device", device
433
434                 # device is the device name, without /dev 
435                 # physdev is the physical device path, which we (might) use to determine the userfriendly name
436                 description = self.getUserfriendlyDeviceName(device, physdev)
437                 
438                 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
439                 self.partitions.append(p)
440                 self.on_partition_list_change("add", p)
441
442                 # see if this is a harddrive
443                 l = len(device)
444                 if l and not device[l-1].isdigit():
445                         error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
446                         if not blacklisted and not removable and not is_cdrom and medium_found:
447                                 self.hdd.append(Harddisk(device))
448                                 self.hdd.sort()
449                                 SystemInfo["Harddisk"] = len(self.hdd) > 0
450
451         def removeHotplugPartition(self, device):
452                 mountpoint = self.getAutofsMountpoint(device)
453                 for x in self.partitions[:]:
454                         if x.mountpoint == mountpoint:
455                                 self.partitions.remove(x)
456                                 self.on_partition_list_change("remove", x)
457                 l = len(device)
458                 if l and not device[l-1].isdigit():
459                         idx = 0
460                         for hdd in self.hdd:
461                                 if hdd.device == device:
462                                         self.hdd[x].stop()
463                                         del self.hdd[idx]
464                                         break
465                         SystemInfo["Harddisk"] = len(self.hdd) > 0
466
467         def HDDCount(self):
468                 return len(self.hdd)
469
470         def HDDList(self):
471                 list = [ ]
472                 for hd in self.hdd:
473                         hdd = hd.model() + " - " + hd.bus()
474                         cap = hd.capacity()
475                         if cap != "":
476                                 hdd += " (" + cap + ")"
477                         list.append((hdd, hd))
478                 return list
479
480         def getCD(self):
481                 return self.cd
482
483         def getMountedPartitions(self, onlyhotplug = False):
484                 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
485                 devs = set([x.device for x in parts])
486                 for devname in devs.copy():
487                         if not devname:
488                                 continue
489                         dev, part = self.splitDeviceName(devname)
490                         if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
491                                 devs.remove(dev)
492
493                 # return all devices which are not removed due to being a wholedisk when a partition exists
494                 return [x for x in parts if not x.device or x.device in devs]
495
496         def splitDeviceName(self, devname):
497                 # 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.
498                 dev = devname[:3]
499                 part = devname[3:]
500                 for p in part:
501                         if not p.isdigit():
502                                 return devname, 0
503                 return dev, part and int(part) or 0
504
505         def getUserfriendlyDeviceName(self, dev, phys):
506                 dev, part = self.splitDeviceName(dev)
507                 description = "External Storage %s" % dev
508                 try:
509                         description = open("/sys" + phys + "/model").read().strip()
510                 except IOError, s:
511                         print "couldn't read model: ", s
512                 for physdevprefix, pdescription in DEVICEDB.items():
513                         if phys.startswith(physdevprefix):
514                                 description = pdescription
515
516                 # not wholedisk and not partition 1
517                 if part and part != 1:
518                         description += " (Partition %d)" % part
519                 return description
520
521         def addMountedPartition(self, device, desc):
522                 already_mounted = False
523                 for x in self.partitions[:]:
524                         if x.mountpoint == device:
525                                 already_mounted = True
526                 if not already_mounted:
527                         self.partitions.append(Partition(mountpoint = device, description = desc))
528                 
529         def removeMountedPartition(self, mountpoint):
530                 for x in self.partitions[:]:
531                         if x.mountpoint == mountpoint:
532                                 self.partitions.remove(x)
533                                 self.on_partition_list_change("remove", x)
534
535 harddiskmanager = HarddiskManager()