use harddiskmanager in about screen
[enigma2.git] / lib / python / Components / Harddisk.py
1 from os import system, listdir, statvfs, popen, makedirs, readlink, stat, major, minor
2 from Tools.Directories import SCOPE_HDD, resolveFilename
3 from Tools.CList import CList
4 from SystemInfo import SystemInfo
5
6 def tryOpen(filename):
7         try:
8                 procFile = open(filename)
9         except IOError:
10                 return ""
11         return procFile
12
13 class Harddisk:
14         def __init__(self, device):
15                 self.device = device
16                 procfile = tryOpen("/sys/block/"+self.device+"/dev")
17                 tmp = procfile.readline().split(':')
18                 s_major = int(tmp[0])
19                 s_minor = int(tmp[1])
20                 for disc in listdir("/dev/discs"):
21                         path = readlink('/dev/discs/'+disc)
22                         devidex = '/dev'+path[2:]+'/'
23                         disc = devidex+'disc'
24                         ret = stat(disc).st_rdev
25                         if s_major == major(ret) and s_minor == minor(ret):
26                                 self.devidex = devidex
27                                 print "new Harddisk",  device, self.devidex
28                                 break
29
30         def __lt__(self, ob):
31                 return self.device < ob.device
32
33         def bus(self):
34                 ide_cf = self.device.find("hd") == 0 and self.devidex.find("host0") == -1 # 7025 specific
35                 internal = self.device.find("hd") == 0 and self.devidex
36                 if ide_cf:
37                         ret = "External (CF)"
38                 elif internal:
39                         ret = "Internal"
40                 else:
41                         ret = "External"
42                 return ret
43
44         def diskSize(self):
45                 procfile = tryOpen("/sys/block/"+self.device+"/size")
46                 if procfile == "":
47                         return 0
48                 line = procfile.readline()
49                 procfile.close()
50                 try:
51                         cap = int(line)
52                 except:
53                         return 0;
54                 return cap / 1000 * 512 / 1000
55
56         def capacity(self):
57                 cap = self.diskSize()
58                 if cap == 0:
59                         return ""
60                 return "%d.%03d GB" % (cap/1024, cap%1024)
61
62         def model(self):
63                 if self.device.find("hd") == 0:
64                         procfile = tryOpen("/proc/ide/"+self.device+"/model")
65                         if procfile == "":
66                                 return ""
67                         line = procfile.readline()
68                         procfile.close()
69                         return line.strip()
70                 elif self.device.find("sd") == 0:
71                         procfile = tryOpen("/sys/block/"+self.device+"/device/vendor")
72                         if procfile == "":
73                                 return ""
74                         vendor = procfile.readline().strip()
75                         procfile.close()
76                         procfile = tryOpen("/sys/block/"+self.device+"/device/model")
77                         model = procfile.readline().strip()
78                         return vendor+'('+model+')'
79                 else:
80                         assert False, "no hdX or sdX"
81
82         def free(self):
83                 procfile = tryOpen("/proc/mounts")
84                 
85                 if procfile == "":
86                         return -1
87
88                 free = -1
89                 while 1:
90                         line = procfile.readline()
91                         if line == "":
92                                 break
93                         if line.startswith(self.devidex):
94                                 parts = line.strip().split(" ")
95                                 try:
96                                         stat = statvfs(parts[1])
97                                 except OSError:
98                                         continue
99                                 free = stat.f_bfree/1000 * stat.f_bsize/1000
100                                 break
101                 procfile.close()
102                 return free
103
104         def numPartitions(self):
105                 try:
106                         idedir = listdir(self.devidex)
107                 except OSError:
108                         return -1
109                 numPart = -1
110                 for filename in idedir:
111                         if filename.startswith("disc"):
112                                 numPart += 1
113                         if filename.startswith("part"):
114                                 numPart += 1
115                 return numPart
116
117         def unmount(self):
118                 procfile = tryOpen("/proc/mounts")
119
120                 if procfile == "":
121                         return -1
122
123                 cmd = "/bin/umount"
124
125                 for line in procfile:
126                         if line.startswith(self.devidex):
127                                 parts = line.split()
128                                 cmd = ' '.join([cmd, parts[1]])
129
130                 procfile.close()
131
132                 res = system(cmd)
133                 return (res >> 8)
134
135         def createPartition(self):
136                 cmd = "/sbin/sfdisk -f " + self.devidex + "disc"
137                 sfdisk = popen(cmd, "w")
138                 sfdisk.write("0,\n;\n;\n;\ny\n")
139                 sfdisk.close()
140                 return 0
141
142         def mkfs(self):
143                 cmd = "/sbin/mkfs.ext3 "
144                 if self.diskSize() > 4 * 1024:
145                         cmd += "-T largefile "
146                 cmd += "-m0 " + self.devidex + "part1"
147                 res = system(cmd)
148                 return (res >> 8)
149
150         def mount(self):
151                 cmd = "/bin/mount -t ext3 " + self.devidex + "part1"
152                 res = system(cmd)
153                 return (res >> 8)
154
155         def createMovieFolder(self):
156                 try:
157                         makedirs(resolveFilename(SCOPE_HDD))
158                 except OSError:
159                         return -1
160                 return 0
161
162         def fsck(self):
163                 # We autocorrect any failures
164                 # TODO: we could check if the fs is actually ext3
165                 cmd = "/sbin/fsck.ext3 -f -p " + self.devidex + "part1"
166                 res = system(cmd)
167                 return (res >> 8)
168
169         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")]
170
171         def initialize(self):
172                 self.unmount()
173
174                 if self.createPartition() != 0:
175                         return -1
176
177                 if self.mkfs() != 0:
178                         return -2
179
180                 if self.mount() != 0:
181                         return -3
182
183                 if self.createMovieFolder() != 0:
184                         return -4
185
186                 return 0
187
188         def check(self):
189                 self.unmount()
190
191                 res = self.fsck()
192                 if res & 2 == 2:
193                         return -6
194
195                 if res & 4 == 4:
196                         return -7
197
198                 if res != 0 and res != 1:
199                         # A sum containing 1 will also include a failure
200                         return -5
201
202                 if self.mount() != 0:
203                         return -3
204
205                 return 0
206
207 class Partition:
208         def __init__(self, mountpoint, description = "", force_mounted = False):
209                 self.mountpoint = mountpoint
210                 self.description = description
211                 self.force_mounted = force_mounted
212                 self.is_hotplug = force_mounted # so far; this might change.
213
214         def stat(self):
215                 return statvfs(self.mountpoint)
216
217         def free(self):
218                 try:
219                         s = self.stat()
220                         return s.f_bavail * s.f_bsize
221                 except OSError:
222                         return None
223         
224         def total(self):
225                 try:
226                         s = self.stat()
227                         return s.f_blocks * s.f_bsize
228                 except OSError:
229                         return None
230
231         def mounted(self):
232                 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
233                 # TODO: can os.path.ismount be used?
234                 if self.force_mounted:
235                         return True
236                 procfile = tryOpen("/proc/mounts")
237                 for n in procfile.readlines():
238                         if n.split(' ')[1] == self.mountpoint:
239                                 return True
240                 return False
241
242 class HarddiskManager:
243         def __init__(self):
244                 self.hdd = [ ]
245                 
246                 self.partitions = [ ]
247                 
248                 self.on_partition_list_change = CList()
249                 
250                 self.enumerateBlockDevices()
251                 
252                 # currently, this is just an enumeration of what's possible,
253                 # this probably has to be changed to support automount stuff.
254                 # still, if stuff is mounted into the correct mountpoints by
255                 # external tools, everything is fine (until somebody inserts 
256                 # a second usb stick.)
257                 p = [
258                                         ("/media/hdd", _("Harddisk")), 
259                                         ("/media/card", _("Card")), 
260                                         ("/media/cf", _("Compact Flash")),
261                                         ("/media/mmc1", _("MMC Card")),
262                                         ("/media/net", _("Network Mount")),
263                                         ("/media/ram", _("Ram Disk")),
264                                         ("/media/usb", _("USB Stick")),
265                                         ("/", _("Internal Flash"))
266                                 ]
267                 
268                 for x in p:
269                         self.partitions.append(Partition(mountpoint = x[0], description = x[1]))
270
271         def getBlockDevInfo(self, blockdev):
272                 devpath = "/sys/block/" + blockdev
273                 error = False
274                 removable = False
275                 blacklisted = False
276                 is_cdrom = False
277                 partitions = []
278                 try:
279                         removable = bool(int(open(devpath + "/removable").read()))
280                         dev = int(open(devpath + "/dev").read().split(':')[0])
281                         if dev in [7, 31]: # loop, mtdblock
282                                 blacklisted = True
283                         if blockdev[0:2] == 'sr':
284                                 is_cdrom = True
285                         if blockdev[0:2] == 'hd':
286                                 try:
287                                         media = open("/proc/ide/%s/media" % blockdev).read()
288                                         if media.find("cdrom") != -1:
289                                                 is_cdrom = True
290                                 except IOError:
291                                         error = True
292                         # check for partitions
293                         if not is_cdrom:
294                                 for partition in listdir(devpath):
295                                         if partition[0:len(blockdev)] != blockdev:
296                                                 continue
297                                         partitions.append(partition)
298                 except IOError:
299                         error = True
300                 return error, blacklisted, removable, is_cdrom, partitions
301
302         def enumerateBlockDevices(self):
303                 print "enumerating block devices..."
304                 for blockdev in listdir("/sys/block"):
305                         error, blacklisted, removable, is_cdrom, partitions = self.getBlockDevInfo(blockdev)
306                         print "found block device '%s':" % blockdev, 
307                         if error:
308                                 print "error querying properties"
309                         elif blacklisted:
310                                 print "blacklisted"
311                         else:
312                                 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
313                                 self.addHotplugPartition(blockdev, blockdev)
314                                 for part in partitions:
315                                         self.addHotplugPartition(part, part)
316
317         def getAutofsMountpoint(self, device):
318                 return "/autofs/%s/" % (device)
319
320         def addHotplugPartition(self, device, description):
321                 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True)
322                 self.partitions.append(p)
323                 self.on_partition_list_change("add", p)
324                 l = len(device)
325                 if l and device[l-1] not in ('0','1','2','3','4','5','6','7','8','9'):
326                         error, blacklisted, removable, is_cdrom, partitions = self.getBlockDevInfo(device)
327                         if not blacklisted and not removable and not is_cdrom:
328                                 self.hdd.append(Harddisk(device))
329                                 self.hdd.sort()
330                                 SystemInfo["Harddisc"] = len(self.hdd) > 0
331
332         def removeHotplugPartition(self, device):
333                 mountpoint = self.getAutofsMountpoint(device)
334                 for x in self.partitions[:]:
335                         if x.mountpoint == mountpoint:
336                                 self.partitions.remove(x)
337                                 self.on_partition_list_change("remove", x)
338                 l = len(device)
339                 if l and device[l-1] not in ('0','1','2','3','4','5','6','7','8','9'):
340                         idx = 0
341                         for hdd in self.hdd:
342                                 if hdd.device == device:
343                                         del self.hdd[idx]
344                                         break
345                         SystemInfo["Harddisc"] = len(self.hdd) > 0
346
347         def HDDCount(self):
348                 return len(self.hdd)
349
350         def HDDList(self):
351                 list = [ ]
352                 for hd in self.hdd:
353                         hdd = hd.model() + " - " + hd.bus()
354                         cap = hd.capacity()
355                         if cap != "":
356                                 hdd += " (" + cap + ")"
357                         list.append((hdd, hd))
358                 return list
359
360         def getMountedPartitions(self, onlyhotplug = False):
361                 return [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
362
363 harddiskmanager = HarddiskManager()