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