Пример #1
0
    def makeKernel(self,quiet=True,showMenuConfig=False,noClean=False,
                   lvmOpt=False,dmraidOpt=False,mdadmOpt=False,
                   mrproper=False,target="all"):
        """Run kernel compilation"""
        clVars = self.clVars
        themeName = "calculate"
        standardParams = ["--splash=%s"%themeName, "--unionfs",
                          "--all-ramdisk-modules","--disklabel",
                          "--no-save-config", "--firmware","--udev",
                          "--lspci"]
        kernelDir = ["--kerneldir=%s"%clVars.Get('cl_kernel_src_path')]
        kernelDestination = clVars.Get('cl_kernel_install_path')
        modulePrefix = ["--module-prefix=%s"%kernelDestination]
        if not path.exists(kernelDestination):
            self.printERROR("Not found destination directory '%s'"%
                                kernelDestination)
            return False
        logLevel = ["--loglevel=%d"%(1 if quiet else 2)]
        makeOpts = clVars.Get('os_builder_makeopts')
        if makeOpts:
            makeOpts = ["--makeopts=%s"%makeOpts]
        else:
            makeOpts = []
        menuConfig = ["--menuconfig"] if showMenuConfig else []
        noClean = ["--no-clean"] if noClean else []
        bootDir = clVars.Get('cl_kernel_boot_path')
        if not path.exists(bootDir):
            os.makedirs(bootDir,mode=0755)
        bootDir = ["--bootdir=%s"%bootDir]
        lvmOpt = ["--lvm"] if lvmOpt else []
        dmraidOpt = ["--dmraid"] if dmraidOpt else []
        mdadmOpt = ["--mdadm"] if mdadmOpt else []
        mrproperOpt = ["--mrproper"] if mrproper else ["--no-mrproper"]
        stdConfigPath = \
            path.join(clVars.Get('cl_kernel_src_path'), ".config")
        if clVars.Get('cl_kernel_config') == stdConfigPath:
            kernelConfig = []
            if mrproper:
                self.printERROR(_("Cannot use the current kernel configuration"
                                  " with option'%s'")%
                    "--mrproper")
                return False
        else:
            kernelConfig = ["--kernel-config=%s"%clVars.Get('cl_kernel_config')]
        kernelName = ["--kernname=%s"%clVars.Get('os_linux_system')]
        cachedir = ["--cachedir=%s"%clVars.Get('cl_kernel_cache_path')]
        tempdir = ["--tempdir=%s"%clVars.Get('cl_kernel_temp_path')]

        params = ["genkernel"]+cachedir+tempdir+\
                    standardParams+kernelDir+modulePrefix+\
                    logLevel+makeOpts+menuConfig+noClean+kernelConfig+\
                    bootDir+lvmOpt+dmraidOpt+mdadmOpt+mrproperOpt+[target]

        try:
            genkernelProcess = process(*params,stdout=None,stderr=STDOUT,
                                       stdin=None,envdict=os.environ)
            return genkernelProcess.success()
        except KeyboardInterrupt:
            self.printERROR("Keyboard interrupt")
            return False
Пример #2
0
 def _packInitRamfs(self,newInitramfsFile=None):
     """Pack initramfs"""
     self.prevDir = os.getcwd()
     try:
         # get file list for pack
         fileList = reduce(lambda x,y: x
                                     +map(lambda z:path.join(y[0],z),y[1])
                                     +map(lambda z:path.join(y[0],z),y[2]),
                           os.walk(self.tmpPath),
                           [])
         fileList = map(lambda x:x[len(self.tmpPath)+1:],fileList)
         # change dir for cpio
         os.chdir(self.tmpPath)
         # create cpio process
         cpioProcess = process("cpio", "-o", "--quiet", "-H","newc")
         # send file list to cpio process
         cpioProcess.write("\n".join(fileList))
         cpioProcess.write("\n")
         # get result of cpio
         cpioData = cpioProcess.read()
         cpioRes = cpioProcess.returncode()
     except KeyboardInterrupt:
         os.chdir(self.prevDir)
         raise KeyboardInterrupt
     except Exception,e:
         print e.__repr__()
         cpioRes = 255
Пример #3
0
def receiveMac(interface="eth0"):
    """Get MAC from interface"""
    ipconfigProg = checkUtils('/sbin/ifconfig')
    ifconfig = process(ipconfigProg,interface)
    res = re.search(r"(?:HWaddr|ether)\s(\S+)",ifconfig.read(),re.S)
    if res:
        return res.group(1)
    else:
        return "00:00:00:00:00:00"
Пример #4
0
 def getKernelUid(self,device):
     """Get Kernel UID by UUID of device"""
     blkidProcess = process('/sbin/blkid','-c','/dev/null','-s','UUID',
                             '-o','value',device)
     res = blkidProcess.read().strip()
     if res:
         return res[:8]
     else:
         return "no_uid"
Пример #5
0
def getIpAndMask(interface="eth0"):
    """Get ip and mask from interface"""
    ipconfigProg = checkUtils('/sbin/ifconfig')
    ifconfig = process(ipconfigProg,interface)
    res = re.search(r"inet(?: addr:| )(\S+)\s.*(?:Mask:|netmask )(\S+)",
                    ifconfig.read(),re.S)
    if res:
        return res.groups()
    else:
        return ("","")
Пример #6
0
 def _unpackInitRamfs(self):
     """Unpack initramfs"""
     self.prevDir = os.getcwd()
     if not path.exists(self.tmpPath):
         os.mkdir(self.tmpPath)
     os.chdir(self.tmpPath)
     cpioProcess = process("cpio", "-di")
     gzipInitrd = gzip.open(self.initrdFile,'r')
     cpioProcess.write(gzipInitrd.read())
     res = cpioProcess.success()
     os.chdir(self.prevDir)
     return res
Пример #7
0
def getRouteTable(onlyIface=[]):
    """Get route table, exclude specifed iface"""
    ipProg = checkUtils('/sbin/ip')
    routes = process(ipProg,"route")
    if onlyIface:
        filterRe = re.compile("|".join(map(lambda x:r"dev %s"%x,onlyIface)))
        routes = filter(filterRe.search,routes)
    for line in routes:
        network,op,line = line.partition(" ")
        routeParams = map(lambda x:x.strip(),line.split())
        # (network,{'via':value,'dev':value})
        if network:
            yield (network,dict(zip(routeParams[0::2],routeParams[1::2])))
Пример #8
0
 def get_os_root_dev(self):
     """Root filesystem device"""
     record = open('/proc/cmdline','rb').read().strip()
     re_resRealRoot=re.search('(?:^|\s)real_root=(\S+)(\s|$)',record)
     re_resFakeRoot=re.search('(?:^|\s)root=(\S+)(\s|$)',record)
     # param real_root priority that root
     re_res = re_resRealRoot or re_resFakeRoot
     if re_res:
         rootparam=re_res.group(1)
         # check root for /dev/sd view
         if re.match("^\/dev\/[a-z]+.*$", rootparam):
             return getUdevDeviceInfo(
                name=rootparam.strip()).get('DEVNAME',rootparam)
         # check root set by uuid
         if re.match("^UUID=.*$",rootparam):
             uuid = rootparam[5:].strip("\"'")
             blkidProcess = process('/sbin/blkid','-c','/dev/null','-U',
                                 uuid)
             if blkidProcess.success():
                 return getUdevDeviceInfo(
                    name=blkidProcess.read().strip()).get('DEVNAME','')
         # check root set by label
         if re.match("^LABEL=.*$",rootparam):
             uuid = rootparam[6:].strip("\"'")
             blkidProcess = process('/sbin/blkid','-c','/dev/null','-L',
                                 uuid)
             if blkidProcess.success():
                 return getUdevDeviceInfo(
                    name=blkidProcess.read().strip()).get('DEVNAME','')
     # get device mounted to root
     dfLines = self._runos("LANG=C df /")
     if not dfLines:
         return ""
     if type(dfLines) == types.ListType and len(dfLines)>1:
         root_dev = dfLines[1].split(" ")[0].strip()
         if root_dev:
             return {'none':'/dev/ram0'}.get(root_dev,root_dev)
     return ""
Пример #9
0
    def performVersionMigrate(self):
        """Generate cl_kernel_uid, write to calculate2.env, fix grub.conf"""
        clVars = self.clVars
        clKernelUid = clVars.Get('cl_kernel_uid')
        clVars.Write('cl_kernel_uid',clKernelUid,force=True)
        grubconf = '/boot/grub/grub.conf'
        grub2conf = '/boot/grub/grub.cfg'
        rootdev = clVars.Get('os_root_dev')
        x11video = clVars.Get('os_x11_video_drv')

        class grubsetUID(changer):
            reChangeKernel = \
                re.compile("(/boot/(?:vmlinuz))(?:-\S+?)?((?:-install)?) ")
            reChangeInitrd = \
                re.compile("(/boot/)(?:initrd|initramfs)"
                           "(?:-\S+?)?((?:-install)?)$")
            drop = lambda self,y: y.startswith('title')
            up = lambda self,y: y.startswith('kernel') and \
                                "root=%s"%rootdev in y
            def change(self,y):
                y = self.reChangeKernel.sub("\\1-%s\\2 "%clKernelUid,y)
                return self.reChangeInitrd.sub("\\1initrd-%s\\2"%clKernelUid,y)

        class grubchangeCONSOLE(grubsetUID):
            up = lambda self,y: y.startswith('kernel') and \
                                "/boot/vmlinuz-%s"%clKernelUid in y
            change = lambda self,y: y.replace('CONSOLE=/dev/','console=')

        class grubchangeVideo(grubchangeCONSOLE):
            reChangeCalculate = re.compile(r'(?: calculate=\S+|$)')
            drop = lambda self,y: not y.startswith('kernel')
            change = lambda self,y:self.reChangeCalculate.sub(
                                  ' calculate=video:%s'%x11video,y,1)

        # if has grub2
        if filter(lambda x:x.startswith("grub-1.99"),
           listDirectory('/var/db/pkg/sys-boot')):
            grubInstall = process('/usr/sbin/cl-core','--method','core_setup',
                                  '--pkg-name','grub',
                                  '--no-progress',stderr=None)
            grubInstall.success()

        if not filter(lambda x:x.startswith("grub-0.9"),
           listDirectory('/var/db/pkg/sys-boot')) or not path.exists(grubconf):
            return True

        if not os.access(grubconf,os.W_OK):
            self.printERROR(_("No permission to write to '%s'")%grubconf)
            return False
        calcKernel = filter(lambda x:x['PN'] == 'calckernel',
                     map(reVerSplitToPV,
                     filter(lambda x:x,
                     map(lambda x:reVerSplit.search(x),
                     listDirectory('/var/db/pkg/sys-kernel')))))
        newGrub = grubsetUID().reduce(open(grubconf,'r'))
        if calcKernel and cmpVersion(calcKernel[-1]['PVR'],"3.4.14") >= 0:
            newGrub = grubchangeCONSOLE().reduce(newGrub)
            newGrub = grubchangeVideo().reduce(newGrub)

        open(grubconf,'w').writelines(newGrub)
        return True
Пример #10
0
 def searchInside(self,searchFunc):
     """Search data in file list of initramfs"""
     cpioProcess = process("cpio", "-tf",
             stdin=process("gzip", "-dc", self.initrdFile))
     return filter(searchFunc,cpioProcess)