update dvbapp.
[vuplus_dvbapp] / lib / python / Components / Harddisk.py
1 from os import system, listdir, statvfs, popen, makedirs, stat, major, minor, path, access
2
3 from Tools.Directories import SCOPE_HDD, resolveFilename, fileExists
4
5 from Tools.CList import CList
6 from SystemInfo import SystemInfo
7 import time
8 from Components.Console import Console
9
10 def MajorMinor(path):
11         rdev = stat(path).st_rdev
12         return (major(rdev),minor(rdev))
13
14 def readFile(filename):
15         file = open(filename)
16         data = file.read().strip()
17         file.close()
18         return data
19
20 def getProcMounts():
21         try:
22                 mounts = open("/proc/mounts", 'r')
23         except IOError, ex:
24                 print "[Harddisk] Failed to open /proc/mounts", ex
25                 return []
26         result = [line.strip().split(' ') for line in mounts]
27         for item in result:
28                 # Spaces are encoded as \040 in mounts
29                 item[1] = item[1].replace('\\040', ' ')
30         return result
31
32 def CheckSfdiskVer():
33         cmd = 'sfdisk --version'
34         lines = popen(cmd).readlines()
35         for l in lines:
36                 if l.find("sfdisk from util-linux") != -1:
37                         ver = l.split()[-1].strip()
38                         break
39         try:
40                 vs = ver.split('.')
41                 if len(vs) > 2:
42                         ver = '.'.join(vs[:2])
43
44                 ver = float(ver)
45         except:
46                 print "[CheckSfdiskVer] check parted version Failed!"
47                 return 0
48         return ver
49
50 def enableUdevEvent(enable = True):
51         if enable:
52                 option = '--start-exec-queue'
53         else:
54                 option = '--stop-exec-queue'
55         cmd = "udevadm control %s" % option
56         print "CMD : ", cmd
57         system(cmd)
58
59 DEVTYPE_UDEV = 0
60 DEVTYPE_DEVFS = 1
61
62 class Harddisk:
63         def __init__(self, device):
64                 self.device = device
65
66                 if access("/dev/.udev", 0):
67                         self.type = DEVTYPE_UDEV
68                 elif access("/dev/.devfsd", 0):
69                         self.type = DEVTYPE_DEVFS
70                 else:
71                         print "Unable to determine structure of /dev"
72
73                 self.max_idle_time = 0
74                 self.idle_running = False
75                 self.timer = None
76
77                 self.dev_path = ''
78                 self.disk_path = ''
79                 self.mount_path = None
80                 self.mount_device = None
81                 self.phys_path = path.realpath(self.sysfsPath('device'))
82
83                 if self.type == DEVTYPE_UDEV:
84                         self.dev_path = '/dev/' + self.device
85                         self.disk_path = self.dev_path
86
87                 elif self.type == DEVTYPE_DEVFS:
88                         tmp = readFile(self.sysfsPath('dev')).split(':')
89                         s_major = int(tmp[0])
90                         s_minor = int(tmp[1])
91                         for disc in listdir("/dev/discs"):
92                                 dev_path = path.realpath('/dev/discs/' + disc)
93                                 disk_path = dev_path + '/disc'
94                                 try:
95                                         rdev = stat(disk_path).st_rdev
96                                 except OSError:
97                                         continue
98                                 if s_major == major(rdev) and s_minor == minor(rdev):
99                                         self.dev_path = dev_path
100                                         self.disk_path = disk_path
101                                         break
102
103                 print "new Harddisk", self.device, '->', self.dev_path, '->', self.disk_path
104                 self.startIdle()
105
106         def __lt__(self, ob):
107                 return self.device < ob.device
108
109         def partitionPath(self, n):
110                 if self.type == DEVTYPE_UDEV:
111                         return self.dev_path + n
112                 elif self.type == DEVTYPE_DEVFS:
113                         return self.dev_path + '/part' + n
114
115         def sysfsPath(self, filename):
116                 return path.realpath('/sys/block/' + self.device + '/' + filename)
117
118         def stop(self):
119                 if self.timer:
120                         self.timer.stop()
121                         self.timer.callback.remove(self.runIdle)
122
123         def bus(self):
124                 # CF (7025 specific)
125                 if self.type == DEVTYPE_UDEV:
126                         ide_cf = False  # FIXME
127                 elif self.type == DEVTYPE_DEVFS:
128                         ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
129
130                 internal = "pci" in self.phys_path
131
132                 if ide_cf:
133                         ret = "External (CF)"
134                 elif internal:
135                         ret = "Internal"
136                 else:
137                         ret = "External"
138                 return ret
139
140         def diskSize(self):
141                 try:
142                         line = readFile(self.sysfsPath('size'))
143                 except:
144                         harddiskmanager.removeHotplugPartition(self.device)
145                         print "error remove",self.device
146                         return -1
147                 try:
148                         cap = int(line)
149                 except:
150                         return 0;
151                 return cap / 1000 * 512 / 1000
152
153         def capacity(self):
154                 cap = self.diskSize()
155                 if cap == 0:
156                         return ""
157                 return "%d.%03d GB" % (cap/1000, cap%1000)
158
159         def model(self):
160                 try:
161                         if self.device[:2] == "hd":
162                                 return readFile('/proc/ide/' + self.device + '/model')
163                         elif self.device[:2] == "sd":
164                                 vendor = readFile(self.sysfsPath('device/vendor'))
165                                 model = readFile(self.sysfsPath('device/model'))
166                                 return vendor + '(' + model + ')'
167                         else:
168                                 assert False, "no hdX or sdX"
169                 except:
170                         harddiskmanager.removeHotplugPartition(self.device)
171                         print "error remove",self.device
172                         return -1
173
174         def free(self):
175                 try:
176                         mounts = open("/proc/mounts")
177                 except IOError:
178                         return -1
179
180                 lines = mounts.readlines()
181                 mounts.close()
182
183                 for line in lines:
184                         parts = line.strip().split(" ")
185                         real_path = path.realpath(parts[0])
186                         if not real_path[-1].isdigit():
187                                 continue
188                         try:
189                                 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
190                                         stat = statvfs(parts[1])
191                                         return stat.f_bfree/1000 * stat.f_bsize/1000
192                         except OSError:
193                                 pass
194                 return -1
195
196         def numPartitions(self):
197                 numPart = -1
198                 if self.type == DEVTYPE_UDEV:
199                         try:
200                                 devdir = listdir('/dev')
201                         except OSError:
202                                 return -1
203                         for filename in devdir:
204                                 if filename.startswith(self.device):
205                                         numPart += 1
206
207                 elif self.type == DEVTYPE_DEVFS:
208                         try:
209                                 idedir = listdir(self.dev_path)
210                         except OSError:
211                                 return -1
212                         for filename in idedir:
213                                 if filename.startswith("disc"):
214                                         numPart += 1
215                                 if filename.startswith("part"):
216                                         numPart += 1
217                 return numPart
218
219         def mountDevice(self):
220                 for parts in getProcMounts():
221                         if path.realpath(parts[0]).startswith(self.dev_path):
222                                 self.mount_device = parts[0]
223                                 self.mount_path = parts[1]
224                                 return parts[1]
225
226         def findMount(self):
227                 if self.mount_path is None:
228                         return self.mountDevice()
229                 return self.mount_path
230
231         def unmount(self):
232                 try:
233                         mounts = open("/proc/mounts")
234                 except IOError:
235                         return -1
236
237                 lines = mounts.readlines()
238                 mounts.close()
239
240                 cmd = "umount"
241
242                 for line in lines:                                                                          
243                         parts = line.strip().split(" ")                                                     
244                         real_path = path.realpath(parts[0])                                                 
245                         if not real_path[-1].isdigit():                                                     
246                                 continue                                                                    
247                         try:                                                                                
248                                 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
249                                         cmd = ' ' . join([cmd, parts[1]])
250                                         break
251                         except OSError:
252                                 pass
253
254                 res = system(cmd)
255                 print "CMD : ", cmd
256                 return (res >> 8)
257
258         def checkPartionPath(self, path):
259                 import time, os
260                 for i in range(1,10):
261                         if os.path.exists(path):
262                                 return True
263                         time.sleep(1)
264                 return False
265
266         def updatePartition(self):
267                 sfdiskVer = CheckSfdiskVer()
268                 if sfdiskVer < 2.26: # sfdisk -R option is deprecated at sfdiskVer >= 2.26
269                         cmd = 'sfdisk -R %s; sleep 5' % (self.disk_path)
270                 elif path.exists('/usr/sbin/partprobe'):
271                         cmd = 'partprobe %s; sleep 5' % (self.disk_path)
272                 elif path.exists('/usr/sbin/partx'):
273                         cmd = 'partx -u %s' % (self.disk_path)
274                 else:
275                         return -1
276
277                 print "CMD : ", cmd
278                 res = system(cmd)
279
280                 return (res >> 8)
281
282         def createPartition(self):
283                 def CheckPartedVer():
284                         cmd = 'parted --version'
285                         lines = popen(cmd).readlines()
286                         for l in lines:
287                                 if l.find("parted (GNU parted)") != -1:
288                                         ver = l.split()[3].strip()
289                                         break
290                         try:
291                                 ver = float(ver)
292                         except:
293                                 print "[CheckPartedVer] check parted version Failed!"
294                                 return 0
295                         return ver
296
297                 disk_size = self.diskSize()
298
299                 if disk_size > 2.2 * 1000 * 1000: # if 2.2 TB
300                         setAlign = ""
301                         partedVer = CheckPartedVer()
302                         if partedVer >= 2.1: # align option is supported in version 2.1 or later
303                                 setAlign = "--align optimal"
304                         cmd = 'parted %s %s --script mklabel gpt mkpart disk ext2 0%% 100%%' % ( setAlign, self.disk_path )
305
306                 else:
307                         sfdiskVer = CheckSfdiskVer()
308                         if sfdiskVer <= 2.21:
309                                 cmd = 'printf "8,\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS ' + self.disk_path
310                         else:
311                                 cmd = 'printf "8,\nquit\nY\n" | sfdisk -f -uS ' + self.disk_path
312
313                 print "CMD : ", cmd
314                 res = system(cmd)
315
316                 if not self.checkPartionPath(self.partitionPath("1")):
317                         print "no exist : ", self.partitionPath("1")
318                         return 1
319                 return (res >> 8)
320
321         def mkfs(self):
322                 cmd = "mkfs.ext3 "
323                 if self.diskSize() > 4 * 1024:
324                         cmd += "-T largefile "
325                 cmd += "-m0 -O dir_index " + self.partitionPath("1")
326                 print "CMD : ", cmd
327                 res = system(cmd)
328                 return (res >> 8)
329
330         def mount(self):
331                 try:
332                         fstab = open("/etc/fstab")
333                 except IOError:
334                         return -1
335
336                 lines = fstab.readlines()
337                 fstab.close()
338
339                 res = -1
340                 mount_point = None
341                 for line in lines:
342                         parts = line.strip().split(" ")
343                         real_path = path.realpath(parts[0])
344                         if not real_path[-1].isdigit():
345                                 continue
346                         try:
347                                 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
348                                         mount_point = parts[0]
349                                         break
350                         except OSError:
351                                 pass
352
353                 if mount_point is None:
354                         return 0
355
356                 cmd = "mount -t ext3 " + mount_point
357                 print "CMD : ", cmd
358                 res = system(cmd)
359
360                 if (res >> 8) != 0:
361                         return -3
362
363                 if self.createMovieFolder() != 0:
364                         return -4
365
366                 return 0
367
368         def createMovieFolder(self):
369                 try:
370                         if not fileExists("/hdd", 0):
371                                 print "not found /hdd"
372                                 system("ln -s /media/hdd /hdd")
373         
374                         makedirs(resolveFilename(SCOPE_HDD))
375                 except OSError:
376                         return -1
377                 return 0
378
379         def fsck(self):
380                 # We autocorrect any failures
381                 # TODO: we could check if the fs is actually ext3
382                 cmd = "fsck.ext3 -f -p " + self.partitionPath("1")
383                 res = system(cmd)
384                 return (res >> 8)
385
386         def killPartition(self, n):
387                 part = self.partitionPath(n)
388
389                 if access(part, 0):
390                         cmd = 'dd bs=512 count=3 if=/dev/zero of=' + part
391                         print "CMD : ", cmd
392                         res = system(cmd)
393                 else:
394                         res = 0
395
396                 return (res >> 8)
397
398         errorList = [ _("Everything is fine"), _("Creating partition failed"), _("Mkfs failed"), _("Mount failed"), _("Create movie folder failed"), _("Fsck failed"), _("Please Reboot"), _("Filesystem contains uncorrectable errors"), _("Unmount failed"), _("partx failed")]
399
400         def initialize(self):
401                 enableUdevEvent(False)
402                 self.unmount()
403
404                 # Udev tries to mount the partition immediately if there is an
405                 # old filesystem on it when fdisk reloads the partition table.
406                 # To prevent that, we overwrite the first 3 sectors of the
407                 # partition, if the partition existed before. That's enough for
408                 # ext3 at least.
409                 self.killPartition("1")
410
411                 if self.updatePartition() != 0:
412                         res = -9
413
414                 elif self.createPartition() != 0:
415                         res = -1
416
417                 elif self.updatePartition() != 0:
418                         res = -9
419
420                 elif self.mkfs() != 0:
421                         res = -2
422
423                 else:
424                         res = self.mount()
425
426                 enableUdevEvent(True)
427                 return res
428
429         def check(self):
430                 self.unmount()
431
432                 res = self.fsck()
433                 if res & 2 == 2:
434                         return -6
435
436                 if res & 4 == 4:
437                         return -7
438
439                 if res != 0 and res != 1:
440                         # A sum containing 1 will also include a failure
441                         return -5
442
443                 if self.mount() != 0:
444                         return -3
445
446                 return 0
447
448         def getDeviceDir(self):
449                 return self.dev_path
450
451         def getDeviceName(self):
452                 return self.disk_path
453
454         # the HDD idle poll daemon.
455         # as some harddrives have a buggy standby timer, we are doing this by hand here.
456         # first, we disable the hardware timer. then, we check every now and then if
457         # any access has been made to the disc. If there has been no access over a specifed time,
458         # we set the hdd into standby.
459         def readStats(self):
460                 try:
461                         l = open("/sys/block/%s/stat" % self.device).read()
462                 except IOError:
463                         return -1,-1
464                 (nr_read, _, _, _, nr_write) = l.split()[:5]
465                 return int(nr_read), int(nr_write)
466
467         def startIdle(self):
468                 self.last_access = time.time()
469                 self.last_stat = 0
470                 self.is_sleeping = False
471                 from enigma import eTimer
472
473                 # disable HDD standby timer
474                 Console().ePopen(("hdparm", "hdparm", "-S0", self.disk_path))
475                 self.timer = eTimer()
476                 self.timer.callback.append(self.runIdle)
477                 self.idle_running = True
478                 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
479
480         def runIdle(self):
481                 if not self.max_idle_time:
482                         return
483                 t = time.time()
484
485                 idle_time = t - self.last_access
486
487                 stats = self.readStats()
488
489                 if stats == -1:
490                         self.setIdleTime(0)
491                         return
492                 print "nr_read", stats[0], "nr_write", stats[1]
493                 l = sum(stats)
494                 print "sum", l, "prev_sum", self.last_stat
495
496                 if l != self.last_stat and l >= 0: # access
497                         print "hdd was accessed since previous check!"
498                         self.last_stat = l
499                         self.last_access = t
500                         idle_time = 0
501                         self.is_sleeping = False
502                 else:
503                         print "hdd IDLE!"
504
505                 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
506                 if idle_time >= self.max_idle_time and not self.is_sleeping:
507                         self.setSleep()
508                         self.is_sleeping = True
509
510         def setSleep(self):
511                 Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
512
513         def setIdleTime(self, idle):
514                 self.max_idle_time = idle
515                 if self.idle_running:
516                         if not idle:
517                                 self.timer.stop()
518                         else:
519                                 self.timer.start(idle * 100, False)  # poll 10 times per period.
520
521         def isSleeping(self):
522                 return self.is_sleeping
523
524 class Partition:
525         def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
526                 self.mountpoint = mountpoint
527                 self.description = description
528                 self.force_mounted = force_mounted
529                 self.is_hotplug = force_mounted # so far; this might change.
530                 self.device = device
531
532         def stat(self):
533                 return statvfs(self.mountpoint)
534
535         def free(self):
536                 try:
537                         s = self.stat()
538                         return s.f_bavail * s.f_bsize
539                 except OSError:
540                         return None
541
542         def total(self):
543                 try:
544                         s = self.stat()
545                         return s.f_blocks * s.f_bsize
546                 except OSError:
547                         return None
548
549         def mounted(self):
550                 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
551                 # TODO: can os.path.ismount be used?
552                 if self.force_mounted:
553                         return True
554
555                 try:
556                         mounts = open("/proc/mounts")
557                 except IOError:
558                         return False
559
560                 lines = mounts.readlines()
561                 mounts.close()
562
563                 for line in lines:
564                         if line.split(' ')[1] == self.mountpoint:
565                                 return True
566                 return False
567
568 DEVICEDB_SR = \
569         {"dm8000":
570                 {
571                         "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("DVD Drive"),
572                         "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("DVD Drive"),
573                         "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host3/target3:0:0/3:0:0:0": _("DVD Drive"),
574                 },
575         "dm800":
576         {
577         },
578         "dm7025":
579         {
580         }
581         }
582
583 DEVICEDB = \
584         {"dm8000":
585                 {
586                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
587                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": _("Back, upper USB Slot"),
588                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": _("Back, lower USB Slot"),
589                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB Slot"),
590                         "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/": _("Internal USB Slot"),
591                         "/devices/platform/brcm-ohci-1.1/usb4/4-1/4-1:1.0/": _("Internal USB Slot"),
592                 },
593         "dm800":
594         {
595                 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": "Upper USB Slot",
596                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": "Lower USB Slot",
597         },
598         "dm7025":
599         {
600                 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "CF Card Slot", #hdc
601                 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
602         }
603         }
604
605 class HarddiskManager:
606         def __init__(self):
607                 self.hdd = [ ]
608                 self.cd = ""
609                 self.partitions = [ ]
610                 self.devices_scanned_on_init = [ ]
611
612                 self.on_partition_list_change = CList()
613
614                 self.enumerateBlockDevices()
615
616                 # currently, this is just an enumeration of what's possible,
617                 # this probably has to be changed to support automount stuff.
618                 # still, if stuff is mounted into the correct mountpoints by
619                 # external tools, everything is fine (until somebody inserts
620                 # a second usb stick.)
621                 p = [
622                                         ("/media/hdd", _("Harddisk")),
623                                         ("/media/card", _("Card")),
624                                         ("/media/cf", _("Compact Flash")),
625                                         ("/media/mmc1", _("MMC Card")),
626                                         ("/media/net", _("Network Mount")),
627                                         ("/media/ram", _("Ram Disk")),
628                                         ("/media/usb", _("USB Stick")),
629                                         ("/", _("Internal Flash"))
630                                 ]
631
632                 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
633
634         def getBlockDevInfo(self, blockdev):
635                 devpath = "/sys/block/" + blockdev
636                 error = False
637                 removable = False
638                 blacklisted = False
639                 is_cdrom = False
640                 partitions = []
641                 try:
642                         removable = bool(int(readFile(devpath + "/removable")))
643                         dev = int(readFile(devpath + "/dev").split(':')[0])
644                         if dev in (7, 31, 179): # loop, mtdblock, mmcblock
645                                 blacklisted = True
646                         if blockdev[0:2] == 'sr':
647                                 is_cdrom = True
648                         if blockdev[0:2] == 'hd':
649                                 try:
650                                         media = readFile("/proc/ide/%s/media" % blockdev)
651                                         if "cdrom" in media:
652                                                 is_cdrom = True
653                                 except IOError:
654                                         error = True
655                         # check for partitions
656                         if not is_cdrom:
657                                 for partition in listdir(devpath):
658                                         if partition[0:len(blockdev)] != blockdev:
659                                                 continue
660                                         partitions.append(partition)
661                         else:
662                                 self.cd = blockdev
663                 except IOError:
664                         error = True
665                 # check for medium
666                 medium_found = True
667                 try:
668                         open("/dev/" + blockdev).close()
669                 except IOError, err:
670                         if err.errno == 159: # no medium present
671                                 medium_found = False
672
673                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
674
675         def enumerateBlockDevices(self):
676                 print "enumerating block devices..."
677                 for blockdev in listdir("/sys/block"):
678                         error, blacklisted, removable, is_cdrom, partitions, medium_found = self.addHotplugPartition(blockdev)
679                         if not error and not blacklisted:
680                                 if medium_found:
681                                         for part in partitions:
682                                                 self.addHotplugPartition(part)
683                                 self.devices_scanned_on_init.append((blockdev, removable, is_cdrom, medium_found))
684
685         def getAutofsMountpoint(self, device):
686                 return "/autofs/%s/" % (device)
687
688
689         def is_hard_mounted(self, device):
690                 mounts = file('/proc/mounts').read().split('\n')
691                 for x in mounts:
692                         if x.find('/autofs') == -1 and x.find(device) != -1:
693                                 return True
694                 return False
695
696         def addHotplugPartition(self, device, physdev = None):
697                 if not physdev:
698                         dev, part = self.splitDeviceName(device)
699                         try:
700                                 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
701                         except OSError:
702                                 physdev = dev
703                                 print "couldn't determine blockdev physdev for device", device
704
705                 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
706                 print "found block device '%s':" % device,
707
708                 if blacklisted:
709                         print "blacklisted"
710                 else:
711                         if error:
712                                 print "error querying properties"
713                         elif not medium_found:
714                                 print "no medium"
715                         else:
716                                 print "ok, removable=%s, cdrom=%s, partitions=%s" % (removable, is_cdrom, partitions)
717
718                         l = len(device)
719                         if l:
720                                 # see if this is a harddrive
721                                 if not device[l-1].isdigit() and not removable and not is_cdrom:
722                                         self.hdd.append(Harddisk(device))
723                                         self.hdd.sort()
724                                         SystemInfo["Harddisk"] = len(self.hdd) > 0
725
726                                 if (not removable or medium_found) and not self.is_hard_mounted(device):
727                                         # device is the device name, without /dev
728                                         # physdev is the physical device path, which we (might) use to determine the userfriendly name
729                                         description = self.getUserfriendlyDeviceName(device, physdev)
730                                         p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True, device = device)
731                                         self.partitions.append(p)
732                                         self.on_partition_list_change("add", p)
733
734                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
735
736         def removeHotplugPartition(self, device):
737                 mountpoint = self.getAutofsMountpoint(device)
738                 for x in self.partitions[:]:
739                         if x.mountpoint == mountpoint:
740                                 self.partitions.remove(x)
741                                 self.on_partition_list_change("remove", x)
742                 l = len(device)
743                 if l and not device[l-1].isdigit():
744                         for hdd in self.hdd:
745                                 if hdd.device == device:
746                                         hdd.stop()
747                                         self.hdd.remove(hdd)
748                                         break
749                         SystemInfo["Harddisk"] = len(self.hdd) > 0
750
751         def HDDCount(self):
752                 return len(self.hdd)
753
754         def HDDList(self):
755                 list = [ ]
756                 for hd in self.hdd:
757                         if hd.model() == -1:
758                                 continue
759                         hdd = hd.model() + " - " + hd.bus()
760                         cap = hd.capacity()
761                         if cap != "":
762                                 hdd += " (" + cap + ")"
763                         list.append((hdd, hd))
764                 return list
765
766         def getCD(self):
767                 return self.cd
768
769         def getMountedPartitions(self, onlyhotplug = False):
770                 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
771                 devs = set([x.device for x in parts])
772                 for devname in devs.copy():
773                         if not devname:
774                                 continue
775                         dev, part = self.splitDeviceName(devname)
776                         if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
777                                 devs.remove(dev)
778
779                 # return all devices which are not removed due to being a wholedisk when a partition exists
780                 return [x for x in parts if not x.device or x.device in devs]
781
782         def splitDeviceName(self, devname):
783                 # this works for: sdaX, hdaX, sr0 (which is in fact dev="sr0", part=""). It doesn't work for other names like mtdblock3, but they are blacklisted anyway.
784                 dev = devname[:3]
785                 part = devname[3:]
786                 for p in part:
787                         if not p.isdigit():
788                                 return devname, 0
789                 return dev, part and int(part) or 0
790
791         def getUserfriendlyDeviceName(self, dev, phys):
792                 dev, part = self.splitDeviceName(dev)
793                 description = "External Storage %s" % dev
794                 have_model_descr = False
795                 try:
796                         description = readFile("/sys" + phys + "/model")
797                         have_model_descr = True
798                 except IOError, s:
799                         print "couldn't read model: ", s
800                 from Tools.HardwareInfo import HardwareInfo
801                 if dev.find('sr') == 0 and dev[2].isdigit():
802                         devicedb = DEVICEDB_SR
803                 else:
804                         devicedb = DEVICEDB
805                 for physdevprefix, pdescription in devicedb.get(HardwareInfo().device_name,{}).items():
806                         if phys.startswith(physdevprefix):
807                                 if have_model_descr:
808                                         description = pdescription + ' - ' + description
809                                 else:
810                                         description = pdescription
811                 # not wholedisk and not partition 1
812                 if part and part != 1:
813                         description += " (Partition %d)" % part
814                 return description
815
816         def addMountedPartition(self, device, desc):
817                 already_mounted = False
818                 for x in self.partitions[:]:
819                         if x.mountpoint == device:
820                                 already_mounted = True
821                 if not already_mounted:
822                         self.partitions.append(Partition(mountpoint = device, description = desc))
823
824         def removeMountedPartition(self, mountpoint):
825                 for x in self.partitions[:]:
826                         if x.mountpoint == mountpoint:
827                                 self.partitions.remove(x)
828                                 self.on_partition_list_change("remove", x)
829
830 harddiskmanager = HarddiskManager()