Example #1
0
def test_is_snapshot(zpool, test_dataset):
    snapname = f"pyzfscmds-{datetime.datetime.now().isoformat()}"
    dataset = "/".join([zpool, test_dataset])

    pyzfscmds.cmd.zfs_snapshot(dataset, snapname)

    assert zfs_utility.is_snapshot(f"{dataset}@{snapname}")
Example #2
0
def get_clones(root_dataset: str, existing: Optional[str]) -> list:

    parent_dataset = zfs_utility.dataset_parent(root_dataset)

    clone_data = []
    list_dataset = None  # Dataset we are listing clones under

    if existing:
        existing_dataset = f"{parent_dataset}/{existing}"
        if zfs_utility.is_snapshot(existing_dataset):
            snap_suffix = existing_dataset.rsplit('@', 1)[-1]
            list_dataset = zfs_utility.snapshot_parent_dataset(
                existing_dataset)
        else:
            if zfs_utility.dataset_exists(existing_dataset):
                snap_suffix = zedenv.lib.be.snapshot(existing, parent_dataset)
                list_dataset = f"{parent_dataset}/{existing}"
            else:
                ZELogger.log(
                    {
                        "level": "EXCEPTION",
                        "message":
                        f"The dataset {existing_dataset} doesn't exist."
                    },
                    exit_on_error=True)
    else:
        snap_suffix = zedenv.lib.be.snapshot(
            zfs_utility.dataset_child_name(root_dataset), parent_dataset)
        list_dataset = root_dataset

    clones = None
    try:
        clones = pyzfscmds.cmd.zfs_list(list_dataset,
                                        recursive=True,
                                        columns=["name"])
    except RuntimeError as e:
        ZELogger.log(
            {
                "level": "EXCEPTION",
                "message": f"Failed to list datasets under {root_dataset}."
            },
            exit_on_error=True)

    for c in [line for line in clones.splitlines()]:

        if zfs_utility.dataset_exists(f"{c}@{snap_suffix}",
                                      zfs_type="snapshot"):
            if c == list_dataset:
                child = ""
            else:
                child = zfs_utility.dataset_child_name(c)
            clone_props = zedenv.lib.be.properties(c, [["canmount", "off"]])
            clone_data.append({
                "snapshot": f"{c}@{snap_suffix}",
                "properties": clone_props,
                "datasetchild": child
            })
        else:
            ZELogger.log(
                {
                    "level": "EXCEPTION",
                    "message": f"Failed to find snapshot {c}@{snap_suffix}."
                },
                exit_on_error=True)

    return clone_data
Example #3
0
def test_is_not_snapshot(snapname):
    assert zfs_utility.is_snapshot(snapname) is False
Example #4
0
def configure_boot_environment_list(be_root: str, columns: list,
                                    scripting: Optional[bool]) -> list:
    """
    Converts a list of boot environments with their properties to be printed
    to a list of column separated strings.
    """
    boot_environments = zedenv.lib.be.list_boot_environments(be_root, columns)
    """
    Add an active column.
    The other columns were ZFS properties, and the active column is not,
    which is why they were added separately
    """

    unformatted_boot_environments = []

    for env in boot_environments:
        if not zfs_utility.is_snapshot(env['name']):
            # Add name column
            boot_environment_entry = [
                zfs_utility.dataset_child_name(env['name'])
            ]

            # Add active column
            active = ""
            if pyzfscmds.system.agnostic.mountpoint_dataset(
                    "/") == env['name']:
                active = "N"
            if zedenv.lib.be.bootfs_for_pool(
                    zedenv.lib.be.dataset_pool(env['name'])) == env['name']:
                active += "R"
            boot_environment_entry.append(active)

            # Add mountpoint
            dataset_mountpoint = pyzfscmds.system.agnostic.dataset_mountpoint(
                env['name'])
            if dataset_mountpoint:
                boot_environment_entry.append(dataset_mountpoint)
            else:
                boot_environment_entry.append("-")

            # Add origin column
            if 'origin' in env:
                origin_list = env['origin'].split("@")
                origin_ds_child = origin_list[0].rsplit('/', 1)[-1]

                if zfs_utility.is_snapshot(env['origin']):
                    origin = f'{origin_ds_child}@{origin_list[1]}'
                else:
                    origin = env['origin']

                boot_environment_entry.append(origin)

            # Add creation
            if 'creation' in env:
                boot_environment_entry.append(env['creation'])

            unformatted_boot_environments.append(boot_environment_entry)

    columns.insert(1, 'active')
    columns.insert(2, 'mountpoint')

    # Set minimum column width to name of column plus one
    widths = [len(l) + 1 for l in columns]

    # Check for largest column entry and use as width.
    for ube in unformatted_boot_environments:
        for i, w in enumerate(ube):
            if len(w) > widths[i]:
                widths[i] = len(w)

    # Add titles
    formatted_boot_environments = []

    if not scripting:
        titles = [t.title() for t in columns]
        formatted_boot_environments.append(
            format_boot_environment(titles, scripting, widths))

    # Add entries
    formatted_boot_environments.extend([
        format_boot_environment(b, scripting, widths)
        for b in unformatted_boot_environments
    ])

    return formatted_boot_environments