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

Diff of /trunk/src/GLIStorageDevice.py

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

Revision 544 Revision 596
1import commands, string, os, parted 1import commands, string, os, parted
2from GLIException import *
3import GLIUtility
2 4
3MEGABYTE = 1024 * 1024 5MEGABYTE = 1024 * 1024
4 6
5archinfo = { 'sparc': { 'fixedparts': [ { 'minor': 3, 'type': "wholedisk" } ], 'disklabel': 'sun', 'extended': False }, 7archinfo = { 'sparc': { 'fixedparts': [ { 'minor': 3, 'type': "wholedisk" } ], 'disklabel': 'sun', 'extended': False },
6 'hppa': { 'fixedparts': [ { 'minor': 1, 'type': "boot" } ], 'disklabel': 'msdos', 'extended': False }, 8 'hppa': { 'fixedparts': [ { 'minor': 1, 'type': "boot" } ], 'disklabel': 'msdos', 'extended': False },
7 'x86': { 'fixedparts': [], 'disklabel': 'msdos', 'extended': True }, 9 'x86': { 'fixedparts': [], 'disklabel': 'msdos', 'extended': True },
10 'amd64': { 'fixedparts': [], 'disklabel': 'msdos', 'extended': True },
8 'ppc': { 'fixedparts': [ { 'minor': 1, 'type': "metadata" } ], 'disklabel': 'mac', 'extended': False } 11 'ppc': { 'fixedparts': [ { 'minor': 1, 'type': "metadata" } ], 'disklabel': 'mac', 'extended': False }
9 } 12 }
10 13
11## 14##
12# This class provides a partitioning abstraction for the frontends 15# This class provides a partitioning abstraction for the frontends
23 _parted_dev = None 26 _parted_dev = None
24 _parted_disk = None 27 _parted_disk = None
25 _sector_bytes = 0 28 _sector_bytes = 0
26 _total_mb = 0 29 _total_mb = 0
27 _arch = None 30 _arch = None
31 _disklabel = None
28 32
29 ## 33 ##
30 # Initialization function for GLIStorageDevice class 34 # Initialization function for GLIStorageDevice class
31 # @param device Device node (e.g. /dev/hda) of device being represented 35 # @param device Device node (e.g. /dev/hda) of device being represented
32 # @param arch="x86" Architecture that we're partition for (defaults to 'x86' for now) 36 # @param arch="x86" Architecture that we're partition for (defaults to 'x86' for now)
33 def __init__(self, device, arch="x86"): 37 def __init__(self, device, arch="x86", set_geometry=True):
34 self._device = device 38 self._device = device
35 self._partitions = {} 39 self._partitions = {}
36 self._geometry = {'cylinders': 0, 'heads': 0, 'sectors': 0, 'sectorsize': 512} 40 self._geometry = {'cylinders': 0, 'heads': 0, 'sectors': 0, 'sectorsize': 512}
37 self._total_bytes = 0 41 self._total_bytes = 0
38 self._cylinder_bytes = 0 42 self._cylinder_bytes = 0
39 self._arch = arch 43 self._arch = arch
40 self._parted_dev = parted.PedDevice.get(self._device) 44 self._parted_dev = parted.PedDevice.get(self._device)
45 try:
41 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:
42 self.set_disk_geometry_from_disk() 51 self.set_disk_geometry_from_disk()
43 52
44 ## 53 ##
45 # Sets disk geometry info from disk. This function is used internally by __init__() 54 # Sets disk geometry info from disk. This function is used internally by __init__()
46 def set_disk_geometry_from_disk(self): 55 def set_disk_geometry_from_disk(self):
47 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
81 90
82 ## 91 ##
83 # Imports partition info from the install profile partition structure (currently does nothing) 92 # Imports partition info from the install profile partition structure (currently does nothing)
84 # @param ips Parameter structure returned from install_profile.get_partition_tables() 93 # @param ips Parameter structure returned from install_profile.get_partition_tables()
85 def set_partitions_from_install_profile_structure(self, ips): 94 def set_partitions_from_install_profile_structure(self, ips):
86 pass
87# for part in ips: 95 for part in ips:
88# tmppart = ips[part] 96 tmppart = ips[part]
89# existing = False 97 existing = False
90# parted_part = self._parted_disk.get_partition(part) 98 if tmppart['origminor'] and not tmppart['format']:
91# if parted_part != None:
92# start = parted_part.geom.start / self._sectors_in_cylinder
93# end = parted_part.geom.end / self._sectors_in_cylinder
94# fs_type = ""
95# if parted_part.fs_type != None: fs_type = parted_part.fs_type.name
96# if parted_part.type == 2: fs_type = "extended"
97# if int(tmppart['start']) == int(start) and int(tmppart['end']) == int(end) and tmppart['type'] == fs_type and tmppart['format'] == False:
98# existing = True 99 existing = True
99# 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=['mountopts'])
100 101
101 ## 102 ##
102 # Returns name of device (e.g. /dev/hda) being represented 103 # Returns name of device (e.g. /dev/hda) being represented
103 def get_device(self): 104 def get_device(self):
104 return self._device 105 return self._device
345 if tmppart.is_extended(): 346 if tmppart.is_extended():
346 return part 347 return part
347 return 0 348 return 0
348 349
349 ## 350 ##
351 # Sets the disklabel type
352 def set_disklabel(self, disklabel):
353 self._disklabel = disklabel
354
355 ##
356 # Returns the disklabel type
357 def get_disklabel(self):
358 return self._disklabel
359
360 ##
350 # Returns the number of sectors on the device 361 # Returns the number of sectors on the device
351 def get_num_sectors(self): 362 def get_num_sectors(self):
352 return int(self._total_sectors) 363 return int(self._total_sectors)
353 364
354 ## 365 ##
384 ## 395 ##
385 # Prints disk geometry to STDOUT (no longer used) 396 # Prints disk geometry to STDOUT (no longer used)
386 def print_geometry(self): 397 def print_geometry(self):
387 print self._total_bytes, self._geometry 398 print self._total_bytes, self._geometry
388 399
389 ##
390 # Utility function for raising an exception
391 # @param message Error message
392 def _error(self, message):
393 "Raises an exception"
394 raise GLIException("DeviceObjectError", 'fatal', 'Device', message)
395
396 ## 400 ##
397 # Utility function for running a command and returning it's output as a list 401 # Utility function for running a command and returning it's output as a list
398 # @param cmd Command to run 402 # @param cmd Command to run
399 def _run(self, cmd): 403 def _run(self, cmd):
400 "Runs a command and returns the output" 404 "Runs a command and returns the output"
447 # @param type Parameter Type of partition (ext2, ext3, fat32, linux-swap, free, extended, etc.) 451 # @param type Parameter Type of partition (ext2, ext3, fat32, linux-swap, free, extended, etc.)
448 # @param mountpoint='' Mountpoint of partition 452 # @param mountpoint='' Mountpoint of partition
449 # @param mountopts='' Mount options of partition 453 # @param mountopts='' Mount options of partition
450 # @param format=True Format partition 454 # @param format=True Format partition
451 # @param existing=False This partition exists on disk 455 # @param existing=False This partition exists on disk
452 def __init__(self, device, minor, mb, start, end, 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):
453 self._device = device 457 self._device = device
454 self._minor = float(minor) 458 self._minor = float(minor)
455 if existing: self._orig_minor = int(minor)
456 self._start = int(start) 459 self._start = int(start)
457 self._end = int(end) 460 self._end = int(end)
458 self._type = type or "unknown" 461 self._type = type or "unknown"
459 self._mountpoint = mountpoint 462 self._mountpoint = mountpoint
460 self._mountopts = mountopts 463 self._mountopts = mountopts
461 self._format = format 464 self._format = format
462 self._mb = mb 465 self._mb = mb
466 self._orig_minor = origminor
467 if type != "free":
468 if existing and not origminor:
469 self._orig_minor = self._minor
470 self._minor = int(self._minor)
471 self._orig_minor = int(self._orig_minor)
463 if existing: 472 if existing:
464 self._orig_minor = self._minor
465 parted_part = device._parted_disk.get_partition(minor) 473 parted_part = device._parted_disk.get_partition(self._orig_minor)
466 label_type = device._parted_disk.type.name 474 label_type = device._parted_disk.type.name
467 if label_type == "loop": 475 if label_type == "loop":
468 dev_node = device._device 476 dev_node = device._device
469 else: 477 else:
470 dev_node = device._device + str(minor) 478 dev_node = device._device + str(self._orig_minor)
479 print "dev_node = " + dev_node
471 if type == "ntfs": 480 if type == "ntfs":
472 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 .\+//'")) 481 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 .\+//'"))
473 self._min_mb_for_resize = int(min_bytes / MEGABYTE) + 1 482 self._min_mb_for_resize = int(min_bytes / MEGABYTE) + 1
474 self._resizeable = True 483 self._resizeable = True
475 elif type == "ext2" or type == "ext3": 484 elif type == "ext2" or type == "ext3":
478 free_bytes = int(block_size * free_blocks) 487 free_bytes = int(block_size * free_blocks)
479 # can't hurt to pad (the +50) it a bit since this is really just a guess 488 # can't hurt to pad (the +50) it a bit since this is really just a guess
480 self._min_mb_for_resize = self._mb - int(free_bytes / MEGABYTE) + 50 489 self._min_mb_for_resize = self._mb - int(free_bytes / MEGABYTE) + 50
481 self._resizeable = True 490 self._resizeable = True
482 else: 491 else:
483 parted_part = self._device._parted_disk.get_partition(int(self._minor)) 492 parted_part = self._device._parted_disk.get_partition(int(self._orig_minor))
484 try: 493 try:
485 parted_fs = parted_part.geom.file_system_open() 494 parted_fs = parted_part.geom.file_system_open()
486 except: 495 except:
487 self._resizeable = False 496 self._resizeable = False
488 return 497 return
696 elif mb > self._mb: 705 elif mb > self._mb:
697 # Growing 706 # Growing
698 self._device._partitions[free_minor]._mb = mb - self._mb 707 self._device._partitions[free_minor]._mb = mb - self._mb
699 self._mb = mb 708 self._mb = mb
700 709
701 ##
702 # Utility function to raise an exception
703 # @param message Error message
704 def _error(self, message):
705 raise GLIException("PartitionObjectError", 'fatal', 'Partition', message)
706
707## 710##
708# Returns a list of detected partitionable devices 711# Returns a list of detected partitionable devices
709def detect_devices(): 712def detect_devices():
710 devices = [] 713 devices = []
711 714
712 # Make sure sysfs exists 715 # Make sure sysfs exists
713 if not os.path.exists("/sys/bus"): 716 if not os.path.exists("/sys/bus"):
714 raise Exception, "no sysfs found (you MUST use a kernel >2.6)" 717 raise GLIException("GLIStorageDeviceError", 'fatal', 'detect_devices', "no sysfs found (you MUST use a kernel >2.6)")
715 # Make sure /proc/partitions exists 718 # Make sure /proc/partitions exists
716 if not os.path.exists("/proc/partitions"): 719 if not os.path.exists("/proc/partitions"):
717 raise Exception, "/proc/partitions does not exist!" 720 raise GLIException("GLIStorageDeviceError", 'fatal', 'detect_devices', "/proc/partitions does not exist! Please make sure procfs is in your kernel and mounted!")
718 721
719 # Load /proc/partitions into the variable 'partitions' 722 # Load /proc/partitions into the variable 'partitions'
720 partitions = [] 723 partitions = []
721 for line in open("/proc/partitions"): 724 for line in open("/proc/partitions"):
722 if len(line.split()) < 4 or not line.split()[0].isdigit() or \ 725 if len(line.split()) < 4 or not line.split()[0].isdigit() or not line.split()[1].isdigit():
723 not line.split()[1].isdigit():
724 continue 726 continue
725 727
726 # Get the major, minor and device name 728 # Get the major, minor and device name
727 major = line.split()[0] 729 major = line.split()[0]
728 minor = line.split()[1] 730 minor = line.split()[1]
761 if os.path.exists("/sys/bus/" + dev_type): 763 if os.path.exists("/sys/bus/" + dev_type):
762 sysfs_devices = os.listdir("/sys/bus/"+dev_type+"/devices") 764 sysfs_devices = os.listdir("/sys/bus/"+dev_type+"/devices")
763 765
764 # For each device in the devices on that bus 766 # For each device in the devices on that bus
765 for sysfs_device in sysfs_devices: 767 for sysfs_device in sysfs_devices:
766 dev_file = "/sys/bus/" + dev_type + "/devices/"\ 768 dev_file = "/sys/bus/" + dev_type + "/devices/" + sysfs_device + "/block/dev"
767 + sysfs_device + "/block/dev"
768 769
769 # If the file is not a block device, loop 770 # If the file is not a block device, loop
770 if not os.path.exists(dev_file): 771 if not os.path.exists(dev_file):
771 continue 772 continue
772 773
774 try: 775 try:
775 major, minor = open(dev_file).read().split(":") 776 major, minor = open(dev_file).read().split(":")
776 major = int(major) 777 major = int(major)
777 minor = int(minor) 778 minor = int(minor)
778 except: 779 except:
779 raise Exception, "invalid major minor in "\ 780 raise GLIException("GLIStorageDeviceError", 'fatal', 'detect_devices', "invalid major minor in " + dev_file)
780 + dev_file
781 781
782 # Find a device listed in /proc/partitions 782 # Find a device listed in /proc/partitions
783 # that has the same minor and major as our 783 # that has the same minor and major as our
784 # current block device. 784 # current block device.
785 for record in partitions: 785 for record in partitions:
786 if major == record[0] and minor == record[1]: 786 if major == record[0] and minor == record[1]:
787 devices.append(record[2]) 787 devices.append(record[2])
788 788
789 # For testing the partitioning code
790 if GLIUtility.is_file("/tmp/disk.img"):
791 devices.append("/tmp/disk.img")
792
789 # We have assembled the list of devices, so return it 793 # We have assembled the list of devices, so return it
790 return devices 794 return devices

Legend:
Removed from v.544  
changed lines
  Added in v.596

  ViewVC Help
Powered by ViewVC 1.1.20