Beispiel #1
0
    def load_vm(self, name):

        show('Loading VM %s' % name)
        self.get_domain(name)  # this fails if VM does not exist

        # TODO: check that it started, if not, wait
        self.start(name)

        # TODO: need a proper retry function
        ip = None
        timeout = 0

        while ip is None:
            ip = self.get_ip(name)
            sleep(2)
            timeout += 2

            if timeout > 20:
                raise RuntimeError("Could not determine IP of VM %s" % name)

        hostname = util.normalize_hostname(ip)
        show('IP determined: %s' % ip)

        return VM(name=name, backend=self, hostname=hostname,
                  domain=locals.DOMAIN, ip=ip)
Beispiel #2
0
    def load_vm(self, name):

        show('Loading VM %s' % name)
        self.get_domain(name)  # this fails if VM does not exist

        # TODO: check that it started, if not, wait
        self.start(name)

        # TODO: need a proper retry function
        ip = None
        timeout = 0

        while ip is None:
            ip = self.get_ip(name)
            sleep(2)
            timeout += 2

            if timeout > 20:
                raise RuntimeError("Could not determine IP of VM %s" % name)

        hostname = util.normalize_hostname(ip)
        show('IP determined: %s' % ip)

        return VM(name=name, backend=self, hostname=hostname,
                  domain=locals.DOMAIN, ip=ip)
Beispiel #3
0
    def __init__(self, url, cluster_name, ca_file, username=None,
                 password=None, kerberos=None, verbose=0, **kwargs):
        super(RHEVM, self).__init__()

        self.url = url
        self.username = username
        self.password = password
        self.cluster = cluster_name
        self.ca_file = ca_file
        self.kerberos = kerberos
        self.verbose = verbose
        self.debug = verbose > 1

        if self.kerberos:
            if self.verbose:
                show("Using Kerberos authentication")
            self.api = API(url=self.url,
                           kerberos=True,
                           ca_file=self.ca_file,
                           filter=True,
                           debug=self.debug
                           )
        else:
            if self.verbose:
                show("Using username and password: %s" % self.username)
            self.api = API(url=self.url,
                           username=self.username,
                           password=self.password,
                           ca_file=self.ca_file,
                           debug=self.debug)
Beispiel #4
0
    def setup_trust(self, hostname=''):
        show('Setting up AD Trust..')

        self.cmd("bash labtool/ipa-fun-setup-trust.sh"
                 " {hostname} {log}".format(hostname=hostname, **self.locals))

        show('Completed!')
Beispiel #5
0
    def setup_trust(self, hostname=''):
        show('Setting up AD Trust..')

        self.cmd("bash labtool/ipa-fun-setup-trust.sh"
                 " {hostname} {log}".format(hostname=hostname, **self.locals))

        show('Completed!')
Beispiel #6
0
 def set_sudoers(self):
     show('Configuring sudo commands execution in sudoers')
     show('Using root login')
     self.connect(user='******')
     self.cmd('sed -i.bak "s/Defaults    requiretty'
              '/# Defaults    requiretty/g" /etc/sudoers')
     self.close()
Beispiel #7
0
    def __init__(self, url, cluster_name, ca_file, username=None,
                 password=None, kerberos=None, verbose=0, **kwargs):
        super(RHEVM, self).__init__()

        self.url = url
        self.username = username
        self.password = password
        self.cluster = cluster_name
        self.ca_file = ca_file
        self.kerberos = kerberos
        self.verbose = verbose
        self.debug = verbose > 1

        if self.kerberos:
            if self.verbose:
                show("Using Kerberos authentication")
            self.api = API(url=self.url,
                           kerberos=True,
                           ca_file=self.ca_file,
                           filter=True,
                           debug=self.debug
                           )
        else:
            if self.verbose:
                show("Using username and password: %s" % self.username)
            self.api = API(url=self.url,
                           username=self.username,
                           password=self.password,
                           ca_file=self.ca_file,
                           debug=self.debug)
Beispiel #8
0
 def set_sudoers(self):
     show('Configuring sudo commands execution in sudoers')
     show('Using root login')
     self.connect(user='******')
     self.cmd('sed -i.bak "s/Defaults    requiretty'
              '/# Defaults    requiretty/g" /etc/sudoers')
     self.close()
Beispiel #9
0
 def install_devel_packages(self, packages=[]):
     if packages:
         show('Installing packages from devel repo: {pckgs}'.format(
             pckgs=', '.join(packages)))
         self.cmd(
             'sudo dnf install -y --enablerepo=ipa-devel {pckgs}'.format(
                 pckgs=' '.join(packages)))
Beispiel #10
0
 def install_client(self, master):
     # TODO: support for replica install settings
     show('Installing client')
     ret = self.cmd("bash labtool/ipa-fun-install-client.sh"
                    " {master} {log}".format(master=master, **self.locals),
                     allow_failure=True)
     if ret:
         show('Client installation failed.')
Beispiel #11
0
 def install_client(self, master):
     # TODO: support for replica install settings
     show('Installing client')
     ret = self.cmd("bash labtool/ipa-fun-install-client.sh"
                    " {master} {log}".format(master=master, **self.locals),
                    allow_failure=True)
     if ret:
         show('Client installation failed.')
Beispiel #12
0
    def shutdown(self, name):
        self.get_vm(name).shutdown()

        show('Waiting for VM %s to reach Down status' % name)
        while self.get_vm_state(name) != 'down':
            sleep(5)

        show('VM %s stopped successfully' % name)
Beispiel #13
0
    def shutdown(self, name):
        self.api.vms.get(name).shutdown()

        show('Waiting for VM %s to reach Down status' % name)
        while self.api.vms.get(name).status.state != 'down':
            sleep(1)

        show('VM %s stopped successfully' % name)
Beispiel #14
0
    def shutdown(self, name):
        self.get_vm(name).shutdown()

        show('Waiting for VM %s to reach Down status' % name)
        while self.get_vm_state(name) != 'down':
            sleep(1)

        show('VM %s stopped successfully' % name)
Beispiel #15
0
    def install_packages(self, action):
        if action[1] == 'local':
            show('Installing local rpm packages')
            self.cmd("bash labtool/ipa-fun-install-rpms.sh"
                     " {log}".format(**self.locals))

        elif action[1] == 'repo':
            show('Installing packages from repositories')
            self.cmd("bash labtool/ipa-fun-install-repo.sh"
                     " {log}".format(**self.locals))
Beispiel #16
0
    def install_packages(self, action):
        if action[1] == 'local':
            show('Installing local rpm packages')
            self.cmd("bash labtool/ipa-fun-install-rpms.sh"
                     " {log}".format(**self.locals))

        elif action[1] == 'repo':
            show('Installing packages from repositories')
            self.cmd("bash labtool/ipa-fun-install-repo.sh"
                     " {log}".format(**self.locals))
Beispiel #17
0
    def start(self, name, vm=None, wait=True):
        if not vm:
            vm = self.get_vm(name)
        if self.get_vm_state(name, vm) == 'down':
            show('Starting VM')
            vm.start()

            while wait and self.get_vm_state(name, vm) != 'up':
                vm = self.get_vm(name)
                sleep(3)
        return vm
Beispiel #18
0
    def start(self, name, vm=None, wait=True):
        if not vm:
            vm = self.get_vm(name)
        if self.get_vm_state(name, vm) == 'down':
            show('Starting VM')
            vm.start()

            while wait and self.get_vm_state(name, vm) != 'up':
                vm = self.get_vm(name)
                sleep(15)
        return vm
Beispiel #19
0
    def start(self, name, vm=None):
        if not vm:
            vm = self.api.vms.get(name)
        if self.get_vm_state(name, vm) == 'down':
            show('Starting VM')
            vm.start()

            while self.get_vm_state(name, vm) != 'up':
                vm = self.api.vms.get(name)
                sleep(3)
        return vm
Beispiel #20
0
    def start(self, name):
        if self.get_domain(name) and not self.get_domain(name).isActive():
            show('Starting %s' % name)

            output, errors, rc = util.run(
                ['virsh', 'start', name, '--force-boot'])

            sleep(20)

            if rc != 0:
                raise RuntimeError("Could not start VM %s" % name)
Beispiel #21
0
    def start(self, name):
        if self.get_domain(name) and not self.get_domain(name).isActive():
            show('Starting %s' % name)

            output, errors, rc = util.run(['virsh',
                                           'start',
                                           name,
                                           '--force-boot'
                                         ])

            sleep(20)

            if rc != 0:
                raise RuntimeError("Could not start VM %s" % name)
Beispiel #22
0
    def create_vm(self, name, template=locals.TEMPLATE_NAME):

        # TODO: check if the VM with the name of name exists

        # Check whether template VM exists
        show('Checking for existence of template')
        template_domain = self.get_domain(template)

        # TODO: check if it is running, if is, print down warning and shut
        # it down

        if template_domain:
            show('Cloning..')

            # Find out next available MAC address in the pool
            new_mac = self.get_next_free_mac()

            output, errors, rc = util.run([
                'virt-clone',
                '-o',
                template,
                '--auto-clone',
                '-n',
                name,
                '-m',
                new_mac,
            ])

            if rc != 0:
                raise RuntimeError("Could not clone VM %s" % template)

            show('Cloning successful')

            # TODO: check that it started, if not, wait
            show('Starting..')
            self.start(name)
            sleep(10)

            # Macs are tied to the IPs
            last_mac_segment = new_mac.split(':')[-1]
            ip = locals.IP_BASE + '%s' % int(last_mac_segment)

            show('IP determined: %s' % ip)
            hostname = util.normalize_hostname(ip)

            return VM(name=name,
                      backend=self,
                      hostname=hostname,
                      domain=locals.DOMAIN,
                      ip=ip)
Beispiel #23
0
    def load_vm(self, name):
        self.start(name)

        # Obtain the IP address. It can take a while for the guest agent
        # to start, so we wait 2 minutes here before giving up.
        show('Waiting to obtain IP address')
        show('Press CTRL+C to interrupt and enter manually.')
        counter = 0
        try:
            while self.get_ip(name) is None:
                counter = counter + 1
                if counter > 120:
                    break
                sleep(1)
        except KeyboardInterrupt:
            counter = 100000

        if counter <= 120:
            ip = self.get_ip(name)
            last_ip_segment = ip.split('.')[-1]
            show("IP address of the VM is %s" % ip)
        else:
            notify('Enter the IP manually.')

            last_ip_segment = ''

            while not (len(last_ip_segment) > 0 and len(last_ip_segment) < 4):
                last_ip_segment = raw_input("IP address could not be "
                "determined. Enter the VM number (no leading zeros):")
                ip = locals.IP_BASE + last_ip_segment

        # Update the description
        hostname = util.normalize_hostname(ip)

        # Set the VM's description so that it can be identified in WebAdmin
        vm = self.api.vms.get(name)
        vm.set_description(hostname)
        vm.update()

        show("Description set to %s" % hostname)

        # Necessary because of RHEV bug
        show("Pinging the VM")
        output, errors, rc = util.run(['ping', '-c', '3', ip])

        show.untab()

        return VM(name=name, backend=self, hostname=hostname,
                  domain=locals.DOMAIN, ip=ip)
Beispiel #24
0
    def create_vm(self, name, template=locals.TEMPLATE_NAME):

        # TODO: check if the VM with the name of name exists

        # Check whether template VM exists
        show('Checking for existence of template')
        template_domain = self.get_domain(template)

        # TODO: check if it is running, if is, print down warning and shut
        # it down

        if template_domain:
            show('Cloning..')

            # Find out next available MAC address in the pool
            new_mac = self.get_next_free_mac()

            output, errors, rc = util.run(['virt-clone',
                                           '-o',
                                           template,
                                           '--auto-clone',
                                           '-n',
                                           name,
                                           '-m',
                                           new_mac,
                                         ])

            if rc != 0:
                raise RuntimeError("Could not clone VM %s" % template)

            show('Cloning successful')

            # TODO: check that it started, if not, wait
            show('Starting..')
            self.start(name)
            sleep(10)

            # Macs are tied to the IPs
            last_mac_segment = new_mac.split(':')[-1]
            ip = locals.IP_BASE + '%s' % int(last_mac_segment)

            show('IP determined: %s' % ip)
            hostname = util.normalize_hostname(ip)

            return VM(name=name, backend=self, hostname=hostname,
                      domain=locals.DOMAIN, ip=ip)
Beispiel #25
0
class VM():
    def __init__(self, name, backend, hostname, domain, ip):
        "Creates a connection to the client"

        self.name = name
        self.backend = backend
        self.hostname = hostname
        self.domain = domain
        self.ip = ip
        self.fqdn = '%s.%s' % (self.hostname, self.domain)
        self.locals = dict()

        show.debug("New VM object!")
        show.debug("Name: %s" % self.name)
        show.debug("Backend: %s" % self.backend)
        show.debug("Hostname: %s" % self.hostname)
        show.debug("Domain: %s" % self.domain)
        show.debug("IP: %s" % self.ip)

    def set_sudoers(self):
        show('Configuring sudo commands execution in sudoers')
        show('Using root login')
        self.connect(user='******')
        self.cmd('sed -i.bak "s/Defaults    requiretty'
                 '/# Defaults    requiretty/g" /etc/sudoers')
        self.close()

    def start(self):
        self.backend.start(self.name)

    def connect(self, user=locals.USER, pkey_path=locals.PRIVATE_KEY):
        # show('Connecting to %s' % self.fqdn)
        success = False
        timeout = 0

        show('Connecting..')

        while not (success or timeout > 60):
            try:
                self.client = SSHClient()
                self.client.set_missing_host_key_policy(WarningPolicy())
                self.client.connect(self.ip,
                                    username=user,
                                    key_filename=pkey_path)
                success = True
            except UserWarning:
                show.debug('UserWarning ignored')
            except Exception, e:
                show.debug('Caught exception: %s' % e)
                sleep(2)
                timeout += 2

        if timeout > 60:
            raise RuntimeError("Could not connect to the %s" % self.ip)

        show('Connection successful!')
Beispiel #26
0
    def revert_to_snapshot(self, name):
        show.tab()

        self.stop(name)

        show('Restoring the snapshot: %s' % locals.SNAPSHOT_NAME)
        snapshot = self.get_snapshot(name, locals.SNAPSHOT_NAME)
        if not snapshot:
            raise ValueError("Snapshot %s does not exist"
                             % locals.SNAPSHOT_NAME)

        snapshot.restore()

        # VM automatically shuts down after creation
        show('Waiting for VM to reach Down status')
        while self.get_vm(name).status.state != 'down':
            sleep(15)
        show.untab()
        return self.load_vm(name)
Beispiel #27
0
    def set_hostname(self, trust=False, subdomain='', domain=locals.DOMAIN):

        last_ip_segment = self.ip.split('.')[-1]
        hostname = self.hostname

        if trust:
            hostname += '.dom{ip_id}.tbad'.format(
                ip_id=util.normalize_ip_suffix(last_ip_segment))

        hostname += '.' + self.domain

        self.hostname = hostname
        show('Setting hostname to %s' % hostname)

        self.cmd("bash labtool/ipa-set-hostname.sh"
                 " {hostname} {log}".format(hostname=hostname, **self.locals))

        show('Creating DNS record for the VM')
        self.backend.create_record(hostname=self.hostname, ip=self.ip)
Beispiel #28
0
    def revert_to_snapshot(self, name):
        show.tab()

        self.stop(name)

        show('Restoring the snapshot: %s' % locals.SNAPSHOT_NAME)
        snapshot = self.get_snapshot(name, locals.SNAPSHOT_NAME)
        if not snapshot:
            raise ValueError("Snapshot %s does not exist"
                             % locals.SNAPSHOT_NAME)

        snapshot.restore()

        # VM automatically shuts down after creation
        show('Waiting for VM to reach Down status')
        while self.api.vms.get(name).status.state != 'down':
            sleep(1)

        return self.load_vm(name)
Beispiel #29
0
    def connect(self, user=locals.USER):
        # show('Connecting to %s' % self.fqdn)
        success = False
        timeout = 0

        show('Connecting..')

        while not (success or timeout > 60):
            try:
                self.client = SSHClient()
                self.client.set_missing_host_key_policy(WarningPolicy())
                self.client.connect(self.ip, username=user,
                                    key_filename=locals.PRIVATE_KEY)
                success = True
            except UserWarning:
                show.debug('UserWarning ignored')
            except Exception, e:
                show.debug('Caught exception: %s' % e)
                sleep(2)
                timeout += 2
Beispiel #30
0
    def run_tests(self):
        show('Testing:')
        show.tab()

        # run the test suite
        show('Configuring VM for tests')
        self.cmd("bash labtool/ipa-fun-setup-tests.sh"
                 " {log}".format(**self.locals))

        show('Running whole test suite')
        ret = self.cmd("bash labtool/ipa-fun-run-tests.sh"
                       " {log}".format(**self.locals),
           allow_failure=True)

        if ret == 0:
            show('PASSED. See {log} for the logs.'.format(**self.locals))
        else:
            show('FAILED. See {log} for the logs.'.format(**self.locals))

        show.untab()
Beispiel #31
0
    def revert_to_snapshot(self, name):
        show.tab()

        if len(self.get_domain(name).listAllSnapshots()) != 1:
            raise RuntimeError("Incorrect number of snapshots for %s" % name)

        show('Correct number of snapshots for %s' % name)

        snapshot = self.get_domain(name).listAllSnapshots()[0].getName()

        stdout, stderr, rc = util.run([
            'virsh', 'snapshot-revert', '--domain', name, '--snapshotname',
            snapshot, '--force'
        ])

        if rc != 0:
            raise RuntimeError("Could not revert to snapshot for %s" % name)

        show('Revert successful')
        show.untab()
Beispiel #32
0
    def run_tests(self):
        show('Testing:')
        show.tab()

        # run the test suite
        show('Configuring VM for tests')
        self.cmd("bash labtool/ipa-fun-setup-tests.sh"
                 " {log}".format(**self.locals))

        show('Running whole test suite')
        ret = self.cmd("bash labtool/ipa-fun-run-tests.sh"
                       " {log}".format(**self.locals),
                       allow_failure=True)

        if ret == 0:
            show('PASSED. See {log} for the logs.'.format(**self.locals))
        else:
            show('FAILED. See {log} for the logs.'.format(**self.locals))

        show.untab()
Beispiel #33
0
    def set_hostname(self, trust=False, subdomain='',
                     domain=locals.DOMAIN):

        last_ip_segment = self.ip.split('.')[-1]
        hostname = self.hostname

        if trust:
            hostname += '.dom{ip_id}.tbad'.format(
                ip_id=util.normalize_ip_suffix(last_ip_segment))

        hostname += '.' + self.domain

        self.hostname = hostname
        show('Setting hostname to %s' % hostname)

        self.cmd("bash labtool/ipa-set-hostname.sh"
                 " {hostname} {log}".format(hostname=hostname,
                                            **self.locals))

        show('Creating DNS record for the VM')
        self.backend.create_record(hostname=self.hostname, ip=self.ip)
Beispiel #34
0
    def connect(self, user=locals.USER, pkey_path=locals.PRIVATE_KEY):
        # show('Connecting to %s' % self.fqdn)
        success = False
        timeout = 0

        show('Connecting..')

        while not (success or timeout > 60):
            try:
                self.client = SSHClient()
                self.client.set_missing_host_key_policy(WarningPolicy())
                self.client.connect(self.ip,
                                    username=user,
                                    key_filename=pkey_path)
                success = True
            except UserWarning:
                show.debug('UserWarning ignored')
            except Exception, e:
                show.debug('Caught exception: %s' % e)
                sleep(2)
                timeout += 2
Beispiel #35
0
    def prepare_install(self, firewall, selinux, trust, subdomain=''):

        # Set firewall
        if firewall:
            switch = "on"
        else:
            switch = "off"

        show('Setting firewall {setting}'.format(setting=switch))
        self.cmd("bash labtool/ipa-set-firewall.sh"
                 " {setting} {log}".format(setting=switch, **self.locals))

        # set SELinux
        if selinux:
            switch = "on"
        else:
            switch = "off"

        show('Setting SELinux {setting}'.format(setting=switch))
        self.cmd("bash labtool/ipa-set-selinux.sh"
                 " {setting} {log}".format(setting=switch, **self.locals))

        # Apply current workarounds
        show('Applying workarounds for IPA install to work')
        self.cmd("bash labtool/ipa-fun-current-workarounds.sh"
                 " {log}".format(**self.locals))
Beispiel #36
0
    def prepare_install(self, firewall, selinux, trust, subdomain=''):

        # Set firewall
        if firewall:
            switch = "on"
        else:
            switch = "off"

        show('Setting firewall {setting}'.format(setting=switch))
        self.cmd("bash labtool/ipa-set-firewall.sh"
                " {setting} {log}".format(setting=switch, **self.locals))

        # set SELinux
        if selinux:
            switch = "on"
        else:
            switch = "off"

        show('Setting SELinux {setting}'.format(setting=switch))
        self.cmd("bash labtool/ipa-set-selinux.sh"
                 " {setting} {log}".format(setting=switch, **self.locals))

        # Apply current workarounds
        show('Applying workarounds for IPA install to work')
        self.cmd("bash labtool/ipa-fun-current-workarounds.sh"
                 " {log}".format(**self.locals))
Beispiel #37
0
def validateBuild(args):

    available_build_actions = ("branch", "patch", "origin")

    action = args.build[0]

    if args.install and (args.install[1] == "repo" or args.install[1] == "develrepo"):
        raise Exception(
            "First building IPA from sources and then " "installing it from repo makes no sense. " "Think about it."
        )

    if action not in available_build_actions:
        raise ValueError("Unknown build action: {s}. Choose either branch " "or patch.".format(s=action))

    if action == "patch":
        show("Checking whether all given patches exist.")
        vm = VM(locals.NFS_VM, locals.DOMAIN, None, None)

        patches_exist = True

        for patch_id in args.build[1:]:
            num = vm.cmd("bash labtool/ipa-fun-get-patch-name.sh %s" % patch_id, allow_failure=True, silent=True)

            if num != 0:
                show("Inappropriate number of patches matching %s" % patch_id)
                patches_exist = False

            if not patches_exist:
                raise ValueError("One of the given patches could not be " "determined.")

        show("Patch check successful.")
        vm.close()

    elif action == "branch":
        pass  # check that such branch indeed exists
Beispiel #38
0
    def remove_vm(self, name):
        show('Removing the VM:')
        show.tab()

        vm = self.api.vms.get(name)
        if vm is None:
            show('Could not obtain VM. Probably does not exist.')
            return

        try:
            vm.stop()
            show('Waiting for VM to reach Down status')
        except Exception:
            show('Vm is not running.')
            pass

        while self.api.vms.get(name).status.state != 'down':
            sleep(1)

        vm.delete()
        show('{name} was removed.'.format(name=name))
        show.untab()
Beispiel #39
0
    def reboot(self, name):
        show('Rebooting the VM:')
        show.tab()

        vm = self.api.vms.get(name)
        vm.shutdown()

        show('Waiting for VM to reach Down status')
        while self.api.vms.get(name).status.state != 'down':
            sleep(1)

        if self.api.vms.get(name).status.state != 'up':
            show('Starting VM')
            vm.start()
            show('Waiting for VM to reach Up status')
            while self.api.vms.get(name).status.state != 'up':
                sleep(1)

        show('Waiting for all the services to start')
        sleep(60)

        show.untab()
Beispiel #40
0
    def reboot(self, name):
        show('Rebooting the VM:')
        show.tab()

        vm = self.get_vm(name)
        vm.shutdown()

        show('Waiting for VM to reach Down status')
        while self.get_vm_state(name, vm) != 'down':
            vm = self.get_vm(name)
            sleep(15)

        if self.get_vm_state(name, vm) != 'up':
            show('Starting VM')
            vm.start()
            show('Waiting for VM to reach Up status')
            while self.get_vm_state(name) != 'up':
                sleep(15)

        show('Waiting for all the services to start')
        sleep(60)

        show.untab()
Beispiel #41
0
    def reboot(self, name):
        show('Rebooting the VM:')
        show.tab()

        vm = self.get_vm(name)
        vm.shutdown()

        show('Waiting for VM to reach Down status')
        while self.get_vm_state(name, vm) != 'down':
            vm = self.get_vm(name)
            sleep(15)

        if self.get_vm_state(name, vm) != 'up':
            show('Starting VM')
            vm.start()
            show('Waiting for VM to reach Up status')
            while self.get_vm_state(name) != 'up':
                sleep(15)

        show('Waiting for all the services to start')
        sleep(60)

        show.untab()
Beispiel #42
0
    def remove_vm(self, name):
        show('Removing the VM:')
        show.tab()

        try:
            vm = self.get_vm(name)
        except ValueError:
            show('Could not obtain VM. Probably does not exist.')
            return

        try:
            vm.stop()
            show('Waiting for VM to reach Down status')
        except Exception:
            show('Vm is not running.')
            pass

        while self.get_vm_state(name) != 'down':
            sleep(10)

        vm.delete()
        show('{name} was removed.'.format(name=name))
        show.untab()
Beispiel #43
0
    def revert_to_snapshot(self, name):
        show.tab()

        if len(self.get_domain(name).listAllSnapshots()) != 1:
            raise RuntimeError("Incorrect number of snapshots for %s" % name)

        show('Correct number of snapshots for %s' % name)

        snapshot = self.get_domain(name).listAllSnapshots()[0].getName()

        stdout, stderr, rc = util.run(['virsh',
                                       'snapshot-revert',
                                       '--domain',
                                       name,
                                       '--snapshotname',
                                       snapshot,
                                       '--force'
                                     ])

        if rc != 0:
            raise RuntimeError("Could not revert to snapshot for %s" % name)

        show('Revert successful')
        show.untab()
Beispiel #44
0
    def stop(self, name):
        if self.api.vms.get(name).status.state != 'down':
            self.api.vms.get(name).stop()

            show('Waiting for VM %s to reach Down status' % name)
            while self.api.vms.get(name).status.state != 'down':
                sleep(1)

            show('VM %s stopped successfully' % name)
        else:
            show('VM %s is already stopped' % name)
Beispiel #45
0
    def stop(self, name):
        vm = self.get_vm(name)
        if self.get_vm_state(name, vm) != 'down':
            vm.stop()

            show('Waiting for VM %s to reach Down status' % name)
            while self.get_vm_state(name) != 'down':
                sleep(1)

            show('VM %s stopped successfully' % name)
        else:
            show('VM %s is already stopped' % name)
Beispiel #46
0
    def stop(self, name):
        vm = self.get_vm(name)
        if self.get_vm_state(name, vm) != 'down':
            vm.stop()

            show('Waiting for VM %s to reach Down status' % name)
            while self.get_vm_state(name) != 'down':
                sleep(5)

            show('VM %s stopped successfully' % name)
        else:
            show('VM %s is already stopped' % name)
Beispiel #47
0
    def check_arguments(self, name, template, connect):

        if connect:
            show('Checking whether given VM exists')
            self.get_vm(name)
        else:
            show('Checking whether given template exists')
            if util.get_latest_template(self.api, template) is None:
                raise ValueError('Template %s does not exist' % template)

            show('Checking whether given VM name is not used')
            if self.get_vm(name):
                raise ValueError('Given VM name %s is already used' % name)
Beispiel #48
0
    def check_arguments(self, name, template, connect):

        if connect:
            show('Checking whether given VM exists')
            self.get_vm(name)
        else:
            show('Checking whether given template exists')
            if util.get_latest_template(self.api, template) is None:
                raise ValueError('Template %s does not exist' % template)

            show('Checking whether given VM name is not used')
            if self.get_vm(name):
                raise ValueError('Given VM name %s is already used' % name)
Beispiel #49
0
    def make_snapshot(self, name):
        # Delete all the snapshots for this VM
        for snap in self.get_domain(name).listAllSnapshots():
            show('Deleting snapshot %s' % snap.getName())
            snap.delete()

        show('Creating new snapshot..')
        stdout, stderr, rc = util.run(
            ['virsh', 'snapshot-create', '--domain', name])

        show('Created!')

        if rc != 0:
            raise RuntimeError("Could not create snapshot for %s" % name)
Beispiel #50
0
    def create_vm(self, name, memory=locals.MEMORY,
                  template=locals.TEMPLATE_NAME):
        """Creates a VM from given parameters and returns its hostname."""

        show('VM creation:')
        show.tab()

        # Set VM's parameters as defined in locals.py
        pars = params.VM(name=name,
                         memory=memory,
                         cluster=self.api.clusters.get(self.cluster),
                         template=util.get_latest_template(self.api, template))

        # locals.HOST can be used to enforce usage of a particular host
        if locals.HOST is not None:
            pars.set_placement_policy(params.VmPlacementPolicy(
                                         host=self.api.hosts.get(locals.HOST),
                                         affinity='pinned'))

        # Check whether the template exist, if so, create the VM
        if util.get_latest_template(self.api, template) is None:
            raise ValueError('Template does not exist.')
        vm = self.api.vms.add(pars)
        show('VM was created from Template successfully')

        # Set corret permissions so that VM can be seen in WebAdmin
        admin_vm_manager_perm = params.Permission(
                                    role=self.api.roles.get('UserVmManager'),
                                    user=self.api.users.get('admin'))

        vm.permissions.add(admin_vm_manager_perm)
        show('Permissions for admin to see VM set')

        # VM automatically shuts down after creation
        show('Waiting for VM to reach Down status')
        while self.api.vms.get(name).status.state != 'down':
            sleep(1)

        return self.load_vm(name)
Beispiel #51
0
    def make_snapshot(self, name):
        # Delete all the snapshots for this VM
        for snap in self.get_domain(name).listAllSnapshots():
            show('Deleting snapshot %s' % snap.getName())
            snap.delete()

        show('Creating new snapshot..')
        stdout, stderr, rc = util.run(['virsh',
                                       'snapshot-create',
                                       '--domain',
                                       name
                                     ])

        show('Created!')

        if rc != 0:
            raise RuntimeError("Could not create snapshot for %s" % name)
Beispiel #52
0
def validateBuild(args):

    available_build_actions = ('branch', 'patch', 'origin')

    action = args.build[0]

    if args.install and (args.install[1] == 'repo'
                         or args.install[1] == 'develrepo'):
        raise Exception('First building IPA from sources and then '
                        'installing it from repo makes no sense. '
                        'Think about it.')

    if action not in available_build_actions:
        raise ValueError('Unknown build action: {s}. Choose either branch '
                         'or patch.'.format(s=action))

    if action == 'patch':
        show('Checking whether all given patches exist.')
        vm = VM(locals.NFS_VM, locals.DOMAIN, None, None)

        patches_exist = True

        for patch_id in args.build[1:]:
            num = vm.cmd('bash labtool/ipa-fun-get-patch-name.sh %s' %
                         patch_id,
                         allow_failure=True,
                         silent=True)

            if num != 0:
                show('Inappropriate number of patches matching %s' % patch_id)
                patches_exist = False

            if not patches_exist:
                raise ValueError("One of the given patches could not be "
                                 "determined.")

        show('Patch check successful.')
        vm.close()

    elif action == 'branch':
        pass  # check that such branch indeed exists
Beispiel #53
0
    def make_snapshot(self, name):
        show("Deleting all previous snapshots")
        show.tab()

        self.shutdown(name)

        for snap in self.api.vms.get(name).snapshots.list():
            if snap.get_description() != 'Active VM':
                show("Deleting snapshot: %s" % snap.get_description())
                snap.delete()

        while len(self.api.vms.get(name).snapshots.list()) > 1:
            show("Waiting for the deletion to complete.")
            sleep(5)

        show.untab()

        try:
            snapshot = params.Snapshot(description=locals.SNAPSHOT_NAME,
                                       vm=self.api.vms.get(name))
            self.api.vms.get(name).snapshots.add(snapshot)
            show("Creating a Snapshot")
            show('Waiting for Snapshot creation to finish')
            while self.api.vms.get(name).status.state == 'image_locked':
                sleep(5)
        except Exception as e:
            show('Failed to Create a Snapshot:\n%s' % str(e))

        if self.get_snapshot(name, locals.SNAPSHOT_NAME):
            show("Snapshot created: %s" % locals.SNAPSHOT_NAME)

        sleep(15)
        show.untab()
Beispiel #54
0
 def create_record(self, hostname, ip):
     show('Creating record in /etc/hosts')
     util.run(['sudo', 'sed', '-i', '/%s/d' % ip, '/etc/hosts'])
     with open('/etc/hosts', 'a') as f:
         f.write('{ip} {name}'.format(ip=ip, name=hostname))
     util.run(['sudo', 'systemctl', 'restart', 'libvirtd'])
Beispiel #55
0
 def clean_log(self):
     show('Removing previous log file for this VM')
     self.cmd("rm -f %s" % self.locals['log_file'])
Beispiel #56
0
 def print_out(line):
     if silent:
         show(line.strip())
     else:
         show.debug(line.strip())
Beispiel #57
0
 def check_services(self):
     ret = self.cmd("bash labtool/ipa-fun-check-services.sh",
                    allow_failure=True)
     if ret:
         show('Service check failed.')
Beispiel #58
0
    vm.connect()

    # Install selected packages from ipa-devel repo
    if args.ipadevel:
        vm.install_devel_packages(packages=args.ipadevel)

    show.untab()

    if args.build:
        vm.build(args.build)

    # Setup a new hostname
    vm.set_hostname(trust=args.trust)

    if args.install:
        show('Preparing:')

        # Installs FreeIPA packages either from local source or from repository
        vm.install_packages(args.install)

        if args.install[0] == 'ipa':
            vm.prepare_install(args.firewall, args.selinux, args.trust)
            show.untab()
            vm.install_ipa()

            show('Post-install configuration:')
            show.tab()
            vm.check_services()
            show.untab()

            if args.test:
Beispiel #59
0
def main(args):
    show('***** Welcome to LabTool *****')
    show('')

    if locals.REQUIRE_ROOT:
        util.require_root()

    BackendClass = getattr(backends, locals.BACKEND)

    show('Estabilishing connection to %s lab' % locals.BACKEND)

    backend = BackendClass(url=locals.URL,
                           username=locals.USERNAME,
                           password=locals.PASSWORD,
                           cluster_name=locals.CLUSTER_NAME,
                           ca_file=locals.CA_FILE)

    # We need to remove the VM before running check_arguments()
    #if args.remove:
    #    backend.remove_vm(args.name)

    #if not args.local:
    #    backend.check_arguments(args.name, args.template, args.connect)

    #show.untab()

    show('Setting up: %s' % args.name)
    show.tab()

    #elif args.local:
    #    hostname = args.name.split('.')[0]
    #    locals.DOMAIN = 'ipa.com'
    #else:

    if backend.exists(args.name) and not args.connect:
        show('VM exists, reverting back to snapshot')
        try:
            backend.revert_to_snapshot(args.name)
        except ValueError as e:
            if args.remove:
                show(str(e) + ': removing the whole VM')
                backend.remove_vm(args.name)
            else:
                raise Exception(
                    str(e) + ': use --remove if you want '
                    'to remove whole VM')

    if not backend.exists(args.name):
        if args.connect:
            raise Exception(
                "You requested --connect but specified VM does not "
                "exist, exiting.")

        vm = backend.create_vm(args.name,
                               template=args.template or locals.TEMPLATE_NAME)
    else:
        vm = backend.load_vm(args.name)

    vm.connect()
    vm.setup_logging_path()

    monitor(vm.hostname, vm.domain)

    if args.workspace or not vm.detect_workspace():
        vm.create_workspace()
    vm.update_workspace()

    backend.make_snapshot(args.name)
    while True:
        try:
            vm.start()
            break
        except Exception, e:
            # vm.start() can fail if disks are not in state 'down'
            show("Skipping error %s" % str(e))
            time.sleep(5)
            pass
Beispiel #60
0
# Import all module
import printer as pr
import math

pr.show('from app')
print('pi:', math.pi)

# Import method from module
from printer import call
from math import e

call('from app')
print('e:', e)

# Import all methods from module
from printer import *
from math import *

view('from app')
print('tau:', tau)