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

Contents of /trunk/src/GLIStorageDevice.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 514 - (show annotations) (download) (as text)
Fri Apr 15 18:37:40 2005 UTC (15 years, 6 months ago) by agaffney
File MIME type: text/x-python
File size: 28186 byte(s)
finish documentation in GLIStorageDevice.py

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

Properties

Name Value
svn:eol-style native

  ViewVC Help
Powered by ViewVC 1.1.20