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