Exemple #1
0
def yaml_write(path, obj):
    try:
        with open(path, 'w') as hdl:
            yaml.dump(obj, hdl, default_flow_style=False)
    except IOError as err:
        raise error.ExecError("Could not write yaml file: {}".format(err))
    except yaml.YAMLError as err:
        raise error.ExecError("Could not write yaml file: {}".format(err))
Exemple #2
0
 def get_groups(self):
     try:
         with self.open('/etc/group', 'r') as source:
             return util.parse_groups(
                 [line.rstrip('\n') for line in source])
     except OSError as err:
         raise error.ExecError("Reading /etc/group failed.")
Exemple #3
0
    def spawn(self):
        domain = self.get_domain(self.entity(), raise_exception=False)
        if domain is not None:
            return

        self.say("spawning...")
        self.xml_dfn = {'devices': ''}
        self.each_attribute("spawn")

        caps = self.get_capabilities()
        self.add_meta('created', time())
        self.add_meta('definition', self.config("runtime/definition"))
        self.add_meta('user', self.io().user())

        xml = self.template('node.xml')
        self.xml_dfn['name'] = self.entity()
        self.xml_dfn['meta'] = self._generate_meta_xml()
        self.xml_dfn.update(caps)

        self.finalize()
        self.each_attribute("after_spawn")
        try:
            self.virt().defineXML(xml.safe_substitute(self.xml_dfn))
        except libvirt.libvirtError as err:
            raise error.ExecError("Could not start {}: {}".format(
                self.entity(), str(err)))
Exemple #4
0
    def run_playbook(self, inventory, playbook, args=[], env={}):
        executable = self.io().which(self.ansible_executable())

        env["host_key_checking"] = False

        args.append("-i")
        args.append(inventory)
        args.append("--extra-vars=" + yaml.dump(env).strip())

        try:
            process = subprocess.Popen([executable] + args + [playbook],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       stdin=subprocess.PIPE,
                                       shell=False)

            recap = []
            has_recap = False
            is_verbose = self.is_verbose()
            is_parallel = self.is_parallel()

            for output in iter(process.stdout.readline, ""):
                line = output.decode('utf-8').strip()

                if (not is_parallel) or is_verbose:
                    for l in line.split("\\n"):
                        self.say("| " + l)
                else:
                    if line.startswith("PLAY RECAP *"):
                        has_recap = True
                    if has_recap:
                        recap.append(line)

            if has_recap:
                map(self.say, recap)

            if process.wait() != 0:
                return False
            return True

        except OSError as e:
            raise error.ExecError(["ansible failed:", e.__str__()])

        except KeyError as e:
            raise error.ExecError(
                ["ansible called with invalid arguments:",
                 __str__(e)])
Exemple #5
0
 def copy(self, source_path, dest_path):
     size = os.path.getsize(source_path)
     try:
         with open(source_path, 'rb') as source:
             with open(dest_path, 'wb') as dest:
                 self._copy_stream(size, source, dest)
     except OSError as err:
         raise error.ExecError(source_path,
                               "Could not copy file: {}".format(err))
Exemple #6
0
 def _generate_hashes(self):
     try:
         self.say("generate image checksum...")
         md5_hash    = hashlib.md5()
         sha256_hash = hashlib.sha256()
         with open(self._image_path(), 'rb') as hdl:
             buf = hdl.read(65536)
             while len(buf) > 0:
                 md5_hash.update(buf)
                 sha256_hash.update(buf)
                 buf = hdl.read(65536)
         return (md5_hash.hexdigest(), sha256_hash.hexdigest())
     except IOError as err:
         raise error.ExecError("Could not create validation hashes")
Exemple #7
0
        def _start_guestfs():
            try:
                path = self.get_tmp_volume_path()
                guest = guestfs.GuestFS()

                guest.add_drive(path)
                guest.launch()
                guest.mount("/dev/sda1", "/")

                if guest.exists('/etc/sysconfig/selinux'):
                    guest.get_selinux = lambda: 1
            except RuntimeError as e:
                raise error.ExecError("guestfs error: {}".format(e))

            return guest
Exemple #8
0
    def _get_delayed_network(self, name):
        network = self.get_network(name, raise_exception=False)

        if not network:
            if not self.has_component("network", name):
                raise error.NotFound("Could not find network ({})"
                                     .format(name))
            # wait for network to become ready
            for _ in range(self.global_get("global/retry_network", 20)):
                network = self.get_network(name, raise_exception=False)

                if network:
                    return network
                sleep(self.global_get("global/wait", 3))

            raise error.ExecError("Network {} has not become ready in "
                                  "time. Giving up".format(name))
        return network
Exemple #9
0
    def used_pool(self):
        pool = self.get_pool(self.settings(), raise_exception=False)

        if not pool:
            if not self.has_component("pool", self.settings()):
                raise error.NotFound("pool {} does not exist.")

            for i in range(self.global_get("global/retry_pool", 20)):
                pool = self.get_pool(name, raise_exception=False)
                if pool:
                    break
                self.counted(
                    i, "Waiting for pool {} to become ready.".format(
                        self.settings()))
                sleep(self.global_get("global/wait", 3))

            raise error.ExecError("Coult not start pool {}!".format(
                self.settings()))
        return pool
Exemple #10
0
    def spawn(self):
        network = self.get_network(self.entity(), raise_exception=False)

        if network is not None:
            return

        self.say("creating...")
        self.each_attribute("spawn")

        replace = {'config': "\n".join(self.xml_net), 'name': self.entity()}

        tpl = self.template('network.xml')
        xml = tpl.safe_substitute(replace)

        # FIXME: Handle case where the network already is used by another
        # device
        try:
            self.virt().networkDefineXML(xml)
            net = self.get_network(self.entity())
            self.success("created!")
            return net
        except libvirt.libvirtError as err:
            raise error.ExecError("Could not define {}: {}".format(
                self.entity(), err))
Exemple #11
0
    def spawn(self):
        self.say("spawning...")
        self.xml_pool = []
        self.each_attribute("spawn")

        pool_tpl = self.template("pool.xml")
        xml = pool_tpl.safe_substitute({
            "type": self.attributes()[0].pool_type,
            "name": self.entity(),
            "config": "\n".join(self.xml_pool)
        })

        self.finalize()
        try:
            if self.get_attribute("persistent").is_persistent():
                self.virt().storagePoolDefineXML(xml)
            else:
                self.warn("is beging created as non-persistent pool storage")
                self.virt().storagePoolCreateXML(xml)
            pool = self.get_pool(self.entity())
            self.each_attribute("after_spawn")
            return pool
        except libvirt.libvirtError as err:
            raise error.ExecError("Could create pool {}: {}".format(self.entity(), err))