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

Diff of /trunk/src/GLIStorageDevice.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.113  
changed lines
  Added in v.631

  ViewVC Help
Powered by ViewVC 1.1.20