/[gli]/trunk/src/GLIStorageDevice.py
Gentoo

Contents of /trunk/src/GLIStorageDevice.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 635 - (show annotations) (download) (as text)
Thu Jun 9 23:13:57 2005 UTC (15 years, 5 months ago) by agaffney
File MIME type: text/x-python
File size: 26014 byte(s)
Apply latest long/mkfsopts patch from robbat2

1 import commands, string, os, parted
2 from GLIException import *
3 import GLIUtility
4
5 MEGABYTE = 1024 * 1024
6
7 archinfo = { 'sparc': { 'fixedparts': [ { 'minor': 3, 'type': "wholedisk" } ], 'disklabel': 'sun', 'extended': False },
8 'hppa': { 'fixedparts': [ { 'minor': 1, 'type': "boot" } ], 'disklabel': 'msdos', 'extended': False },
9 'x86': { 'fixedparts': [], 'disklabel': 'msdos', 'extended': True },
10 'amd64': { 'fixedparts': [], 'disklabel': 'msdos', 'extended': True },
11 'ppc': { 'fixedparts': [ { 'minor': 1, 'type': "metadata" } ], 'disklabel': 'mac', 'extended': False }
12 }
13
14 ##
15 # This class provides a partitioning abstraction for the frontends
16 class Device:
17 "Class representing a partitionable device."
18
19 _device = None
20 _partitions = None
21 _geometry = None
22 _total_bytes = 0
23 _total_sectors = 0
24 _cylinder_bytes = 0
25 _sectors_in_cylinder = 0
26 _parted_dev = None
27 _parted_disk = None
28 _sector_bytes = 0
29 _total_mb = 0
30 _arch = None
31 _disklabel = None
32
33 ##
34 # Initialization function for GLIStorageDevice class
35 # @param device Device node (e.g. /dev/hda) of device being represented
36 # @param arch="x86" Architecture that we're partition for (defaults to 'x86' for now)
37 def __init__(self, device, arch="x86", set_geometry=True):
38 self._device = device
39 self._partitions = {}
40 self._geometry = {'cylinders': 0, 'heads': 0, 'sectors': 0, 'sectorsize': 512}
41 self._total_bytes = 0
42 self._cylinder_bytes = 0
43 self._arch = arch
44 self._parted_dev = parted.PedDevice.get(self._device)
45 try:
46 self._parted_disk = parted.PedDisk.new(self._parted_dev)
47 except:
48 self._parted_disk = self._parted_dev.disk_new_fresh(parted.disk_type_get(archinfo[self._arch]['disklabel']))
49 self._disklabel = self._parted_disk.type.name
50 if set_geometry:
51 self.set_disk_geometry_from_disk()
52
53 ##
54 # Sets disk geometry info from disk. This function is used internally by __init__()
55 def set_disk_geometry_from_disk(self):
56 self._total_bytes = self._parted_dev.length * self._parted_dev.sector_size
57 self._geometry['heads'], self._geometry['sectors'], self._geometry['cylinders'] = self._parted_dev.heads, self._parted_dev.sectors, self._parted_dev.cylinders
58 self._sector_bytes = self._parted_dev.sector_size
59 self._cylinder_bytes = self._geometry['heads'] * self._geometry['sectors'] * self._sector_bytes
60 self._total_sectors = self._parted_dev.length
61 self._sectors_in_cylinder = self._geometry['heads'] * self._geometry['sectors']
62 self._total_mb = long(self._total_bytes / MEGABYTE)
63
64 ##
65 # Sets partition info from disk.
66 def set_partitions_from_disk(self):
67 last_part = 0
68 last_log_part = 4
69 parted_part = self._parted_disk.next_partition()
70 while parted_part:
71 part_mb = long((parted_part.geom.end - parted_part.geom.start + 1) * self._sector_bytes / MEGABYTE)
72 if parted_part.num >= 1:
73 fs_type = ""
74 if parted_part.fs_type != None: fs_type = parted_part.fs_type.name
75 if parted_part.type == 2: fs_type = "extended"
76 if archinfo[self._arch]['extended'] and parted_part.num > 4:
77 last_log_part = parted_part.num
78 else:
79 last_part = parted_part.num
80 self._partitions[int(parted_part.num)] = Partition(self, parted_part.num, part_mb, parted_part.geom.start, parted_part.geom.end, fs_type, format=False, existing=True)
81 elif parted_part.type_name == "free":
82 parent_part = self.get_partition_at(parted_part.geom.start, ignore_extended=0)
83 if parent_part:
84 self._partitions[last_log_part+0.9] = Partition(self, last_log_part+0.9, part_mb, parted_part.geom.start, parted_part.geom.end, "free", format=False, existing=False)
85 last_log_part += 1
86 else:
87 self._partitions[last_part+0.1] = Partition(self, last_part+0.1, part_mb, parted_part.geom.start, parted_part.geom.end, "free", format=False, existing=False)
88 last_part += 1
89 parted_part = self._parted_disk.next_partition(parted_part)
90
91 ##
92 # Imports partition info from the install profile partition structure (currently does nothing)
93 # @param ips Parameter structure returned from install_profile.get_partition_tables()
94 def set_partitions_from_install_profile_structure(self, ips):
95 for part in ips:
96 tmppart = ips[part]
97 existing = False
98 if tmppart['origminor'] and not tmppart['format']:
99 existing = True
100 self._partitions[tmppart['minor']] = Partition(self, tmppart['minor'], tmppart['mb'], tmppart['start'], tmppart['end'], tmppart['type'], format=tmppart['format'], origminor=tmppart['origminor'], existing=existing, mountpoint=tmppart['mountpoint'], mountopts=tmppart['mountopts'], mkfsopts=tmppart['mkfsopts'])
101
102 ##
103 # Returns name of device (e.g. /dev/hda) being represented
104 def get_device(self):
105 return self._device
106
107 ##
108 # Combines free space and closes gaps in minor numbers. This is used internally
109 def tidy_partitions(self):
110 last_minor = 0
111 last_log_minor = 4
112 last_free = 0
113 last_log_free = 0
114 parts = self._partitions.keys()
115 parts.sort()
116 for part in parts:
117 if archinfo[self._arch]['extended'] and part > 4: break
118 tmppart = self._partitions[part]
119 if tmppart.get_type() == "extended":
120 for part_log in parts:
121 if part_log < 4.9: continue
122 tmppart_log = self._partitions[part_log]
123 if tmppart_log.get_type() == "free":
124 if last_log_minor < last_log_free:
125 self._partitions[last_log_free].set_mb(self._partitions[last_log_free].get_mb()+tmppart_log.get_mb())
126 del self._partitions[part_log]
127 else:
128 if not last_log_free:
129 last_log_free = last_log_minor + 0.9
130 else:
131 last_log_free = part_log
132 tmppart_log.set_minor(last_log_free)
133 self._partitions[last_log_free] = tmppart_log
134 if part_log != last_log_free: del self._partitions[part_log]
135 else:
136 if part_log > (last_log_minor + 1):
137 tmppart_log.set_minor(last_log_minor + 1)
138 last_log_minor = last_log_minor + 1
139 self._partitions[last_log_minor] = tmppart_log
140 del self._partitions[part_log]
141 else:
142 last_log_minor = part_log
143 elif tmppart.get_type() == "free":
144 if last_minor < last_free:
145 self._partitions[last_free].set_mb(self._partitions[last_free].get_mb()+tmppart.get_mb())
146 del self._partitions[part]
147 else:
148 if not last_free:
149 last_free = last_minor + 0.1
150 else:
151 last_free = part
152 tmppart.set_minor(last_free)
153 self._partitions[last_free] = tmppart
154 if part != last_free: del self._partitions[part]
155 else:
156 if part > (last_minor + 1):
157 tmppart.set_minor(last_minor + 1)
158 last_minor = last_minor + 1
159 self._partitions[last_minor] = tmppart
160 del self._partitions[part]
161 else:
162 last_minor = part
163
164 ##
165 # Adds a new partition to the partition info
166 # @param free_minor minor of unallocated space partition is being created in
167 # @param mb size of partition in MB
168 # @param start Start sector (only used for existing partitions)
169 # @param end End sector (only used for existing partitions)
170 # @param type Partition type (ext2, ext3, fat32, linux-swap, free, extended, etc.)
171 # @param mountpoint='' Partition mountpoint
172 # @param mountopts='' Partition mount options
173 # @param mkfsopts='' Additional mkfs options
174 def add_partition(self, free_minor, mb, start, end, type, mountpoint='', mountopts='',mkfsopts=''):
175 new_minor = int(free_minor) + 1
176 if self._partitions.has_key(new_minor):
177 parts = self._partitions.keys()
178 parts.sort()
179 parts.reverse()
180 hole_at = 0
181 for i in range(1, parts[0]+1):
182 if i <= new_minor: continue
183 if not self._partitions.has_key(i):
184 hole_at = i
185 break
186 stopscooting = 0
187 for i in parts:
188 if stopscooting: break
189 if i >= hole_at and hole_at: continue
190 if i >= new_minor:
191 self._partitions[i].set_minor(i+1)
192 self._partitions[i+1] = self._partitions[i]
193 if i == new_minor: stopscooting = 1
194 if mb != self._partitions[free_minor].get_mb():
195 old_free_mb = self._partitions[free_minor].get_mb()
196 del self._partitions[free_minor]
197 if archinfo[self._arch]['extended'] and new_minor >= 5:
198 free_minor = new_minor + 0.9
199 else:
200 free_minor = new_minor + 0.1
201 self._partitions[free_minor] = Partition(self, free_minor, old_free_mb-mb, 0, 0, "free")
202 # print "add_partition(): new part doesn't use all freespace. new free part is: minor=" + str(free_minor)
203 else:
204 del self._partitions[free_minor]
205 self._partitions[new_minor] = Partition(self, new_minor, mb, start, end, type, mountpoint=mountpoint, mountopts=mountopts,mkfsopts=mkfsopts)
206 if type == "extended":
207 self._partitions[4.9] = Partition(self, 4.9, mb, 0, 0, "free")
208 self.tidy_partitions()
209
210 ##
211 # Removes partition from partition info
212 # @param minor Minor of partition to remove
213 def remove_partition(self, minor):
214 tmppart = self._partitions[int(minor)]
215 free_minor = 0
216 if tmppart.is_logical():
217 free_minor = minor-0.1
218 else:
219 free_minor = minor-0.9
220 self._partitions[free_minor] = Partition(self, free_minor, tmppart.get_mb(), 0, 0, "free", format=False, existing=False)
221 del self._partitions[int(minor)]
222 self.tidy_partitions()
223
224 ##
225 # Returns free space (no longer used)
226 # @param start Start sector for search
227 def get_free_space(self, start):
228 GAP_SIZE = 100
229 parts = self._partitions.keys()
230 parts.sort()
231 lastend_pri = 0
232 lastend_log = 0
233 free_start = -1
234 free_end = -1
235 if start > self._total_sectors: return (-1, -1)
236 for part in parts:
237 if part > 4: break
238 tmppart = self._partitions[part]
239 if (tmppart.get_start() > (lastend_pri + GAP_SIZE)) and (lastend_pri >= start):
240 free_start = lastend_pri
241 free_end = tmppart.get_start() - 1
242 break
243 if tmppart.is_extended() and start < tmppart.get_end():
244 lastend_log = tmppart.get_start()
245 for part_log in parts:
246 if part_log < 5: continue
247 tmppart_log = self._partitions[part_log]
248 if (tmppart_log.get_start() > (lastend_log + GAP_SIZE)) and (lastend_log >= start):
249 free_start = lastend_log
250 free_end = tmppart_log.get_start() - 1
251 break
252 lastend_log = tmppart_log.get_end() + 1
253 if free_start == -1 and lastend_log < tmppart.get_end():
254 free_start = lastend_log
255 free_end = tmppart.get_end()
256 break
257 lastend_pri = tmppart.get_end() + 1
258 if free_start == -1 and lastend_pri < self._total_sectors:
259 free_start = lastend_pri
260 free_end = self._total_sectors
261 return (free_start, free_end)
262
263 ##
264 # Gets partition containing a certain sector (no longer used)
265 # @param sector Sector to look at
266 # @param ignore_extended=1 Ignore extended partitions
267 def get_partition_at(self, sector, ignore_extended=1):
268 parts = self._partitions.keys()
269 parts.sort()
270 for part in parts:
271 tmppart = self._partitions[part]
272 if ignore_extended and tmppart.is_extended(): continue
273 if (sector >= tmppart.get_start()) and (sector <= tmppart.get_end()):
274 return part
275 return 0
276
277 ##
278 # Returns free minor (no longer used)
279 # @param start Parameter description
280 # @param end Parameter description
281 def get_free_minor_at(self, start, end):
282 parts = self._partitions.keys()
283 parts.sort()
284 minor = 1
285 lastpart = 0
286 for part in parts:
287 if part > 4: break
288 tmppart = self._partitions[part]
289 if end < tmppart.get_start():
290 minor = part
291 if (minor - 1) > lastpart: minor = lastpart + 1
292 break
293 if tmppart.is_extended() and start < tmppart.get_end():
294 minor = 5
295 lastpart = 4
296 for part_log in parts:
297 if part_log < 5: continue
298 tmppart_log = self._partitions[part_log]
299 if end < tmppart_log.get_start():
300 minor = part_log
301 if (minor - 1) > lastpart: minor = lastpart + 1
302 break
303 minor = part_log + 1
304 lastpart = part_log
305 break
306 minor = part + 1
307 lastpart = part
308 return minor
309
310 ##
311 # Returns an ordered list (disk order) of partition minors
312 def get_ordered_partition_list(self):
313 parts = self._partitions.keys()
314 parts.sort()
315 partlist = []
316 tmppart = None
317 for part in parts:
318 if archinfo[self._arch]['extended'] and part > 4.1: break
319 tmppart = self._partitions[part]
320 partlist.append(part)
321 if tmppart.is_extended():
322 for part_log in parts:
323 if part_log < 4.9: continue
324 partlist.append(part_log)
325 return partlist
326
327 ##
328 # Returns partition info in a format suitable for passing to install_profile.set_partition_tables()
329 def get_install_profile_structure(self):
330 devdic = {}
331 for part in self._partitions:
332 tmppart = self._partitions[part]
333 devdic[part] = { 'mb': tmppart.get_mb(), 'minor': float(part), 'origminor': tmppart.get_orig_minor(), 'type': tmppart.get_type(), 'mountpoint': tmppart.get_mountpoint(), 'mountopts': tmppart.get_mountopts(), 'format': tmppart.get_format(), 'mkfsopts': tmppart.get_mkfsopts(), 'start': 0, 'end': 0 }
334 return devdic
335
336 ##
337 # Returns the minor of the extended partition, if any
338 def get_extended_partition(self):
339 for part in self._partitions:
340 tmppart = self._partitions[part]
341 if tmppart.is_extended():
342 return part
343 return 0
344
345 ##
346 # Returns the drive model
347 def get_model(self):
348 return self._parted_dev.model
349
350 ##
351 # Sets the disklabel type
352 def set_disklabel(self, disklabel):
353 self._disklabel = disklabel
354
355 ##
356 # Returns the disklabel type
357 def get_disklabel(self):
358 return self._disklabel
359
360 ##
361 # Returns the number of sectors on the device
362 def get_num_sectors(self):
363 return long(self._total_sectors)
364
365 ##
366 # Returns the size of a cylinder in bytes
367 def get_cylinder_size(self):
368 return long(self._cylinder_bytes)
369
370 ##
371 # Returns the size of a sector in bytes
372 def get_sector_size(self):
373 return long(self._sector_bytes)
374
375 ##
376 # Returns the number of cylinders
377 def get_num_cylinders(self):
378 return long(self._geometry['cylinders'])
379
380 ##
381 # Returns the total number of bytes on the device
382 def get_drive_bytes(self):
383 return long(self._total_bytes)
384
385 ##
386 # Returns the total number of MB on the device
387 def get_total_mb(self):
388 return self._total_mb
389
390 ##
391 # Returns partition info dictionary
392 def get_partitions(self):
393 return self._partitions
394
395 ##
396 # Prints disk geometry to STDOUT (no longer used)
397 def print_geometry(self):
398 print self._total_bytes, self._geometry
399
400 ##
401 # Utility function for running a command and returning it's output as a list
402 # @param cmd Command to run
403 def _run(self, cmd):
404 "Runs a command and returns the output"
405
406 # Run command
407 output_string = commands.getoutput(cmd)
408
409 # What we will return
410 output_list = []
411
412 # As long as there is a new line in the output_string
413 while output_string.find("\n") != -1:
414
415 # Find the \n in the string
416 index = output_string.find("\n") + 1
417
418 # Add the line to the output and remove it from
419 # the output_string
420 output_list.append(output_string[:index])
421 output_string = output_string[index:]
422
423 # return output
424 return output_list
425
426 ##
427 # This class represents a partition within a GLIStorageDevice object
428 class Partition:
429 "Class representing a single partition within a Device object"
430
431 _device = None
432 _minor = 0
433 _orig_minor = 0
434 _start = 0
435 _end = 0
436 _type = None
437 _mountpoint = None
438 _mountopts = None
439 _format = None
440 _resizeable = None
441 _min_mb_for_resize = 0
442 _mb = 0
443 _mkfsopts = None
444
445 ##
446 # Initialization function for the Partition class
447 # @param device Parent GLIStorageDevice object
448 # @param minor Minor of partition
449 # @param mb Parameter Size of partition in MB
450 # @param start Parameter Start sector of partition
451 # @param end Parameter Start sector of partition
452 # @param type Parameter Type of partition (ext2, ext3, fat32, linux-swap, free, extended, etc.)
453 # @param mountpoint='' Mountpoint of partition
454 # @param mountopts='' Mount options of partition
455 # @param mkfsopts='' Additional mkfs options
456 # @param format=True Format partition
457 # @param existing=False This partition exists on disk
458 def __init__(self, device, minor, mb, start, end, type, mountpoint='', mountopts='', format=True, existing=False, origminor=0, mkfsopts=''):
459 self._device = device
460 self._minor = float(minor)
461 self._start = long(start)
462 self._end = long(end)
463 self._type = type or "unknown"
464 self._mountpoint = mountpoint
465 self._mountopts = mountopts
466 self._format = format
467 self._mb = mb
468 self._orig_minor = origminor
469 self._mkfsopts = mkfsopts
470 if type != "free":
471 if existing and not origminor:
472 self._orig_minor = self._minor
473 self._minor = int(self._minor)
474 self._orig_minor = int(self._orig_minor)
475 if existing:
476 parted_part = device._parted_disk.get_partition(self._orig_minor)
477 label_type = device._parted_disk.type.name
478 if label_type == "loop":
479 dev_node = device._device
480 else:
481 dev_node = device._device + str(self._orig_minor)
482 # print "dev_node = " + dev_node
483 if type == "ntfs":
484 min_bytes = long(commands.getoutput("ntfsresize -f --info " + dev_node + " | grep -e '^You might resize' | sed -e 's/You might resize at //' -e 's/ bytes or .\+//'"))
485 self._min_mb_for_resize = long(min_bytes / MEGABYTE) + 1
486 self._resizeable = True
487 elif type == "ext2" or type == "ext3":
488 block_size = long(string.strip(commands.getoutput("dumpe2fs -h " + dev_node + r" 2>&1 | grep -e '^Block size:' | sed -e 's/^Block size:\s\+//'")))
489 free_blocks = long(string.strip(commands.getoutput("dumpe2fs -h " + dev_node + r" 2>&1 | grep -e '^Free blocks:' | sed -e 's/^Free blocks:\s\+//'")))
490 free_bytes = long(block_size * free_blocks)
491 # can't hurt to pad (the +50) it a bit since this is really just a guess
492 self._min_mb_for_resize = self._mb - long(free_bytes / MEGABYTE) + 50
493 self._resizeable = True
494 else:
495 parted_part = self._device._parted_disk.get_partition(int(self._orig_minor))
496 try:
497 parted_fs = parted_part.geom.file_system_open()
498 except:
499 self._resizeable = False
500 return
501 resize_constraint = parted_fs.get_resize_constraint()
502 min_bytes = resize_constraint.min_size * self._device._sector_bytes
503 self._min_mb_for_resize = long(min_bytes / MEGABYTE) + 1
504 self._resizeable = True
505
506 ##
507 # Returns whether or not the partition is extended
508 def is_extended(self):
509 if self._type == "extended":
510 return True
511 else:
512 return False
513
514 ##
515 # Returns whether or not the partition is logical
516 def is_logical(self):
517 if self._type == "free":
518 if int(self._minor) + 0.9 == self._minor:
519 return True
520 else:
521 return False
522 elif archinfo[self._device._arch]['extended'] and self._minor > 4:
523 return True
524 else:
525 return False
526
527 ##
528 # Returns a list of logical partitions if this is an extended partition
529 def get_logicals(self):
530 if not self.is_extended():
531 return None
532 logicals = []
533 parts = self._device._partitions.keys()
534 parts.sort()
535 for part in parts:
536 if part < 5: continue
537 logicals.append(part)
538 logicals.sort()
539 return logicals
540
541 ##
542 # Returns the extened parent partition if this is a logical partition (no longer used)
543 def get_extended_parent(self):
544 if not self.is_logical():
545 return None
546 else:
547 return self._device.get_partition_at(self._start, ignore_extended=0)
548
549 ##
550 # Sets the options passed to mkfs
551 # @param mkfsopts Options passed to mkfs
552 def set_mkfsopts(self, mkfsopts):
553 self._mkfsopts = mkfsopts
554
555 ##
556 # Returns the options passes to mkfs
557 def get_mkfsopts(self):
558 return self._mkfsopts
559
560 ##
561 # Sets the start sector for the partition
562 # @param start Start sector
563 def set_start(self, start):
564 self._start = long(start)
565
566 ##
567 # Returns the start sector for the partition
568 def get_start(self):
569 return long(self._start)
570
571 ##
572 # Sets the end sector of the partition
573 # @param end End sector
574 def set_end(self, end):
575 self._end = long(end)
576
577 ##
578 # Returns end sector for the partition
579 def get_end(self):
580 return long(self._end)
581
582 ##
583 # Returns size of partition in MB
584 def get_mb(self):
585 return long(self._mb)
586
587 ##
588 # Sets size of partition in MB
589 # @param mb Parameter description
590 def set_mb(self, mb):
591 self._mb = long(mb)
592
593 ##
594 # Sets type of partition
595 # @param type Parameter description
596 def set_type(self, type):
597 self._type = type
598
599 ##
600 # Returns type of partition
601 def get_type(self):
602 return self._type
603
604 ##
605 # Returns parent GLIStorageDevice object
606 def get_device(self):
607 return self._device
608
609 ##
610 # Sets minor of partition
611 # @param minor New minor
612 def set_minor(self, minor):
613 self._minor = float(minor)
614
615 ##
616 # Returns minor of partition
617 def get_minor(self):
618 return float(self._minor)
619
620 ##
621 # Sets the original minor of the partition
622 # @param orig_minor Parameter description
623 def set_orig_minor(self, orig_minor):
624 self._orig_minor = int(orig_minor)
625
626 ##
627 # Returns the original minor of the partition
628 def get_orig_minor(self):
629 return self._orig_minor
630
631 ##
632 # Sets the mountpoint for the partition
633 # @param mountpoint Mountpoint
634 def set_mountpoint(self, mountpoint):
635 self._mountpoint = mountpoint
636
637 ##
638 # Returns the mountpoint for the partition
639 def get_mountpoint(self):
640 return self._mountpoint
641
642 ##
643 # Sets the mount options for the partition
644 # @param mountopts Mount options
645 def set_mountopts(self, mountopts):
646 self._mountopts = mountopts
647
648 ##
649 # Returns the mount options for the partition
650 def get_mountopts(self):
651 return self._mountopts
652
653 ##
654 # Set whether to format the partition
655 # @param format Format this partition (True/False)
656 def set_format(self, format):
657 self._format = format
658
659 ##
660 # Returns whether to format the partition
661 def get_format(self):
662 return self._format
663
664 ##
665 # Returns whether the partition is resizeable
666 def is_resizeable(self):
667 return self._resizeable
668
669 ##
670 # Returns minimum MB for resize
671 def get_min_mb_for_resize(self):
672 # if self.is_extended():
673 # min_size = self._start
674 # for part in self._device._partitions:
675 # if part < 5: continue
676 # if part.get_end > min_size: min_size = part.get_end()
677 # return min_size
678 # else:
679 if self._resizeable:
680 return self._min_mb_for_resize
681 else:
682 return -1
683
684 ##
685 # Returns maximum MB for resize
686 def get_max_mb_for_resize(self):
687 if self._resizeable:
688 free_minor = 0
689 if self.is_logical():
690 free_minor = self._minor + 0.9
691 else:
692 free_minor = self._minor + 0.1
693 if free_minor in self._device._partitions:
694 return self._mb + self._device._partitions[free_minor]._mb
695 else:
696 return self._mb
697 else:
698 return -1
699
700 ##
701 # Resizes the partition
702 # @param mb New size in MB
703 def resize(self, mb):
704 free_minor = self._minor
705 if self.is_logical():
706 free_minor += 0.9
707 else:
708 free_minor += 0.1
709 if mb < self._mb:
710 # Shrinking
711 if not free_minor in self._device._partitions:
712 self._device._partitions[free_minor] = Partition(self._device, free_minor, 0, 0, 0, "free", format=False, existing=False)
713 self._device._partitions[free_minor]._mb += self._mb - mb
714 self._mb = mb
715 elif mb == self._mb + self._device._partitions[free_minor]._mb:
716 # Using all available unallocated space
717 del self._device._partitions[free_minor]
718 self._mb = mb
719 elif mb > self._mb:
720 # Growing
721 self._device._partitions[free_minor]._mb = mb - self._mb
722 self._mb = mb
723
724 ##
725 # Returns a list of detected partitionable devices
726 def detect_devices():
727 devices = []
728
729 # Make sure sysfs exists
730 if not os.path.exists("/sys/bus"):
731 raise GLIException("GLIStorageDeviceError", 'fatal', 'detect_devices', "no sysfs found (you MUST use a kernel >2.6)")
732 # Make sure /proc/partitions exists
733 if not os.path.exists("/proc/partitions"):
734 raise GLIException("GLIStorageDeviceError", 'fatal', 'detect_devices', "/proc/partitions does not exist! Please make sure procfs is in your kernel and mounted!")
735
736 # Load /proc/partitions into the variable 'partitions'
737 partitions = []
738 for line in open("/proc/partitions"):
739 if len(line.split()) < 4 or not line.split()[0].isdigit() or not line.split()[1].isdigit():
740 continue
741
742 # Get the major, minor and device name
743 major = line.split()[0]
744 minor = line.split()[1]
745 device = "/dev/" + line.split()[3]
746
747 if not major.isdigit() or not minor.isdigit():
748 continue
749
750 major = int(major)
751 minor = int(minor)
752
753 # If there is no /dev/'device_name', then scan
754 # all the devices in /dev to try and find a
755 # devices with the same major and minor
756 if not os.path.exists(device):
757 device = None
758 for path, dirs, files in os.walk("/dev"):
759 for d_file in files:
760 full_file = os.path.join(path, d_file)
761 if not os.path.exists(full_file):
762 continue
763 statres = os.stat(full_file)
764 fmaj = os.major(statres.st_rdev)
765 fmin = os.minor(statres.st_rdev)
766 if fmaj == major and fmin == minor:
767 device = full_file
768 break
769 if not device:
770 continue
771
772 partitions.append(( major, minor, device ))
773
774 # Scan sysfs for the devices of type 'x'
775 # 'x' being a member of the list below:
776 for dev_type in [ "ide", "scsi" ]: # Other device types? usb? fw?
777 if os.path.exists("/sys/bus/" + dev_type):
778 sysfs_devices = os.listdir("/sys/bus/"+dev_type+"/devices")
779
780 # For each device in the devices on that bus
781 for sysfs_device in sysfs_devices:
782 dev_file = "/sys/bus/" + dev_type + "/devices/" + sysfs_device + "/block/dev"
783
784 # If the file is not a block device, loop
785 if not os.path.exists(dev_file):
786 continue
787
788 # Get the major and minor info
789 try:
790 major, minor = open(dev_file).read().split(":")
791 major = int(major)
792 minor = int(minor)
793 except:
794 raise GLIException("GLIStorageDeviceError", 'fatal', 'detect_devices', "invalid major minor in " + dev_file)
795
796 # Find a device listed in /proc/partitions
797 # that has the same minor and major as our
798 # current block device.
799 for record in partitions:
800 if major == record[0] and minor == record[1]:
801 devices.append(record[2])
802
803 # For testing the partitioning code
804 if GLIUtility.is_file("/tmp/disk.img"):
805 devices.append("/tmp/disk.img")
806
807 # We have assembled the list of devices, so return it
808 return devices

Properties

Name Value
svn:eol-style native

  ViewVC Help
Powered by ViewVC 1.1.20