Best Python code snippet using autotest_python
kvm_installer.py
Source:kvm_installer.py  
...222                        bin_list=self.qemu_bin_paths,223                        unittest=self.unittest_prefix)224        self.reload_modules_if_needed()225        if self.save_results:226            virt_utils.archive_as_tarball(self.srcdir, self.results_dir)227class KojiInstaller(YumInstaller):228    """229    Class that handles installing KVM from the fedora build service, koji.230    It uses yum to install and remove packages. Packages are specified231    according to the syntax defined in the PkgSpec class.232    """233    def set_install_params(self, test, params):234        """235        Gets parameters and initializes the package downloader.236        @param test: kvm test object237        @param params: Dictionary with test arguments238        """239        super(KojiInstaller, self).set_install_params(test, params)240        self.tag = params.get("koji_tag", None)241        self.koji_cmd = params.get("koji_cmd", None)242        if self.tag is not None:243            virt_utils.set_default_koji_tag(self.tag)244        self.koji_pkgs = eval(params.get("koji_pkgs", "[]"))245    def _get_packages(self):246        """247        Downloads the specific arch RPMs for the specific build name.248        """249        koji_client = virt_utils.KojiClient(cmd=self.koji_cmd)250        for pkg_text in self.koji_pkgs:251            pkg = virt_utils.KojiPkgSpec(pkg_text)252            if pkg.is_valid():253                koji_client.get_pkgs(pkg, dst_dir=self.srcdir)254            else:255                logging.error('Package specification (%s) is invalid: %s', pkg,256                              pkg.describe_invalid())257    def _clean_previous_installs(self):258        kill_qemu_processes()259        removable_packages = " ".join(self._get_rpm_names())260        utils.system("yum -y remove %s" % removable_packages)261    def install(self):262        self._clean_previous_installs()263        self._get_packages()264        self._install_packages()265        self.install_unittests()266        create_symlinks(test_bindir=self.test_bindir,267                        bin_list=self.qemu_bin_paths,268                        unittest=self.unittest_prefix)269        self.reload_modules_if_needed()270        if self.save_results:271            virt_utils.archive_as_tarball(self.srcdir, self.results_dir)272    def _get_rpm_names(self):273        all_rpm_names = []274        koji_client = virt_utils.KojiClient(cmd=self.koji_cmd)275        for pkg_text in self.koji_pkgs:276            pkg = virt_utils.KojiPkgSpec(pkg_text)277            rpm_names = koji_client.get_pkg_rpm_names(pkg)278            all_rpm_names += rpm_names279        return all_rpm_names280    def _get_rpm_file_names(self):281        all_rpm_file_names = []282        koji_client = virt_utils.KojiClient(cmd=self.koji_cmd)283        for pkg_text in self.koji_pkgs:284            pkg = virt_utils.KojiPkgSpec(pkg_text)285            rpm_file_names = koji_client.get_pkg_rpm_file_names(pkg)286            all_rpm_file_names += rpm_file_names287        return all_rpm_file_names288    def _install_packages(self):289        """290        Install all downloaded packages.291        """292        os.chdir(self.srcdir)293        rpm_file_names = " ".join(self._get_rpm_file_names())294        utils.system("yum --nogpgcheck -y localinstall %s" % rpm_file_names)295class SourceDirInstaller(BaseInstaller):296    """297    Class that handles building/installing KVM directly from a tarball or298    a single source code dir.299    """300    def set_install_params(self, test, params):301        """302        Initializes class attributes, and retrieves KVM code.303        @param test: kvm test object304        @param params: Dictionary with test arguments305        """306        super(SourceDirInstaller, self).set_install_params(test, params)307        self.mod_install_dir = os.path.join(self.prefix, 'modules')308        srcdir = params.get("srcdir", None)309        self.path_to_roms = params.get("path_to_rom_images", None)310        if self.install_mode == 'localsrc':311            if srcdir is None:312                raise error.TestError("Install from source directory specified"313                                      "but no source directory provided on the"314                                      "control file.")315            else:316                shutil.copytree(srcdir, self.srcdir)317        elif self.install_mode == 'localtar':318            tarball = params.get("tarball")319            if not tarball:320                raise error.TestError("KVM Tarball install specified but no"321                                      " tarball provided on control file.")322            logging.info("Installing KVM from a local tarball")323            logging.info("Using tarball %s")324            tarball = utils.unmap_url("/", params.get("tarball"), "/tmp")325            utils.extract_tarball_to_dir(tarball, self.srcdir)326        if self.install_mode in ['localtar', 'srcdir']:327            self.repo_type = virt_utils.check_kvm_source_dir(self.srcdir)328            p = os.path.join(self.srcdir, 'configure')329            self.configure_options = virt_installer.check_configure_options(p)330    def _build(self):331        make_jobs = utils.count_cpus()332        os.chdir(self.srcdir)333        # For testing purposes, it's better to build qemu binaries with334        # debugging symbols, so we can extract more meaningful stack traces.335        cfg = "./configure --prefix=%s" % self.prefix336        if "--disable-strip" in self.configure_options:337            cfg += " --disable-strip"338        steps = [cfg, "make clean", "make -j %s" % make_jobs]339        logging.info("Building KVM")340        for step in steps:341            utils.system(step)342    def _install(self):343        os.chdir(self.srcdir)344        logging.info("Installing KVM userspace")345        if self.repo_type == 1:346            utils.system("make -C qemu install")347        elif self.repo_type == 2:348            utils.system("make install")349        if self.path_to_roms:350            install_roms(self.path_to_roms, self.prefix)351        self.install_unittests()352        create_symlinks(test_bindir=self.test_bindir,353                        prefix=self.prefix,354                        unittest=self.unittest_prefix)355    def install(self):356        self._build()357        self._install()358        self.reload_modules_if_needed()359        if self.save_results:360            virt_utils.archive_as_tarball(self.srcdir, self.results_dir)361class GitRepo(object):362    def __init__(self, installer, prefix,363            srcdir, build_steps=[], repo_param=None):364        params = installer.params365        self.installer = installer366        self.repo = params.get(repo_param or (prefix + '_repo'))367        self.branch = params.get(prefix + '_branch', 'master')368        self.lbranch = params.get(prefix + '_lbranch', 'master')369        self.commit = params.get(prefix + '_commit', None)370        # The config system yields strings, which have to be evalued371        self.patches = eval(params.get(prefix + '_patches', "[]"))372        self.build_steps = build_steps373        self.srcdir = os.path.join(self.installer.srcdir, srcdir)374    def fetch_and_patch(self):375        if not self.repo:376            return377        virt_utils.get_git_branch(self.repo, self.branch, self.srcdir,378                                 self.commit, self.lbranch)379        os.chdir(self.srcdir)380        for patch in self.patches:381            utils.get_file(patch, os.path.join(self.srcdir,382                                               os.path.basename(patch)))383            utils.system('patch -p1 < %s' % os.path.basename(patch))384    def build(self):385        os.chdir(self.srcdir)386        for step in self.build_steps:387            logging.info(step)388            utils.run(step)389class GitInstaller(SourceDirInstaller):390    def _pull_code(self):391        """392        Retrieves code from git repositories.393        """394        params = self.params395        make_jobs = utils.count_cpus()396        cfg = 'PKG_CONFIG_PATH="%s/lib/pkgconfig:%s/share/pkgconfig" ./configure' % (397            self.prefix, self.prefix)398        self.spice_protocol = GitRepo(installer=self, prefix='spice_protocol',399            srcdir='spice-protocol',400            build_steps= ['./autogen.sh',401                          './configure --prefix=%s' % self.prefix,402                          'make clean',403                          'make -j %s' % (make_jobs),404                          'make install'])405        self.spice = GitRepo(installer=self, prefix='spice', srcdir='spice',406            build_steps= ['PKG_CONFIG_PATH="%s/lib/pkgconfig:%s/share/pkgconfig" CXXFLAGS=-Wl,--add-needed ./autogen.sh --prefix=%s' % (self.prefix, self.prefix, self.prefix),407                          'make clean',408                          'make -j %s' % (make_jobs),409                          'make install'])410        self.userspace = GitRepo(installer=self, prefix='user',411            repo_param='user_git_repo', srcdir='kvm_userspace')412        p = os.path.join(self.userspace.srcdir, 'configure')413        self.configure_options = virt_installer.check_configure_options(p)414        cfg = cfg + ' --prefix=%s' % self.prefix415        if "--disable-strip" in self.configure_options:416            cfg += ' --disable-strip'417        if self.extra_configure_options:418            cfg += ' %s' % self.extra_configure_options419        self.userspace.build_steps=[cfg, 'make clean', 'make -j %s' % make_jobs]420        if not self.userspace.repo:421            message = "KVM user git repository path not specified"422            logging.error(message)423            raise error.TestError(message)424        for repo in [self.userspace, self.spice_protocol, self.spice]:425            if not repo.repo:426                continue427            repo.fetch_and_patch()428    def _build(self):429        if self.spice_protocol.repo:430            logging.info('Building Spice-protocol')431            self.spice_protocol.build()432        if self.spice.repo:433            logging.info('Building Spice')434            self.spice.build()435        logging.info('Building KVM userspace code')436        self.userspace.build()437    def _install(self):438        os.chdir(self.userspace.srcdir)439        utils.system('make install')440        if self.path_to_roms:441            install_roms(self.path_to_roms, self.prefix)442        self.install_unittests()443        create_symlinks(test_bindir=self.test_bindir, prefix=self.prefix,444                        bin_list=None,445                        unittest=self.unittest_prefix)446    def install(self):447        self._pull_code()448        self._build()449        self._install()450        self.reload_modules_if_needed()451        if self.save_results:452            virt_utils.archive_as_tarball(self.srcdir, self.results_dir)453class PreInstalledKvm(BaseInstaller):454    def install(self):455        logging.info("Expecting KVM to be already installed. Doing nothing")456class FailedInstaller:457    """458    Class used to be returned instead of the installer if a installation fails459    Useful to make sure no installer object is used if KVM installation fails.460    """461    def __init__(self, msg="KVM install failed"):462        self._msg = msg463    def load_modules(self):464        """Will refuse to load the KVM modules as install failed"""465        raise FailedKvmInstall("KVM modules not available. reason: %s" % (self._msg))466installer_classes = {...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
