/[gli]/branches/overhaul/src/Partitioning.py
Gentoo

Contents of /branches/overhaul/src/Partitioning.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1594 - (show annotations) (download) (as text)
Sun Jan 7 01:58:50 2007 UTC (7 years, 3 months ago) by codeman
File MIME type: text/x-python
File size: 24628 byte(s)
starting in on the mounts screen.
redid the list_partitions function.

1 # Copyright 1999-2006 Gentoo Foundation
2 # This source code is distributed under the terms of version 2 of the GNU
3 # General Public License as published by the Free Software Foundation, a copy
4 # of which can be found in the main directory of this project.
5
6 import commands, string, os, parted
7 from glob import glob
8 from GLIException import *
9 import GLIUtility
10 import time
11
12 MEGABYTE = 1024 * 1024
13
14 supported_filesystems = {
15 'all': ( 'ext2', 'ext3', 'linux-swap', 'xfs', 'jfs', 'reiserfs' ),
16 'x86': ( 'ntfs', 'fat16', 'fat32' ),
17 'amd64': ( 'ntfs', 'fat16', 'fat32' ),
18 'ppc': ( 'reiserfs', 'apple_bootstrap', 'hfs' )
19 }
20
21 labelinfo = {
22 'msdos': { 'ignoredparts': [], 'extended': True },
23 'mac': { 'ignoredparts': [1], 'extended': False },
24 'sun': { 'ignoredparts': [3], 'extended': False },
25 'loop': { 'ignoredparts': [], 'extended': False }
26 }
27
28 archinfo = {
29 'sparc': 'sun',
30 'hppa': 'msdos',
31 'x86': 'msdos',
32 'amd64': 'msdos',
33 'ppc': 'mac'
34 }
35
36 ##
37 # This class provides a partitioning abstraction for the frontends
38 class Device:
39 "Class representing a partitionable device."
40
41 _device = None
42 _partitions = None
43 _geometry = None
44 _parted_dev = None
45 _parted_disk = None
46 _arch = None
47 _disklabel = None
48
49 ##
50 # Initialization function for Device class
51 # @param device Device node (e.g. /dev/hda) of device being represented
52 # @param arch Architecture that we're partition for (defaults to 'x86' for now)
53 def __init__(self, device, arch="x86"):
54 self._device = device
55 self._arch = arch
56 self._partitions = []
57 self._geometry = {}
58 self._parted_dev = parted.PedDevice.get(self._device)
59 try:
60 self._parted_disk = parted.PedDisk.new(self._parted_dev)
61 except:
62 self._parted_disk = self._parted_dev.disk_new_fresh(parted.disk_type_get(archinfo[self._arch]))
63 self._disklabel = self._parted_disk.type.name
64 self._labelinfo = labelinfo[self._disklabel]
65 self.set_disk_geometry_from_disk()
66 self.set_partitions_from_disk()
67
68 def __getitem__(self, name):
69 return self.get_partition(name)
70
71 def __iter__(self):
72 for part in self.get_partitions():
73 yield part
74
75 ##
76 # Returns list of supported filesystems based on arch
77 def get_supported_filesystems(self):
78 return supported_filesystems['all'] + supported_filesystems[self._arch]
79
80 ##
81 # Sets disk geometry info from disk. This function is used internally by __init__()
82 def set_disk_geometry_from_disk(self):
83 self._geometry = {
84 'sector_size': self._parted_dev.sector_size,
85 'total_bytes': self._parted_dev.length * self._parted_dev.sector_size,
86 'heads': self._parted_dev.heads,
87 'cylinders': self._parted_dev.cylinders,
88 'sectors': self._parted_dev.sectors,
89 'cylinder_bytes': self._parted_dev.heads * self._parted_dev.sectors * self._parted_dev.sector_size,
90 'total_sectors': self._parted_dev.length,
91 'sectors_in_cylinder': self._parted_dev.heads * self._parted_dev.sectors,
92 'total_mb': long((self._parted_dev.length * self._parted_dev.sector_size) / MEGABYTE)
93 }
94
95 ##
96 # Sets partition info from disk.
97 def set_partitions_from_disk(self):
98 self._partitions = []
99 parted_part = self._parted_disk.next_partition()
100 while parted_part:
101 # Make sure it's a physical partition or unallocated space
102 if parted_part.num >= 1 or parted_part.type_name == "free":
103 self._partitions.append(Partition(self, parted_part))
104 parted_part = self._parted_disk.next_partition(parted_part)
105
106 ##
107 # Returns the partition object with the specified minor
108 # @param idx Index of partition object
109 def get_partition(self, idx):
110 # for part in self._partitions:
111 # if part.get_minor() == minor:
112 # return part
113 # return None
114 return self._partitions[idx]
115
116 def get_partition_position(self, minor):
117 for i, part in enumerate(self._partitions):
118 if part['minor'] == minor:
119 return i
120 return -1
121
122 def get_partiton_at_start(self, start):
123 for i, part in enumerate(self._partitions):
124 if part['start'] == start:
125 return i
126 return -1
127
128 ##
129 # Returns name of device (e.g. /dev/hda) being represented
130 def get_device(self):
131 return self._device
132
133 ##
134 # Uses magic to apply the recommended partition layout
135 def do_recommended(self):
136 freeidx = -1
137 free_part = None
138 recommended_parts = [ { 'type': "ext2", 'size': 100, 'mountpoint': "/boot" },
139 { 'type': "linux-swap", 'size': 512, 'mountpoint': "" },
140 { 'type': "ext3", 'size': "*", 'mountpoint': "/" } ]
141 to_create = []
142 physical_memory = int(GLIUtility.spawn(r"free -m | egrep '^Mem:' | sed -e 's/^Mem: \+//' -e 's/ \+.\+$//'", return_output=True)[1].strip())
143
144 self.clear_partitions()
145
146 # parts = self.get_ordered_partition_list()
147 # Search for concurrent unallocated space >=4GB
148 for idx, part in self._partitions:
149 if part['type'] == "free" and part['mb'] >= 4096:
150 freeidx = idx
151 free_part = part
152 break
153 else:
154 raise GLIException("RecommendedPartitionLayoutError", "notice", "do_recommended", "You do not have atleast 4GB of concurrent unallocated space. Please remove some partitions and try again.")
155 remaining_free = free_part['mb']
156 # XXX: I left off here
157 for newpart in recommended_parts:
158 # extended/logical partitions suck like a hoover
159 if self._labelinfo['extended'] and free_minor == (3 + FREE_MINOR_FRAC_PRI) and not newpart == recommended_parts[-1]:
160 if self.get_extended_partition():
161 raise GLIException("RecommendedPartitionLayoutError", "notice", "do_recommended", "This code is not yet robust enough to handle automatic partitioning with your current layout.")
162 to_create.append({ 'type': "extended", 'size': remaining_free, 'mountpoint': "", 'free_minor': free_minor })
163 free_minor = 4 + FREE_MINOR_FRAC_LOG
164 newpart['free_minor'] = free_minor
165 # Small hack to calculate optimal swap partition size
166 if newpart['type'] == "linux-swap" and physical_memory:
167 newpart['size'] = physical_memory * 2
168 if newpart['size'] > 1024:
169 newpart['size'] = 1024
170 to_create.append(newpart)
171 free_minor = free_minor + 1
172 if not newpart['size'] == "*":
173 remaining_free = remaining_free - newpart['size']
174 for newpart in to_create:
175 if newpart['size'] == "*":
176 # This doesn't seem quite right...it should probably be set to remaining_free
177 # newpart['size'] = self.get_partition(newpart['free_minor']).get_mb()
178 newpart['size'] = remaining_free
179 self.add_partition(newpart['free_minor'], newpart['size'], 0, 0, newpart['type'], mountpoint=newpart['mountpoint'])
180
181 def _megabytes_to_sectors(self, mb, sector_bytes=512):
182 return long(mb * MEGABYTE / sector_bytes)
183
184 def _sectors_to_megabytes(self, sectors, sector_bytes=512):
185 return float((float(sectors) * sector_bytes)/ float(MEGABYTE))
186
187 def _wait_for_device_node(self, devnode):
188 if GLIUtility.is_file("/sbin/udevsettle"):
189 GLIUtility.spawn("/sbin/udevsettle")
190 if not GLIUtility.is_file(devnode):
191 GLIUtility.spawn("/sbin/udevsettle")
192 else:
193 for i in range(0, 10):
194 if GLIUtility.is_file(devnode):
195 break
196 time.sleep(1)
197 time.sleep(1)
198 for i in range(0, 10):
199 if GLIUtility.is_file(devnode):
200 break
201 time.sleep(1)
202
203 ##
204 # Adds a new partition to the partition info
205 # @param freeidx minor of unallocated space partition is being created in
206 # @param mb size of partition in MB
207 # @param type Partition type (ext2, ext3, fat32, linux-swap, free, extended, etc.)
208 def add_partition(self, freeidx, mb, fs, pregap=0):
209 types = { 'primary': parted.PARTITION_PRIMARY, 'extended': parted.PARTITION_EXTENDED, 'logical': parted.PARTITION_LOGICAL }
210 fs_types = {}
211 fstype = None
212 try:
213 free_part = self._partitions[freeidx]
214 except:
215 # raise an exception here
216 pass
217 if mb > free_part['mb']:
218 # raise an exception here
219 pass
220 # Enumerate supported filesystem types
221 fs_type = parted.file_system_type_get_next()
222 while fs_type:
223 fs_types[fs_type.name] = fs_type
224 fs_type = parted.file_system_type_get_next(fs_type)
225 # apple_bootstrap is a "magic" hfs
226 if fs == "apple_bootstrap":
227 fs = "hfs"
228 # grab relevant parted filesystemtype object
229 if fs:
230 fstype = fs_types[fs]
231 # determine correct partition type
232 parttype = "primary"
233 if fs == "extended":
234 fstype = None
235 parttype = "extended"
236 elif free_part.is_logical():
237 parttype = "logical"
238 # figure out start/end sectors
239 start = free_part['start'] + self._megabytes_to_sectors(pregap)
240 end = start + self._megabytes_to_sectors(mb)
241 parted_newpart = self._parted_disk.partition_new(types[parttype], fstype, start, end)
242 constraint = self._parted_disk.dev.constraint_any()
243 self._parted_disk.add_partition(parted_newpart, constraint)
244 self._parted_disk.commit()
245 self.set_partitions_from_disk()
246 if parttype != "extended":
247 newpart = self._partitions[self.get_partition_position(parted_newpart.num)]
248 devnode = newpart['devnode']
249 format_cmds = { 'linux-swap': "mkswap", 'fat16': "mkfs.vfat -F 16", 'fat32': "mkfs.vfat -F 32",
250 'ntfs': "mkntfs", 'xfs': "mkfs.xfs -f", 'jfs': "mkfs.jfs -f",
251 'reiserfs': "mkfs.reiserfs -f", 'ext2': "mkfs.ext2", 'ext3': "mkfs.ext3",
252 'hfs': "hformat", 'apple_bootstrap': "hformat"
253 }
254 if fs in format_cmds:
255 cmdname = format_cmds[fs]
256 else:
257 raise GLIException("PartitionFormatError", 'fatal', '_partition_format_step', "Unknown partition type " + fstype)
258 # sleep a bit first
259 time.sleep(1)
260 self._wait_for_device_node(devnode)
261 cmd = "%s %s" % (cmdname, devnode)
262 ret = GLIUtility.spawn(cmd)
263 if not GLIUtility.exitsuccess(ret):
264 raise GLIException("PartitionFormatError", 'fatal', '_partition_format_step', "Could not create %s filesystem on %s" % (fstype, devnode))
265 self.set_partitions_from_disk()
266
267 ##
268 # Removes partition from partition info
269 # @param minor Minor of partition to remove
270 def delete_partition(self, partidx):
271 try:
272 tmp_part = self._partitions[partidx]
273 except:
274 # raise exception here
275 pass
276 if tmp_part['minor'] < 1:
277 # raise an exception here
278 pass
279 try:
280 self._parted_disk.delete_partition(self._parted_disk.get_partition(tmp_part['minor']))
281 except:
282 # raise an exception here
283 pass
284 self._parted_disk.commit()
285 self.set_partitions_from_disk()
286
287 # def resize_partition(self, partidx, mb):
288 # part = self._partitions[partidx]
289 # type = part['type']
290 # start = part['start']
291 # end = start + long(mb * MEGABYTE / 512) - 1
292 #
293 # total_sectors = end - start + 1
294 # total_bytes = long(total_sectors) * 512
295 #
296 # # Delete partition and recreate at same start point with new size if growing
297 # if mb > part['mb']:
298 # curminor = self._find_current_minor_for_part(device, start)
299 # self._parted_disk.delete_partition(self._parted_disk.get_partition(part['minor']))
300 # if part['logical']:
301 # tmptype = "logical"
302 # else:
303 # tmptype = "primary"
304 # self._add_partition(parted_disk, start, end, tmptype, tmppart_new['type'], strict_start=True)
305 # parted_disk.commit()
306 #
307 # curminor = self._find_current_minor_for_part(device, start)
308 # devnode = device + str(curminor)
309 #
310 # self._wait_for_device_node(devnode)
311 #
312 # if type in ("ext2", "ext3"):
313 # resizecmd = "resize2fs %s %sK" % (devnode, str(int((total_bytes - (2 * MEGABYTE)) / 1024)))
314 # self._logger.log("_partition_resize_step(): running: " + resizecmd)
315 # ret = GLIUtility.spawn(resizecmd, logfile=self._compile_logfile, append_log=True)
316 # if not GLIUtility.exitsuccess(ret):
317 # raise GLIException("PartitionResizeError", 'fatal', 'partition', "could not resize ext2/3 filesystem on " + devnode)
318 # elif type == "ntfs":
319 # ret = GLIUtility.spawn("yes | ntfsresize -v --size " + str(total_bytes) + " " + devnode, logfile=self._compile_logfile, append_log=True)
320 # if not GLIUtility.exitsuccess(ret):
321 # raise GLIException("PartitionResizeError", 'fatal', 'partition', "could not resize NTFS filesystem on " + devnode)
322 # elif type in ("linux-swap", "fat32", "fat16"):
323 # parted_fs = parted_disk.get_partition(curminor).geom.file_system_open()
324 # resize_constraint = parted_fs.get_resize_constraint()
325 # if total_sectors < resize_constraint.min_size or start != resize_constraint.start_range.start:
326 # raise GLIException("PartitionError", 'fatal', 'partition', "New size specified for " + devnode + " is not within allowed boundaries (blame parted)")
327 # new_geom = resize_constraint.start_range.duplicate()
328 # new_geom.set_start(start)
329 # new_geom.set_end(end)
330 # try:
331 # parted_fs.resize(new_geom)
332 # except:
333 # raise GLIException("PartitionResizeError", 'fatal', 'partition', "could not resize " + devnode)
334 # self._logger.log(" Deleting old minor " + str(oldpart) + " to be recreated in next pass")
335 # self._delete_partition(parted_disk, oldpart)
336 # parted_disk.delete_all()
337 # parted_disk.commit()
338
339
340 ##
341 # This function clears the partition table
342 def clear_partitions(self, disklabel=None):
343 if not disklabel:
344 disklabel = archinfo[self._arch]
345 self._parted_disk = self._parted_dev.disk_new_fresh(parted.disk_type_get(disklabel))
346 self._disklabel = disklabel
347 self._parted_disk.commit()
348 self.set_partitions_from_disk()
349
350 ##
351 # Returns an ordered list (disk order) of partitions
352 def get_partitions(self):
353 return self._partitions
354
355 ##
356 # Returns the minor of the extended partition, if any
357 def get_extended_partition(self):
358 for part in self._partitions:
359 if part.is_extended():
360 return part['minor']
361 return 0
362
363 ##
364 # Returns the drive model
365 def get_model(self):
366 return self._parted_dev.model
367
368 ##
369 # Returns the disklabel type
370 def get_disklabel(self):
371 return self._disklabel
372
373 ##
374 # Returns all the geometry information
375 def get_geometry(self):
376 return self._geometry
377
378 ##
379 # This class represents a partition within a GLIStorageDevice object
380 class Partition:
381 "Class representing a single partition within a Device object"
382
383 ##
384 # Initialization function for the Partition class
385 # @param device Parent GLIStorageDevice object
386 # @param parted_part parted.Partition object
387 def __init__(self, device, parted_part):
388 self._device = device
389 self._start = parted_part.geom.start
390 self._end = parted_part.geom.end
391 self._type = parted_part.type_name
392 self._minor = parted_part.num
393 self._mb = float((self._end - self._start + 1) * device._geometry['sector_size'] / MEGABYTE)
394 self._part_name = ""
395 self._resizeable = False
396
397 # determine the /dev node that refers to this partition
398 tmpdevice = device.get_device()
399 label_type = device._parted_disk.type.name
400 if label_type == "loop":
401 self._devnode = tmpdevice
402 elif tmpdevice[-1] in "0123456789":
403 self._devnode = tmpdevice + "p" + str(self._minor)
404 else:
405 self._devnode = tmpdevice + str(self._minor)
406
407 if not self._type == "free":
408 if parted_part.fs_type:
409 self._type = parted_part.fs_type.name
410 if self._type == "hfs" and parted_part.is_flag_available(1) and parted_part.get_flag(1):
411 self._type = "apple_bootstrap"
412 else:
413 # Add additional partition identification code here
414 self._type = "unknown"
415 if parted_part.type == 2: self._type = "extended"
416 if device._parted_disk.type.check_feature(parted.DISK_TYPE_PARTITION_NAME):
417 self._part_name = parted_part.get_name()
418 # The 10 is completely arbitrary. If flags seem to be missed, this number should be increased
419 for flag in range(0, 10):
420 if parted_part.is_flag_available(flag) and parted_part.get_flag(flag):
421 self._flags.append(flag)
422
423 if type == "ext2" or type == "ext3":
424 block_size = long(string.strip(commands.getoutput("dumpe2fs -h " + self._devnode + r" 2>&1 | grep -e '^Block size:' | sed -e 's/^Block size:\s\+//'")))
425 free_blocks = long(string.strip(commands.getoutput("dumpe2fs -h " + self._devnode + r" 2>&1 | grep -e '^Free blocks:' | sed -e 's/^Free blocks:\s\+//'")))
426 free_bytes = long(block_size * free_blocks)
427 # can't hurt to pad (the +50) it a bit since this is really just a guess
428 self._min_size = self._mb - long(free_bytes / MEGABYTE) + 50
429 self._resizeable = True
430 elif type == "ntfs":
431 min_bytes = long(commands.getoutput("ntfsresize -f --info " + self._devnode + " | grep -e '^You might resize' | sed -e 's/You might resize at //' -e 's/ bytes or .\+//'"))
432 self._min_size = long(min_bytes / MEGABYTE) + 50
433 self._resizeable = True
434 else:
435 try:
436 parted_fs = parted_part.geom.file_system_open()
437 resize_constraint = parted_fs.get_resize_constraint()
438 min_bytes = resize_constraint.min_size * self._device._geometry['sector_size']
439 self._min_size = long(min_bytes / MEGABYTE) + 1
440 self._resizeable = True
441 except:
442 self._resizeable = False
443
444 def __getitem__(self, name):
445 tmpdict = {
446 'start': self.get_start,
447 'end': self.get_end,
448 'type': self.get_type,
449 'minor': self.get_minor,
450 'mb': self.get_mb,
451 'flags': self.get_flags,
452 'name': self.get_name,
453 'devnode': self.get_devnode,
454 'resizeable': self.get_resizeable,
455 'min_size': self.get_min_size,
456 'max_size': self.get_max_size,
457 'extended': self.is_extended,
458 'logical': self.is_logical
459 }
460 if name in tmpdict:
461 return tmpdict[name]()
462 else:
463 raise ValueError(name + " is not a valid attribute!")
464
465 def __setitem__(self, name, value):
466 tmpdict = {
467 'flags': self.set_flags,
468 'name': self.set_name
469 }
470 if name in tmpdict:
471 tmpdict[name](value)
472 else:
473 raise ValueError(name + " is not a valid attribute!")
474
475 ##
476 # Returns the dev node that this partition will have
477 def get_devnode(self):
478 return self._devnode
479
480 ##
481 # Returns whether or not the partition is extended
482 def is_extended(self):
483 if self._type == "extended":
484 return True
485 else:
486 return False
487
488 ##
489 # Returns whether or not the partition is logical
490 def is_logical(self):
491 if self._type == "free":
492 ext_part = self._device.get_extended_partition()
493 if not ext_part: return False
494 if self._start >= ext_part['start'] and self._start <= ext_part['end'] and self._end >= ext_part['start'] and self._end <= ext_part['end']:
495 return True
496 else:
497 return False
498 elif self._device._labelinfo['extended'] and self._minor > 4:
499 return True
500 else:
501 return False
502
503 ##
504 # Returns a list of logical partitions if this is an extended partition
505 def get_logicals(self):
506 if not self.is_extended():
507 return None
508 logicals = []
509 for part in self._device._partitions:
510 if part.is_logical():
511 logicals.append(part)
512 return logicals
513
514 ##
515 # Returns the start sector for the partition
516 def get_start(self):
517 return long(self._start)
518
519 ##
520 # Returns end sector for the partition
521 def get_end(self):
522 return long(self._end)
523
524 ##
525 # Returns size of partition in MB
526 def get_mb(self):
527 return self._mb
528
529 ##
530 # Returns type of partition
531 def get_type(self):
532 return self._type
533
534 ##
535 # Returns parent Device object
536 def get_device(self):
537 return self._device
538
539 ##
540 # Returns minor of partition
541 def get_minor(self):
542 return self._minor
543
544 ##
545 # Returns whether the partition is resizeable
546 def get_resizeable(self):
547 return self._resizeable
548
549 ##
550 # Sets partition flags
551 def set_flags(self, flags):
552 self._flags = flags
553
554 ##
555 # Returns partition flags
556 def get_flags(self):
557 return self._flags
558
559 ##
560 # Sets partition name
561 def set_name(self, name):
562 self._name = name
563
564 ##
565 # Returns partition name
566 def get_name(self):
567 return self._name
568
569 ##
570 # Returns minimum MB for resize
571 def get_min_size(self):
572 if self._resizeable:
573 return self._min_size
574 else:
575 return -1
576
577 ##
578 # Returns maximum MB for resize
579 def get_max_size(self):
580 if self._resizeable:
581 partidx = self._device.get_partition_position(self._minor)
582 free_part = self._device._partitions[partidx + 1]
583 if free_part['type'] == "free":
584 return self._mb
585 if free_part.is_logical():
586 if self.is_logical():
587 return self._mb + free_part['mb']
588 else:
589 return self._mb
590 else:
591 return self._mb + free_part['mb']
592 else:
593 return -1
594
595 ##
596 # Resizes the partition
597 # @param mb New size in MB
598 def resize(self, mb):
599 minor_pos = self._device.get_partition_position(self._minor)
600 try:
601 free_minor = self._device._partitions[minor_pos+1].get_minor()
602 except:
603 free_minor = 0
604 if mb < self._mb:
605 # Shrinking
606 if not free_minor or not self._device.get_partition(free_minor).get_type() == "free":
607 if self._device._disklabel == "mac":
608 free_minor = self._minor + 1
609 elif self.is_logical():
610 free_minor = self._minor + FREE_MINOR_FRAC_LOG
611 else:
612 free_minor = self._minor + FREE_MINOR_FRAC_PRI
613 if self._device.get_partition(free_minor):
614 for i, part in enumerate(self._device._partitions):
615 if i <= minor_pos or free_minor > part.get_minor(): continue
616 part.set_minor(part.get_minor() + 1)
617 self._device._partitions.insert(minor_pos+1, Partition(self._device, free_minor, self._mb - mb, 0, 0, "free", format=False, existing=False))
618 else:
619 self._device.get_partition(free_minor).set_mb(self._device.get_partition(free_minor).get_mb() + (self._mb - mb))
620 self._mb = mb
621 else:
622 if mb == self._mb + self._device.get_partition(free_minor).get_mb():
623 # Using all available unallocated space
624 self._device._partitions.pop(self._device.get_partition_position(free_minor))
625 self._mb = mb
626 else:
627 # Growing
628 self._device.get_partition(free_minor).set_mb(self._device.get_partition(free_minor).get_mb() - (mb - self._mb))
629 self._mb = mb
630 self._resized = True
631 self._device.tidy_partitions()
632
633 ##
634 # Returns a list of detected partitionable devices
635 def detect_devices():
636 devices = []
637
638 # Make sure sysfs exists
639 # TODO: rewrite for 2.4 support
640 if not os.path.exists("/sys/bus"):
641 raise GLIException("GLIStorageDeviceError", 'fatal', 'detect_devices', "no sysfs found (you MUST use a kernel >2.6)")
642 # Make sure /proc/partitions exists
643 if not os.path.exists("/proc/partitions"):
644 raise GLIException("GLIStorageDeviceError", 'fatal', 'detect_devices', "/proc/partitions does not exist! Please make sure procfs is in your kernel and mounted!")
645
646 # Load /proc/partitions into the variable 'partitions'
647 partitions = []
648 for line in open("/proc/partitions"):
649 tmpparts = line.split()
650 if len(tmpparts) < 4 or not tmpparts[0].isdigit() or not tmpparts[1].isdigit():
651 continue
652
653 # Get the major, minor and device name
654 major = int(tmpparts[0])
655 minor = int(tmpparts[1])
656 device = "/dev/" + tmpparts[3]
657
658 # If there is no /dev/'device_name', then scan
659 # all the devices in /dev to try and find a
660 # devices with the same major and minor
661 if not os.path.exists(device):
662 device = None
663 for path, dirs, files in os.walk("/dev"):
664 for d_file in files:
665 full_file = os.path.join(path, d_file)
666 if not os.path.exists(full_file):
667 continue
668 statres = os.stat(full_file)
669 fmaj = os.major(statres.st_rdev)
670 fmin = os.minor(statres.st_rdev)
671 if fmaj == major and fmin == minor:
672 device = full_file
673 break
674 if not device:
675 continue
676
677 partitions.append(( major, minor, device ))
678
679 # Scan sysfs for the devices of type 'x'
680 # 'x' being a member of the list below:
681 # Compaq cards.../sys/block/{cciss,ida}!cXdX/dev
682 for dev_glob in ("/sys/bus/ide/devices/*/block*/dev", "/sys/bus/scsi/devices/*/block*/dev", "/sys/block/cciss*/dev", "/sys/block/ida*/dev"):
683 sysfs_devices = glob(dev_glob)
684 if not sysfs_devices: continue
685 for sysfs_device in sysfs_devices:
686 # Get the major and minor info
687 try:
688 major, minor = open(sysfs_device).read().split(":")
689 major = int(major)
690 minor = int(minor)
691 except:
692 raise GLIException("GLIStorageDeviceError", 'fatal', 'detect_devices', "invalid major/minor in " + sysfs_device)
693
694 # Find a device listed in /proc/partitions
695 # that has the same minor and major as our
696 # current block device.
697 for record in partitions:
698 if major == record[0] and minor == record[1]:
699 devices.append(record[2])
700
701 # For testing the partitioning code
702 if GLIUtility.is_file("/tmp/disk.img"):
703 devices.append("/tmp/disk.img")
704
705 # We have assembled the list of devices, so return it
706 return devices
707
708 def list_partitions():
709 # Load /proc/partitions into the variable 'partitions'
710 # return [("/dev/" + x[3]) for x in [y.strip().split() for y in open("/proc/partitions", "r").readlines()] if len(x) >= 4 and x[3][-1].isdigit()]
711 partitions = []
712 for line in open("/proc/partitions"):
713 tmpparts = line.split()
714 if len(tmpparts) < 4 or not tmpparts[0].isdigit() or not tmpparts[1].isdigit():
715 continue
716 device = "/dev/" + tmpparts[3]
717 if device == "/dev/loop0": #we don't want this.
718 continue
719 if not device[-1].isdigit(): #A Drive
720 continue
721 else:
722 partitions[device] = tmpparts[2]
723 return partitions

Properties

Name Value
svn:eol-style native

  ViewVC Help
Powered by ViewVC 1.1.20