fix typo
[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         }
259
260 class HarddiskManager:
261         def __init__(self):
262                 self.hdd = [ ]
263                 self.cd = ""
264                 self.partitions = [ ]
265                 
266                 self.on_partition_list_change = CList()
267                 
268                 self.enumerateBlockDevices()
269                 
270                 # currently, this is just an enumeration of what's possible,
271                 # this probably has to be changed to support automount stuff.
272                 # still, if stuff is mounted into the correct mountpoints by
273                 # external tools, everything is fine (until somebody inserts 
274                 # a second usb stick.)
275                 p = [
276                                         ("/media/hdd", _("Harddisk")), 
277                                         ("/media/card", _("Card")), 
278                                         ("/media/cf", _("Compact Flash")),
279                                         ("/media/mmc1", _("MMC Card")),
280                                         ("/media/net", _("Network Mount")),
281                                         ("/media/ram", _("Ram Disk")),
282                                         ("/media/usb", _("USB Stick")),
283                                         ("/", _("Internal Flash"))
284                                 ]
285                 
286                 for x in p:
287                         self.partitions.append(Partition(mountpoint = x[0], description = x[1]))
288
289         def getBlockDevInfo(self, blockdev):
290                 devpath = "/sys/block/" + blockdev
291                 error = False
292                 removable = False
293                 blacklisted = False
294                 is_cdrom = False
295                 partitions = []
296                 try:
297                         removable = bool(int(open(devpath + "/removable").read()))
298                         dev = int(open(devpath + "/dev").read().split(':')[0])
299                         if dev in [7, 31]: # loop, mtdblock
300                                 blacklisted = True
301                         if blockdev[0:2] == 'sr':
302                                 is_cdrom = True
303                         if blockdev[0:2] == 'hd':
304                                 try:
305                                         media = open("/proc/ide/%s/media" % blockdev).read()
306                                         if media.find("cdrom") != -1:
307                                                 is_cdrom = True
308                                 except IOError:
309                                         error = True
310                         # check for partitions
311                         if not is_cdrom:
312                                 for partition in listdir(devpath):
313                                         if partition[0:len(blockdev)] != blockdev:
314                                                 continue
315                                         partitions.append(partition)
316                         else:
317                                 self.cd = blockdev
318                 except IOError:
319                         error = True
320                 # check for medium
321                 medium_found = True
322                 try:
323                         open("/dev/" + blockdev).close()
324                 except IOError, err:
325                         if err.errno == 159: # no medium present
326                                 medium_found = False
327                         
328                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
329
330         def enumerateBlockDevices(self):
331                 print "enumerating block devices..."
332                 for blockdev in listdir("/sys/block"):
333                         error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(blockdev)
334                         print "found block device '%s':" % blockdev, 
335                         if error:
336                                 print "error querying properties"
337                         elif blacklisted:
338                                 print "blacklisted"
339                         elif not medium_found:
340                                 print "no medium"
341                         else:
342                                 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
343
344                                 self.addHotplugPartition(blockdev)
345                                 for part in partitions:
346                                         self.addHotplugPartition(part)
347
348         def getAutofsMountpoint(self, device):
349                 return "/autofs/%s/" % (device)
350
351         def addHotplugPartition(self, device, physdev = None):
352                 if not physdev:
353                         dev, part = self.splitDeviceName(device)
354                         try:
355                                 physdev = readlink("/sys/block/" + dev + "/device")[6:]
356                         except OSError:
357                                 print "couldn't determine blockdev physdev for device", dev, "try", device, "now"
358                                 try:
359                                         physdev = readlink("/sys/block/" + device + "/device")[6:]
360                                 except OSError:
361                                         physdev = dev
362                                         print "couldn't determine blockdev physdev for device", device
363
364                 # device is the device name, without /dev 
365                 # physdev is the physical device path, which we (might) use to determine the userfriendly name
366                 description = self.getUserfriendlyDeviceName(device, physdev)
367                 
368                 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
369                 self.partitions.append(p)
370                 self.on_partition_list_change("add", p)
371
372                 # see if this is a harddrive
373                 l = len(device)
374                 if l and device[l-1] not in string.digits:
375                         error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
376                         if not blacklisted and not removable and not is_cdrom and medium_found:
377                                 self.hdd.append(Harddisk(device))
378                                 self.hdd.sort()
379                                 SystemInfo["Harddisk"] = len(self.hdd) > 0
380
381         def removeHotplugPartition(self, device):
382                 mountpoint = self.getAutofsMountpoint(device)
383                 for x in self.partitions[:]:
384                         if x.mountpoint == mountpoint:
385                                 self.partitions.remove(x)
386                                 self.on_partition_list_change("remove", x)
387                 l = len(device)
388                 if l and device[l-1] not in string.digits:
389                         idx = 0
390                         for hdd in self.hdd:
391                                 if hdd.device == device:
392                                         del self.hdd[idx]
393                                         break
394                         SystemInfo["Harddisk"] = len(self.hdd) > 0
395
396         def HDDCount(self):
397                 return len(self.hdd)
398
399         def HDDList(self):
400                 list = [ ]
401                 for hd in self.hdd:
402                         hdd = hd.model() + " - " + hd.bus()
403                         cap = hd.capacity()
404                         if cap != "":
405                                 hdd += " (" + cap + ")"
406                         list.append((hdd, hd))
407                 return list
408
409         def getCD(self):
410                 return self.cd
411
412         def getMountedPartitions(self, onlyhotplug = False):
413                 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
414                 devs = set([x.device for x in parts])
415                 for devname in devs.copy():
416                         if not devname:
417                                 continue
418                         dev, part = self.splitDeviceName(devname)
419                         if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
420                                 devs.remove(dev)
421
422                 # return all devices which are not removed due to being a wholedisk when a partition exists
423                 return [x for x in parts if not x.device or x.device in devs]
424
425         def splitDeviceName(self, devname):
426                 dev = ""
427                 part = ""
428                 for i in devname:
429                         if i in string.digits:
430                                 part += i
431                         else:
432                                 dev += i
433                 return dev, part and int(part) or 0
434
435         def getUserfriendlyDeviceName(self, dev, phys):
436                 dev, part = self.splitDeviceName(dev)
437                 description = "External Storage %s" % dev
438                 try:
439                         description = open("/sys/" + phys + "/model").read().strip()
440                 except IOError, s:
441                         print "couldn't read model (from /sys/" + phys + "/model): ", s
442                 for physdevprefix, pdescription in DEVICEDB.items():
443                         if phys.startswith(physdevprefix):
444                                 description = pdescription
445
446                 # not wholedisk and not partition 1
447                 if part and part != 1:
448                         description += " (Partition %d)" % part
449                 return description
450
451 harddiskmanager = HarddiskManager()