def getDeviceGeometry(self, devname):
     sectors = None
     sectorSize = None
     spt = None
     spc = None
     cyls = None
     res = execWithCapture(FDISK, [FDISK, '-l', '-u', devname])
     lines = res.splitlines()
     for line in lines:
         if re.match('^Units = sectors .* [0-9]* bytes', line):
             words = line.split()
             if (words[len(words) - 1] == 'bytes'):
                 sectorSize = int(words[len(words) - 2])
             else:
                 raise 'bad fdisk output for device ' + devname
         elif re.match('.* [0-9]* sectors/track, [0-9]* cylinders, total [0-9]* sectors', line):
             words = line.split()
             if (words[len(words) - 1] == 'sectors') and (words[len(words) - 3] == 'total'):
                 sectors = int(words[len(words) - 2])
             else:
                 raise 'bad fdisk output for device ' + devname
             if words[3].rstrip(',') == 'sectors/track':
                 spt = int(words[2])
             else:
                 raise 'bad fdisk output for device ' + devname
             if words[5].rstrip(',') == 'cylinders':
                 cyls = int(words[4])
             else:
                 raise 'bad fdisk output for device ' + devname
     if sectors == None or sectorSize == None or spt == None or cyls == None:
         raise 'bad fdisk output for device ' + devname
     return [sectors, sectorSize, cyls, spt, sectors/cyls]
 def getPartitions(self, devname):
     sectorSize = self.getDeviceGeometry(devname)[1]
     parts = list()
     res = execWithCapture(SFDISK, [SFDISK, '-l', '-uS', devname])
     lines = res.splitlines()
     for line in lines:
         if not re.match('^/dev/', line):
             continue
         words = line.split()
         # partition num
         tmp = words[0].strip()
         part_num = int(tmp[len(devname):])
         del(words[0])
         # bootable
         if words[0] == '*':
             bootable = True
             del(words[0])
         else:
             bootable = False
         beg, end, ignore, id = words[:4]
         # beg
         if beg == '-':
             continue
         else:
             beg = int(beg)
         #end
         if end == '-':
             continue
         else:
             end = int(end)
         # partition id
         id = int(id, 16)
         part = Partition(beg, end, id, part_num, bootable, sectorSize)
         parts.append(part)
     return parts
def get_fs(path):
    for fs in get_filesystems():
        if fs.probe(path):
            return fs

    if path not in cache_file_results:
        result = execWithCapture("/usr/bin/file",
                                 ['/usr/bin/file', '-s', '-L', path])
        cache_file_results[path] = result
    else:
        result = cache_file_results[path]

    if re.search('FAT \(12 bit\)', result, re.I):
        return Unknown('vfat12')
    elif re.search('FAT \(16 bit\)', result, re.I):
        return Unknown('vfat16')
    elif re.search('FAT \(32 bit\)', result, re.I):
        return Unknown('vfat32')
    elif re.search('minix', result, re.I):
        return Unknown('minix')
    elif re.search('jfs', result, re.I):
        return Unknown('jfs')
    elif re.search('reiserfs', result, re.I):
        return Unknown('reiserfs')
    elif re.search('swap', result, re.I):
        return Unknown('swap')
    else:
        return NoFS()
Exemplo n.º 4
0
 def __query_PVs(self):
   pvlist = list()
   arglist = list()
   arglist.append(LVM_BIN_PATH)
   arglist.append("pvs")
   arglist.append("--nosuffix")
   arglist.append("--noheadings")
   arglist.append("--units")
   arglist.append("g")
   arglist.append("--separator")
   arglist.append(",")
   arglist.append("-o")
   arglist.append("+pv_pe_count,pv_pe_alloc_count")
   result_string = execWithCapture(LVM_BIN_PATH, arglist)
   lines = result_string.splitlines()
   for line in lines:
     line = line.strip()
     words = line.split(",")
     path = words[P_NAME_COL]
     pv = PhysicalVolume(path, 
                         words[P_FMT_COL], 
                         words[P_ATTR_COL], 
                         words[P_SIZE_COL], 
                         words[P_FREE_COL],
                         True,
                         words[P_PE_COUNT_COL], 
                         words[P_PE_ALLOC_COL])
     pv.set_path(path)
     vgname = words[P_VG_NAME_COL]
     if vgname == '':
       pv.set_vg(None)
     else:
       self.__VGs[vgname].add_pv(pv)
     pvlist.append(pv)
   return pvlist
Exemplo n.º 5
0
 def __query_PVs(self):
     pvlist = list()
     arglist = list()
     arglist.append(LVM_BIN_PATH)
     arglist.append("pvs")
     arglist.append("--config")
     arglist.append("'log{command_names=0}'")
     arglist.append("--nosuffix")
     arglist.append("--noheadings")
     arglist.append("--units")
     arglist.append("g")
     arglist.append("--separator")
     arglist.append(",")
     arglist.append("-o")
     arglist.append("+pv_pe_count,pv_pe_alloc_count")
     result_string = execWithCapture(LVM_BIN_PATH, arglist)
     lines = result_string.splitlines()
     for line in lines:
         line = line.strip()
         words = line.split(",")
         path = words[P_NAME_COL]
         pv = PhysicalVolume(path, words[P_FMT_COL], words[P_ATTR_COL],
                             words[P_SIZE_COL], words[P_FREE_COL], True,
                             words[P_PE_COUNT_COL], words[P_PE_ALLOC_COL])
         pv.set_path(path)
         vgname = words[P_VG_NAME_COL]
         if vgname == '':
             pv.set_vg(None)
         else:
             self.__VGs[vgname].add_pv(pv)
         pvlist.append(pv)
     return pvlist
 def getDeviceGeometry(self, devname):
     sectors = None
     sectorSize = None
     spt = None
     spc = None
     cyls = None
     res = execWithCapture(FDISK, [FDISK, '-l', '-u', devname])
     lines = res.splitlines()
     for line in lines:
         if re.match('^Units = sectors .* [0-9]* bytes', line):
             words = line.split()
             if (words[len(words) - 1] == 'bytes'):
                 sectorSize = int(words[len(words) - 2])
             else:
                 raise 'bad fdisk output for device ' + devname
         elif re.match('.* [0-9]* sectors/track, [0-9]* cylinders, total [0-9]* sectors', line):
             words = line.split()
             if (words[len(words) - 1] == 'sectors') and (words[len(words) - 3] == 'total'):
                 sectors = int(words[len(words) - 2])
             else:
                 raise 'bad fdisk output for device ' + devname
             if words[3].rstrip(',') == 'sectors/track':
                 spt = int(words[2])
             else:
                 raise 'bad fdisk output for device ' + devname
             if words[5].rstrip(',') == 'cylinders':
                 cyls = int(words[4])
             else:
                 raise 'bad fdisk output for device ' + devname
     if sectors == None or sectorSize == None or spt == None or cyls == None:
         raise 'bad fdisk output for device ' + devname
     return [sectors, sectorSize, cyls, spt, sectors/cyls]
Exemplo n.º 7
0
 def __query_VGs(self):
   vglist = list()
   arglist = list()
   arglist.append(LVM_BIN_PATH)
   arglist.append("vgs")
   arglist.append("--nosuffix")
   arglist.append("--noheadings")
   arglist.append("--units")
   arglist.append("b")
   arglist.append("--separator")
   arglist.append(",")
   arglist.append("-o")
   arglist.append("vg_name,vg_attr,vg_size,vg_extent_size,vg_free_count,max_lv,max_pv")
   
   result_string = execWithCapture(LVM_BIN_PATH,arglist)
   lines = result_string.splitlines()
   for line in lines:
     line = line.strip()
     words = line.split(",")
     
     extent_size = int(words[3])
     extents_total = int(words[2]) / extent_size
     extents_free = int(words[4])
     
     vgname = words[0].strip()
     
     max_lvs, max_pvs = int(words[5]), int(words[6])
     if max_lvs == 0:
       max_lvs = 256
     if max_pvs == 0:
       max_pvs = 256
     
     vg = VolumeGroup(vgname, words[1], extent_size, extents_total, extents_free, max_pvs, max_lvs)
     vglist.append(vg)
   return vglist
Exemplo n.º 8
0
 def __get_wwid(self, device):
     try:
         output = execWithCapture(
             SCSIID_BIN_PATH,
             ["--page=0x83", "--whitelisted", "--device=" + device])
         return output
     except Exception:
         return None
    def probe(self, path):
        if path not in cache_file_results:
            result = execWithCapture("/usr/bin/file",
                                     ['/usr/bin/file', '-s', '-L', path])
            cache_file_results[path] = result
        else:
            result = cache_file_results[path]

        if re.search('SGI XFS', result, re.I):
            return True
    def __init__(self, glade_xml, app):

        # check locking type
        locking_type = lvm_conf_get_locking_type()
        if locking_type != 1:
            should_exit = False
            if locking_type == 0:
                msg = _(
                    "LVM locks are disabled!!! \nMassive data corruption may occur.\nEnable locking (locking_type=1, 2 or 3 in /etc/lvm/lvm.conf)."
                )
                should_exit = True
            elif locking_type == 2 or locking_type == 3:
                ps_out = execWithCapture('/bin/ps', ['/bin/ps', '-A'])
                if ps_out.find('clvmd') == -1:
                    msg = _(
                        "LVM is configured to use Cluster Locking mechanism, but clvmd daemon is not running. Start daemon with command:\nservice clvmd start \nor, turn off cluster locking (locking_type=1 in /etc/lvm/lvm.conf)."
                    )
                    should_exit = True
                else:
                    if not Cluster().running():
                        msg = _(
                            "LVM is configured to use Cluster Locking mechanism, but cluster is not quorate.\nEither wait until cluster is quorate or turn off cluster locking (locking_type=1 in /etc/lvm/lvm.conf)."
                        )
                        should_exit = True
            else:
                msg = _(
                    "%s only supports file and cluster based lockings (locking_type=1, 2 or 3 in /etc/lvm/lvm.conf)."
                )
                msg = msg % PROGNAME
                should_exit = True
            if should_exit:
                dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR,
                                        gtk.BUTTONS_OK, msg)
                dlg.run()
                sys.exit(10)

        #Need to suppress the spewing of file descriptor errors to terminal
        os.environ["LVM_SUPPRESS_FD_WARNINGS"] = "1"

        self.lvmm = lvm_model()

        self.main_win = app
        self.glade_xml = glade_xml

        self.volume_tab_view = Volume_Tab_View(glade_xml, self.lvmm,
                                               self.main_win)

        self.glade_xml.signal_autoconnect({
            "on_quit1_activate":
            self.quit,
            "on_about1_activate":
            self.on_about,
            "on_reload_lvm_activate":
            self.on_reload
        })
Exemplo n.º 11
0
 def printSupportedPartitions(self):
     result = execWithCapture(SFDISK, [SFDISK, '-T'])
     lines = result.splitlines()
     for line in lines:
         if 'Id' in line:
             continue
         if line.strip() == '':
             continue
         id = int(line[:2].strip(), 16)
         name = line[2:].strip()
         print str(id), ':', '\'' + name + '\'' + ','
 def printSupportedPartitions(self):
     result = execWithCapture(SFDISK, [SFDISK, '-T'])
     lines = result.splitlines()
     for line in lines:
         if 'Id' in line:
             continue
         if line.strip() == '':
             continue
         id = int(line[:2].strip(), 16)
         name = line[2:].strip()
         print str(id), ':', '\'' + name + '\'' + ','
Exemplo n.º 13
0
 def __set_PVs_props(self):
   arglist = list()
   arglist.append(LVM_BIN_PATH)
   arglist.append("pvs")
   arglist.append("--noheadings")
   arglist.append("--separator")
   arglist.append(",")
   arglist.append("-o")
   arglist.append(PVS_OPTION_STRING)
   pvs_output = execWithCapture(LVM_BIN_PATH,arglist)
   for pv in self.__PVs:
     pv.set_properties(self.__get_data_for_PV(pv, pvs_output))
Exemplo n.º 14
0
 def is_dm_snapshot_loaded(self):
   arglist = list()
   arglist.append("/sbin/dmsetup")
   arglist.append("targets")
   result  = execWithCapture("/sbin/dmsetup", arglist)
   textlines = result.splitlines()
   for textline in textlines:
     text_words = textline.split()
     possible_target = text_words[0].strip()
     if possible_target == "snapshot":
       return True
   return False
Exemplo n.º 15
0
    def savePartTable(self, devpath, parts):
        if len(self.getPartitions(devpath)) != 0:
            print 'partition table already exists'
            sys.exit(1)
        if len(parts) != 1:
            print 'parted save implementation is not complete'
            sys.exit(1)

        # create partition table
        execWithCapture(PARTED, [PARTED, devpath, 'mklabel', 'gpt', '-s'])
        # create partition
        part = parts[0]
        beg = part.beg * part.sectorSize / 1024.0 / 1024  # parted uses Magabytes
        end = part.end * part.sectorSize / 1024.0 / 1024
        #print beg, end
        execWithCapture(
            PARTED,
            [PARTED, devpath, 'mkpart', 'primary',
             str(beg),
             str(end), '-s'])
        # add flags - if any
        if part.id == ID_LINUX_LVM:
            print execWithCapture(
                PARTED,
                [PARTED, devpath, 'set',
                 str(part.num), 'lvm', 'on', '-s'])
Exemplo n.º 16
0
 def getMountPoint(self, path):
   # follow links
   paths = [path]
   if follow_links_to_target(path, paths) == None:
     return None
   
   result = execWithCapture('/bin/cat', ['/bin/cat', '/proc/mounts', '/etc/mtab'])
   lines = result.splitlines()
   for line in lines:
     words = line.split()
     possible_path = words[0]
     if possible_path in paths:
       return words[1]
   return None
Exemplo n.º 17
0
 def __set_VGs_props(self):
   arglist = [LVM_BIN_PATH]
   arglist.append("vgs")
   arglist.append("--nosuffix")
   arglist.append("--noheadings")
   #arglist.append("--units")
   #arglist.append("g")
   arglist.append("--separator")
   arglist.append(",")
   arglist.append("-o")
   arglist.append(VGS_OPTION_STRING)
   vgs_output = execWithCapture(LVM_BIN_PATH,arglist)
   for vg in self.__VGs.values():
     vg.set_properties(self.__get_data_for_VG(vg, vgs_output))
Exemplo n.º 18
0
 def getDeviceNames(self):
     res = execWithCapture(SFDISK, [SFDISK, '-s'])
     lines = res.splitlines()
     devices = list()
     for line in lines:
         if not re.match('^/dev/', line):
             continue
         words = line.split(':')
         devname = words[0].strip()
         if not re.match('.*[0-9]', devname):
             # check if partition table is OK       
             # out, err, ret = rhpl.executil.execWithCaptureErrorStatus(SFDISK, [SFDISK, '-V', devname])
             out, ret = execWithCaptureStatus(SFDISK, [SFDISK, '-V', devname])
             if ret != 0:
                 #print 'THERE IS A PROBLEM WITH PARTITION TABLE at device ' + devname
                 # print err
                 pass
             devices.append(devname)
     # check if geometry can be detected
     for dev in devices[:]:
         res = execWithCapture(SFDISK, [SFDISK, '-s', dev])
         if re.match('.*cannot get geometry.*', res):
             devices.remove(dev)
     return devices
    def getDeviceNames(self):
        res = execWithCapture(SFDISK, [SFDISK, '-s'])
        lines = res.splitlines()
        devices = list()
        for line in lines:
            if not re.match('^/dev/', line):
                continue
            words = line.split(':')
            devname = words[0].strip()
            if not re.match('.*[0-9]', devname):
                # check if partition table is OK       
                # out, err, ret = rhpl.executil.execWithCaptureErrorStatus(SFDISK, [SFDISK, '-V', devname])
                out, ret = execWithCaptureStatus(SFDISK, [SFDISK, '-V', devname])
                if ret != 0:
                    #print 'THERE IS A PROBLEM WITH PARTITION TABLE at device ' + devname
                    # print err
                    pass
                devices.append(devname)
        # check if geometry can be detected
        for dev in devices[:]:
            res = execWithCapture(SFDISK, [SFDISK, '-s', dev])
            if re.match('.*cannot get geometry.*', res):
                devices.remove(dev)

        # check with blkid to remove false PV (all logical volumes in /dev/mapper)
        for dev in devices[:]:
            out, ret = execWithCaptureStatus(BLKID, [BLKID, dev])
            if ret == 0:
                devices.remove(dev)
                continue
            out, ret = execWithCaptureStatus(LVDISPLAY, [LVDISPLAY, dev])
            if ret == 0:
                devices.remove(dev)
                continue
        
        return devices
Exemplo n.º 20
0
 def __reload_logical_volumes_paths(self):
   self.__lvs_paths = {}
   arglist = [LVDISPLAY_BIN_PATH] #lvs does not give path info
   arglist.append('-c')
   if LVS_HAS_ALL_OPTION:
     arglist.append('-a')
   result_string = execWithCapture(LVDISPLAY_BIN_PATH,arglist)
   lines = result_string.splitlines()
   for line in lines:
     words = line.strip().split(":")
     vgname = words[LV_VGNAME_COL].strip()
     lvpath = words[LV_PATH_COL].strip()
     last_slash_index = lvpath.rfind("/") + 1
     lvname = lvpath[last_slash_index:]
     self.__lvs_paths[vgname + '`' + lvname] = lvpath
  def __init__(self, glade_xml, app):
    
    
    # check locking type
    locking_type = lvm_conf_get_locking_type()
    if locking_type != 1:
        should_exit = False
        if locking_type == 0:
            msg = _("LVM locks are disabled!!! \nMassive data corruption may occur.\nEnable locking (locking_type=1, 2 or 3 in /etc/lvm/lvm.conf).")
            should_exit = True
        elif locking_type == 2 or locking_type == 3:
            ps_out = execWithCapture('/bin/ps', ['/bin/ps', '-A'])
            if ps_out.find('clvmd') == -1:
                msg = _("LVM is configured to use Cluster Locking mechanism, but clvmd daemon is not running. Start daemon with command:\nservice clvmd start \nor, turn off cluster locking (locking_type=1 in /etc/lvm/lvm.conf).")
                should_exit = True
            else:
                if not Cluster().running():
                    msg = _("LVM is configured to use Cluster Locking mechanism, but cluster is not quorate.\nEither wait until cluster is quorate or turn off cluster locking (locking_type=1 in /etc/lvm/lvm.conf).")
                    should_exit = True
        else:
            msg = _("%s only supports file and cluster based lockings (locking_type=1, 2 or 3 in /etc/lvm/lvm.conf).")
            msg = msg % PROGNAME
            should_exit = True
        if should_exit:
            dlg = gtk.MessageDialog(None, 0,
                                    gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                                    msg)
            dlg.run()
            sys.exit(10)

    
    #Need to suppress the spewing of file descriptor errors to terminal
    os.environ["LVM_SUPPRESS_FD_WARNINGS"] = "1"

    self.lvmm = lvm_model()
                                                                                
    self.main_win = app
    self.glade_xml = glade_xml

    self.volume_tab_view = Volume_Tab_View(glade_xml, self.lvmm, self.main_win)

    self.glade_xml.signal_autoconnect(
      {
        "on_quit1_activate" : self.quit,
        "on_about1_activate" : self.on_about,
        "on_reload_lvm_activate" : self.on_reload
      }
    )
Exemplo n.º 22
0
 def __set_VGs_props(self):
     arglist = [LVM_BIN_PATH]
     arglist.append("vgs")
     arglist.append("--config")
     arglist.append("'log{command_names=0}'")
     arglist.append("--nosuffix")
     arglist.append("--noheadings")
     #arglist.append("--units")
     #arglist.append("g")
     arglist.append("--separator")
     arglist.append(",")
     arglist.append("-o")
     arglist.append(VGS_OPTION_STRING)
     vgs_output = execWithCapture(LVM_BIN_PATH, arglist)
     for vg in self.__VGs.values():
         vg.set_properties(self.__get_data_for_VG(vg, vgs_output))
Exemplo n.º 23
0
 def __reload_logical_volumes_paths(self):
     self.__lvs_paths = {}
     arglist = [LVDISPLAY_BIN_PATH]  #lvs does not give path info
     arglist.append("--config")
     arglist.append("'log{command_names=0}'")
     arglist.append('-c')
     if LVS_HAS_ALL_OPTION:
         arglist.append('-a')
     result_string = execWithCapture(LVDISPLAY_BIN_PATH, arglist)
     lines = result_string.splitlines()
     for line in lines:
         words = line.strip().split(":")
         vgname = words[LV_VGNAME_COL].strip()
         lvpath = words[LV_PATH_COL].strip()
         last_slash_index = lvpath.rfind("/") + 1
         lvname = lvpath[last_slash_index:]
         self.__lvs_paths[vgname + '`' + lvname] = lvpath
Exemplo n.º 24
0
    def getMountPoint(self, path):
        # follow links
        paths = [path]
        if follow_links_to_target(path, paths) == None:
            return None

        result = execWithCapture('/bin/cat',
                                 ['/bin/cat', '/proc/mounts', '/etc/mtab'])
        lines = result.splitlines()
        for line in lines:
            words = line.split()
            possible_path = words[0]
            if possible_path in paths:
                return words[1]
            if follow_links_to_target(possible_path, []) in paths:
                return words[1]
        return None
Exemplo n.º 25
0
    def check_mountable(self, fsname, module):
        global cache_mountable_fs

        if fsname in cache_mountable_fs:
            return cache_mountable_fs[fsname]

        mountable = False
        out = execWithCapture('/bin/cat', ['/bin/cat', '/proc/filesystems'])
        if re.search(fsname, out, re.I):
            mountable = True
        if mountable == False:
            out, status = execWithCaptureStatus(
                '/sbin/modprobe', ['/sbin/modprobe', '-n', module])
            if status == 0:
                mountable = True
        cache_mountable_fs[fsname] = mountable
        return mountable
Exemplo n.º 26
0
 def pvmove_in_progress(self):
   LVS_OPTION_STRING="move_pv"
   arglist = list()
   arglist.append(LVM_BIN_PATH)
   arglist.append("lvs")
   arglist.append("--noheadings")
   arglist.append("-o")
   arglist.append('move_pv')
   if LVS_HAS_ALL_OPTION:
     arglist.append("--all")
   
   result_string = execWithCapture(LVM_BIN_PATH, arglist)
   lines = result_string.splitlines()
   for line in lines:
     if line.strip() != '':
       return True
   return False
Exemplo n.º 27
0
    def pvmove_in_progress(self):
        LVS_OPTION_STRING = "move_pv"
        arglist = list()
        arglist.append(LVM_BIN_PATH)
        arglist.append("lvs")
        arglist.append("--config")
        arglist.append("'log{command_names=0}'")
        arglist.append("--noheadings")
        arglist.append("-o")
        arglist.append('move_pv')
        if LVS_HAS_ALL_OPTION:
            arglist.append("--all")

        result_string = execWithCapture(LVM_BIN_PATH, arglist)
        lines = result_string.splitlines()
        for line in lines:
            if line.strip() != '':
                return True
        return False
Exemplo n.º 28
0
    def __query_VGs(self):
        vglist = list()
        arglist = list()
        arglist.append(LVM_BIN_PATH)
        arglist.append("vgs")
        arglist.append("--config")
        arglist.append("'log{command_names=0}'")
        arglist.append("--nosuffix")
        arglist.append("--noheadings")
        arglist.append("--units")
        arglist.append("b")
        arglist.append("--separator")
        arglist.append(",")
        arglist.append("-o")
        arglist.append(
            "vg_name,vg_attr,vg_size,vg_extent_size,vg_free_count,max_lv,max_pv"
        )

        result_string = execWithCapture(LVM_BIN_PATH, arglist)
        lines = result_string.splitlines()
        for line in lines:
            line = line.strip()
            words = line.split(",")

            extent_size = int(words[3])
            extents_total = int(words[2]) / extent_size
            extents_free = int(words[4])

            vgname = words[0].strip()

            max_lvs, max_pvs = int(words[5]), int(words[6])
            if max_lvs == 0:
                max_lvs = 256
            if max_pvs == 0:
                max_pvs = 256

            vg = VolumeGroup(vgname, words[1], extent_size, extents_total,
                             extents_free, max_pvs, max_lvs)
            vglist.append(vg)
        return vglist
Exemplo n.º 29
0
    def __set_PVs_props(self):
        arglist = list()
        arglist.append(LVM_BIN_PATH)
        arglist.append("pvs")
        arglist.append("--config")
        arglist.append("'log{command_names=0}'")
        arglist.append("--noheadings")
        arglist.append("--separator")
        arglist.append(",")
        arglist.append("-o")
        arglist.append(PVS_OPTION_STRING)
        pvs_output = execWithCapture(LVM_BIN_PATH, arglist)
        for pv in self.__PVs:
            prop = []
            for path in pv.get_paths():
                wwid = self.__get_wwid(path)
                if wwid != None and wwid != "":
                    prop.append("SCSI WWID: ")
                    prop.append(wwid)

            pv.set_properties(prop)
            pv.set_properties(self.__get_data_for_PV(pv, pvs_output))
 def getPartitions(self, devname):
     sectorSize = self.getDeviceGeometry(devname)[1]
     parts = list()
     res = execWithCapture(SFDISK, [SFDISK, '-l', '-uS', devname])
     lines = res.splitlines()
     for line in lines:
         if not re.match('^/dev/', line):
             continue
         words = line.split()
         # partition num
         tmp = words[0].strip()
         try:
             part_num = int(tmp[len(devname):])
         except ValueError:
             continue
         del(words[0])
         # bootable
         if words[0] == '*':
             bootable = True
             del(words[0])
         else:
             bootable = False
         beg, end, ignore, id = words[:4]
         # beg
         if beg == '-':
             continue
         else:
             beg = int(beg)
         #end
         if end == '-':
             continue
         else:
             end = int(end)
         # partition id
         id = int(id, 16)
         part = Partition(beg, end, id, part_num, bootable, sectorSize)
         parts.append(part)
     return parts
 def savePartTable(self, devpath, parts):
     if len(self.getPartitions(devpath)) != 0:
         print 'partition table already exists'
         sys.exit(1)
     if len(parts) != 1:
         print 'parted save implementation is not complete'
         sys.exit(1)
     
     # create partition table
     execWithCapture(PARTED, [PARTED, devpath, 'mklabel', 'gpt', '-s'])
     # create partition
     part = parts[0]
     beg = part.beg * part.sectorSize / 1024.0 / 1024 # parted uses Magabytes
     end = part.end * part.sectorSize / 1024.0 / 1024
     #print beg, end
     execWithCapture(PARTED, [PARTED, devpath, 'mkpart', 'primary', str(beg), str(end), '-s'])
     # add flags - if any
     if part.id == ID_LINUX_LVM:
         print execWithCapture(PARTED, [PARTED, devpath, 'set', str(part.num), 'lvm', 'on', '-s'])
Exemplo n.º 32
0
    def __query_LVs(self):
        if LVS_HAS_MIRROR_OPTIONS:
            LVS_OPTION_STRING = "lv_name,vg_name,stripes,stripesize,lv_attr,lv_uuid,devices,origin,snap_percent,seg_start,seg_size,vg_extent_size,lv_size,mirror_log"
        else:
            LVS_OPTION_STRING = "lv_name,vg_name,stripes,stripesize,lv_attr,lv_uuid,devices,origin,snap_percent,seg_start,seg_size,vg_extent_size,lv_size"
        LV_NAME_IDX = 0
        LV_VG_NAME_IDX = 1
        LV_STRIPES_NUM_IDX = 2
        LV_STRIPE_SIZE_IDX = 3
        LV_ATTR_IDX = 4
        LV_UUID_IDX = 5
        LV_DEVICES_IDX = 6
        LV_SNAP_ORIGIN_IDX = 7
        LV_SNAP_PERCENT_IDX = 8
        LV_SEG_START_IDX = 9
        LV_SEG_SIZE_IDX = 10
        LV_EXTENT_SIZE_IDX = 11
        LV_SIZE_IDX = 12
        LV_MIRROR_LOG_IDX = 13

        self.__reload_logical_volumes_paths()

        arglist = list()
        arglist.append(LVM_BIN_PATH)
        arglist.append("lvs")
        arglist.append("--config")
        arglist.append("'log{command_names=0}'")
        arglist.append("--nosuffix")
        arglist.append("--noheadings")
        arglist.append("--units")
        arglist.append("b")
        arglist.append("--separator")
        arglist.append("\";\"")
        arglist.append("-o")
        arglist.append(LVS_OPTION_STRING)
        if LVS_HAS_ALL_OPTION:
            arglist.append("--all")
        result_string = execWithCapture(LVM_BIN_PATH, arglist)
        lines = result_string.splitlines()
        for line in lines:
            line = line.strip()
            words = line.split(';')
            vgname = words[LV_VG_NAME_IDX].strip()
            attrs = words[LV_ATTR_IDX].strip()
            uuid = words[LV_UUID_IDX].strip()
            extent_size = int(words[LV_EXTENT_SIZE_IDX])
            seg_start = int(words[LV_SEG_START_IDX]) / extent_size
            lv_size = int(words[LV_SIZE_IDX]) / extent_size
            seg_size = int(words[LV_SEG_SIZE_IDX]) / extent_size
            devices = words[LV_DEVICES_IDX]

            if attrs[0] == 't' or attrs[0] == 'V':
                # thin pools/volumes are not supported
                continue

            if LVS_HAS_MIRROR_OPTIONS:
                mirror_log = words[LV_MIRROR_LOG_IDX].strip()

            lvname = words[LV_NAME_IDX].strip()
            # remove [] if there (used to mark hidden lvs)
            lvname = lvname.lstrip('[')
            lvname = lvname.rstrip(']')

            vg = self.__VGs[vgname]
            vg_lvs = vg.get_lvs()
            lv = None
            if lvname not in vg_lvs:
                lv = LogicalVolume(
                    lvname,
                    self.__get_logical_volume_path(lvname, vg.get_name()),
                    True, attrs, uuid)
                lv.set_extent_count(lv_size, lv_size)
                vg.add_lv(lv)
            lv = vg_lvs[lvname]

            segment = None
            devs = devices.split(',')
            if attrs[0] == 'm' or attrs[0] == 'M':
                # mirrored LV
                lv.set_mirror_log(
                    mirror_log
                )  # tmp, will get replaced with real one at __link_mirrors()
                segment = MirroredSegment(seg_start, seg_size)
                images = devs
                for image_name in images:
                    idx = image_name.find('(')
                    image_lv = LogicalVolume(
                        image_name[:idx], None, True, None, None
                    )  # tmp, will get replaced with real one at __link_mirrors()
                    segment.add_image(image_lv)
            elif len(devs) == 1:
                # linear segment
                segment = LinearSegment(seg_start, seg_size)
                idx = devs[0].find('(')
                pvpath = devs[0][:idx]
                ph_ext_beg = int(devs[0][idx + 1:len(devs[0]) - 1])
                pv = None
                for pv_t in self.__PVs:
                    if pv_t.get_path() == pvpath:
                        pv = pv_t
                        break
                extent_block = ExtentBlock(pv, lv, ph_ext_beg, seg_size)
                segment.set_extent_block(extent_block)
            else:
                # striped segment
                lv.set_stripes_num(int(words[LV_STRIPES_NUM_IDX]))
                stripe_size = int(words[LV_STRIPE_SIZE_IDX])
                segment = StripedSegment(stripe_size, seg_start, seg_size)
                stripe_id = 0
                for stripe in devs:
                    idx = stripe.find('(')
                    pvpath = stripe[:idx]
                    ph_ext_beg = int(stripe[idx + 1:len(stripe) - 1])
                    pv = None
                    for pv_t in self.__PVs:
                        if pv_t.get_path() == pvpath:
                            pv = pv_t
                            break
                    if pv != None:
                        extent_block = ExtentBlock(pv, lv, ph_ext_beg,
                                                   seg_size / len(devs))
                        segment.add_stripe(stripe_id, extent_block)
                        stripe_id = stripe_id + 1

            lv.add_segment(segment)

            origin = words[LV_SNAP_ORIGIN_IDX].strip()
            if origin != '':
                # snapshot
                usage = float(0)
                if (words[LV_SNAP_PERCENT_IDX] != ""):
                    usage = float(words[LV_SNAP_PERCENT_IDX].strip())
                lv.set_snapshot_info(
                    origin, usage
                )  # set name for now, real LV will get set at __link_snapshots()
Exemplo n.º 33
0
 def __query_partitions(self):
     parts = {}  # PVs on a partition
     segs = []  # PVs on free space
     # get partitions from hard drives
     self.__block_device_model.reload()
     devs = self.__block_device_model.getDevices()
     # multipathing
     multipath_obj = Multipath()
     multipath_data = multipath_obj.get_multipath_data()
     for multipath in multipath_data:
         segments = []
         for path in multipath_data[multipath]:
             if path in devs:
                 segments = devs[path]
                 devs.pop(path)
         devs[multipath] = segments
     for devname in devs:
         self.__query_partitions2(devname, devs[devname], parts, segs)
     for pv in parts.values()[:]:
         devname = pv.getPartition()[0]
         if devname in multipath_data:
             parts.pop(pv.get_path())
             pv.removeDevname(devname)
             pv.setMultipath(devname)
             for path in multipath_data[devname]:
                 pv.addDevname(path)
         for path in pv.get_paths():
             parts[path] = pv
     for pv in segs:
         devname = pv.getPartition()[0]
         if devname in multipath_data:
             pv.removeDevname(devname)
             pv.setMultipath(devname)
             for path in multipath_data[devname]:
                 pv.addDevname(path)
     # disable swap partitions if in use
     result = execWithCapture('/bin/cat', ['/bin/cat', '/proc/swaps'])
     lines = result.splitlines()
     for line in lines:
         swap = line.split()[0]
         for multipath in multipath_data:
             if swap in multipath_data[multipath]:
                 swap = multipath
         if swap in parts:
             parts[swap].initializable = False
             parts[swap].add_property(NOT_INITIALIZABLE, SWAP_IN_USE)
         for seg in segs:
             # swap could be a whole drive
             if swap == seg.get_path():
                 seg.name = seg.extract_name(seg.get_path())
                 seg.initializable = False
                 seg.add_property(NOT_INITIALIZABLE, SWAP_IN_USE)
     # disable bootable partitions only if EXTended FS NOT on it (bootable flag is used by windows only)
     for path in parts:
         partition = parts[path].getPartition()[1]
         if partition.bootable:
             fs = self.__getFS(path)
             if re.match('.*ext[23].*', fs, re.I):
                 # EXTended FS on it
                 pass
             else:
                 # some other filesystem on it
                 parts[path].initializable = False
                 parts[path].add_property(NOT_INITIALIZABLE,
                                          FOREIGN_BOOT_PARTITION)
     # disable unformated space, unless whole drive
     for seg in segs:
         if not seg.wholeDevice():
             # fdisk_wrapper not tested enough, so use it only on unpartitioned drives
             seg.initializable = False
             seg.add_property(NOT_INITIALIZABLE, _("Partition manually"))
     # merge parts with PVs
     for pv in self.__query_PVs():
         # assign unpartitioned drives, to PVs, if already used by LVM
         for seg in segs[:]:
             if pv.get_path() in seg.get_paths() or pv.get_path(
             ) == seg.getMultipath():
                 pv.setPartition(seg.getPartition())
                 pv.setMultipath(seg.getMultipath())
                 for devname in seg.getDevnames():
                     pv.addDevname(devname)
                 pv.set_name(pv.extract_name(
                     pv.get_path()))  # overwrite Free Space label
                 segs.remove(seg)
         # merge
         path = pv.get_path()
         if path in parts:
             old_pv = parts[path]
             pv.setPartition(old_pv.getPartition())
             pv.setMultipath(old_pv.getMultipath())
             for devname in old_pv.getDevnames():
                 pv.addDevname(devname)
         else:
             # pv is not a partition, eg. loop device, or LV
             pass
         for path in pv.get_paths():
             parts[path] = pv
     # create return list
     pvs_list = list()
     for part in parts.values():
         if part not in pvs_list:
             pvs_list.append(part)
     for seg in segs:
         pvs_list.append(seg)
     # disable initialization of multipathed devices (for now)
     for pv in pvs_list:
         if len(pv.get_paths()) > 1:
             if pv.get_type() == UNINITIALIZED_TYPE:
                 pv.add_property(NOT_INITIALIZABLE, _("Multipath device"))
                 if pv.initializable:
                     pv.initializable = False
                     pv.add_property(_("Note:"), _("Initialize manually"))
     # all done
     return pvs_list
Exemplo n.º 34
0
 def __query_partitions(self):
   parts = {} # PVs on a partition
   segs = []  # PVs on free space
   # get partitions from hard drives
   self.__block_device_model.reload()
   devs = self.__block_device_model.getDevices()
   # multipathing
   multipath_obj = Multipath()
   multipath_data = multipath_obj.get_multipath_data()
   for multipath in multipath_data:
     segments = []
     for path in multipath_data[multipath]:
       if path in devs:
         segments = devs[path]
         devs.pop(path)
     devs[multipath] = segments
   for devname in devs:
     self.__query_partitions2(devname, devs[devname], parts, segs)
   for pv in parts.values()[:]:
     devname = pv.getPartition()[0]
     if devname in multipath_data:
       parts.pop(pv.get_path())
       pv.removeDevname(devname)
       pv.setMultipath(devname)
       for path in multipath_data[devname]:
         pv.addDevname(path)
     for path in pv.get_paths():
       parts[path] = pv
   for pv in segs:
     devname = pv.getPartition()[0]
     if devname in multipath_data:
       pv.removeDevname(devname)
       pv.setMultipath(devname)
       for path in multipath_data[devname]:
         pv.addDevname(path)
   # disable swap partitions if in use
   result = execWithCapture('/bin/cat', ['/bin/cat', '/proc/swaps'])
   lines = result.splitlines()
   for line in lines:
     swap = line.split()[0]
     for multipath in multipath_data:
       if swap in multipath_data[multipath]:
         swap = multipath
     if swap in parts:
       parts[swap].initializable = False
       parts[swap].add_property(NOT_INITIALIZABLE, SWAP_IN_USE)
     for seg in segs:
       # swap could be a whole drive
       if swap == seg.get_path():
         seg.name = seg.extract_name(seg.get_path())
         seg.initializable = False
         seg.add_property(NOT_INITIALIZABLE, SWAP_IN_USE)
   # disable bootable partitions only if EXTended FS NOT on it (bootable flag is used by windows only)
   for path in parts:
     partition = parts[path].getPartition()[1]
     if partition.bootable:
       fs = self.__getFS(path)
       if re.match('.*ext[23].*', fs, re.I):
         # EXTended FS on it
         pass
       else:
         # some other filesystem on it
         parts[path].initializable = False
         parts[path].add_property(NOT_INITIALIZABLE, FOREIGN_BOOT_PARTITION)
   # disable unformated space, unless whole drive
   for seg in segs:
     if not seg.wholeDevice():
       # fdisk_wrapper not tested enough, so use it only on unpartitioned drives
       seg.initializable = False
       seg.add_property(NOT_INITIALIZABLE, _("Partition manually"))
   # merge parts with PVs
   for pv in self.__query_PVs():
     # assign unpartitioned drives, to PVs, if already used by LVM
     for seg in segs[:]:
       if pv.get_path() in seg.get_paths() or pv.get_path() == seg.getMultipath():
         pv.setPartition(seg.getPartition())
         pv.setMultipath(seg.getMultipath())
         for devname in seg.getDevnames():
           pv.addDevname(devname)
         pv.set_name(pv.extract_name(pv.get_path())) # overwrite Free Space label
         segs.remove(seg)
     # merge
     path = pv.get_path()
     if path in parts:
       old_pv = parts[path]
       pv.setPartition(old_pv.getPartition())
       pv.setMultipath(old_pv.getMultipath())
       for devname in old_pv.getDevnames():
         pv.addDevname(devname)
     else:
       # pv is not a partition, eg. loop device, or LV
       pass
     for path in pv.get_paths():
       parts[path] = pv
   # create return list
   pvs_list = list()
   for part in parts.values():
     if part not in pvs_list:
       pvs_list.append(part)
   for seg in segs:
     pvs_list.append(seg)
   # disable initialization of multipathed devices (for now)
   for pv in pvs_list:
     if len(pv.get_paths()) > 1:
       if pv.get_type() == UNINITIALIZED_TYPE:
         pv.add_property(NOT_INITIALIZABLE, _("Multipath device"))
         if pv.initializable:
           pv.initializable = False
           pv.add_property(_("Note:"), _("Initialize manually"))
   # all done
   return pvs_list
Exemplo n.º 35
0
 def __query_LVs(self):
   if LVS_HAS_MIRROR_OPTIONS:
     LVS_OPTION_STRING="lv_name,vg_name,stripes,stripesize,lv_attr,lv_uuid,devices,origin,snap_percent,seg_start,seg_size,vg_extent_size,lv_size,mirror_log"
   else:
     LVS_OPTION_STRING="lv_name,vg_name,stripes,stripesize,lv_attr,lv_uuid,devices,origin,snap_percent,seg_start,seg_size,vg_extent_size,lv_size"
   LV_NAME_IDX         = 0
   LV_VG_NAME_IDX      = 1
   LV_STRIPES_NUM_IDX  = 2
   LV_STRIPE_SIZE_IDX  = 3
   LV_ATTR_IDX         = 4
   LV_UUID_IDX         = 5
   LV_DEVICES_IDX      = 6
   LV_SNAP_ORIGIN_IDX  = 7
   LV_SNAP_PERCENT_IDX = 8
   LV_SEG_START_IDX    = 9
   LV_SEG_SIZE_IDX     = 10
   LV_EXTENT_SIZE_IDX  = 11
   LV_SIZE_IDX         = 12
   LV_MIRROR_LOG_IDX   = 13
   
   self.__reload_logical_volumes_paths()
   
   arglist = list()
   arglist.append(LVM_BIN_PATH)
   arglist.append("lvs")
   arglist.append("--nosuffix")
   arglist.append("--noheadings")
   arglist.append("--units")
   arglist.append("b")
   arglist.append("--separator")
   arglist.append("\";\"")
   arglist.append("-o")
   arglist.append(LVS_OPTION_STRING)
   if LVS_HAS_ALL_OPTION:
     arglist.append("--all")
   result_string = execWithCapture(LVM_BIN_PATH, arglist)
   lines = result_string.splitlines()
   for line in lines:
     line = line.strip()
     words = line.split(';')
     vgname = words[LV_VG_NAME_IDX].strip()
     attrs = words[LV_ATTR_IDX].strip()
     uuid = words[LV_UUID_IDX].strip()
     extent_size = int(words[LV_EXTENT_SIZE_IDX])
     seg_start = int(words[LV_SEG_START_IDX]) / extent_size
     lv_size = int(words[LV_SIZE_IDX]) / extent_size
     seg_size = int(words[LV_SEG_SIZE_IDX]) / extent_size
     devices = words[LV_DEVICES_IDX]
     if LVS_HAS_MIRROR_OPTIONS:
       mirror_log = words[LV_MIRROR_LOG_IDX].strip()
     
     lvname = words[LV_NAME_IDX].strip()
     # remove [] if there (used to mark hidden lvs)
     lvname = lvname.lstrip('[')
     lvname = lvname.rstrip(']')
     
     vg = self.__VGs[vgname]
     vg_lvs = vg.get_lvs()
     lv = None
     if lvname not in vg_lvs:
       lv = LogicalVolume(lvname, self.__get_logical_volume_path(lvname, vg.get_name()), True, attrs, uuid)
       lv.set_extent_count(lv_size, lv_size)
       vg.add_lv(lv)
     lv = vg_lvs[lvname]
     
     segment = None
     devs = devices.split(',')
     if attrs[0] == 'm' or attrs[0] == 'M':
       # mirrored LV
       lv.set_mirror_log(mirror_log) # tmp, will get replaced with real one at __link_mirrors()
       segment = MirroredSegment(seg_start, seg_size)
       images = devs
       for image_name in images:
         idx = image_name.find('(')
         image_lv = LogicalVolume(image_name[:idx], None, True, None, None) # tmp, will get replaced with real one at __link_mirrors()
         segment.add_image(image_lv)
     elif len(devs) == 1:
       # linear segment
       segment = LinearSegment(seg_start, seg_size)
       idx = devs[0].find('(')
       pvpath = devs[0][:idx]
       ph_ext_beg = int(devs[0][idx+1:len(devs[0])-1])
       pv = None
       for pv_t in self.__PVs:
         if pv_t.get_path() == pvpath:
           pv = pv_t
           break
       extent_block = ExtentBlock(pv, lv, ph_ext_beg, seg_size)
       segment.set_extent_block(extent_block)
     else:
       # striped segment
       lv.set_stripes_num(int(words[LV_STRIPES_NUM_IDX]))
       stripe_size = int(words[LV_STRIPE_SIZE_IDX])
       segment = StripedSegment(stripe_size, seg_start, seg_size)
       stripe_id = 0
       for stripe in devs:
         idx = stripe.find('(')
         pvpath = stripe[:idx]
         ph_ext_beg = int(stripe[idx+1:len(stripe)-1])
         pv = None
         for pv_t in self.__PVs:
           if pv_t.get_path() == pvpath:
             pv = pv_t
             break
         extent_block = ExtentBlock(pv, lv, ph_ext_beg, seg_size/len(devs))
         segment.add_stripe(stripe_id, extent_block)
         stripe_id = stripe_id + 1
     
     lv.add_segment(segment)
     
     origin = words[LV_SNAP_ORIGIN_IDX].strip()
     if origin != '':
       # snapshot
       usage = float(words[LV_SNAP_PERCENT_IDX].strip())
       lv.set_snapshot_info(origin, usage) # set name for now, real LV will get set at __link_snapshots()