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

Contents of /trunk/src/GLIStorageDevice.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 463 - (show annotations) (download) (as text)
Wed Mar 30 22:11:27 2005 UTC (15 years, 6 months ago) by agaffney
File MIME type: text/x-python
File size: 19187 byte(s)
Check for disklabel type loop and use the device name without a minor.

1 import commands, string, re, os, parted
2
3 class Device:
4 "Class representing a partitionable device."
5
6 _device = None
7 _partitions = None
8 _geometry = None
9 _total_bytes = 0
10 _total_sectors = 0
11 _cylinder_bytes = 0
12 _sectors_in_cylinder = 0
13 _parted_dev = None
14 _parted_disk = None
15 _sector_bytes = 0
16
17 def __init__(self, device):
18 self._device = device
19 self._partitions = {}
20 self._geometry = {'cylinders': 0, 'heads': 0, 'sectors': 0, 'sectorsize': 512}
21 self._total_bytes = 0
22 self._cylinder_bytes = 0
23 self._parted_dev = parted.PedDevice.get(self._device)
24 self._parted_disk = parted.PedDisk.new(self._parted_dev)
25 self.set_disk_geometry_from_disk()
26
27 def set_disk_geometry_from_disk(self):
28 self._total_bytes = self._parted_dev.length * self._parted_dev.sector_size
29 # if string.strip(commands.getoutput("echo " + self._device + " | grep '/hd'")) == self._device: # IDE
30 # proc_dir = "/proc/ide/" + commands.getoutput("echo " + self._device + " | cut -d '/' -f 3")
31 # proc_dir = string.strip(proc_dir)
32 # heads = commands.getoutput("cat " + proc_dir + "/geometry | grep logical | cut -d '/' -f 2")
33 # sectors = commands.getoutput("cat " + proc_dir + "/geometry | grep logical | cut -d '/' -f 3")
34 # total_sectors = commands.getoutput("cat " + proc_dir + "/capacity")
35 # cylinders = int(total_sectors) / (int(heads) * int(sectors))
36 # self._geometry['heads'], self._geometry['sectors'], self._geometry['cylinders'] = int(heads), int(sectors), int(cylinders)
37 # else: #SCSI
38 self._geometry['heads'], self._geometry['sectors'], self._geometry['cylinders'] = self._parted_dev.heads, self._parted_dev.sectors, self._parted_dev.cylinders
39
40 self._sector_bytes = self._parted_dev.sector_size
41 self._cylinder_bytes = self._geometry['heads'] * self._geometry['sectors'] * self._sector_bytes
42 # self._total_sectors = self._geometry['cylinders'] * self._geometry['heads'] * self._geometry['sectors']
43 self._total_sectors = self._parted_dev.length
44 self._sectors_in_cylinder = self._geometry['heads'] * self._geometry['sectors']
45
46 def set_partitions_from_disk(self):
47 parted_part = self._parted_disk.next_partition()
48 while parted_part != None:
49 if parted_part.num < 1:
50 parted_part = self._parted_disk.next_partition(parted_part)
51 continue
52 fs_type = ""
53 if parted_part.fs_type != None: fs_type = parted_part.fs_type.name
54 if parted_part.type == 2: fs_type = "extended"
55 self._partitions[int(parted_part.num)] = Partition(self, parted_part.num, '', parted_part.geom.start, parted_part.geom.end, (parted_part.geom.end - parted_part.geom.start), fs_type, format=False, existing=True)
56 parted_part = self._parted_disk.next_partition(parted_part)
57
58 def set_partitions_from_install_profile_structure(self, ips):
59 for part in ips:
60 tmppart = ips[part]
61 existing = False
62 parted_part = self._parted_disk.get_partition(part)
63 if parted_part != None:
64 start = parted_part.geom.start / self._sectors_in_cylinder
65 end = parted_part.geom.end / self._sectors_in_cylinder
66 fs_type = ""
67 if parted_part.fs_type != None: fs_type = parted_part.fs_type.name
68 if parted_part.type == 2: fs_type = "extended"
69 if int(tmppart['start']) == int(start) and int(tmppart['end']) == int(end) and tmppart['type'] == fs_type and tmppart['format'] == False:
70 existing = True
71 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']))
72
73 def get_device(self):
74 return self._device
75
76 def clear_partitions(self):
77 self._partitions = {}
78
79 def add_partition(self, minor, start, end, type, mountpoint='', mountopts=''):
80 free_start, free_end = self.get_free_space(start)
81 minor = int(minor)
82 if not free_end:
83 return False
84 if self._partitions.has_key(minor):
85 parts = self._partitions.keys()
86 parts.sort()
87 parts.reverse()
88 hole_at = 0
89 for i in range(1, parts[0]+1):
90 if i <= minor: continue
91 if not self._partitions.has_key(int(i)):
92 hole_at = i
93 break
94 stopscooting = 0
95 for i in parts:
96 if stopscooting: break
97 if (i >= hole_at) and (hole_at): continue
98 if i >= minor:
99 self._partitions[i].set_minor(i+1)
100 self._partitions[i+1] = self._partitions[i]
101 if i == minor: stopscooting = 1
102 self._partitions[minor] = Partition(self, minor, '', start, end, 0, type, mountpoint=mountpoint, mountopts=mountopts)
103
104 def remove_partition(self, minor):
105 del self._partitions[int(minor)]
106
107 def get_free_space(self, start):
108 GAP_SIZE = 100
109 parts = self._partitions.keys()
110 parts.sort()
111 lastend_pri = 0
112 lastend_log = 0
113 free_start = -1
114 free_end = -1
115 if start > self._total_sectors: return (-1, -1)
116 for part in parts:
117 if part > 4: break
118 tmppart = self._partitions[part]
119 if (tmppart.get_start() > (lastend_pri + GAP_SIZE)) and (lastend_pri >= start):
120 free_start = lastend_pri
121 free_end = tmppart.get_start() - 1
122 break
123 if tmppart.is_extended() and start < tmppart.get_end():
124 lastend_log = tmppart.get_start()
125 for part_log in parts:
126 if part_log < 5: continue
127 tmppart_log = self._partitions[part_log]
128 if (tmppart_log.get_start() > (lastend_log + GAP_SIZE)) and (lastend_log >= start):
129 free_start = lastend_log
130 free_end = tmppart_log.get_start() - 1
131 break
132 lastend_log = tmppart_log.get_end() + 1
133 if free_start == -1 and lastend_log < tmppart.get_end():
134 free_start = lastend_log
135 free_end = tmppart.get_end()
136 break
137 lastend_pri = tmppart.get_end() + 1
138 if free_start == -1 and lastend_pri < self._total_sectors:
139 free_start = lastend_pri
140 free_end = self._total_sectors
141 return (free_start, free_end)
142
143 def get_partition_at(self, sector, ignore_extended=1):
144 parts = self._partitions.keys()
145 parts.sort()
146 for part in parts:
147 tmppart = self._partitions[part]
148 if ignore_extended and tmppart.is_extended(): continue
149 if (sector >= tmppart.get_start()) and (sector <= tmppart.get_end()):
150 return part
151 return 0
152
153 def get_free_minor_at(self, start, end):
154 parts = self._partitions.keys()
155 parts.sort()
156 minor = 1
157 lastpart = 0
158 for part in parts:
159 if part > 4: break
160 tmppart = self._partitions[part]
161 if end < tmppart.get_start():
162 minor = part
163 if (minor - 1) > lastpart: minor = lastpart + 1
164 break
165 if tmppart.is_extended() and start < tmppart.get_end():
166 minor = 5
167 lastpart = 4
168 for part_log in parts:
169 if part_log < 5: continue
170 tmppart_log = self._partitions[part_log]
171 if end < tmppart_log.get_start():
172 minor = part_log
173 if (minor - 1) > lastpart: minor = lastpart + 1
174 break
175 minor = part_log + 1
176 lastpart = part_log
177 break
178 minor = part + 1
179 lastpart = part
180 return minor
181
182 def get_ordered_partition_list(self):
183 parts = self._partitions.keys()
184 parts.sort()
185 partlist = []
186 free_start, free_end = self.get_free_space(0)
187 tmppart = None
188 tmppart_log = None
189 for part in parts:
190 if part > 4: break
191 tmppart = self._partitions[part]
192 if free_end < tmppart.get_start() and not free_start == -1:
193 partlist.append("Free Space (" + str(free_start) + "-" + str(free_end) + ")")
194 free_start, free_end = self.get_free_space(free_end)
195 newitem = self._device + str(part) + ": " + str(tmppart.get_start()) + "-" + str(tmppart.get_end())
196 if tmppart.is_extended(): newitem = newitem + " extended"
197 partlist.append(newitem)
198 if tmppart.is_extended():
199 for part_log in parts:
200 if part_log < 5: continue
201 tmppart_log = self._partitions[part_log]
202 if free_end < tmppart_log.get_start() and free_end <= tmppart.get_end() and not free_start == -1:
203 partlist.append("Free Space (" + str(free_start) + "-" + str(free_end) + ")")
204 free_start, free_end = self.get_free_space(free_end)
205 newitem = self._device + str(part_log) + ": " + str(tmppart_log.get_start()) + "-" + str(tmppart_log.get_end()) + " logical"
206 partlist.append(newitem)
207 if ((tmppart_log == None) or (free_start > tmppart_log.get_end())) and free_start < tmppart.get_end():
208 partlist.append("Free Space (" + str(free_start) + "-" + str(free_end) + ") logical")
209 free_start, free_end = self.get_free_space(free_end)
210 if (tmppart == None) or (free_start > tmppart.get_end()):
211 partlist.append("Free Space (" + str(free_start) + "-" + str(free_end) + ")")
212 return partlist
213
214 def get_install_profile_structure(self):
215 devdic = {}
216 for part in self._partitions:
217 tmppart = self._partitions[part]
218 devdic[part] = { 'mb': 0, 'minor': int(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() }
219 return devdic
220
221 def get_extended_partition(self):
222 for part in self._partitions:
223 tmppart = self._partitions[part]
224 if tmppart.is_extended():
225 return part
226 return 0
227
228 def get_num_sectors(self):
229 return int(self._total_sectors)
230
231 def get_cylinder_size(self):
232 return int(self._cylinder_bytes)
233
234 def get_sector_size(self):
235 return int(self._sector_bytes)
236
237 def get_num_cylinders(self):
238 return int(self._geometry['cylinders'])
239
240 def get_drive_bytes(self):
241 return int(self._total_bytes)
242
243 def get_partitions(self):
244 return self._partitions
245
246 def print_partitions(self):
247 for part in self._partitions.keys():
248 print self._partitions[part].return_info()
249
250 def print_geometry(self):
251 print self._total_bytes, self._geometry
252
253 def _error(self, message):
254 "Raises an exception"
255 raise "DeviceObjectError", message
256
257 def _run(self, cmd):
258 "Runs a command and returns the output"
259
260 # Run command
261 output_string = commands.getoutput(cmd)
262
263 # What we will return
264 output_list = []
265
266 # As long as there is a new line in the output_string
267 while output_string.find("\n") != -1:
268
269 # Find the \n in the string
270 index = output_string.find("\n") + 1
271
272 # Add the line to the output and remove it from
273 # the output_string
274 output_list.append(output_string[:index])
275 output_string = output_string[index:]
276
277 # return output
278 return output_list
279
280
281 class Partition:
282 "Class representing a single partition within a Device object"
283
284 _device = None
285 _minor = None
286 _orig_minor = ""
287 _bootflag = None
288 _start = None
289 _end = None
290 _blocks = None
291 _type = None
292 _mountpoint = None
293 _mountopts = None
294 _format = None
295 _resizeable = None
296 _min_sectors_for_resize = 0
297
298 def __init__(self, device, minor, bootflag, start, end, blocks, type, mountpoint='', mountopts='', format=True, existing=False):
299 self._device = device
300 self._minor = int(minor)
301 if existing: self._orig_minor = int(minor)
302 self._bootflag = bootflag
303 self._start = int(start)
304 self._end = int(end)
305 self._blocks = int(blocks)
306 if type == "": type = "unknown"
307 self._type = type
308 self._mountpoint = mountpoint
309 self._mountopts = mountopts
310 self._format = format
311 if blocks == 0:
312 self._blocks = ((self._end - self._start) * self._device.get_cylinder_size()) / 512
313 if existing:
314 parted_part = device._parted_disk.get_partition(minor)
315 label_type = device._parted_disk.type.name
316 if label_type == "loop":
317 dev_node = device._device + str(minor)
318 else:
319 dev_node = device._device
320 if type == "ntfs":
321 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 .\+//'"))
322 self._min_cylinders_for_resize = int(min_bytes / self._device._cylinder_bytes) + 1
323 self._resizeable == True
324 elif type == "ext2" or type == "ext3":
325 block_size = string.strip(commands.getoutput("dumpe2fs -h " + dev_node + r" 2>&1 | grep -e '^Block size:' | sed -e 's/^Block size:\s\+//'"))
326 free_blocks = string.strip(commands.getoutput("dumpe2fs -h " + dev_node + r" 2>&1 | grep -e '^Free blocks:' | sed -e 's/^Free blocks:\s\+//'"))
327 free_sec = int(int(block_size) * int(free_blocks) / self._device._sector_bytes)
328 free_sec = free_sec - 2000 # just to be safe
329 self._min_sectors_for_resize = (self._end - self._start + 1) - free_sec
330 self._resizeable == True
331 else:
332 parted_part = self._device._parted_disk.get_partition(self._minor)
333 try:
334 parted_fs = parted_part.geom.file_system_open()
335 except:
336 self._resizeable = False
337 return
338 resize_constraint = parted_fs.get_resize_constraint()
339 min_size = resize_constraint.min_size
340 if int(min_size) != min_size: min_size = int(min_size) + 1
341 self._min_sectors_for_resize = min_size
342 self._resizeable = True
343
344 def is_extended(self):
345 if self._type == "extended":
346 return True
347 else:
348 return False
349
350 def is_logical(self):
351 part = self._device.get_partition_at(self._start, ignore_extended=0)
352 if part and self._device._partitions[part].is_extended() and not part == self._minor:
353 return True
354 return False
355
356 def get_logicals(self):
357 if not self.is_extended():
358 return None
359 logicals = []
360 start = self._start
361 parts = self._device._partitions.keys()
362 parts.sort()
363 for part in parts:
364 if part < 5: continue
365 logicals.append(part)
366 logicals.sort()
367 return logicals
368
369 def get_extended_parent(self):
370 if not self.is_logical():
371 return None
372 else:
373 return self._device.get_partition_at(self._start, ignore_extended=0)
374
375 def set_start(self, start):
376 self._start = int(start)
377 self._blocks = ((self._end - self._start) * self._device.get_cylinder_size()) / 512
378
379 def get_start(self):
380 return int(self._start)
381
382 def set_end(self, end):
383 self._end = int(end)
384 self._blocks = ((self._end - self._start) * self._device.get_cylinder_size()) / 512
385
386 def get_end(self):
387 return int(self._end)
388
389 def set_type(self, type):
390 self._type = type
391
392 def get_type(self):
393 return self._type
394
395 def get_device(self):
396 return self._device
397
398 def set_minor(self, minor):
399 self._minor = int(minor)
400
401 def get_minor(self):
402 return int(self._minor)
403
404 def set_orig_minor(self, orig_minor):
405 self._orig_minor = int(orig_minor)
406
407 def get_orig_minor(self):
408 return self._orig_minor
409
410 def set_mountpoint(self, mountpoint):
411 self._mountpoint = mountpoint
412
413 def get_mountpoint(self):
414 return self._mountpoint
415
416 def set_mountopts(self, mountopts):
417 self._mountopts = mountopts
418
419 def get_mountopts(self):
420 return self._mountopts
421
422 def set_format(self, format):
423 self._format = format
424
425 def get_format(self):
426 return self._format
427
428 def get_blocks(self):
429 return int(self._blocks)
430
431 def get_min_sectors_for_resize(self):
432 if self.is_extended():
433 min_size = self._start
434 for part in self._device._partitions:
435 if part < 5: continue
436 if part.get_end > min_size: min_size = part.get_end()
437 return min_size
438 else:
439 return self._min_sectors_for_resize
440
441 def get_max_sectors_for_resize(self):
442 free_start, free_end = self._device.get_free_space(self._end)
443 if free_end == -1: return self._end
444 if free_start - 1 == self._end:
445 if self.is_logical():
446 if free_end <= self._device._partitions[self.get_extended_parent()]._end:
447 return free_end - self._start
448 else:
449 return self._end - self._start
450 else:
451 return free_end - self._start
452
453 def resize(self, start, end):
454 part_at_start = self._device.get_partition_at(int(start))
455 part_at_end = self._device.get_partition_at(int(end))
456 logicals = None
457 if self.is_logical():
458 parent = self.get_extended_parent()
459 parentstart = int(self._device._partitions[parent].get_start())
460 parentend = int(self._device._partitions[parent].get_end())
461 if (start < parentstart) or (end > parentend): return 0
462 if self.is_extended():
463 logicals = self.get_logicals()
464 if len(logicals):
465 logicals_start = self._device._partitions[logicals[0]].get_start()
466 logicals_end = self._device._partitions[logicals[len(logicals)-1]].get_end()
467 if (start > logicals_start) or (end < logicals_end): return 0
468 if part_at_start in logicals: part_at_start = 0
469 if part_at_end in logicals: part_at_end = 0
470 if ((not part_at_start == 0) and (part_at_start != self._minor)) or ((not part_at_end == 0) and (part_at_end != self._minor)):
471 return 0
472 self.set_start(start)
473 self.set_end(end)
474 return 1
475
476 def _error(self, message):
477 "Raises an exception"
478 raise "PartitionObjectError", message
479
480
481 def detect_devices():
482 "Returns a list of partitionable devices on the system"
483
484 devices = []
485
486 # Make sure sysfs exists
487 if not os.path.exists("/sys/bus"):
488 raise Exception, "no sysfs found (you MUST use a kernel >2.6)"
489 # Make sure /proc/partitions exists
490 if not os.path.exists("/proc/partitions"):
491 raise Exception, "/proc/partitions does not exist!"
492
493 # Load /proc/partitions into the variable 'partitions'
494 partitions = []
495 for line in open("/proc/partitions"):
496 if len(line.split()) < 4 or not line.split()[0].isdigit() or \
497 not line.split()[1].isdigit():
498 continue
499
500 # Get the major, minor and device name
501 major = line.split()[0]
502 minor = line.split()[1]
503 device = "/dev/" + line.split()[3]
504
505 if not major.isdigit() or not minor.isdigit():
506 continue
507
508 major = int(major)
509 minor = int(minor)
510
511 # If there is no /dev/'device_name', then scan
512 # all the devices in /dev to try and find a
513 # devices with the same major and minor
514 if not os.path.exists(device):
515 device = None
516 for path, dirs, files in os.walk("/dev"):
517 for file in files:
518 full_file = os.path.join(path, file)
519 if not os.path.exists(full_file):
520 continue
521 statres = os.stat(full_file)
522 fmaj = os.major(statres.st_rdev)
523 fmin = os.minor(statres.st_rdev)
524 if fmaj == major and fmin == minor:
525 device = full_file
526 break
527 if not device:
528 continue
529
530 partitions.append(( major, minor, device ))
531
532 # Scan sysfs for the devices of type 'x'
533 # 'x' being a member of the list below:
534 for dev_type in [ "ide", "scsi" ]: # Other device types? usb? fw?
535 if os.path.exists("/sys/bus/" + dev_type):
536 sysfs_devices = os.listdir("/sys/bus/"+dev_type+"/devices")
537
538 # For each device in the devices on that bus
539 for sysfs_device in sysfs_devices:
540 dev_file = "/sys/bus/" + dev_type + "/devices/"\
541 + sysfs_device + "/block/dev"
542
543 # If the file is not a block device, loop
544 if not os.path.exists(dev_file):
545 continue
546
547 # Get the major and minor info
548 try:
549 major, minor = open(dev_file).read().split(":")
550 major = int(major)
551 minor = int(minor)
552 except:
553 raise Exception, "invalid major minor in "\
554 + dev_file
555
556 # Find a device listed in /proc/partitions
557 # that has the same minor and major as our
558 # current block device.
559 for record in partitions:
560 if major == record[0] and minor == record[1]:
561 devices.append(record[2])
562
563 # We have assembled the list of devices, so return it
564 return devices

Properties

Name Value
svn:eol-style native

  ViewVC Help
Powered by ViewVC 1.1.20