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

Contents of /trunk/src/GLIStorageDevice.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 312 - (show annotations) (download) (as text)
Wed Feb 2 05:06:11 2005 UTC (15 years, 8 months ago) by agaffney
File MIME type: text/x-python
File size: 18853 byte(s)
undo change with fix

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), '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 _bootflag = None
287 _start = None
288 _end = None
289 _blocks = None
290 _type = None
291 _mountpoint = None
292 _mountopts = None
293 _format = None
294 _resizeable = None
295 _min_sectors_for_resize = 0
296
297 def __init__(self, device, minor, bootflag, start, end, blocks, type, mountpoint='', mountopts='', format=True, existing=False):
298 self._device = device
299 self._minor = int(minor)
300 self._bootflag = bootflag
301 self._start = int(start)
302 self._end = int(end)
303 self._blocks = int(blocks)
304 if type == "": type = "unknown"
305 self._type = type
306 self._mountpoint = mountpoint
307 self._mountopts = mountopts
308 self._format = format
309 if blocks == 0:
310 self._blocks = ((self._end - self._start) * self._device.get_cylinder_size()) / 512
311 if existing:
312 parted_part = device._parted_disk.get_partition(minor)
313 if type == "ntfs":
314 min_bytes = int(commands.getoutput("ntfsresize -f --info " + device._device + str(minor) + " | grep -e '^You might resize' | sed -e 's/You might resize at //' -e 's/ bytes or .\+//'"))
315 self._min_cylinders_for_resize = int(min_bytes / self._device._cylinder_bytes) + 1
316 self._resizeable == True
317 elif type == "ext2" or type == "ext3":
318 block_size = string.strip(commands.getoutput("dumpe2fs -h " + device._device + str(minor) + " 2>&1 | grep -e '^Block size:' | sed -e 's/^Block size:\s\+//'"))
319 free_blocks = string.strip(commands.getoutput("dumpe2fs -h " + device._device + str(minor) + " 2>&1 | grep -e '^Free blocks:' | sed -e 's/^Free blocks:\s\+//'"))
320 free_sec = int(int(block_size) * int(free_blocks) / self._device._sector_bytes)
321 free_sec = free_sec - 2000 # just to be safe
322 self._min_sectors_for_resize = (self._end - self._start + 1) - free_sec
323 self._resizeable == True
324 else:
325 parted_part = self._device._parted_disk.get_partition(self._minor)
326 try:
327 parted_fs = parted_part.geom.file_system_open()
328 except:
329 self._resizeable = False
330 return
331 resize_constraint = parted_fs.get_resize_constraint()
332 min_size = resize_constraint.min_size
333 if int(min_size) != min_size: min_size = int(min_size) + 1
334 self._min_sectors_for_resize = min_size
335 self._resizeable = True
336
337 def is_extended(self):
338 if self._type == "extended":
339 return True
340 else:
341 return False
342
343 def is_logical(self):
344 part = self._device.get_partition_at(self._start, ignore_extended=0)
345 if part and self._device._partitions[part].is_extended() and not part == self._minor:
346 return True
347 return False
348
349 def get_logicals(self):
350 if not self.is_extended():
351 return None
352 logicals = []
353 start = self._start
354 parts = self._device._partitions.keys()
355 parts.sort()
356 for part in parts:
357 if part < 5: continue
358 logicals.append(part)
359 logicals.sort()
360 return logicals
361
362 def get_extended_parent(self):
363 if not self.is_logical():
364 return None
365 else:
366 return self._device.get_partition_at(self._start, ignore_extended=0)
367
368 def set_start(self, start):
369 self._start = int(start)
370 self._blocks = ((self._end - self._start) * self._device.get_cylinder_size()) / 512
371
372 def get_start(self):
373 return int(self._start)
374
375 def set_end(self, end):
376 self._end = int(end)
377 self._blocks = ((self._end - self._start) * self._device.get_cylinder_size()) / 512
378
379 def get_end(self):
380 return int(self._end)
381
382 def set_type(self, type):
383 self._type = type
384
385 def get_type(self):
386 return self._type
387
388 def get_device(self):
389 return self._device
390
391 def set_minor(self, minor):
392 self._minor = int(minor)
393
394 def get_minor(self):
395 return int(self._minor)
396
397 def set_mountpoint(self, mountpoint):
398 self._mountpoint = mountpoint
399
400 def get_mountpoint(self):
401 return self._mountpoint
402
403 def set_mountopts(self, mountopts):
404 self._mountopts = mountopts
405
406 def get_mountopts(self):
407 return self._mountopts
408
409 def set_format(self, format):
410 self._format = format
411
412 def get_format(self):
413 return self._format
414
415 def get_blocks(self):
416 return int(self._blocks)
417
418 def get_min_sectors_for_resize(self):
419 if self.is_extended():
420 min_size = self._start
421 for part in self._device._partitions:
422 if part < 5: continue
423 if part.get_end > min_size: min_size = part.get_end()
424 return min_size
425 else:
426 return self._min_sectors_for_resize
427
428 def get_max_sectors_for_resize(self):
429 free_start, free_end = self._device.get_free_space(self._end)
430 if free_end == -1: return self._end
431 if free_start - 1 == self._end:
432 if self.is_logical():
433 if free_end <= self._device._partitions[self.get_extended_parent()]._end:
434 return free_end - self._start
435 else:
436 return self._end - self._start
437 else:
438 return free_end - self._start
439
440 def resize(self, start, end):
441 part_at_start = self._device.get_partition_at(int(start))
442 part_at_end = self._device.get_partition_at(int(end))
443 logicals = None
444 if self.is_logical():
445 parent = self.get_extended_parent()
446 parentstart = int(self._device._partitions[parent].get_start())
447 parentend = int(self._device._partitions[parent].get_end())
448 if (start < parentstart) or (end > parentend): return 0
449 if self.is_extended():
450 logicals = self.get_logicals()
451 if len(logicals):
452 logicals_start = self._device._partitions[logicals[0]].get_start()
453 logicals_end = self._device._partitions[logicals[len(logicals)-1]].get_end()
454 if (start > logicals_start) or (end < logicals_end): return 0
455 if part_at_start in logicals: part_at_start = 0
456 if part_at_end in logicals: part_at_end = 0
457 if ((not part_at_start == 0) and (part_at_start != self._minor)) or ((not part_at_end == 0) and (part_at_end != self._minor)):
458 return 0
459 self.set_start(start)
460 self.set_end(end)
461 return 1
462
463 def _error(self, message):
464 "Raises an exception"
465 raise "PartitionObjectError", message
466
467
468 def detect_devices():
469 "Returns a list of partitionable devices on the system"
470
471 devices = []
472
473 # Make sure sysfs exists
474 if not os.path.exists("/sys/bus"):
475 raise Exception, "no sysfs found (you MUST use a kernel >2.6)"
476 # Make sure /proc/partitions exists
477 if not os.path.exists("/proc/partitions"):
478 raise Exception, "/proc/partitions does not exist!"
479
480 # Load /proc/partitions into the variable 'partitions'
481 partitions = []
482 for line in open("/proc/partitions"):
483 if len(line.split()) < 4 or not line.split()[0].isdigit() or \
484 not line.split()[1].isdigit():
485 continue
486
487 # Get the major, minor and device name
488 major = line.split()[0]
489 minor = line.split()[1]
490 device = "/dev/" + line.split()[3]
491
492 if not major.isdigit() or not minor.isdigit():
493 continue
494
495 major = int(major)
496 minor = int(minor)
497
498 # If there is no /dev/'device_name', then scan
499 # all the devices in /dev to try and find a
500 # devices with the same major and minor
501 if not os.path.exists(device):
502 device = None
503 for path, dirs, files in os.walk("/dev"):
504 for file in files:
505 full_file = os.path.join(path, file)
506 if not os.path.exists(full_file):
507 continue
508 statres = os.stat(full_file)
509 fmaj = os.major(statres.st_rdev)
510 fmin = os.minor(statres.st_rdev)
511 if fmaj == major and fmin == minor:
512 device = full_file
513 break
514 if not device:
515 continue
516
517 partitions.append(( major, minor, device ))
518
519 # Scan sysfs for the devices of type 'x'
520 # 'x' being a member of the list below:
521 for dev_type in [ "ide", "scsi" ]: # Other device types? usb? fw?
522 if os.path.exists("/sys/bus/" + dev_type):
523 sysfs_devices = os.listdir("/sys/bus/"+dev_type+"/devices")
524
525 # For each device in the devices on that bus
526 for sysfs_device in sysfs_devices:
527 dev_file = "/sys/bus/" + dev_type + "/devices/"\
528 + sysfs_device + "/block/dev"
529
530 # If the file is not a block device, loop
531 if not os.path.exists(dev_file):
532 continue
533
534 # Get the major and minor info
535 try:
536 major, minor = open(dev_file).read().split(":")
537 major = int(major)
538 minor = int(minor)
539 except:
540 raise Exception, "invalid major minor in "\
541 + dev_file
542
543 # Find a device listed in /proc/partitions
544 # that has the same minor and major as our
545 # current block device.
546 for record in partitions:
547 if major == record[0] and minor == record[1]:
548 devices.append(record[2])
549
550 # We have assembled the list of devices, so return it
551 return devices

Properties

Name Value
svn:eol-style native

  ViewVC Help
Powered by ViewVC 1.1.20