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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:eol-style native

  ViewVC Help
Powered by ViewVC 1.1.20