enigma2 (20120321 rel32 -> 20120327 rel32)
[enigma2.git] / usr / lib / enigma2 / python / Components / Harddisk.py
1 from os import system, listdir, statvfs, popen, makedirs, stat, major, minor, path, access, readlink, symlink, rmdir, unlink, rename, getcwd, chdir, W_OK
2 from Tools.Directories import SCOPE_HDD, resolveFilename
3 from Tools.BoundFunction import boundFunction
4 from Tools.CList import CList
5 from SystemInfo import SystemInfo
6 import time
7 import re, shutil
8 from Components.Console import Console
9 from config import config, configfile, ConfigYesNo, ConfigText, ConfigSubDict, ConfigSubsection, ConfigBoolean
10
11 def MajorMinor(path):
12         rdev = stat(path).st_rdev
13         return (major(rdev),minor(rdev))
14
15 def readFile(filename):
16         file = open(filename)
17         data = file.read().strip()
18         file.close()
19         return data
20
21 DEVTYPE_UDEV = 0
22 DEVTYPE_DEVFS = 1
23
24
25 class Harddisk:
26         def __init__(self, device, removable = False):
27                 self.device = device
28                 self.isRemovable = removable
29
30                 if access("/dev/.udev", 0):
31                         self.type = DEVTYPE_UDEV
32                 elif access("/dev/.devfsd", 0):
33                         self.type = DEVTYPE_DEVFS
34                 else:
35                         print "Unable to determine structure of /dev fallback to udev"
36                         self.type = DEVTYPE_UDEV
37
38                 self.is_sleeping = False
39                 self.max_idle_time = 0
40                 self.idle_running = False
41                 self.timer = None
42
43                 self.dev_path = ''
44                 self.disk_path = ''
45                 self.phys_path = path.realpath(self.sysfsPath('device'))
46
47                 if self.type == DEVTYPE_UDEV:
48                         self.dev_path = '/dev/' + self.device
49                         self.disk_path = self.dev_path
50
51                 elif self.type == DEVTYPE_DEVFS:
52                         tmp = readFile(self.sysfsPath('dev')).split(':')
53                         s_major = int(tmp[0])
54                         s_minor = int(tmp[1])
55                         for disc in listdir("/dev/discs"):
56                                 dev_path = path.realpath('/dev/discs/' + disc)
57                                 disk_path = dev_path + '/disc'
58                                 try:
59                                         rdev = stat(disk_path).st_rdev
60                                 except OSError:
61                                         continue
62                                 if s_major == major(rdev) and s_minor == minor(rdev):
63                                         self.dev_path = dev_path
64                                         self.disk_path = disk_path
65                                         break
66
67                 print "new Harddisk", self.device, '->', self.dev_path, '->', self.disk_path
68                 if not self.isRemovable:
69                         self.startIdle()
70
71         def __lt__(self, ob):
72                 return self.device < ob.device
73
74         def partitionPath(self, n):
75                 if self.type == DEVTYPE_UDEV:
76                         return self.dev_path + n
77                 elif self.type == DEVTYPE_DEVFS:
78                         return self.dev_path + '/part' + n
79
80         def sysfsPath(self, filename):
81                 return path.realpath('/sys/block/' + self.device + '/' + filename)
82
83         def stop(self):
84                 if self.timer:
85                         self.timer.stop()
86                         self.timer.callback.remove(self.runIdle)
87
88         def bus(self):
89                 # CF (7025 specific)
90                 if self.type == DEVTYPE_UDEV:
91                         ide_cf = False  # FIXME
92                 elif self.type == DEVTYPE_DEVFS:
93                         ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
94
95                 internal = "pci" in self.phys_path
96
97                 if ide_cf:
98                         ret = "External (CF)"
99                 elif internal:
100                         ret = "Internal"
101                 else:
102                         ret = "External"
103                 return ret
104
105         def bus_type(self):
106                 # CF (7025 specific)
107                 if self.type == DEVTYPE_UDEV:
108                         ide_cf = False  # FIXME
109                 elif self.type == DEVTYPE_DEVFS:
110                         ide_cf = self.device[:2] == "hd" and "host0" not in self.dev_path
111
112                 sata = "pci" in self.phys_path
113                 sata_desc = self.bus_description()
114
115                 if ide_cf:
116                         ret = "IDE"
117                 elif sata:
118                         if sata_desc is not None:
119                                 ret = sata_desc
120                         else:
121                                 ret = "SATA"
122                 else:
123                         ret = "USB"
124                 return ret
125
126         def bus_description(self):
127                 phys = self.phys_path[4:]
128                 from Tools.HardwareInfo import HardwareInfo
129                 if self.device.find('sr') == 0 and self.device[2].isdigit():
130                         devicedb = DEVICEDB_SR
131                 else:
132                         devicedb = DEVICEDB
133
134                 for physdevprefix, pdescription in devicedb.get(HardwareInfo().device_name,{}).items():
135                         #print "bus_description:",phys, physdevprefix, pdescription
136                         if phys.startswith(physdevprefix):
137                                 return pdescription
138                 if phys.find('pci') != -1:
139                         return "SATA"
140                 elif phys.find('usb') != -1:
141                         return "USB"
142                 return "External Storage"
143
144         def diskSize(self):
145                 try:
146                         line = readFile(self.sysfsPath('size'))
147                         cap = int(line)
148                 except:
149                         return 0;
150                 return cap / 1000 * 512 / 1000
151
152         def capacity(self):
153                 cap = self.diskSize()
154                 if cap == 0:
155                         return ""
156                 return "%d.%03d GB" % (cap/1000, cap%1000)
157
158         def model(self, model_only = False, vendor_only = False):
159                 if self.device[:2] == "hd":
160                         return readFile('/proc/ide/' + self.device + '/model')
161                 elif self.device[:2] == "sd":
162                         try:
163                                 vendor = readFile(self.sysfsPath('device/vendor'))
164                                 model = readFile(self.sysfsPath('device/model'))
165                         except:
166                                 vendor = ""
167                                 model = ""
168
169                         if vendor_only:
170                                 return vendor
171                         if model_only:
172                                 return model
173                         return vendor + '-' + model
174                 else:
175                         assert False, "no hdX or sdX"
176
177         def free(self):
178                 try:
179                         mounts = open("/proc/mounts")
180                 except IOError:
181                         return -1
182
183                 lines = mounts.readlines()
184                 mounts.close()
185
186                 for line in lines:
187                         parts = line.strip().split(" ")
188                         real_path = path.realpath(parts[0])
189                         if not real_path[-1].isdigit():
190                                 continue
191                         try:
192                                 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
193                                         stat = statvfs(parts[1])
194                                         return stat.f_bfree/1000 * stat.f_bsize/1000
195                         except OSError:
196                                 pass
197                 return -1
198
199         def numPartitions(self):
200                 numPart = -1
201                 if self.type == DEVTYPE_UDEV:
202                         try:
203                                 devdir = listdir('/dev')
204                         except OSError:
205                                 return -1
206                         for filename in devdir:
207                                 if filename.startswith(self.device):
208                                         numPart += 1
209
210                 elif self.type == DEVTYPE_DEVFS:
211                         try:
212                                 idedir = listdir(self.dev_path)
213                         except OSError:
214                                 return -1
215                         for filename in idedir:
216                                 if filename.startswith("disc"):
217                                         numPart += 1
218                                 if filename.startswith("part"):
219                                         numPart += 1
220                 return numPart
221
222         def unmount(self, numpart = None):
223                 try:
224                         mounts = open("/proc/mounts")
225                 except IOError:
226                         return -1
227
228                 lines = mounts.readlines()
229                 mounts.close()
230
231                 cmd = "umount"
232                 for line in lines:
233                         parts = line.strip().split(" ")
234                         real_path = path.realpath(parts[0])
235                         if not real_path[-1].isdigit():
236                                 if numpart is not None and numpart == 0:
237                                         if real_path.startswith("/dev/sd"):
238                                                 uuid = harddiskmanager.getPartitionUUID(self.device)
239                                                 if uuid is not None:
240                                                         try:
241                                                                 if MajorMinor(real_path) == MajorMinor(self.dev_path):
242                                                                         cmd = ' ' . join([cmd, parts[1]])
243                                                                         break
244                                                         except OSError:
245                                                                 pass
246                         try:
247                                 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
248                                         cmd = ' ' . join([cmd, parts[1]])
249                                         break
250                         except OSError:
251                                 pass
252                 res = system(cmd)
253                 if cmd == "umount": # nothing found to unmount
254                         res = 0
255                 return (res >> 8)
256
257         def createPartition(self, numpart):
258                 #gpt partitiontype support currently disabled.
259                 """devicename = self.device + "1"
260                 if numpart is not None:
261                         if numpart == 0:
262                                 devicename = self.device
263                         if numpart >= 1:
264                                 devicename = self.device + (str(numpart))
265                 type, sys, size, sizeg = harddiskmanager.getFdiskInfo(devicename)"""
266
267                 cmd = 'printf "8,\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS ' + self.disk_path
268
269                 #if sys is not None and "GPT" in sys:
270                 #       cmd = 'printf "34,,'+type+'\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS ' + self.disk_path
271                 res = system(cmd)
272                 return (res >> 8)
273
274         def mkfs(self):
275                 cmd = "mkfs.ext3 "
276                 if self.diskSize() > 4 * 1024:
277                         cmd += "-T largefile "
278                 cmd += "-m0 -O dir_index " + self.partitionPath("1")
279                 res = system(cmd)
280                 return (res >> 8)
281
282         def mount(self):
283                 try:
284                         fstab = open("/etc/fstab")
285                 except IOError:
286                         return -1
287
288                 lines = fstab.readlines()
289                 fstab.close()
290
291                 res = -1
292                 for line in lines:
293                         parts = line.strip().split(" ")
294                         real_path = path.realpath(parts[0])
295                         if not real_path[-1].isdigit():
296                                 continue
297                         try:
298                                 if MajorMinor(real_path) == MajorMinor(self.partitionPath(real_path[-1])):
299                                         cmd = "mount -t auto " + parts[0]
300                                         res = system(cmd)
301                                         break
302                         except OSError:
303                                 pass
304
305                 return (res >> 8)
306
307         def createMovieFolder(self, isFstabMounted = False):
308                 if isFstabMounted:
309                         try:
310                                 makedirs(resolveFilename(SCOPE_HDD))
311                         except OSError:
312                                 return -1
313                 else:
314                         try:
315                                 makedirs("/autofs/" + self.device + "1/movie")
316                         except OSError:
317                                 return -1
318                 return 0
319
320         def fsck(self, numpart):
321                 # We autocorrect any failures and check if the fs is actually one we can check (currently ext2/ext3)
322                 partitionPath = self.partitionPath("1")
323                 if numpart is not None:
324                         if numpart == 0:
325                                 partitionPath = self.dev_path
326                         if numpart >= 1:
327                                 partitionPath = self.partitionPath(str(numpart))
328
329                 partitionType = harddiskmanager.getBlkidPartitionType(partitionPath)
330
331                 res = -1
332                 if access(partitionPath, 0):
333                         if partitionType is not None and partitionType in ("ext2", "ext3"):
334                                 cmd = "fsck." + partitionType + " -f -p " + partitionPath
335                                 res = system(cmd)
336                 return (res >> 8)
337
338         def killPartition(self, n):
339                 part = self.partitionPath("1")
340                 if n is not None:
341                         if n == 0:
342                                 part = self.disk_path
343                         if n >= 1:
344                                 part = self.partitionPath(str(n))
345                 if access(part, 0):
346                         #cmd = 'dd bs=512 count=3 if=/dev/zero of=' + part
347                         cmd = 'dd bs=4k count=3 if=/dev/zero of=' + part
348                         res = system(cmd)
349                 else:
350                         res = 0
351                 return (res >> 8)
352
353         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")]
354
355         def initialize(self, isFstabMounted = False, numpart = None):
356                 if self.unmount(numpart) != 0:
357                         return -8
358
359                 # Udev tries to mount the partition immediately if there is an
360                 # old filesystem on it when fdisk reloads the partition table.
361                 # To prevent that, we overwrite the first sectors of the
362                 # partitions, if the partition existed before. This should work
363                 # for ext2/ext3 and also for GPT/EFI partitions.
364                 if numpart is not None:
365                         for p in range(numpart+1):
366                                 self.killPartition(p)
367                 else:
368                         self.killPartition(1)
369                 if self.createPartition(numpart) != 0:
370                         return -1
371
372                 if self.mkfs() != 0:
373                         return -2
374
375                 if isFstabMounted:
376                         if self.mount() != 0:
377                                 return -3
378
379                 if self.createMovieFolder(isFstabMounted) != 0:
380                         return -4
381
382                 return 0
383
384         def check(self, isFstabMounted = False, numpart = None):
385
386                 if self.unmount(numpart) != 0:
387                         return -8
388
389                 res = self.fsck(numpart)
390                 if res & 2 == 2:
391                         return -6
392
393                 if res & 4 == 4:
394                         return -7
395
396                 if res != 0 and res != 1:
397                         # A sum containing 1 will also include a failure
398                         return -5
399
400                 if isFstabMounted:
401                         if self.mount() != 0:
402                                 return -3
403
404                 return 0
405
406         def getDeviceDir(self):
407                 return self.dev_path
408
409         def getDeviceName(self):
410                 return self.disk_path
411
412         # the HDD idle poll daemon.
413         # as some harddrives have a buggy standby timer, we are doing this by hand here.
414         # first, we disable the hardware timer. then, we check every now and then if
415         # any access has been made to the disc. If there has been no access over a specifed time,
416         # we set the hdd into standby.
417         def readStats(self):
418                 try:
419                         l = open("/sys/block/%s/stat" % self.device).read()
420                 except IOError:
421                         return -1,-1
422                 (nr_read, _, _, _, nr_write) = l.split()[:5]
423                 return int(nr_read), int(nr_write)
424
425         def startIdle(self):
426                 self.last_access = time.time()
427                 self.last_stat = 0
428                 from enigma import eTimer
429
430                 # disable HDD standby timer
431                 if self.bus() == "External":
432                         Console().ePopen(("sdparm", "sdparm", "--set=SCT=0", self.disk_path))
433                 else:
434                         Console().ePopen(("hdparm", "hdparm", "-S0", self.disk_path))
435                 self.timer = eTimer()
436                 self.timer.callback.append(self.runIdle)
437                 self.idle_running = True
438                 self.setIdleTime(self.max_idle_time) # kick the idle polling loop
439
440         def runIdle(self):
441                 if not self.max_idle_time:
442                         return
443                 t = time.time()
444
445                 idle_time = t - self.last_access
446
447                 stats = self.readStats()
448                 print "nr_read", stats[0], "nr_write", stats[1]
449                 l = sum(stats)
450                 print "sum", l, "prev_sum", self.last_stat
451
452                 if l != self.last_stat and l >= 0: # access
453                         print "hdd was accessed since previous check!"
454                         self.last_stat = l
455                         self.last_access = t
456                         idle_time = 0
457                         self.is_sleeping = False
458                 else:
459                         print "hdd IDLE!"
460
461                 print "[IDLE]", idle_time, self.max_idle_time, self.is_sleeping
462                 if idle_time >= self.max_idle_time and not self.is_sleeping:
463                         self.setSleep()
464
465         def setSleep(self):
466                 if self.bus() == "External":
467                         Console().ePopen(("sdparm", "sdparm", "--command=stop", self.disk_path))
468                 else:
469                         Console().ePopen(("hdparm", "hdparm", "-y", self.disk_path))
470                 self.is_sleeping = True
471
472         def setIdleTime(self, idle):
473                 self.max_idle_time = idle
474                 if self.idle_running:
475                         if not idle:
476                                 self.timer.stop()
477                         else:
478                                 self.timer.start(idle * 100, False)  # poll 10 times per period.
479
480         def isSleeping(self):
481                 return self.is_sleeping
482
483         def isIdle(self):
484                 return self.idle_running
485
486 class Partition:
487         def __init__(self, mountpoint, device = None, description = "", force_mounted = False):
488                 self.mountpoint = mountpoint
489                 self.description = description
490                 self.force_mounted = force_mounted
491                 self.is_hotplug = force_mounted # so far; this might change.
492                 self.device = device
493                 self.disc_path = None
494                 self.uuid = None
495                 self.isMountable = False
496                 self.isReadable = False
497                 self.isWriteable = False
498                 self.isInitialized = False
499                 self.fsType = None
500                 if self.device is not None:
501                         self.updatePartitionInfo()
502
503         def updatePartitionInfo(self, dstpath = "", dev = None ):
504                 curdir = getcwd()
505                 testpath = ""
506                 if dstpath != "" and dev is not None:
507                         self.device = dev
508                         testpath = dstpath + self.device
509
510                 if self.device is not None:
511                         if testpath == "":
512                                 testpath = "/autofs/" + self.device
513                         self.uuid = harddiskmanager.getPartitionUUID(self.device)
514                         try:
515                                 chdir(testpath)
516                                 self.isMountable = True
517                         except OSError:
518                                 pass
519                         if self.isMountable:
520                                 try:
521                                         listdir(testpath)
522                                         self.isReadable = True
523                                 except OSError:
524                                         pass
525                         if self.uuid is not None:
526                                 if self.fsType is None:
527                                         self.fsType = harddiskmanager.getBlkidPartitionType("/dev/" + self.device)
528                         if self.isReadable:
529                                 mountpoint, fsType, mountopt = harddiskmanager.getMountInfo("/dev/" + self.device)
530                                 if self.fsType is None and fsType is not None:
531                                         self.fsType = fsType
532                                 if mountopt is not None and mountopt == 'rw':
533                                         self.isWriteable = True
534                                         if not access(testpath, W_OK):
535                                                 self.isWriteable = False
536                         if self.isWriteable:
537                                 if access(testpath + "/movie", W_OK):
538                                         self.isInitialized = True
539                 else:
540                         self.uuid = None
541                         self.isMountable = False
542                         self.isReadable = False
543                         self.isWriteable = False
544                         self.isInitialized = False
545                         self.fsType = None
546                 chdir(curdir)
547
548         def stat(self):
549                 return statvfs(self.mountpoint)
550
551         def free(self):
552                 try:
553                         s = self.stat()
554                         return s.f_bavail * s.f_bsize
555                 except OSError:
556                         return None
557
558         def total(self):
559                 try:
560                         s = self.stat()
561                         return s.f_blocks * s.f_bsize
562                 except OSError:
563                         return None
564
565         def mounted(self):
566                 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
567                 # TODO: can os.path.ismount be used?
568                 if self.force_mounted:
569                         return True
570                 try:
571                         mounts = open("/proc/mounts")
572                 except IOError:
573                         return False
574
575                 lines = mounts.readlines()
576                 mounts.close()
577
578                 for line in lines:
579                         if line.split(' ')[1] == self.mountpoint:
580                                 return True
581                 return False
582
583
584 DEVICEDB_SR = \
585         {"dm8000":
586                 {
587                         "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("DVD Drive"),
588                         "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("DVD Drive"),
589                         "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/host3/target3:0:0/3:0:0:0": _("DVD Drive"),
590                 },
591         "dm800":
592         {
593         },
594         "dm7025":
595         {
596         }
597         }
598
599 DEVICEDB = \
600         {"dm8000":
601                 {
602                         "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("SATA"),
603                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1:1.0": _("Front USB"),
604                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.1/1-1.1.": _("Front USB"),
605                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2:1.0": _("Back, upper USB"),
606                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.2/1-1.2.": _("Back, upper USB"),
607                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3:1.0": _("Back, lower USB"),
608                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.3/1-1.3.": _("Back, lower USB"),
609                         "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0/": _("Internal USB"),
610                         "/devices/platform/brcm-ohci-1.1/usb4/4-1/4-1:1.0/": _("Internal USB"),
611                         "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.4/1-1.4.": _("Internal USB"),
612                 },
613         "dm7020hd":
614         {
615                 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("SATA"),
616                 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("eSATA"),
617                 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1:1.0": _("Front USB"),
618                 "/devices/platform/brcm-ehci-1.1/usb2/2-1/2-1.": _("Front USB"),
619                 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": _("Back, upper USB"),
620                 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2.": _("Back, upper USB"),
621                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": _("Back, lower USB"),
622                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1.": _("Back, lower USB"),
623         },
624         "dm800":
625         {
626                 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("SATA"),
627                 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": _("Upper USB"),
628                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": _("Lower USB"),
629         },
630         "dm800se":
631         {
632                 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("SATA"),
633                 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("eSATA"),
634                 "/devices/platform/brcm-ehci.0/usb1/1-2/1-2:1.0": _("Upper USB"),
635                 "/devices/platform/brcm-ehci.0/usb1/1-1/1-1:1.0": _("Lower USB"),
636         },
637         "dm500hd":
638         {
639                 "/devices/pci0000:01/0000:01:00.0/host1/target1:0:0/1:0:0:0": _("eSATA"),
640                 "/devices/pci0000:01/0000:01:00.0/host0/target0:0:0/0:0:0:0": _("eSATA"),
641         },
642         "dm7025":
643         {
644                 "/devices/pci0000:00/0000:00:14.1/ide1/1.0": "Compact Flash", #hdc
645                 "/devices/pci0000:00/0000:00:14.1/ide0/0.0": "Internal Harddisk"
646         }
647         }
648
649 class HarddiskManager:
650         def __init__(self):
651                 config.storage_options = ConfigSubsection()
652                 config.storage_options.default_device = ConfigText(default = "<undefined>")
653                 config.storage = ConfigSubDict()
654                 self.hdd = [ ]
655                 self.cd = ""
656                 self.partitions = [ ]
657                 self.devices_scanned_on_init = [ ]
658                 self.delayed_device_Notifier = [ ]
659
660                 self.on_partition_list_change = CList()
661
662                 # currently, this is just an enumeration of what's possible,
663                 # this probably has to be changed to support automount stuff.
664                 # still, if stuff is mounted into the correct mountpoints by
665                 # external tools, everything is fine (until somebody inserts
666                 # a second usb stick.)
667                 p = [
668                                         ("/media/hdd", _("Hard disk")),
669                                         ("/media/card", _("Card")),
670                                         ("/media/cf", _("Compact Flash")),
671                                         ("/media/mmc1", _("SD/MMC")),
672                                         ("/media/net", _("Network Mount")),
673                                         ("/media/ram", _("Ram Disk")),
674                                         ("/media/usb", _("USB Stick")),
675                                         ("/", _("Internal Flash"))
676                                 ]
677                 self.partitions.extend([ Partition(mountpoint = x[0], description = x[1]) for x in p ])
678
679         def getBlockDevInfo(self, blockdev):
680                 devpath = "/sys/block/" + blockdev
681                 error = False
682                 removable = False
683                 blacklisted = False
684                 is_cdrom = False
685                 partitions = []
686                 try:
687                         removable = bool(int(readFile(devpath + "/removable")))
688                         dev = int(readFile(devpath + "/dev").split(':')[0])
689                         if dev in (7, 31): # loop, mtdblock
690                                 blacklisted = True
691                         if blockdev[0:2] == 'sr':
692                                 is_cdrom = True
693                         if blockdev[0:2] == 'hd':
694                                 try:
695                                         media = readFile("/proc/ide/%s/media" % blockdev)
696                                         if "cdrom" in media:
697                                                 is_cdrom = True
698                                 except IOError:
699                                         error = True
700                         # check for partitions
701                         if not is_cdrom:
702                                 for partition in listdir(devpath):
703                                         if partition[0:len(blockdev)] != blockdev:
704                                                 continue
705                                         partitions.append(partition)
706                         else:
707                                 self.cd = blockdev
708                 except IOError:
709                         error = True
710                 # check for medium
711                 medium_found = True
712                 try:
713                         open("/dev/" + blockdev).close()
714                 except IOError, err:
715                         if err.errno == 159: # no medium present
716                                 medium_found = False
717                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
718
719         def enumerateBlockDevices(self):
720                 self.setupConfigEntries(initial_call = True)
721                 print "enumerating block devices..."
722                 for blockdev in listdir("/sys/block"):
723                         error, blacklisted, removable, is_cdrom, partitions, medium_found = self.addHotplugPartition(blockdev)
724                         if not error and not blacklisted:
725                                 if medium_found:
726                                         for part in partitions:
727                                                 self.addHotplugPartition(part)
728                                 self.devices_scanned_on_init.append((blockdev, removable, is_cdrom, medium_found))
729                                 print "[enumerateBlockDevices] devices_scanned_on_init:",self.devices_scanned_on_init
730
731         def getAutofsMountpoint(self, device):
732                 return "/autofs/%s/" % (device)
733
734         def is_hard_mounted(self, device):
735                 mounts = file('/proc/mounts').read().split('\n')
736                 for x in mounts:
737                         if x.find('/autofs') == -1 and x.find(device) != -1:
738                                 #print "is_hard_mounted:",device
739                                 return True
740                 return False
741
742         def get_mountdevice(self, mountpoint):
743                 mounts = file('/proc/mounts').read().split('\n')
744                 for x in mounts:
745                         if not x.startswith('/'):
746                                 continue
747                         device, mp = x.split()[0:2]
748                         if mp == mountpoint:
749                                 #print "get_mountdevice for '%s' -> %s " % (device, mp)
750                                 return device
751                 return None
752
753         def get_mountpoint(self, mountpath):
754                 mounts = file('/proc/mounts').read().split('\n')
755                 for x in mounts:
756                         if not x.startswith('/'):
757                                 continue
758                         path, mp = x.split()[0:2]
759                         if path == mountpath:
760                                 #print "get_mountpoint for '%s' -> %s " % (path, mp)
761                                 return mp
762                 return None
763
764         def is_uuidpath_mounted(self, uuidpath, mountpoint):
765                 mounts = file('/proc/mounts').read().split('\n')
766                 for x in mounts:
767                         if not x.startswith('/'):
768                                 continue
769                         path, mp = x.split()[0:2]
770                         if (path == uuidpath and mp == mountpoint):
771                                 #print "is_uuid_mounted:'%s' for: %s " % (path, mp)
772                                 return True
773                 return False
774
775         def is_fstab_mountpoint(self, device, mountpoint):
776                 mounts = file('/etc/fstab').read().split('\n')
777                 for x in mounts:
778                         if not x.startswith('/'):
779                                 continue
780                         dev, mp = x.split()[0:2]
781                         if (dev == device and mp == mountpoint):
782                                 #print "is_fstab_mountpoint:'%s' for: %s " % (mp, dev)
783                                 return True
784                 return False
785
786         def get_fstab_mountstate(self, device, mountpoint):
787                 mounts = file('/etc/fstab').read().split('\n')
788                 for x in mounts:
789                         if not x.startswith('/'):
790                                 continue
791                         dev, mp, ms = x.split()[0:3]
792                         if (dev == device and mp == mountpoint):
793                                 #print "got_fstab_mountstate:'%s' for: %s - %s" % (ms, dev, mp)
794                                 return ms
795                 return False
796
797         def get_fstab_mountpoint(self, device):
798                 mounts = file('/etc/fstab').read().split('\n')
799                 for x in mounts:
800                         if not x.startswith('/'):
801                                 continue
802                         dev, mp = x.split()[0:2]
803                         if device == dev:
804                                 #print "got_fstab_mountpoint:'%s' for: %s" % (mp, dev)
805                                 return mp
806                 return None
807
808         def modifyFstabEntry(self, partitionPath, mountpoint, mode = "add_deactivated"):
809                 try:
810                         alreadyAdded = self.is_fstab_mountpoint(partitionPath, mountpoint)
811                         oldLine = None
812                         mounts = file('/etc/fstab').read().split('\n')
813                         fp = file("/etc/fstab", 'w')
814                         fp.write("#automatically edited by enigma2, " + str(time.strftime( "%a" + ", " + "%d " + "%b" + " %Y %H:%M:%S", time.localtime(time.time() ))) + "\n")
815                         for x in mounts:
816                                 if (x.startswith(partitionPath) and mountpoint in x):
817                                         oldLine = x
818                                         continue
819                                 if len(x):
820                                         if x.startswith('#automatically'):
821                                                 continue
822                                         fp.write(x + "\n")
823                         if not alreadyAdded:
824                                 if mode == "add_deactivated":
825                                         print "modifyFstabEntry - add_deactivated:", partitionPath, mountpoint
826                                         fp.write(partitionPath + "\t" + mountpoint + "\tnoauto\tdefaults\t0 0\n")
827                         else:
828                                 if mode == "add_deactivated":
829                                         if oldLine is not None:
830                                                 if "noauto" in oldLine:
831                                                         fp.write(oldLine + "\n")
832                                                 else:
833                                                         fp.write(oldLine.replace("auto","noauto") + "\n")
834                         fp.close()
835                 except:
836                         print "error adding fstab entry for: %s" % (partitionPath)
837
838         def addHotplugPartition(self, device, physdev = None):
839                 if not physdev:
840                         dev, part = self.splitDeviceName(device)
841                         try:
842                                 physdev = path.realpath('/sys/block/' + dev + '/device')[4:]
843                         except OSError:
844                                 physdev = dev
845                                 print "couldn't determine blockdev physdev for device", device
846
847                 error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
848                 print "found block device '%s':" % device,
849
850                 if blacklisted:
851                         print "blacklisted"
852                 else:
853                         if error:
854                                 print "error querying properties"
855                         elif not medium_found:
856                                 print "no medium"
857                         else:
858                                 print "ok, removable=%s, cdrom=%s, partitions=%s" % (removable, is_cdrom, partitions)
859
860                         l = len(device)
861                         if l:
862                                 # see if this is a harddrive or removable drive (usb stick/cf/sd)
863                                 if not device[l-1].isdigit() and not is_cdrom:
864                                         if self.getHDD(device) is None and medium_found:
865                                                 if removable:
866                                                         self.hdd.append(Harddisk(device, True))
867                                                 else:
868                                                         self.hdd.append(Harddisk(device, False))
869                                         self.hdd.sort()
870                                         SystemInfo["Harddisk"] = len(self.hdd) > 0
871                                 if (not removable or medium_found):
872                                         self.addDevicePartition(device, physdev)
873
874                 return error, blacklisted, removable, is_cdrom, partitions, medium_found
875
876         def removeHotplugPartition(self, device):
877                 mountpoint = self.getAutofsMountpoint(device)
878                 uuid = self.getPartitionUUID(device)
879                 print "[removeHotplugPartition] for device:'%s' uuid:'%s' and mountpoint:'%s'" % (device, uuid, mountpoint)
880                 p = self.getPartitionbyDevice(device)
881                 if p is None:
882                         p = self.getPartitionbyMountpoint(mountpoint)
883                 if p is not None:
884                         if uuid is None and p.uuid is not None:
885                                 print "[removeHotplugPartition] WE GOT uuid:'%s' but have:'%s'" % (uuid,p.uuid)
886                                 uuid = p.uuid
887                                 harddiskmanager.unmountPartitionbyMountpoint(p.mountpoint)
888                         if uuid is not None and config.storage.get(uuid, None) is not None:
889                                 self.unmountPartitionbyUUID(uuid)
890                                 if not config.storage[uuid]['enabled'].value:
891                                         del config.storage[uuid]
892                                         print "[removeHotplugPartition] - remove uuid %s from temporary drive add" % (uuid)
893                         if p.mountpoint != "/media/hdd":
894                                 self.partitions.remove(p)
895                                 self.on_partition_list_change("remove", p)
896
897                 l = len(device)
898                 if l and not device[l-1].isdigit():
899                         for hdd in self.hdd:
900                                 if hdd.device == device:
901                                         hdd.stop()
902                                         self.hdd.remove(hdd)
903                                         break
904                         SystemInfo["Harddisk"] = len(self.hdd) > 0
905
906                         #call the notifier only after we have fully removed the disconnected drive
907                         for callback in self.delayed_device_Notifier:
908                                 try:
909                                         callback(device, "remove_delayed" )
910                                 except AttributeError:
911                                         self.delayed_device_Notifier.remove(callback)
912
913         def addDevicePartition(self, device, physdev):
914                 # device is the device name, without /dev
915                 # physdev is the physical device path, which we (might) use to determine the userfriendly name
916                 description = self.getUserfriendlyDeviceName(device, physdev)
917                 device_mountpoint = self.getAutofsMountpoint(device)
918                 uuid = self.getPartitionUUID(device)
919                 print "[addDevicePartition] device:'%s' with UUID:'%s'" % (device, uuid)
920                 if config.storage.get(uuid, None) is not None:
921                         if config.storage[uuid]['enabled'].value and config.storage[uuid]['mountpoint'].value != "":
922                                 device_mountpoint = config.storage[uuid]['mountpoint'].value
923
924                 if uuid is not None:
925                         if config.storage.get(uuid, None) is None:
926                                 tmp = self.getPartitionbyDevice(device)
927                                 if tmp is not None:
928                                         if uuid != tmp.uuid and tmp.uuid == config.storage_options.default_device.value and tmp.mountpoint == "/media/hdd": #default hdd re/initialize
929                                                 tmp.device = None
930                                                 tmp.updatePartitionInfo()
931                                 self.setupConfigEntries(initial_call = False, dev = device)
932                         else:
933                                 tmp = self.getPartitionbyMountpoint(device_mountpoint)
934                                 if tmp is not None and (tmp.uuid != uuid or tmp.mountpoint != device_mountpoint):
935                                         self.storageDeviceChanged(uuid)
936
937                 p = self.getPartitionbyMountpoint(device_mountpoint)
938                 if p is not None:
939                         if uuid is not None:
940                                 if p.uuid is not None and p.uuid != uuid:
941                                         if config.storage.get(p.uuid, None) is not None:
942                                                 del config.storage[p.uuid] #delete old uuid reference entries
943                         p.updatePartitionInfo()
944                 else:
945                         forced = True
946                         if uuid is not None:
947                                 cfg_uuid = config.storage.get(uuid, None)
948                                 if cfg_uuid is not None:
949                                         if cfg_uuid['enabled'].value:
950                                                 forced = False
951                                         else:
952                                                 device_mountpoint = self.getAutofsMountpoint(device)
953                         x = self.getPartitionbyDevice(device)
954                         if x is None:
955                                 p = Partition(mountpoint = device_mountpoint, description = description, force_mounted = forced, device = device)
956                                 self.partitions.append(p)
957                                 self.on_partition_list_change("add", p)
958                         else:   # found old partition entry
959                                 if config.storage.get(x.uuid, None) is not None:
960                                         del config.storage[x.uuid] #delete old uuid reference entries
961                                 x.mountpoint = device_mountpoint
962                                 x.force_mounted = True
963                                 x.updatePartitionInfo()
964
965                 for callback in self.delayed_device_Notifier:
966                         try:
967                                 callback(device, "add_delayed" )
968                         except AttributeError:
969                                 self.delayed_device_Notifier.remove(callback)
970
971         def HDDCount(self):
972                 return len(self.hdd)
973
974         def HDDList(self):
975                 list = [ ]
976                 for hd in self.hdd:
977                         hdd = hd.model() + " - " + hd.bus()
978                         cap = hd.capacity()
979                         if cap != "":
980                                 hdd += " (" + cap + ")"
981                         list.append((hdd, hd))
982                 return list
983
984         def HDDEnabledCount(self):
985                 cnt = 0
986                 for uuid, cfg in config.storage.items():
987                         #print "uuid", uuid, "cfg", cfg
988                         if cfg["enabled"].value:
989                                 cnt += 1
990                 return cnt
991
992         def getHDD(self, part):
993                 for hdd in self.hdd:
994                         if hdd.device == part[:3]:
995                                 return hdd
996                 return None
997
998         def getCD(self):
999                 return self.cd
1000
1001         def getMountInfo(self, device):
1002                 dev = mountpoint = fstype = mountopt = None
1003                 try:
1004                         mounts = file('/proc/mounts').read().split('\n')
1005                         for x in mounts:
1006                                 if not x.startswith('/'):
1007                                         continue
1008                                 if x.startswith(device):
1009                                         data = x.split(',')
1010                                         dev, mountpoint, fstype, mountopt = data[0].split(None,4)
1011                 except:
1012                         print "error getting mount info"
1013                 #print "getMountInfo:",mountpoint, fstype, mountopt
1014                 return mountpoint, fstype, mountopt
1015
1016         def getFdiskInfo(self, devname):
1017                 size = sizeg = fstype = sys = None
1018                 cmd = "fdisk -l /dev/" + devname
1019                 try:
1020                         for line in popen(cmd).read().split('\n'):
1021                                 if line.startswith("Disk"):
1022                                         sizeobj = re.search(r', ((?:[a-zA-Z0-9])*) bytes', line)
1023                                         if sizeobj:
1024                                                 size = sizeobj.group(1)
1025                                         sizegobj = re.search(r': ((?:[0-9.0-9])*) GB', line)
1026                                         if sizegobj:
1027                                                 sizeg = sizegobj.group(1)
1028                                 if not line.startswith('/'):
1029                                         continue
1030                                 if line.startswith("/dev/" + devname):
1031                                         a,b,c,d, fstype, sys = line.split(None,5)
1032                 except:
1033                         print "error getting fdisk device info"
1034                 #print "getFdiskInfo:",devname, fstype, sys, size, sizeg
1035                 return fstype, sys, size, sizeg
1036
1037         def getBlkidPartitionType(self, device):
1038                 #print "getBlkidPartitionType",device
1039                 fstype = None
1040                 cmd = "blkid " + str(device)
1041                 try:
1042                         for line in popen(cmd).read().split('\n'):
1043                                 if not line.startswith(device):
1044                                         continue
1045                                 print "getBlkidPartitionType",line
1046                                 fstobj = re.search(r' TYPE="((?:[^"\\]|\\.)*)"', line)
1047                                 if fstobj:
1048                                         fstype = fstobj.group(1)
1049                 except:
1050                         print "error getting blkid partition type"
1051                 #print "getBlkidPartitionType:",device, fstype
1052                 return fstype
1053
1054         def getLinkPath(self,link):
1055                 if path.islink(link):
1056                         p = path.normpath(readlink(link))
1057                         if path.isabs(p):
1058                                 return p
1059                         return path.join(path.dirname(link), p)
1060
1061         def getRealPath(self, dstpath):
1062                 p = self.getLinkPath(dstpath)
1063                 if p:
1064                         return p
1065                 return path.realpath(dstpath)
1066
1067         def isMount(self, mountdir):
1068                 return path.ismount( self.getRealPath(mountdir) )
1069
1070         def _inside_mountpoint(self, filename):
1071                 #print "is mount? '%s'" % filename
1072                 if filename == "":
1073                         return False
1074                 if filename == "/":
1075                         return False
1076                 if path.ismount(filename):
1077                         return True
1078                 return self._inside_mountpoint("/".join(filename.split("/")[:-1]))
1079
1080         def inside_mountpoint(self,filename):
1081                 return self._inside_mountpoint(path.realpath(filename))
1082
1083         def isUUIDpathFsTabMount(self, uuid, mountpath):
1084                 uuidpartitionPath = "/dev/disk/by-uuid/" + uuid
1085                 if self.is_hard_mounted(uuidpartitionPath) and self.is_fstab_mountpoint(uuidpartitionPath, mountpath):
1086                         if self.get_fstab_mountstate(uuidpartitionPath, mountpath) == 'auto':
1087                                 return True
1088                 return False
1089
1090         def isPartitionpathFsTabMount(self, uuid, mountpath):
1091                 dev = self.getDeviceNamebyUUID(uuid)
1092                 if dev is not None:
1093                         partitionPath = "/dev/" + str(dev)
1094                         if self.is_hard_mounted(partitionPath) and self.is_fstab_mountpoint(partitionPath, mountpath):
1095                                 if self.get_fstab_mountstate(partitionPath, mountpath) == 'auto':
1096                                         return True
1097                 return False
1098
1099         def getPartitionVars(self, hd, partitionNum = False):
1100                 #print "getPartitionVars for hdd:'%s' and partitionNum:'%s'" % (hd.device, partitionNum)
1101                 hdd = hd
1102                 numPartitions = hdd.numPartitions()
1103                 uuid = partitionType = partitionPath = uuidPath = deviceName = None
1104                 if partitionNum is False:
1105                         if numPartitions == 0:
1106                                 deviceName = hdd.device
1107                                 uuid = self.getPartitionUUID(deviceName)
1108                                 partitionPath = hdd.dev_path
1109                         if numPartitions == 1:
1110                                 deviceName = hdd.device + str(numPartitions)
1111                                 uuid = self.getPartitionUUID(deviceName)
1112                                 partitionPath = hdd.partitionPath(str(numPartitions))
1113                         else: #just in case, we should never get here
1114                                 deviceName = hdd.device
1115                                 partitionPath = hdd.dev_path
1116                 else:
1117                         deviceName = hdd.device + str(partitionNum)
1118                         uuid = self.getPartitionUUID(deviceName)
1119                         partitionPath = hdd.partitionPath(str(partitionNum))
1120                 if uuid is not None:
1121                         uuidPath = "/dev/disk/by-uuid/" + uuid
1122                 return deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath
1123
1124         def suggestDeviceMountpath(self,uuid):
1125                 p = self.getPartitionbyUUID(uuid)
1126                 if p is not None:
1127                         hdd = self.getHDD(p.device)
1128                         if hdd is not None:
1129                                 val = str(hdd.model(model_only = True)).strip().replace(' ','').replace('-','').replace('_','')
1130                                 cnt = 0
1131                                 for dev in self.hdd:
1132                                         tmpval = str(dev.model(model_only = True)).strip().replace(' ','').replace('-','').replace('_','')
1133                                         if tmpval == val:
1134                                                 cnt +=1
1135                                 if cnt <=1:
1136                                         cnt = 0
1137                                         for uid in config.storage.keys():
1138                                                 if uid == uuid:
1139                                                         cnt += 1
1140                                                         continue
1141                                                 data = config.storage[uid]["device_description"].value.split(None,1)
1142                                                 tmpval = data[0].strip().replace(' ','').replace('-','').replace('_','')
1143                                                 if tmpval == val or tmpval.endswith(val):
1144                                                         cnt += 1
1145                                 if cnt >= 2:
1146                                         val += "HDD" + str(cnt)
1147                                 if hdd.numPartitions() >= 2:
1148                                         partNum = p.device[3:]
1149                                         if str(partNum).isdigit():
1150                                                 val += "Part" + str(partNum)
1151                                 print "suggestDeviceMountpath for uuid: '%s' -> '%s'" %(uuid,val)
1152                                 return "/media/" + val
1153                 else:
1154                         mountpath = ""
1155                         uuid_cfg = config.storage.get(uuid, None)
1156                         if uuid_cfg is not None:
1157                                 if uuid_cfg["mountpoint"].value != "" and uuid_cfg["mountpoint"].value != "/media/hdd":
1158                                         mountpath = uuid_cfg["mountpoint"].value
1159                                 else:
1160                                         if uuid_cfg["device_description"].value != "":
1161                                                 tmp = uuid_cfg["device_description"].value.split(None,1)
1162                                                 mountpath = "/media/" + tmp[0].strip().replace(' ','').replace('-','').replace('_','')
1163                         if mountpath != "":
1164                                 cnt = 0
1165                                 for uid in config.storage.keys():
1166                                         if config.storage[uid]["mountpoint"].value != "" and config.storage[uid]["mountpoint"].value != "/media/hdd":
1167                                                 tmp = config.storage[uid]["mountpoint"].value
1168                                         else:
1169                                                 data = config.storage[uid]["device_description"].value.split(None,1)
1170                                                 tmp = "/media/" + data[0].strip().replace(' ','').replace('-','').replace('_','')
1171                                         if tmp == mountpath:
1172                                                 cnt += 1
1173                                 if cnt >= 2:
1174                                         mountpath += "HDD" + str(cnt)
1175                                 return mountpath
1176                 return ""
1177
1178         def changeStorageDevice(self, uuid = None, action = None , mountData = None ):
1179                 # mountData should be [oldenable,oldmountpath, newenable,newmountpath]
1180                 print "[changeStorageDevice] uuid:'%s' - action:'%s' - mountData:'%s'" %(uuid, action, mountData)
1181                 currentDefaultStorageUUID = config.storage_options.default_device.value
1182                 print "[changeStorageDevice]: currentDefaultStorageUUID:",currentDefaultStorageUUID
1183                 successfully = False
1184                 def_mp = "/media/hdd"
1185                 cur_default_newmp = new_default_newmp = old_cur_default_mp = old_new_default_mp = ""
1186                 cur_default = new_default = None
1187                 cur_default_dev = new_default_dev = None
1188                 cur_default_cfg = new_default_cfg = None
1189                 old_cur_default_enabled = old_new_default_enabled = False
1190
1191                 if action == "mount_default":
1192                         if currentDefaultStorageUUID != "<undefined>" and currentDefaultStorageUUID != uuid:
1193                                 cur_default = self.getDefaultStorageDevicebyUUID(currentDefaultStorageUUID)
1194                         new_default = self.getPartitionbyUUID(uuid)
1195                         if cur_default is not None:
1196                                 cur_default_cfg = config.storage.get(currentDefaultStorageUUID, None)
1197                         new_default_cfg = config.storage.get(uuid, None)
1198                         if new_default is not None:
1199                                 new_default_dev = new_default.device
1200                                 if currentDefaultStorageUUID != "<undefined>" and currentDefaultStorageUUID != uuid:
1201                                         cur_default_newmp = self.suggestDeviceMountpath(currentDefaultStorageUUID)
1202                                 if cur_default is not None:
1203                                         cur_default_dev = cur_default.device
1204                                 if new_default_cfg is not None:
1205                                         old_new_default_enabled = new_default_cfg["enabled"].value
1206                                         old_new_default_mp = new_default_cfg["mountpoint"].value
1207                                         #[oldmountpath, oldenable, newmountpath, newenable]
1208                                         if mountData is not None and isinstance(mountData, (list, tuple)):
1209                                                 old_new_default_enabled = mountData[1]
1210                                                 old_new_default_mp = mountData[0]
1211                                         if cur_default_cfg is not None and path.exists(def_mp) and self.isMount(def_mp) and cur_default_cfg["enabled"].value and cur_default_cfg["mountpoint"].value == def_mp:
1212                                                 old_cur_default_enabled = cur_default_cfg["enabled"].value
1213                                                 old_cur_default_mp = cur_default_cfg["mountpoint"].value
1214                                                 self.unmountPartitionbyMountpoint(def_mp)
1215                                         if not path.exists(def_mp) or (path.exists(def_mp) and not self.isMount(def_mp)):
1216                                                 if cur_default_cfg is not None:
1217                                                         cur_default_cfg["mountpoint"].value = cur_default_newmp
1218                                                 if cur_default_dev is not None:
1219                                                         self.setupConfigEntries(initial_call = False, dev = cur_default_dev)
1220                                                 if cur_default_dev is None or (path.exists(cur_default_newmp) and self.isMount(cur_default_newmp)):
1221                                                         if new_default_cfg["enabled"].value and path.exists(new_default_cfg["mountpoint"].value) and self.isMount(new_default_cfg["mountpoint"].value):
1222                                                                 self.unmountPartitionbyMountpoint(new_default_cfg["mountpoint"].value, new_default_dev )
1223                                                         if not new_default_cfg["enabled"].value or (path.exists(new_default_cfg["mountpoint"].value) and not self.isMount(new_default_cfg["mountpoint"].value)):
1224                                                                 new_default_cfg["mountpoint"].value = def_mp
1225                                                                 new_default_cfg["enabled"].value = True
1226                                                                 self.storageDeviceChanged(uuid)
1227                                                                 new_default = self.getPartitionbyMountpoint(def_mp)
1228                                                                 if cur_default_cfg is None and cur_default_newmp is not "": #currentdefault was offline
1229                                                                         cur_default_cfg = config.storage.get(currentDefaultStorageUUID, None)
1230                                                                 if cur_default_cfg is not None:
1231                                                                         old_cur_default_enabled = cur_default_cfg["enabled"].value
1232                                                                         old_cur_default_mp = cur_default_cfg["mountpoint"].value
1233                                                                         cur_default_cfg["mountpoint"].value = cur_default_newmp
1234                                                                 if new_default is not None and new_default_cfg["mountpoint"].value == def_mp and path.exists(def_mp) and self.isMount(def_mp) and new_default.mountpoint == def_mp:
1235                                                                         successfully = True
1236                                                                         config.storage_options.default_device.value = uuid
1237                                                                         if new_default_cfg is not None:
1238                                                                                 new_default_cfg.save()
1239                                                                         if cur_default_cfg is not None:
1240                                                                                 cur_default_cfg.save()
1241                 if action == "mount_only":
1242                         new_default = self.getPartitionbyUUID(uuid)
1243                         new_default_cfg = config.storage.get(uuid, None)
1244                         if new_default is not None:
1245                                 new_default_dev = new_default.device
1246                                 new_default_newmp = self.suggestDeviceMountpath(uuid)
1247                                 if new_default_cfg is not None:
1248                                         old_new_default_enabled = new_default_cfg["enabled"].value
1249                                         old_new_default_mp = new_default_cfg["mountpoint"].value
1250                                         #[oldmountpath, oldenable, newmountpath, newenable]
1251                                         if mountData is not None and isinstance(mountData, (list, tuple)):
1252                                                 old_new_default_enabled = mountData[1]
1253                                                 old_new_default_mp = mountData[0]
1254                                                 new_default_newmp = mountData[2]
1255                                         if old_new_default_enabled and path.exists(def_mp) and self.isMount(def_mp) and old_new_default_mp == def_mp:
1256                                                 if uuid == currentDefaultStorageUUID:
1257                                                         self.unmountPartitionbyMountpoint(def_mp) #current partition is default, unmount!
1258                                         if old_new_default_enabled and old_new_default_mp != "" and old_new_default_mp != def_mp and path.exists(old_new_default_mp) and self.isMount(old_new_default_mp):
1259                                                 self.unmountPartitionbyMountpoint(old_new_default_mp, new_default_dev) #current partition is already mounted atm. unmount!
1260                                         if not new_default_cfg["enabled"].value or old_new_default_mp == "" or (new_default_cfg["enabled"].value and path.exists(old_new_default_mp) and not self.isMount(old_new_default_mp)):
1261                                                 new_default_cfg["enabled"].value = True
1262                                                 new_default_cfg["mountpoint"].value = new_default_newmp
1263                                                 if path.exists(new_default_newmp) and self.isMount(new_default_newmp):
1264                                                         tmppath = self.get_mountdevice(new_default_newmp)
1265                                                         if tmppath is not None and tmppath == "/dev/disk/by-uuid/" + uuid:
1266                                                                 self.unmountPartitionbyMountpoint(new_default_newmp)
1267                                                 else:
1268                                                         x = None
1269                                                         if new_default_dev is not None:
1270                                                                 x = self.getPartitionbyDevice(new_default_dev)
1271                                                         if x is None:
1272                                                                 self.setupConfigEntries(initial_call = False, dev = new_default_dev)
1273                                                         else:
1274                                                                 self.storageDeviceChanged(uuid)
1275                                                 new_default = self.getPartitionbyUUID(uuid)
1276                                                 if new_default is not None and path.exists(new_default_newmp) and self.isMount(new_default_newmp):
1277                                                         successfully = True
1278                                                         if uuid == currentDefaultStorageUUID:
1279                                                                 config.storage_options.default_device.value = "<undefined>"
1280                                                         new_default_cfg.save()
1281                 if action == "unmount":
1282                         new_default = self.getPartitionbyUUID(uuid)
1283                         new_default_cfg = config.storage.get(uuid, None)
1284                         if new_default is not None:
1285                                 new_default_dev = new_default.device
1286                                 if new_default_cfg is not None and new_default_cfg["mountpoint"].value == new_default.mountpoint:
1287                                         old_new_default_mp = new_default_cfg["mountpoint"].value
1288                                         old_new_default_enabled = new_default_cfg["enabled"].value
1289                                         #[oldmountpath, oldenable, newmountpath, newenable]
1290                                         if mountData is not None and isinstance(mountData, (list, tuple)):
1291                                                 old_new_default_enabled = mountData[1]
1292                                                 old_new_default_mp = mountData[0]
1293                                 if new_default_cfg is not None and path.exists(old_new_default_mp) and self.isMount(old_new_default_mp):
1294                                         if uuid == currentDefaultStorageUUID:
1295                                                 self.unmountPartitionbyMountpoint(old_new_default_mp)
1296                                         else:
1297                                                 self.unmountPartitionbyMountpoint(old_new_default_mp, new_default_dev)
1298                                 if path.exists(old_new_default_mp) and not self.isMount(old_new_default_mp):
1299                                         new_default_cfg["mountpoint"].value = ""
1300                                         new_default_cfg["enabled"].value = False
1301                                         self.setupConfigEntries(initial_call = False, dev = new_default_dev)
1302                                         if path.exists(old_new_default_mp) and not self.isMount(old_new_default_mp):
1303                                                 successfully = True
1304                                                 new_default_cfg.save()
1305                                                 if uuid == currentDefaultStorageUUID:
1306                                                         config.storage_options.default_device.value = "<undefined>"
1307                 if not successfully:
1308                         print "<< not successfully >>"
1309                         if cur_default_cfg is not None:
1310                                 cur_default_cfg["mountpoint"].value = old_cur_default_mp
1311                                 cur_default_cfg["enabled"].value = old_cur_default_enabled
1312                                 cur_default_cfg.save()
1313                                 if currentDefaultStorageUUID != "<undefined>":
1314                                         self.storageDeviceChanged(currentDefaultStorageUUID)
1315                         if new_default_cfg is not None:
1316                                 new_default_cfg["mountpoint"].value = old_new_default_mp
1317                                 new_default_cfg["enabled"].value = old_new_default_enabled
1318                                 new_default_cfg.save()
1319                                 self.storageDeviceChanged(uuid)
1320                 config.storage_options.default_device.save()
1321                 config.storage_options.save()
1322                 config.storage.save()
1323                 config.save()
1324                 configfile.save()
1325                 print "changeStorageDevice default is now:",config.storage_options.default_device.value
1326                 return successfully
1327
1328         def isConfiguredStorageDevice(self,uuid):
1329                 cfg_uuid = config.storage.get(uuid, None)
1330                 if cfg_uuid is not None and cfg_uuid["enabled"].value:
1331                         #print "isConfiguredStorageDevice:",uuid
1332                         return True
1333                 return False
1334
1335         def isDefaultStorageDeviceActivebyUUID(self, uuid):
1336                 p = self.getDefaultStorageDevicebyUUID(uuid)
1337                 if p is not None and p.uuid == uuid:
1338                         #print "isDefaultStorageDeviceActivebyUUID--for UUID:->",uuid,p.description, p.device, p.mountpoint, p.uuid
1339                         return True
1340                 return False
1341
1342         def getDefaultStorageDevicebyUUID(self, uuid):
1343                 for p in self.getConfiguredStorageDevices():
1344                         if p.uuid == uuid:
1345                                 #print "getDefaultStorageDevicebyUUID--p:",uuid, p.description, p.device, p.mountpoint, p.uuid
1346                                 return p
1347                 return None
1348
1349         def getConfiguredStorageDevices(self):
1350                 parts = [x for x in self.partitions if (x.uuid is not None and x.mounted() and self.isConfiguredStorageDevice(x.uuid))]
1351                 return [x for x in parts]
1352
1353         def getMountedPartitions(self, onlyhotplug = False):
1354                 parts = [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
1355                 devs = set([x.device for x in parts])
1356                 for devname in devs.copy():
1357                         if not devname:
1358                                 continue
1359                         dev, part = self.splitDeviceName(devname)
1360                         if part and dev in devs: # if this is a partition and we still have the wholedisk, remove wholedisk
1361                                 devs.remove(dev)
1362
1363                 # return all devices which are not removed due to being a wholedisk when a partition exists
1364                 return [x for x in parts if not x.device or x.device in devs]
1365
1366         def splitDeviceName(self, devname):
1367                 # 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.
1368                 dev = devname[:3]
1369                 part = devname[3:]
1370                 for p in part:
1371                         if not p.isdigit():
1372                                 return devname, 0
1373                 return dev, part and int(part) or 0
1374
1375         def getUserfriendlyDeviceName(self, dev, phys):
1376                 #print "getUserfriendlyDeviceName",dev, phys
1377                 dev, part = self.splitDeviceName(dev)
1378                 description = "External Storage %s" % dev
1379                 have_model_descr = False
1380                 try:
1381                         description = readFile("/sys" + phys + "/model")
1382                         have_model_descr = True
1383                 except IOError, s:
1384                         print "couldn't read model: ", s
1385                 from Tools.HardwareInfo import HardwareInfo
1386                 if dev.find('sr') == 0 and dev[2].isdigit():
1387                         devicedb = DEVICEDB_SR
1388                 else:
1389                         devicedb = DEVICEDB
1390                 for physdevprefix, pdescription in devicedb.get(HardwareInfo().device_name,{}).items():
1391                         if phys.startswith(physdevprefix):
1392                                 if have_model_descr:
1393                                         description = pdescription + ' - ' + description
1394                                 else:
1395                                         description = pdescription
1396                 # not wholedisk and not partition 1
1397                 if part and part != 1:
1398                         description += " (Partition %d)" % part
1399                 return description
1400
1401         def addMountedPartition(self, device, desc):
1402                 already_mounted = False
1403                 for x in self.partitions[:]:
1404                         if x.mountpoint == device:
1405                                 already_mounted = True
1406                 if not already_mounted:
1407                         self.partitions.append(Partition(mountpoint = device, description = desc))
1408
1409         def removeMountedPartition(self, mountpoint):
1410                 for x in self.partitions[:]:
1411                         if x.mountpoint == mountpoint:
1412                                 self.partitions.remove(x)
1413                                 self.on_partition_list_change("remove", x)
1414
1415         def removeMountedPartitionbyDevice(self, device):
1416                 p = self.getPartitionbyDevice(device)
1417                 if p is not None:
1418                         #print "[removeMountedPartitionbyDevice] '%s', '%s', '%s', '%s', '%s'" % (p.mountpoint,p.description,p.device,p.force_mounted,p.uuid)
1419                         self.partitions.remove(p)
1420                         self.on_partition_list_change("remove", p)
1421
1422         def trigger_udev(self):
1423                 # We have to trigger udev to rescan sysfs
1424                 cmd = "udevadm trigger"
1425                 res = system(cmd)
1426                 return (res >> 8)
1427
1428         def getPartitionbyUUID(self, uuid):
1429                 for x in self.partitions[:]:
1430                         if x.uuid == uuid:
1431                                 #print "[getPartitionbyUUID] '%s', '%s', '%s', '%s', '%s'" % (x.mountpoint,x.description,x.device,x.force_mounted,x.uuid)
1432                                 return x
1433                 return None
1434
1435         def getPartitionbyDevice(self, dev):
1436                 for x in self.partitions[:]:
1437                         if x.device == dev:
1438                                 #print "[getPartitionbyDevice] '%s', '%s', '%s', '%s', '%s'" % (x.mountpoint,x.description,x.device,x.force_mounted,x.uuid)
1439                                 return x
1440                 return None
1441
1442         def getPartitionbyMountpoint(self, mountpoint):
1443                 for x in self.partitions[:]:
1444                         if x.mountpoint == mountpoint:
1445                                 #print "[getPartitionbyMountpoint] '%s', '%s', '%s', '%s', '%s'" % (x.mountpoint,x.description,x.device,x.force_mounted,x.uuid)
1446                                 return x
1447                 return None
1448
1449         def getDeviceNamebyUUID(self, uuid):
1450                 if path.exists("/dev/disk/by-uuid/" + uuid):
1451                         return path.basename(path.realpath("/dev/disk/by-uuid/" + uuid))
1452                 return None
1453
1454         def getPartitionUUID(self, part):
1455                 if not path.exists("/dev/disk/by-uuid"):
1456                         return None
1457                 for uuid in listdir("/dev/disk/by-uuid/"):
1458                         if not path.exists("/dev/disk/by-uuid/" + uuid):
1459                                 return None
1460                         if path.basename(path.realpath("/dev/disk/by-uuid/" + uuid)) == part:
1461                                 #print "[getPartitionUUID] '%s' - '%s'" % (uuid, path.basename(path.realpath("/dev/disk/by-uuid/" + uuid)) )
1462                                 return uuid
1463                 return None
1464
1465         def getDeviceDescription(self, dev):
1466                 physdev = path.realpath('/sys/block/' + dev[:3] + '/device')[4:]
1467                 description = self.getUserfriendlyDeviceName(dev[:3], physdev)
1468                 #print "[getDeviceDescription] -> device:'%s' - desc: '%s' phy:'%s'" % (dev, description, physdev)
1469                 return description
1470
1471         def reloadExports(self):
1472                 if path.exists("/etc/exports"):
1473                         Console().ePopen(("exportfs -r"))
1474
1475         def unmountPartitionbyMountpoint(self, mountpoint, device = None):
1476                 if path.exists(mountpoint) and path.ismount(mountpoint):
1477                         cmd = "umount" + " " + mountpoint
1478                         print "[unmountPartitionbyMountpoint] %s:" % (cmd)
1479                         system(cmd)
1480                 if path.exists(mountpoint) and not path.ismount(mountpoint):
1481                         part = self.getPartitionbyMountpoint(mountpoint)
1482                         if part is not None:
1483                                 if part.uuid is not None and part.uuid == config.storage_options.default_device.value: #unmounting Default Mountpoint /media/hdd
1484                                         #call the notifier also here if we unmounted the default partition
1485                                         for callback in self.delayed_device_Notifier:
1486                                                 try:
1487                                                         callback(part.device, "remove_default" )
1488                                                 except AttributeError:
1489                                                         self.delayed_device_Notifier.remove(callback)
1490                                         part.device = None
1491                                         part.updatePartitionInfo()
1492                         if device is not None and not path.ismount(mountpoint):
1493                                 self.removeMountedPartitionbyDevice(device)
1494                         self.reloadExports()
1495
1496         def unmountPartitionbyUUID(self, uuid):
1497                 mountpoint = config.storage[uuid]['mountpoint'].value
1498                 if mountpoint != "":
1499                         if path.exists(mountpoint) and path.ismount(mountpoint):
1500                                 if self.isUUIDpathFsTabMount(uuid, mountpoint) or self.isPartitionpathFsTabMount(uuid, mountpoint):
1501                                         print "[unmountPartitionbyUUID] disabling config entry for external mounted mountpoint %s:" % (mountpoint)
1502                                         config.storage[uuid]["enabled"].value = False
1503                                         config.storage.save()
1504                                 else:
1505                                         cmd = "umount" + " " + mountpoint
1506                                         print "[unmountPartitionbyUUID] %s:" % (mountpoint)
1507                                         system(cmd)
1508                                 self.reloadExports()
1509
1510         def mountPartitionbyUUID(self, uuid):
1511                 if path.exists("/dev/disk/by-uuid/" + uuid):
1512                         cfg_uuid = config.storage.get(uuid, None)
1513                         partitionPath = "/dev/disk/by-uuid/" + uuid
1514                         mountpoint = cfg_uuid['mountpoint'].value
1515                         dev = self.getDeviceNamebyUUID(uuid)
1516                         devicepath = "/dev/" + str(dev)
1517                         #print "[mountPartitionbyUUID] for UUID:'%s' - '%s'" % (uuid,mountpoint)
1518
1519                         #verify if mountpoint is still mounted from elsewhere (e.g fstab)
1520                         if path.exists(mountpoint) and path.ismount(mountpoint):
1521                                 tmppath = self.get_mountdevice(mountpoint)
1522                                 if tmppath is not None and tmppath.startswith("/dev/disk/by-uuid/") and tmppath != partitionPath: #probably different device mounted on our mountpoint
1523                                         tmpuuid = tmppath.rsplit("/",1)[1]
1524                                         if not self.isUUIDpathFsTabMount(tmpuuid, mountpoint) and not self.isPartitionpathFsTabMount(tmpuuid, mountpoint):
1525                                                 self.unmountPartitionbyMountpoint(mountpoint)
1526
1527                         #verify if our device is still mounted to somewhere else
1528                         tmpmount = self.get_mountpoint(partitionPath)
1529                         if tmpmount is not None and tmpmount != mountpoint and path.exists(tmpmount) and path.ismount(tmpmount):
1530                                 if not self.isUUIDpathFsTabMount(uuid, tmpmount) and not self.isPartitionpathFsTabMount(uuid, tmpmount):
1531                                                 self.unmountPartitionbyMountpoint(tmpmount)
1532
1533
1534                         if self.isUUIDpathFsTabMount(uuid, mountpoint) or self.isPartitionpathFsTabMount(uuid, mountpoint):
1535                                 print "[unmountPartitionbyUUID] disabling config entry for external mounted mountpoint %s:" % (mountpoint)
1536                                 cfg_uuid["enabled"].value = False
1537                                 config.storage.save()
1538
1539                         if cfg_uuid['enabled'].value:
1540                                 if mountpoint != "":
1541                                         if not path.exists(mountpoint):
1542                                                 try:
1543                                                         makedirs(mountpoint)
1544                                                 except OSError:
1545                                                         print "[mountPartitionbyUUID] could not create mountdir:",mountpoint
1546
1547                                         if path.exists(mountpoint) and not path.ismount(mountpoint) and not path.islink(mountpoint):
1548                                                 cmd = "mount -t auto /dev/disk/by-uuid/" + uuid + " " + mountpoint
1549                                                 system(cmd)
1550                                                 print "[mountPartitionbyUUID]:",cmd
1551
1552                                         if path.ismount(mountpoint):
1553                                                 dev = self.getDeviceNamebyUUID(uuid)
1554                                                 if dev is not None:
1555                                                         p = self.getPartitionbyMountpoint(mountpoint)
1556                                                         if p is not None:
1557                                                                 x = self.getPartitionbyDevice(dev)
1558                                                                 if x is not None and x.mountpoint.startswith('/autofs'):
1559                                                                         self.removeMountedPartitionbyDevice(dev) #remove now obsolete entry
1560                                                                 p.mountpoint = mountpoint
1561                                                                 p.uuid = uuid
1562                                                                 p.device = dev
1563                                                                 p.force_mounted = False
1564                                                                 p.updatePartitionInfo()
1565                                                         else:
1566                                                                 p = self.getPartitionbyDevice(dev)
1567                                                                 if p is not None:
1568                                                                         p.mountpoint = mountpoint
1569                                                                         p.uuid = uuid
1570                                                                         p.device = dev
1571                                                                         p.force_mounted = False
1572                                                                         p.updatePartitionInfo()
1573                                         else:
1574                                                 print "[mountPartitionbyUUID] could not mount mountdir:",mountpoint
1575                 else:
1576                         print "[mountPartitionbyUUID] failed for UUID:'%s'" % (uuid)
1577
1578         def storageDeviceChanged(self, uuid):
1579                 if config.storage[uuid]["enabled"].value:
1580                         #print "[storageDeviceChanged] for enabled UUID:'%s'" % (uuid)
1581                         self.mountPartitionbyUUID(uuid)
1582                 else:
1583                         #print "[storageDeviceChanged] for disabled UUID:'%s'" % (uuid)
1584                         self.unmountPartitionbyUUID(uuid)
1585
1586         def setupConfigEntries(self, initial_call = False, dev = None):
1587                 if initial_call and not dev:
1588                         for uuid in config.storage.stored_values:
1589                                 print "[setupConfigEntries] initial_call for stored uuid:",uuid,config.storage.stored_values[uuid]
1590                                 config.storage[uuid] = ConfigSubDict()
1591                                 config.storage[uuid]["enabled"] = ConfigYesNo(default = False)
1592                                 config.storage[uuid]["mountpoint"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1593                                 config.storage[uuid]["device_description"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1594                                 config.storage[uuid]["device_info"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1595                                 config.storage[uuid]["isRemovable"] = ConfigBoolean(default = False)
1596                                 if config.storage[uuid]['enabled'].value:
1597                                         dev = self.getDeviceNamebyUUID(uuid)
1598                                         if uuid == config.storage_options.default_device.value and config.storage[uuid]["mountpoint"].value != "/media/hdd":
1599                                                 print "[setupConfigEntries] initial_call discovered a default storage device misconfiguration, reapplied default storage config for:",uuid
1600                                                 if path.exists("/media/hdd") and path.islink("/media/hdd") and self.getLinkPath("/media/hdd") == config.storage[uuid]["mountpoint"].value:
1601                                                         unlink("/media/hdd")
1602                                                 if dev is not None:
1603                                                         self.unmountPartitionbyMountpoint(config.storage[uuid]["mountpoint"].value, dev)
1604                                                 config.storage[uuid]["mountpoint"].value = "/media/hdd"
1605                                         if dev is not None:
1606                                                 p = self.getPartitionbyDevice(dev) or self.getPartitionbyMountpoint(config.storage[uuid]["mountpoint"].value)
1607                                                 if p is None: # manually add partition entry
1608                                                         description = self.getDeviceDescription(dev)
1609                                                         device_mountpoint = self.getAutofsMountpoint(dev)
1610                                                         if config.storage[uuid]['mountpoint'].value != "":
1611                                                                 device_mountpoint = config.storage[uuid]['mountpoint'].value
1612                                                         p = Partition(mountpoint = device_mountpoint, description = description, force_mounted = False, device = dev)
1613                                                         p.uuid = uuid
1614                                                         p.updatePartitionInfo()
1615                                                         self.partitions.append(p)
1616                                                         self.on_partition_list_change("add", p)
1617                                         if path.exists("/dev/disk/by-uuid/" + uuid):
1618                                                 self.storageDeviceChanged(uuid)
1619                                 else:
1620                                         del config.storage[uuid]
1621                 if dev is not None:
1622                         uuid = self.getPartitionUUID(dev)
1623                         if uuid is not None:
1624                                 if config.storage.get(uuid, None) is None: #new unconfigured device added
1625                                         print "[setupConfigEntries] new device add for '%s' with uuid:'%s'" % (dev, uuid)
1626                                         hdd = self.getHDD(dev)
1627                                         if hdd is not None:
1628                                                 hdd_description = hdd.model()
1629                                                 cap = hdd.capacity()
1630                                                 if cap != "":
1631                                                         hdd_description += " (" + cap + ")"
1632                                                 device_info =  hdd.bus_description()
1633                                         else:
1634                                                 device_info = dev
1635                                                 hdd_description = self.getDeviceDescription(dev)
1636                                         config.storage[uuid] = ConfigSubDict()
1637                                         config.storage[uuid]["enabled"] = ConfigYesNo(default = False)
1638                                         config.storage[uuid]["mountpoint"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1639                                         config.storage[uuid]["device_description"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1640                                         config.storage[uuid]["device_info"] = ConfigText(default = "", visible_width = 50, fixed_size = False)
1641                                         config.storage[uuid]["isRemovable"] = ConfigBoolean(default = False)
1642                                         removable = False
1643                                         if hdd is not None:
1644                                                 removable = hdd.isRemovable
1645                                         config.storage[uuid]["device_description"].setValue(hdd_description)
1646                                         config.storage[uuid]["device_info"].setValue(device_info)
1647                                         config.storage[uuid]["isRemovable"].setValue(removable)
1648                                         p = self.getPartitionbyDevice(dev)
1649                                         if p is None: # manually add partition entry (e.g. on long spinup times)
1650                                                 description = self.getDeviceDescription(dev)
1651                                                 device_mountpoint = self.getAutofsMountpoint(dev)
1652                                                 p = Partition(mountpoint = device_mountpoint, description = description, force_mounted = True, device = dev)
1653                                                 p.uuid = uuid
1654                                                 p.updatePartitionInfo()
1655                                                 self.partitions.append(p)
1656                                                 self.on_partition_list_change("add", p)
1657                                         self.storageDeviceChanged(uuid)
1658                                 else:
1659                                         p = self.getPartitionbyDevice(dev)
1660                                         device_mountpoint = self.getAutofsMountpoint(dev)
1661                                         if config.storage[uuid]['enabled'].value and config.storage[uuid]['mountpoint'].value != "":
1662                                                 device_mountpoint = config.storage[uuid]['mountpoint'].value
1663                                         if p is None: # manually add partition entry (e.g. on default storage device change) !!!!!!!!!!!
1664                                                 description = self.getDeviceDescription(dev)
1665                                                 p = Partition(mountpoint = device_mountpoint, description = description, force_mounted = True, device = dev)
1666                                                 p.uuid = uuid
1667                                                 p.updatePartitionInfo()
1668                                                 self.partitions.append(p)
1669                                                 self.on_partition_list_change("add", p)
1670                                                 print "[setupConfigEntries] new/changed device add for '%s' with uuid:'%s'" % (dev, uuid)
1671                                                 self.storageDeviceChanged(uuid)
1672                                         else:
1673                                                 tmp = self.getPartitionbyMountpoint(device_mountpoint)
1674                                                 if tmp is not None and (tmp.uuid != uuid or tmp.mountpoint != config.storage[uuid]['mountpoint'].value):
1675                                                         print "[setupConfigEntries] new/changed device add for '%s' with uuid:'%s'" % (dev, uuid)
1676                                                         self.storageDeviceChanged(uuid)
1677                         else:
1678                                 print "[setupConfigEntries] device add for '%s' without uuid !!!" % (dev)
1679
1680         def verifyInstalledStorageDevices(self):
1681                 if config.storage_options.default_device.value == "<undefined>" and self.HDDCount() == 1 and not self.HDDEnabledCount(): #only one installed and unconfigured device
1682                         hdd = self.hdd[0]
1683                         if hdd and hdd.numPartitions() <= 1:
1684                                 numPart = hdd.numPartitions()
1685                                 device = hdd.device
1686                                 partitionPath = hdd.dev_path
1687                                 if numPart == 1:
1688                                         device = hdd.device + "1"
1689                                         partitionPath = hdd.partitionPath(str(numPart))
1690                                 p = self.getPartitionbyDevice(device)
1691                                 if p is not None and p.isInitialized: #only one by e2 initialized partition
1692                                         if not self.inside_mountpoint("/media/hdd") and not path.islink("/media/hdd") and not self.isUUIDpathFsTabMount(p.uuid, "/media/hdd") and not self.isPartitionpathFsTabMount(p.uuid, "/media/hdd"):
1693                                                 print "verifyInstalledStorageDevices: using found %s as default storage device" % device
1694                                                 config.storage_options.default_device.value = p.uuid
1695                                                 config.storage_options.save()
1696                                                 cfg_uuid = config.storage.get(p.uuid, None)
1697                                                 if cfg_uuid is not None and not cfg_uuid["enabled"].value:
1698                                                         cfg_uuid["enabled"].value = True
1699                                                         cfg_uuid["mountpoint"].value = "/media/hdd"
1700                                                         cfg_uuid.save()
1701                                                         config.storage.save()
1702                                                         harddiskmanager.modifyFstabEntry("/dev/disk/by-uuid/" + p.uuid, "/media/hdd", mode = "add_deactivated")
1703                                                         self.storageDeviceChanged(p.uuid)
1704
1705 harddiskmanager = HarddiskManager()
1706 harddiskmanager.enumerateBlockDevices()
1707 harddiskmanager.verifyInstalledStorageDevices() #take sure enumerateBlockdev is finished so we don't miss any at startup installed storage devices