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

Contents of /trunk/src/GLIStorageDevice.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 112 - (show annotations) (download) (as text)
Fri Nov 12 01:25:33 2004 UTC (15 years, 11 months ago) by agaffney
File MIME type: text/x-python
File size: 17730 byte(s)
minor fix (extra tab) in GLIStorageDevice

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

Properties

Name Value
svn:eol-style native

  ViewVC Help
Powered by ViewVC 1.1.20