Exemple #1
0
    def test_creates_real_fresh_directory(self):
        stored_text = factory.make_string()
        filename = factory.make_name("test-file")
        with tempdir() as directory:
            self.assertThat(directory, DirExists())
            write_text_file(os.path.join(directory, filename), stored_text)
            retrieved_text = read_text_file(os.path.join(directory, filename))
            files = os.listdir(directory)

        self.assertEqual(stored_text, retrieved_text)
        self.assertEqual([filename], files)
Exemple #2
0
    def load_pem_file(self, pem_file):
        """Load a PEM file. Returning `OpenSSL.crypto.X509` object and the
        contents of the file.

        :param pem_file: file to load
        """
        pem_data = read_text_file(pem_file)
        try:
            cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
                                                   pem_data)
        except OpenSSL.crypto.Error as err:
            raise WinRMX509Error("Failed to load certificate: %s" % err)
        return cert, pem_data
Exemple #3
0
def is_pid_in_container(pid, proc_path="/proc"):
    """Return True if the `pid` is running in a container.

    This should only be called when not running in a container itself, because
    if this process is running in a container than the `pid` process is
    sure to be running in the container as well.
    """
    cgroup_path = os.path.join(proc_path, str(pid), "cgroup")
    cgroup_info = read_text_file(cgroup_path)
    for line in cgroup_info.splitlines():
        id_num, subsytem, hierarchy = line.split(":", 2)
        if hierarchy.startswith("/lxc") or "docker" in hierarchy:
            return True
    return False
Exemple #4
0
def meta_contains(storage, content):
    """Does the `maas.meta` file match `content`?

    If the file's contents match the latest data, there is no need to update.

    The file's timestamp is also updated to now to reflect the last time
    that this import was run.
    """
    current_meta = os.path.join(storage, "current", "maas.meta")
    exists = os.path.isfile(current_meta)
    if exists:
        # Touch file to the current timestamp so that the last time this
        # import ran can be determined.
        os.utime(current_meta, None)
    return exists and content == read_text_file(current_meta)
Exemple #5
0
def get_lastest_fixed_address(lease_path):
    """Return the lastest fixed address assigned in `lease_path`."""
    try:
        lease_contents = read_text_file(lease_path)
    except FileNotFoundError:
        return None

    matches = re_entry.findall(lease_contents)
    if len(matches) > 0:
        # Get the IP address assigned to the interface.
        last_lease = matches[-1]
        for line in last_lease.splitlines():
            line = line.strip()
            if len(line) > 0:
                statement, value = line.split(" ", 1)
                if statement in ["fixed-address", "fixed-address6"]:
                    return value.split(";", 1)[0].strip()
    # No matches or unable to identify fixed-address{6} in the last match.
    return None
Exemple #6
0
def get_dhclient_info(proc_path="/proc"):
    """Return dictionary mapping interfaces to assigned address from
    dhclient.
    """
    dhclient_pids = get_running_pids_with_command("dhclient",
                                                  proc_path=proc_path)
    dhclient_info = {}
    for pid in dhclient_pids:
        cmdline = read_text_file(os.path.join(proc_path, str(pid),
                                              "cmdline")).split("\x00")
        if "-lf" in cmdline:
            idx_lf = cmdline.index("-lf")
            lease_path = cmdline[idx_lf + 1]  # After '-lf' option.
            interface_name = cmdline[-2]  # Last argument.
            ip_address = get_lastest_fixed_address(lease_path)
            if (ip_address is not None and len(ip_address) > 0
                    and not ip_address.isspace()):
                dhclient_info[interface_name] = ip_address
    return dhclient_info
Exemple #7
0
def get_shared_secret_from_filesystem():
    """Load the secret from the filesystem.

    `get_shared_secret_filesystem_path` defines where the file will be
    written. If the directory does not already exist, this will attempt to
    create it, including all parent directories.

    :return: A byte string of arbitrary length.
    """
    secret_path = get_shared_secret_filesystem_path()
    makedirs(dirname(secret_path), exist_ok=True)
    with FileLock(secret_path).wait(10):
        # Load secret from the filesystem, if it exists.
        try:
            secret_hex = read_text_file(secret_path)
        except IOError as e:
            if e.errno == errno.ENOENT:
                return None
            else:
                raise
        else:
            return to_bin(secret_hex)
Exemple #8
0
def load_builtin_scripts():
    for script in BUILTIN_SCRIPTS:
        script_content = read_text_file(script.script_path)
        try:
            script_in_db = Script.objects.get(name=script.name)
        except Script.DoesNotExist:
            Script.objects.create(name=script.name,
                                  title=script.title,
                                  description=script.description,
                                  tags=script.tags,
                                  script_type=script.script_type,
                                  script=script_content,
                                  comment="Created by maas-%s" %
                                  get_maas_version(),
                                  timeout=script.timeout,
                                  destructive=script.destructive,
                                  default=True)
        else:
            if script_in_db.script.data != script_content:
                # Don't add back old versions of a script. This prevents two
                # connected regions with different versions of a script from
                # fighting with eachother.
                no_update = False
                for vtf in script_in_db.script.previous_versions():
                    if vtf.data == script_content:
                        # Don't update anything if we detect we have an old
                        # version of the builtin scripts
                        no_update = True
                        break
                if no_update:
                    continue
                script_in_db.script = script_in_db.script.update(
                    script_content, "Updated by maas-%s" % get_maas_version())
            script_in_db.title = script.title
            script_in_db.description = script.description
            script_in_db.script_type = script.script_type
            script_in_db.destructive = script.destructive
            script_in_db.save()
 def test_removes_hosts_from_leases_file(self):
     path = self.make_file(contents=LEASES_FILE_WITH_HOSTS)
     call_and_check(["%s/scripts/maas-dhcp-helper" % root, "clean", path])
     self.assertEquals(LEASES_FILE_WITHOUT_HOSTS, read_text_file(path))
Exemple #10
0
 def read_secret(self):
     secret_path = security.get_shared_secret_filesystem_path()
     secret_hex = read_text_file(secret_path)
     return security.to_bin(secret_hex)
Exemple #11
0
 def test_defaults_to_utf8(self):
     # Test input: "registered trademark" (ringed R) symbol.
     text = "\xae"
     self.assertEqual(
         text, read_text_file(self.make_file(contents=text.encode("utf-8")))
     )
Exemple #12
0
 def test_reads_file(self):
     text = factory.make_string()
     self.assertEqual(text, read_text_file(self.make_file(contents=text)))
Exemple #13
0
def read_snippet(snippets_dir, name, encoding="utf-8"):
    """Read a snippet file.

    :rtype: `unicode`
    """
    return read_text_file(os.path.join(snippets_dir, name), encoding=encoding)