def create_dir(path, **kwargs) -> bool: """Validate and attempt to create a directory, if it does not exist.""" # If input path is not a path object, try to make it one if not isinstance(path, Path): try: path = Path(path) except TypeError: error("{p} is not a valid path", p=path) # If path does not exist, try to create it if not path.exists(): try: path.mkdir(**kwargs) except PermissionError: error( "{u} does not have permission to create {p}. Try running with sudo?", u=os.getlogin(), p=path, ) # Verify the path was actually created if path.exists(): success("Created {p}", p=path) # If the path already exists, inform the user elif path.exists(): info("{p} already exists", p=path) return True
def move_files(src, dst, files): # noqa: C901 """Move iterable of files from source to destination. Arguments: src {Path} -- Current directory of files dst {Path} -- Target destination directory files {Iterable} -- Iterable of files """ if not isinstance(src, Path): try: src = Path(src) except TypeError: error("{p} is not a valid path", p=src) if not isinstance(dst, Path): try: dst = Path(dst) except TypeError: error("{p} is not a valid path", p=dst) if not isinstance(files, Iterable): error( "{fa} must be an iterable (list, tuple, or generator). Received {f}", fa="Files argument", f=files, ) for path in (src, dst): if not path.exists(): error("{p} does not exist", p=str(path)) migrated = 0 for file in files: dst_file = dst / file.name if not file.exists(): error("{f} does not exist", f=file) try: if dst_file.exists(): warning("{f} already exists", f=dst_file) else: shutil.copyfile(file, dst_file) migrated += 1 info("Migrated {f}", f=dst_file) except Exception as e: error("Failed to migrate {f}: {e}", f=dst_file, e=e) if migrated == 0: warning("Migrated {n} files", n=migrated) elif migrated > 0: success("Successfully migrated {n} files", n=migrated) return True
def system_info(): """Create a markdown table of various system information. Returns: {str}: Markdown table """ # Project from hyperglass.util.system_info import get_system_info values = get_system_info() def _code(val): return f"`{str(val)}`" def _bold(val): return f"**{str(val)}**" def _suffix(val, suffix): return f"{str(val)}{str(suffix)}" columns = ( ("hyperglass Version", _bold), ("hyperglass Path", _code), ("Python Version", _code), ("Platform Info", _code), ("CPU Info", None), ("Logical Cores", _code), ("Physical Cores", _code), ("Processor Speed", "GHz"), ("Total Memory", " GB"), ("Memory Utilization", "%"), ("Total Disk Space", " GB"), ("Disk Utilization", "%"), ) md_table_lines = ("| Metric | Value |", "| ------ | ----- |") for i, metric in enumerate(values): title, mod = columns[i] value = metric if isinstance(mod, str): value = _suffix(value, mod) elif callable(mod): value = mod(value) md_table_lines += (f"| **{title}** | {value} |", ) md_table = "\n".join(md_table_lines) info("Please copy & paste this table in your bug report:\n") echo(md_table + "\n") return True
def make_systemd(user): """Generate a systemd file based on the local system. Arguments: user {str} -- User hyperglass needs to be run as Returns: {str} -- Generated systemd template """ # Third Party import distro template = """ [Unit] Description=hyperglass After=network.target Requires={redis_name} [Service] User={user} Group={group} ExecStart={hyperglass_path} start [Install] WantedBy=multi-user.target """ known_rhel = ("rhel", "centos") distro = distro.linux_distribution(full_distribution_name=False) if distro[0] in known_rhel: redis_name = "redis" else: redis_name = "redis-server" hyperglass_path = shutil.which("hyperglass") if not hyperglass_path: hyperglass_path = "python3 -m hyperglass.console" warning("hyperglass executable not found, using {h}", h=hyperglass_path) systemd = template.format(redis_name=redis_name, user=user, group=user, hyperglass_path=hyperglass_path) info(f"Generated systemd service:\n{systemd}") return systemd
def migrate_systemd(source, destination): """Copy example systemd service file to /etc/systemd/system/.""" import os import shutil basefile, extension = os.path.splitext(source) newfile = os.path.join(destination, basefile) try: status("Migrating example systemd service...") if os.path.exists(newfile): info("'{f}' already exists", f=str(newfile)) else: shutil.copyfile(source, newfile) except Exception as e: error("Error migrating example systemd service: {e}", e=e) success("Successfully migrated systemd service to: {f}", f=str(newfile))
def migrate_config(config_dir): """Copy example config files and remove .example extensions.""" status("Migrating example config files...") import shutil examples = Path(PROJECT_ROOT / "examples").glob("*.yaml.example") if not isinstance(config_dir, Path): config_dir = Path(config_dir) if not config_dir.exists(): error("'{d}' does not exist", d=str(config_dir)) migrated = 0 for file in examples: target_file = config_dir / file.with_suffix("").name try: if target_file.exists(): info("{f} already exists", f=str(target_file)) else: shutil.copyfile(file, target_file) migrated += 1 info("Migrated {f}", f=str(target_file)) except Exception as e: error("Failed to migrate '{f}': {e}", f=str(target_file), e=e) if migrated == 0: info("Migrated {n} example config files", n=migrated) elif migrated > 0: success("Successfully migrated {n} example config files", n=migrated)