"type" -> "tuner_type"... tuner_type is one of "DVB-S" "DVB-T" "DVB-C"
[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 string
6
7 def tryOpen(filename):
8         try:
9                 procFile = open(filename)
10         except IOError:
11                 return ""
12         return procFile
13
14 class Harddisk:
15         def __init__(self, device):
16                 self.device = device
17                 procfile = tryOpen("/sys/block/"+self.device+"/dev")
18                 tmp = procfile.readline().split(':')
19                 s_major = int(tmp[0])
20                 s_minor = int(tmp[1])
21                 for disc in listdir("/dev/discs"):
22                         path = readlink('/dev/discs/'+disc)
23                         devidex = '/dev/discs/'+disc+'/'
24                         devidex2 = '/dev'+path[2:]+'/'
25                         disc = devidex2+'disc'
26                         ret = stat(disc).st_rdev
27                         if s_major == major(ret) and s_minor == minor(ret):
28                                 self.devidex = devidex
29                                 self.devidex2 = devidex2
30                                 print "new Harddisk", device, '->', self.devidex, '->', self.devidex2
31                                 break
32
33         def __lt__(self, ob):
34                 return self.device < ob.device
35
36         def bus(self):
37                 ide_cf = self.device.find("hd") == 0 and self.devidex2.find("host0") == -1 # 7025 specific
38                 internal = self.device.find("hd") == 0
39                 if ide_cf:
40                         ret = "External (CF)"
41                 elif internal:
42                         ret = "Internal"
43                 else:
44                         ret = "External"
45                 return ret
46
47         def diskSize(self):
48                 procfile = tryOpen("/sys/block/"+self.device+"/size")
49                 if procfile == "":
50                         return 0
51                 line = procfile.readline()
52                 procfile.close()
53                 try:
54                         cap = int(line)
55                 except:
56                         return 0;
57                 return cap / 1000 * 512 / 1000
58
59         def capacity(self):
60                 cap = self.diskSize()
61                 if cap == 0:
62                         return ""
63                 return "%d.%03d GB" % (cap/1024, cap%1024)
64
65         def model(self):
66                 if self.device.find("hd") == 0:
67                         procfile = tryOpen("/proc/ide/"+self.device+"/model")
68                         if procfile == "":
69                                 return ""
70                         line = procfile.readline()
71                         procfile.close()
72                         return line.strip()
73                 elif self.device.find("sd") == 0:
74                         procfile = tryOpen("/sys/block/"+self.device+"/device/vendor")
75                         if procfile == "":
76                                 return ""
77                         vendor = procfile.readline().strip()
78                         procfile.close()
79                         procfile = tryOpen("/sys/block/"+self.device+"/device/model")
80                         model = procfile.readline().strip()
81                         return vendor+'('+model+')'
82                 else:
83                         assert False, "no hdX or sdX"
84
85         def free(self):
86                 procfile = tryOpen("/proc/mounts")
87                 
88                 if procfile == "":
89                         return -1
90
91                 free = -1
92                 while 1:
93                         line = procfile.readline()
94                         if line == "":
95                                 break
96                         if line.startswith(self.devidex):
97                                 parts = line.strip().split(" ")
98                                 try:
99                                         stat = statvfs(parts[1])
100                                 except OSError:
101                                         continue
102                                 free = stat.f_bfree/1000 * stat.f_bsize/1000
103                                 break
104                 procfile.close()
105                 return free
106
107         def numPartitions(self):
108                 try:
109                         idedir = listdir(self.devidex)
110                 except OSError:
111                         return -1
112                 numPart = -1
113                 for filename in idedir:
114                         if filename.startswith("disc"):
115                                 numPart += 1
116                         if filename.startswith("part"):
117                                 numPart += 1
118                 return numPart
119
120         def unmount(self):
121                 procfile = tryOpen("/proc/mounts")
122
123                 if procfile == "":
124                         return -1
125
126                 cmd = "/bin/umount"
127
128                 for line in procfile:
129                         if line.startswith(self.devidex):
130                                 parts = line.split()
131                                 cmd = ' '.join([cmd, parts[1]])
132
133                 procfile.close()
134
135                 res = system(cmd)
136                 return (res >> 8)
137
138         def createPartition(self):
139                 cmd = "/sbin/sfdisk -f " + self.devidex + "disc"
140                 sfdisk = popen(cmd, "w")
141                 sfdisk.write("0,\n;\n;\n;\ny\n")
142                 sfdisk.close()
143                 return 0
144
145         def mkfs(self):
146                 cmd = "/sbin/mkfs.ext3 "
147                 if self.diskSize() > 4 * 1024:
148                         cmd += "-T largefile "
149                 cmd += "-m0 " + self.devidex + "part1"
150                 res = system(cmd)
151                 return (res >> 8)
152
153         def mount(self):
154                 cmd = "/bin/mount -t ext3 " + self.devidex + "part1"
155                 res = system(cmd)
156                 return (res >> 8)
157
158         def createMovieFolder(self):
159                 try:
160                         makedirs(resolveFilename(SCOPE_HDD))
161                 except OSError:
162                         return -1
163                 return 0
164
165         def fsck(self):
166                 # We autocorrect any failures
167                 # TODO: we could check if the fs is actually ext3
168                 cmd = "/sbin/fsck.ext3 -f -p " + self.devidex + "part1"
169                 res = system(cmd)
170                 return (res >> 8)
171
172         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")]
173
174         def initialize(self):
175                 self.unmount()
176
177                 if self.createPartition() != 0:
178                         return -1
179
180                 if self.mkfs() != 0:
181                         return -2
182
183                 if self.mount() != 0:
184                         return -3
185
186                 if self.createMovieFolder() != 0:
187                         return -4
188
189                 return 0
190
191         def check(self):
192                 self.unmount()
193
194                 res = self.fsck()
195                 if res & 2 == 2:
196                         return -6
197
198                 if res & 4 == 4:
199                         return -7
200
201                 if res != 0 and res != 1:
202                         # A sum containing 1 will also include a failure
203                         return -5
204
205                 if self.mount() != 0:
206                         return -3
207
208                 return 0
209         
210         def getDeviceDir(self):
211                 return self.devidex
212         
213         def getDeviceName(self):
214                 return self.getDeviceDir() + "disc"
215
216 class Partition:
217         def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
218                 self.mountpoint = mountpoint
219                 self.description = description
220                 self.force_mounted = force_mounted
221                 self.is_hotplug = force_mounted # so far; this might change.
222                 self.device = device
223
224         def stat(self):
225                 return statvfs(self.mountpoint)
226
227         def free(self):
228                 try:
229                         s = self.stat()
230                         return s.f_bavail * s.f_bsize
231                 except OSError:
232                         return None
233         
234         def total(self):
235                 try:
236                         s = self.stat()
237                         return s.f_blocks * s.f_bsize
238                 except OSError:
239                         return None
240
241         def mounted(self):
242                 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
243                 # TODO: can os.path.ismount be used?
244                 if self.force_mounted:
245                         return True
246                 procfile = tryOpen("/proc/mounts")
247                 for n in procfile.readlines():
248                         if n.split(' ')[1] == self.mountpoint:
249                                 return True
250                 return False
251
252 DEVICEDB =  \
253         {
254                 # dm8000:
255                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": "Front USB Slot",
256                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": "Back, upper USB Slot",
257                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": "Back, lower USB Slot",
258                 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host1/target1:0:0/1:0:0:0": "DVD Drive",
259         }
260
261 class HarddiskManager:
262         def __init__(self):
263                 self.hdd = [ ]
264                 self.cd = ""
265                 self.partitions = [ ]
266                 
267                 self.on_partition_list_change = CList()
268                 
269                 self.enumerateBlockDevices()
270                 
271                 # currently, this is just an enumeration of what's possible,
272                 # this probably has to be changed to support automount stuff.
273                 # still, if stuff is mounted into the correct mountpoints by
274                 # external tools, everything is fine (until somebody inserts 
275                 # a second usb stick.)
276                 p = [
277                                         ("/media/hdd", _("Harddisk")), 
278                                         ("/media/card", _("Card")), 
279                                         ("/media/cf", _("Compact Flash")),
280                                         ("/media/mmc1", _("MMC Card")),
281                                         ("/media/net", _("Network Mount")),
282                                         ("/media/ram", _("Ram Disk")),
283                                         ("/media/usb", _("USB Stick")),
284                                         ("/", _("Internal Flash"))
285                                 ]
286                 
287                 for x in p:
288                         self.partitions.append(Partition(mountpoint = x[0], description = x[1]))
289
290         def getBlockDevInfo(self, blockdev):
291                 devpath = "/sys/block/" + blockdev
292                 error = False
293                 removable = False
294                 blacklisted = False
295                 is_cdrom = False
296                 partitions = []
297                 try:
298                         removable = bool(int(open(devpath + "/removable").read()))
299                         dev = int(open(devpath + "/dev").read().split(':')[0])
300                         if dev in [7, 31]: # loop, mtdblock
301                                 blacklisted = True
302                         if blockdev[0:2] == 'sr':
303                                 is_cdrom = True
304                         if blockdev[0:2] == 'hd':
305                                 try:
306                                         media = open("/proc/ide/%s/media" % blockdev).read()
307                                         if media.find("cdrom") != -1:
308                                                 is_cdrom = True
309                                 except IOError:
310                                         error = True
311                         # check for partitions
312                         if not is_cdrom:
313                                 for partition in listdir(devpath):
314                                         if partition[0:len(blockdev)] != blockdev:
315                                                 continue
316                                         partitions.append(partition)
317                         else:
318                                 self.cd = blockdev
319                 except IOError:
320                         error = True
321                 # check for medium
322                 medium_found = True
323                 try:
324                         open("/dev/" + blockdev).close()
325                 except IOError, err:
326                         if err.errno == 159: # no medium present
327                                 medium_found = False
328                         
329                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
330
331         def enumerateBlockDevices(self):
332                 print "enumerating block devices..."
333                 for blockdev in listdir("/sys/block"):
334                         error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(blockdev)
335                         print "found block device '%s':" % blockdev, 
336                         if error:
337                                 print "error querying properties"
338                         elif blacklisted:
339                                 print "blacklisted"
340                         elif not medium_found:
341                                 print "no medium"
342                         else:
343                                 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
344
345                                 self.addHotplugPartition(blockdev)
346                                 for part in partitions:
347                                         self.addHotplugPartition(part)
348
349         def getAutofsMountpoint(self, device):
350                 return "/autofs/%s/" % (device)
351
352         def addHotplugPartition(self, device, physdev = None):
353                 if not physdev:
354                         dev, part = self.splitDeviceName(device)
355                         try:
356                                 physdev = readlink("/sys/block/" + dev + "/device")[5:]
357                         except OSError:
358                                 physdev = dev
359                                 print "couldn't determine blockdev physdev for device", device
360
361                 # device is the device name, without /dev 
362                 # physdev is the physical device path, which we (might) use to determine the userfriendly name
363                 description = self.getUserfriendlyDeviceName(device, physdev)
364                 
365                 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
366                 self.partitions.append(p)
367                 self.on_partition_list_change("add", p)
368
369                 # see if this is a harddrive
370                 l = len(device)
371                 if l and device[l-1] not in string.digits:
372                         error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
373                         if not blacklisted and not removable and not is_cdrom and medium_found:
374                                 self.hdd.append(Harddisk(device))
375                                 self.hdd.sort()
376                                 SystemInfo["Harddisk"] = len(self.hdd) > 0
377
378         def removeHotplugPartition(self, device):
379                 mountpoint = self.getAutofsMountpoint(device)
380                 for x in self.partitions[:]:
381                         if x.mountpoint == mountpoint:
382                                 self.partitions.remove(x)
383                                 self.on_partition_list_change("remove", x)
384                 l = len(device)
385                 if l and device[l-1] not in string.digits:
386                         idx = 0
387                         for hdd in self.hdd:
388                                 if hdd.device == device:
389                                         del self.hdd[idx]
390                                         break
391                         SystemInfo["Harddisk"] = len(self.hdd) > 0
392
393         def HDDCount(self):
394                 return len(self.hdd)
395
396         def HDDList(self):
397                 list = [ ]
398                 for hd in self.hdd:
399                         hdd = hd.model() + " - " + hd.bus()
400                         cap = hd.capacity()
401                         if cap != "":
402                                 hdd += " (" + cap + ")"
403                         list.append((hdd, hd))
404                 return list
405
406         def getCD(self):
407                 return self.cd
408
409         def getMountedPartitions(self, onlyhotplug = False):
410                 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
411                 devs = set([x.device for x in parts])
412                 for devname in devs.copy():
413                         if not devname:
414                                 continue
415                         dev, part = self.splitDeviceName(devname)
416                         if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
417                                 devs.remove(dev)
418
419                 # return all devices which are not removed due to being a wholedisk when a partition exists
420                 return [x for x in parts if not x.device or x.device in devs]
421
422         def splitDeviceName(self, devname):
423                 # 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.
424                 dev = devname[:3]
425                 part = devname[3:]
426                 for p in part:
427                         if p not in string.digits:
428                                 return devname, 0
429                 return dev, part and int(part) or 0
430
431         def getUserfriendlyDeviceName(self, dev, phys):
432                 dev, part = self.splitDeviceName(dev)
433                 description = "External Storage %s" % dev
434                 try:
435                         description = open("/sys" + phys + "/model").read().strip()
436                 except IOError, s:
437                         print "couldn't read model: ", s
438                 for physdevprefix, pdescription in DEVICEDB.items():
439                         if phys.startswith(physdevprefix):
440                                 description = pdescription
441
442                 # not wholedisk and not partition 1
443                 if part and part != 1:
444                         description += " (Partition %d)" % part
445                 return description
446
447 harddiskmanager = HarddiskManager()