Skip to content

API Documentation for nua-lib

Package nua.lib

Low-level utilities for both NUA build and NUA agent.

Package nua.lib.actions

install_build_packages

install_build_packages(packages, keep_lists=False, installed=None)

Install packages needed for building a project.

jinja2_render_file

jinja2_render_file(template, dest, data)

Render a Jinja2 template file.

jinja2_render_from_str_template

jinja2_render_from_str_template(template, dest, data)

Render a Jinja2 template from a string.

install_git_source

install_git_source(url, branch, dest_dir)

Install a project from git source.

install_meta_packages

install_meta_packages(packages, keep_lists=False)

Install meta packages.

install_source

install_source(url, dest_dir, name, checksum='')

Guess meaning of url string and send back local path of the dowloaded source.

(WIP)

install_nodejs

install_nodejs(version='16', keep_lists=False)

Install nodejs.

from: https://nodesource.com/

build_python

build_python(path='', user='')

Build a python project from source.

check_python_version

check_python_version()

Check that curent python is >=3.10.

python_package_installed

python_package_installed(pkg_name)

Utility to test if a python package is installed.

Nota: replaced by some function using importlib.

install_ruby

install_ruby(version='3.2.1', keep_lists=False)

Installation of Ruby via ‘ruby-install’.

Exec as root.

Parameters:

Name Type Description Default
version str

Ruby version to install.

'3.2.1'
keep_lists bool

Do not erase apt sources lists.

False

camel_format

camel_format(name)

Convert a string to CamelCase format.

camel_format(“my-project”)
‘MyProject’

copy_from_package

copy_from_package(package, filename, destdir, destname='')

Copy a file from a package to a destination directory.

download_extract

download_extract(url, dest, dest_name, checksum='')

Download and extract a file from a URL.

kebab_format

kebab_format(name)

Convert a string to kebab_case format.

kebab_format(“my_project”)
‘my-project’

replace_in

replace_in(file_pattern, string_pattern, replacement)

Replace a string in a set of files, defined by a glob pattern.

snake_format

snake_format(name)

Convert a string to snake_case format.

snake_format(“my-project”)
‘my_project’

string_in

string_in(file_pattern, string_pattern)

Return list of Path of files that contains the pattern str string.

to_kebab_cases

to_kebab_cases(data, recurse=999, unchanged=None)

Converts all keys in a dict to snake_case, recursion level, in place.

to_snake_cases

to_snake_cases(data, recurse=999, unchanged=None)

Converts all keys in a dict to snake_case, recursion level, in place.

Module nua.lib.actions.apt

install_build_packages

install_build_packages(packages, keep_lists=False, installed=None)

Install packages needed for building a project.

Module nua.lib.actions.constants

Module nua.lib.actions.jinja

jinja2_render_file

jinja2_render_file(template, dest, data)

Render a Jinja2 template file.

jinja2_render_from_str_template

jinja2_render_from_str_template(template, dest, data)

Render a Jinja2 template from a string.

Module nua.lib.actions.misc

install_meta_packages

install_meta_packages(packages, keep_lists=False)

Install meta packages.

compile_openssl_1_1

compile_openssl_1_1()

Compile OpenSSL 1.1.x.

Returns:

Name Type Description
str str

The path to the compiled OpenSSL.

install_mariadb_1_1_5

install_mariadb_1_1_5(keep_lists=True)

Python connector for MariaDB, since version 1.1.5post3.

install_psycopg2_python

install_psycopg2_python(keep_lists=True)

Python connector for PostgreSQL.

install_source

install_source(url, dest_dir, name, checksum='')

Guess meaning of url string and send back local path of the dowloaded source.

(WIP)

install_git_source

install_git_source(url, branch, dest_dir)

Install a project from git source.

Module nua.lib.actions.nodejs

npm_install

npm_install(package, force=False)

Install a node package globally.

install_nodejs

install_nodejs(version='16', keep_lists=False)

Install nodejs.

from: https://nodesource.com/

install_nodejs_via_nvm

install_nodejs_via_nvm(home='/nua')

Install nodejs via nvm.

Module nua.lib.actions.python

Nua scripting: action commands.

build_python

build_python(path='', user='')

Build a python project from source.

install_python

install_python(version='3.10', venv='', keep_lists=False)

Install a Python version and create a virtual environment.

python_venv

python_venv(venv)

Activate a Python virtual environment.

install_mariadb_python

install_mariadb_python(version='1.1.4')

Connector for MariaDB.

check_python_version

check_python_version()

Check that curent python is >=3.10.

python_package_installed

python_package_installed(pkg_name)

Utility to test if a python package is installed.

Nota: replaced by some function using importlib.

Module nua.lib.actions.ruby

install_ruby

install_ruby(version='3.2.1', keep_lists=False)

Installation of Ruby via ‘ruby-install’.

Exec as root.

Parameters:

Name Type Description Default
version str

Ruby version to install.

'3.2.1'
keep_lists bool

Do not erase apt sources lists.

False

Module nua.lib.actions.util

download_extract

download_extract(url, dest, dest_name, checksum='')

Download and extract a file from a URL.

verify_checksum

verify_checksum(target, checksum)

If a checksum is provided, verify that the Path has the same sha256 hash.

Abort the programm if hashes differ. Currently supporting only sha256.

is_local_dir

is_local_dir(project)

Analysis of some ptoject string and guess wether local path or URL.

(WIP)

set_php_ini_keys

set_php_ini_keys(replacements, path)

Set keys in a php.ini file.

replace_in

replace_in(file_pattern, string_pattern, replacement)

Replace a string in a set of files, defined by a glob pattern.

string_in

string_in(file_pattern, string_pattern)

Return list of Path of files that contains the pattern str string.

environ_replace_in

environ_replace_in(str_path, env=None)

Replace environment variables in a file.

append_bashrc

append_bashrc(home, content)

Append content to the bashrc file.

snake_format

snake_format(name)

Convert a string to snake_case format.

snake_format(“my-project”)
‘my_project’

kebab_format

kebab_format(name)

Convert a string to kebab_case format.

kebab_format(“my_project”)
‘my-project’

camel_format

camel_format(name)

Convert a string to CamelCase format.

camel_format(“my-project”)
‘MyProject’

to_snake_cases

to_snake_cases(data, recurse=999, unchanged=None)

Converts all keys in a dict to snake_case, recursion level, in place.

to_kebab_cases

to_kebab_cases(data, recurse=999, unchanged=None)

Converts all keys in a dict to snake_case, recursion level, in place.

copy_from_package

copy_from_package(package, filename, destdir, destname='')

Copy a file from a package to a destination directory.

ArchiveSearch

ArchiveSearch(archive)

Utilities to search files in a container image stored as a .tar archive.

Current usage: retrieve the nua-config.toml config used when
building the Nua app.

get_nua_config_dict

get_nua_config_dict()

Return the nua-config.toml of the archive as a dict.

read

read(path)

Return the content of a file on the archive.

Module nua.lib.backports

chdir

chdir(path)

Non thread-safe context manager to change the current working directory.

Module nua.lib.console

print_magenta_no_lf

print_magenta_no_lf(msg)

Print specialized for lines including a LF (Docker build log).

Module nua.lib.constants

NUA_BUILD_PATH module-attribute

NUA_BUILD_PATH = '/nua/build'

The directory where the application is built.

NUA_APP_PATH module-attribute

NUA_APP_PATH = '/nua/app'

The directory where the application is installed.

NUA_METADATA_PATH module-attribute

NUA_METADATA_PATH = '/nua/metadata'

The directory where the application metadata is stored.

NUA_SCRIPTS_PATH module-attribute

NUA_SCRIPTS_PATH = '/nua/scripts'

The directory where the operation and maintenance scripts are stored.

Module nua.lib.dates

backup_date

backup_date()

Return a string of the current datetime for backup files.

Format: 2023-05-30-120255

Module nua.lib.docker

Docker scripting utils.

docker_sanitized_name

docker_sanitized_name(name)

Docker valid name.

https://docs.docker.com/engine/reference/commandline/
tag/#extended-description

Module nua.lib.elapsed

elapsed

elapsed(delta)

Readable time string from duration in seconds.

elapsed(123.456)
‘2min 3s’
elapsed(23.456)
‘23.46s’

Module nua.lib.exceptions

Module nua.lib.exec

Nua scripting: exec commands.

exec_as_nua

exec_as_nua(cmd, cwd=None, env=None, timeout=None)

Exec command or list of commands as user nua.

mp_exec_as_nua

mp_exec_as_nua(cmd, cwd=None, env=None, timeout=None)

Exec exec_as_nua() as a python external process to allow several use of function
without mangling ENV and UID.

exec_as_root_daemon

exec_as_root_daemon(cmd, env=None)

Exec a subprocess daemon as root().

mp_exec_as_postgres

mp_exec_as_postgres(cmd, cwd=None, env=None, timeout=None, show_cmd=True)

Exec as user ‘postgres’ in a python external process to allow several use of
function without mangling ENV and UID.

exec_as_root

exec_as_root(cmd, cwd=None, env=None, timeout=None, show_cmd=True)

Exec command or list of commands as user root.

set_nua_user

set_nua_user()

Ensure user is Nua and related environment.

Will raise OSError if fails.

Module nua.lib.gen_password

gen_password

gen_password(length=24)

Generate random password.

With ascii and digits, lenght 24, log10(62**16) ~ 43, and basic constraints. Added
constraint for usernames: first char is letter.

gen_randint

gen_randint()

Generate random integer of 64 bits.

Module nua.lib.normalization

Module nua.lib.nua_config

Class to manage the “nua-config.toml” file.

NuaConfig

NuaConfig(path=None)

Class to manage the “nua-config.toml” file.

The config file can be any of nua-config.[toml|json|yaml|yml]

metadata_rendered cached property

metadata_rendered

Return the metadata and build sections with rendered f-string values.

version property

version

Version of package source.

wrap_image cached property

wrap_image

Optional container image to be used as base for ‘wrap’ strategy.

If the ‘base-image’ metadata is defined, the build strategy is to add the
‘/nua/metadata/nua-config.json’ file on the declared image, when build method is
‘wrap’.

src_checksum property

src_checksum

Return checksum associated to ‘src-url’ or null string.

project cached property

project

The project URL to build with autodetection.

build_command cached property

build_command

Return the list of build commands, each cmd rendered with metadata.

build_method property

build_method

Build method (or default build method).

Can be empty string if not defined (then autodetection from metadata).

packages property

packages

Return list of run packages (packages remanent after build).

volumes property

volumes

The list of declared volumes.

providers property

providers

The list of providers (tag ‘provider’).

fetch_source

fetch_source(name='')

Download, check and extract source URL, returning the source Path.

Set ownership to ‘nua’ user if launched by ‘root’.

hyphen_get

hyphen_get(data, key, default=None)

Return value from dict for key either hyphen “-” or underscore “_” in it,
priority to “-“.

force_list

force_list(content)

Return always a list, if a single string is provided, wrap it into list.

force_list(“foo”)
[‘foo’]
force_list([“foo”, “bar”])
[‘foo’, ‘bar’]
force_list([])
[]
force_list(“”)
[]

Module nua.lib.nua_config_format

Class to manage NuaConfig format.

Module nua.lib.nua_tag

Generate the long nua tag of packages.

For container and network names, the “:” will be replaced by “-“.

nua_tag_string

nua_tag_string(metadata)

Return long tag string with version and release.

“hedgedoc” -> “nua-hedgedoc:1.9.7-3”

Module nua.lib.panic

Nua scripting: print shortcuts.

All printing function should be encapsulated by a with verbosity(v) context for
future use in other message dispatching.

only for errors or serious warnings

raise Abort()
warning() # got a Warning: prefix

warning lines

red_line()

title of actions list

title()

yellow bold + white: title of actions list
title_info()

when we’re about to start something important

important()

when it’s done (i.e. for success messages)

show()

green + cyan: information message with last part make visible
info()

nocolor bold (default): : for normal immpotant messages (print)
bold()

nocolor (default): for normal messages (print)
vprint() # with dependency on verbosity, so different from print
vfprint() # and with stdout flush for rare special cases

for docker default log stream (without LF)

print_stream()

wrong or takes too much time)
debug()

for emphasis in debug messages

bold_debug()

print_stream

print_stream(message)

Print Docker log stream already containing a LF.

Module nua.lib.shell

Scripting shell utils for Nua scripts.

chown_r

chown_r(path, user, group=None)

Apply recursively chown with str arguments.

Similar to chown -R.

example

chown_r(document_root, “www-data”, “www-data”)

chmod_r

chmod_r(path, file_mode, dir_mode=None)

Apply recursively chmod with int arguments.

Similar to chmod -R but with int arguments (usually expressed as octal numbers).

example

chmod_r(document_root, 0o644, 0o755)

rm_fr

rm_fr(path)

Alias for rm_rf.

rm_rf

rm_rf(path)

Wrapper for shutil.rmtree().

sh

sh(cmd, timeout=600, env=None, show_cmd=True, capture_output=False, cwd=None)

Run a shell command.

Package nua.lib.tool

Low-level utilities for both NUA build and NUA agent.

Module nua.lib.tool.color_str

Return text string colorized.

from color_str import ColorStr as C print(C.green_bright(‘Take’) + C.blue(’ it ‘,
underline=True) + C.yellow_bold(‘easy’, bgcolor=’red’))

ColorStr

colorize classmethod

colorize(txt, color='', bgcolor='', **kwargs)

Return text string colorized.

kwargs are bools for keys “bright”, “bold”, “underline” and “reversed”.

Module nua.lib.tool.state

is_inside_container cached

is_inside_container()

Test if current execution environment is inside a container.

Module nua.lib.unarchiver

Unarchiver

ABC for unarchivers.

Module nua.lib.version