Top-level module for Wtforg Library.

class FakedProcessResult(stdout='', stderr='', returncode=0)[source]

Bases: object

Faked process result.

class Commander(opts=None)[source]

Bases: Options

Base class for subprocess management.

run_command(args, **kwargs)[source]

Run a command.

Return type:

Union[CompletedProcess[str], FakedProcessResult]

Parameters

argsTuple[str, …]

List of arguments to pass to subprocess

kwargsbool

Keyword arguments, see below

Keyword Arguments

alwaysbool

If True, always run the command, even if isnoop() returns True (default: False)

checkbool

If True, check the return code of the command and raise CalledProcessError if it is not 0 (default: True)

Returns

CommanderResult

CompletedProcess or FakedProcessResult

Top-level module for wtforglib Library.

ensure_directory(target, perm=493)[source]

Creates a directory if it doesn’t exist.

Return type:

bool

Parameters

targetFspec

The path to the target directory

permint Optional

The mode to use if creation needed

Returns

bool

True if directory exists

Raises

NotADirectoryError

if target exists, but not a directory

verify_directory(dspec, ex=False)[source]

Verify that a directory exits and is writable.

Return type:

Tuple[bool, str]

Parameters

dspecFspec

Pathlike object specifying the directory

exbool, optional

When True exceptions are raised, by default False

Returns

Tuple[bool, str]

When ex is False the status is returned

Raises

error

NotADirectoryError, FileNotFoundError or other exception is raised on failure when ex is True

delete_empty_dirs(path)[source]

Delete empty directories in the given path recursively.

Return type:

int

Parameters

pathFspec

The given path to walk through

Returns

int

Number of directories deleted

prune_older_files(path, max_days)[source]

Delete files recursively in path if they are older than days.

Return type:

int

Parameters

pathFspec

Path to the folder to prune

max_daysint

Number of days to keep

Returns

int

Number of files pruned

prune_older_files_empty_dir(path, max_days)[source]

Delete files recursively in path if they are older than days, delete empty dirs.

Return type:

int

Parameters

pathFspec

Path to the folder to prune

max_daysint

Number of days to keep

Returns

int

Number of items removed

Top-level module for Wtforg Library.

exception ShellError[source]

Bases: Exception

Raised when subprocess resultcode not 0.

raise_filenotfound(filenm)[source]

Raises a FileNotFoundError execption for the given filenm.

Return type:

NoReturn

Parameters

filenmUnion[str,PathLike[str]]

The yaml file to load

Raises

FileNotFoundError

FileNotFoundError

raise_filenotfound_if(filenm)[source]

Call raise_filenotfound for the given filenm if it doesn’t exist.

Return type:

None

Parameters

filenmFspec

Name of the file to test

Top-level module for wtforglib Library.

load_yaml_file(file_spec, missing_ok=True)[source]

Loads a yaml file.

Return type:

Dict[str, Any]

Parameters

file_specFspec

The yaml file to load

missing_okbool optional default True

When False and file does not exist raises FileNotFound exception

Returns

StrAnyDict

Representing contents of file_spec

safe_write_yaml_file(file_spec, src_data, **kwargs)[source]

Writes src_data to a file in a yaml format.

Return type:

bool

Parameters

file_specFspec

The yaml filename to write to

src_dataStrAnyDict

The data to write to a file

kwargsOptional

Args passed to yaml.safe_dump

Returns

bool

True if file exists else False

write_yaml_file(file_spec, src_data, encoding='utf-8')[source]

Writes src_data to a file in a yaml format.

Return type:

bool

Parameters

file_specFspec

The yaml filename to write to

src_dataStrAnyDict

The data to write to a file

encodingstr Optional

encoding default ‘utf-8’

Returns

bool

True if file exists else False

load_json_file(file_spec, missing_ok=True)[source]

Loads a json file.

Return type:

Dict[str, Any]

Parameters

file_specFspec

The yaml file to load

missing_okbool optional default True

When False and file does not exist raises FileNotFound exception

Returns

StrAnyDict

Representing contents of file_spec

write_json_file(file_spec, src_data, indent=2)[source]

Writes src_data to a file in a json format.

Return type:

bool

Parameters

file_specFspec

The json filename to write to

src_dataStrAnyDict

The data to write to a file

indentint Optional

The number of spaces to indent

Returns

bool

True if file exists else False

Top-level module for wtforglib Library.

set_file_perms(tgt, mode)[source]

Sets the owner group permissions for a posix file if needed.

Return type:

bool

Parameters

tgtFspec

Path to the target file

modestr

Mode of the target file

Returns

bool : True if changes are made to the target

Raises

ValueError

When mode is not valid

get_new_owner(tgt, own)[source]

Sets the owner for a posix file in needed.

Return type:

Optional[str]

Parameters

tgtFspec

Path to the target file

ownOwnGrpId

Owner of the target file

Returns

Optional[str] : new_owner or None

get_new_group(tgt, grp)[source]

Sets the owner for a posix file in needed.

Return type:

Optional[str]

Parameters

tgtFspec

Path to the target file

grpOwnGrpId

Group of the target file

Returns

Optional[str] : new_group or None

set_owner_group(tgt, own, grp)[source]

Sets the owner group for a posix file in needed.

Return type:

bool

Parameters

tgtFspec

Path to the target file

ownstr

Owner of the target file

grpstr

Group of the target file

Returns

bool : True if changes are made to the target

set_owner_group_perms(tgt, own, grp, mode)[source]

Sets the owner group permissions for a posix file if needed.

Return type:

bool

Parameters

tgtFspec

Path to the target file

ownstr

Owner of the target file

grpstr

Group of the target file

modestr

Mode of the target file

Returns

bool : True if changes are made to the target

Top-level module for wtforglib Library.

class WtfSingleton[source]

Bases: object

Singleton class.

domainname(test=False)[source]

Return hosts domain name.

Return type:

str

Parameters

testbool Optional

Default False, when true return example.com

Returns

str

domain name

Raises

ShellError

if subprocess return code is not 0

hostname(test=False)[source]

Return hosts’ hostname.

Return type:

str

Parameters

testbool Optional

Default False, when true return nombre

Returns

str

hostname

Raises

ShellError

if subprocess return code is not 0

strtobool(rts)[source]

Covert string rts to boolean.

Return type:

bool

windoze_not_implemented(foo_name)[source]

Raised and exception if platform is Windows.

Return type:

None

Parameters

foo_namestr

Name of function not supported

Raises

NotImplementedError

When platform is Windows

unix_basename(fn, ext=None)[source]

Return unix basename of file name.

Return type:

str

Parameters

fnFileName

The file to get basename of

extstr Optional

File extension

Returns

str

unix basename of file name

Top-level module for wtforglib Library.

is_ipv6_address(ipaddr)[source]

Returns True if ipaddr is a valid IPv6 address.

Return type:

bool

Parameters

ipaddrstr

A string representation of a IPv6 address

Returns

bool

True if ipaddr is a valid IPv6 address

is_ipv6_network(ipaddr)[source]

Returns True if ipaddr is a valid IPv6 network.

Return type:

bool

Parameters

ipaddrstr

A string representation of a IPv6 network

Returns

bool

True if ipaddr is a valid IPv6 network

is_ipv6(ipvalue)[source]

Returns True if ipvalue is a valid IPv6 address or IPv6 network.

Return type:

bool

Parameters

ipvaluestr

A string representation of a IPv6 address or IPv6 network

Returns

bool

True if ipvalue is a valid IPv6 address or IPv6 network

ipv6_to_netprefix(ipaddr, prefix_len, ipv6net_style='standard')[source]

Returns ipv6 network prefix.

Return type:

str

Parameters

ipaddrstr

The ip address

prefix_lenint

The network prefix length

ipv6net_stylestring

One of standard, postfix

Returns

str

ipv6 network prefix Example: ‘1111:2222:3333:4444::/64’ or postfix style ipv6 network prefix Example: ‘[1111:2222:3333:4444::]/64’

Raises

ValueError

When ipaddr is not a valid ipv6 address

Top-level module kinds for wtforglib.

The kinds module supports definitions of types used in the wtforglib package and used in various projects the author provides.

Types

KeyType

Generic mapping key type

ValueType

Generic mapping value type

Fspec

Fspec = Union[str, PathLike[str]]

Filename

FSpec

StrAnyDict

StrAnyDict = Dict[str, Any]

StrStrDict

StrStrDict = Dict[str, str]

StrStrInt

StrStrInt = Dict[str, Union[int, str]]

StrStrBool

StrStrBool = Dict[str, Union[bool, str]]

StrStrIntBool

StrStrIntBool = Dict[str, Union[int, str, bool]]

StrStrIntBoolNone

StrStrIntBoolNone = Dict[str, Union[int, str, bool, None]]

Top-level module for Wtforg Library.

log_level_name(level, default='info')[source]

Return logger level name.

Return type:

str

Parameters

levelint

Level number

defaultstr, optional

Default if not matched, by default “info”

Returns

str

Level name

basic_options(debug, test, verbose)[source]

Return a dictionary of basic options.

Return type:

Dict[str, Union[str, int, bool]]

Parameters

debugUnion[bool, int]

Sets debug: int in the returned dictionary

testbool

Sets test: bool in the returned dictionary

verboseUnion[bool, int]

Sets verbose: int in the returned dictionary

Returns

OptionsDict

Options dictionary

class SimpleScribe(opts=None)[source]

Bases: object

Class for simple screen logging.

debug(message)[source]

Utility trace debug method.

Return type:

None

info(message)[source]

Utility trace info method.

Return type:

None

warning(message)[source]

Utility trace warning method.

Return type:

None

warn(message)[source]

Utility trace warn method.

Return type:

None

error(message)[source]

Utility trace error method.

Return type:

None

class Options(opts=None)[source]

Bases: SimpleScribe

A class to handle Options.

isdebug()[source]

Returns True if debug > 0.

Return type:

bool

isverbose()[source]

Returns True if verbose > 0.

Return type:

bool

isnoop()[source]

Returns True if noop.

Return type:

bool

isforce()[source]

Returns True if noop.

Return type:

bool

istest()[source]

Returns value of test flag.

Return type:

bool

debug(message, level=1)[source]

Utility debug method.

Return type:

None

verbose(message, level=1)[source]

Utility verbose method.

Return type:

None

This module implements a simple-to-use decorator to implement the singleton pattern.

Exports:

  • r_singleton: resettable singleton wrapper

  • singleton: ignores the arguments to the constructor on subsequent calls

  • singleton_argenforce: raises a ValueError if the arguments on subsequent

    calls vary from the initial ones.

r_singleton(cls)[source]

Use this decorator to wrap a class to make it a resettable singleton.

The first time the wrapped class is instantiated, it will create an object with those arguments and store it. Every subsequent instantiation will return the stored object, regardless of the provided parameters. The stored object can be reset to None by calling the reset method.

Parameters:

cls (Type[T]) – The class to make a singleton

Returns:

The singleton-wrapped class

Return type:

_ResettableWrapper[T]

singleton(cls)[source]

Use this decorator to wrap a class to make it a singleton.

The first time the wrapped class is instantiated, it will create an object with those arguments and store it. Every subsequent instantiation will return the stored object, regardless of the provided parameters.

Parameters:

cls (Type[T]) – The class to make a singleton

Returns:

The singleton-wrapped class

Return type:

_SingletonWrapper[T]

singleton_argenforce(cls)[source]

Use this decorator to wrap a class to make it an arg-enforce singleton.

The first time the wrapped class is instantiated, it will create an object with those arguments and store it. Every subsequent instantiation will return the stored object, unless the arguments are different than the first call, in which case a ValueError will be thrown.

Parameters:

cls (Type[T]) – The class to make a singleton

Returns:

The singleton-wrapped class

Return type:

_ArgEnforceSingletonWrapper[T]

Top-level module for wtforglib Library.

exception AdminStateUnknownError[source]

Bases: Exception

Cannot determine whether the user is an admin.

issuper()[source]

Return True/False depending on process euid.

Return type:

bool

Returns

bool : true if process euid is 0

requires_super_user(prefix='Specified action')[source]

Raises exception if process isn’t euid 0.

Return type:

None

Parameters

prefixstr

Text to prefix to exception message

Raises

PermissionError

if process euid is not 0

Top level module for dynaddrmgr application.

Classes:

TemplateManager

class TemplateWriter(opts=None, j_env=None)[source]

Bases: Commander

Template generator.

This class is responsible for managing the templates specified in the configuration file.

generate(tmpl_name, tmpl_value, tmpl_var)[source]

Generates the template if needed.

Return type:

int

Parameters

tmpl_namestr

Template name

tmpl_valueStrAnyDict

Template information

tmpl_varStrAnyDict

Template variable data

Returns

int

Exit code

Top-level module for wtforglib Library.

get_user_name(uid)[source]

Returns the user name of the user identified by uid.

Return type:

str

Parameters

uidint

User id

Returns

str

User name

get_user_groups(user)[source]

Returns a tuple of groups user belongs to.

Return type:

Tuple[str, ...]

Parameters

userUnion[str, int]

User name or uid

Returns

Tuple[str,…]

Groups user belongs to

url_validator(url)[source]

Validate url.

Return type:

bool

Top-level module for wtforglib.

Unlink file with version support.

Return type:

None

Parameters

fspecFspec

Specification of file to unlink

missing_okbool

Flag to specify if file must exist

Raises

FileNotFoundError

If missing_ok is False and file does not exist.

clear_slot(root, idx, max_versions, debug=False)[source]

Clear backup slot for file being backed up.

Return type:

str

Parameters

rootstr

un-numbered basename

idxint

version number

max_versionsint

maximum number of versions

debugbool, optional

debug flag, by default False

Returns

str

numbered slot name

clear_directory_slot(dirfpn, basenm, idx, max_versions, debug=False)[source]

Clear backup slot in directory other than file to backup.

Return type:

str

Parameters

dirfpnstr

pathname of directory where backups are stored

basenmstr

un-numbered basename of file

idxint

version number

max_versionsint

maximum number of versions

debugbool, optional

debug flag, by default False

Returns

str

numbered slot name

check_root_filename(file_spec)[source]

Determine root filename so the extension doesn’t get longer.

Return type:

str

Parameters

file_specstr

Path name of the file to check

Returns

str

Path name of the file to backup

Raises

ValueError

If file_spec ends with one or more digit extension

version_file(file_spec, vtype='rename', max_versions=5, debug=False, dir_spec=None)[source]

Save max versions of file.

Return type:

int

Parameters

file_specstr

Path to the file to be versioned.

vtypestr, optional

Either rename or copy when versioning, by default “rename”

max_versionsint, optional

maximum number of versions, by default 5

debugbool, optional

debug flag, by default False

dir_specOptional[str]

Path to the directory were versions are stored, by default file_spec directory

Returns

int

exit code