7.1.10. cobbler.utils package

7.1.10.1. Submodules

7.1.10.2. cobbler.utils.event module

This module contains logic to support the events Cobbler generates in its XML-RPC API.

class cobbler.utils.event.CobblerEvent(name: str = '', statetime: float = 0.0)[source]

Bases: object

This is a small helper class that represents an event in Cobbler.

property event_id: str

Read only property to retrieve the internal ID of the event.

property name: str

Read only property to retrieve the human-readable name of the event.

7.1.10.3. cobbler.utils.filesystem_helpers module

Utilities for filesystem operations used by Cobbler, including file linking, copying, hashing, and directory management.

cobbler.utils.filesystem_helpers.cachefile(src: str, dst: str) None[source]

Copy a file into a cache and link it into place. Use this with caution, otherwise you could end up copying data twice if the cache is not on the same device as the destination.

Parameters:
  • src – The sourcefile for the copy action.

  • dst – The destination for the copy action.

cobbler.utils.filesystem_helpers.copyfile(src: str, dst: str, symlink: bool = False) None[source]

Copy a file from source to the destination.

Parameters:
  • src – The source file. This may also be a folder.

  • dst – The destination for the file or folder.

  • symlink – If instead of a copy, a symlink is okay, then this may be set explicitly to “True”.

Raises:

OSError – Raised in case src could not be read.

cobbler.utils.filesystem_helpers.copyfileimage(src: str, image_location: str, dst: str) None[source]

Copy a file from source to the destination in the image.

Parameters:
  • src – The source file.

  • image_location – The location of the image.

  • dst – The destination for the file.

cobbler.utils.filesystem_helpers.copyremotefile(src: str, dst1: str, api: CobblerAPI | None = None) None[source]

Copys a file from a remote place to the local destionation.

Parameters:
  • src – The remote file URI.

  • dst1 – The copy destination on the local filesystem.

  • api – This parameter is not used currently.

Raises:

OSError – Raised in case an error occurs when fetching or writing the file.

cobbler.utils.filesystem_helpers.create_json_database_dirs(api: CobblerAPI) None[source]

Creates the database directories for the file serializer

Parameters:

api – CobblerAPI

cobbler.utils.filesystem_helpers.create_tftpboot_dirs(api: CobblerAPI) None[source]

Create directories for tftpboot images

Parameters:

api – CobblerAPI

cobbler.utils.filesystem_helpers.create_trigger_dirs(api: CobblerAPI) None[source]

Creates the directories that the user/admin can fill with dynamically executed scripts.

Parameters:

api – CobblerAPI

cobbler.utils.filesystem_helpers.create_web_dirs(api: CobblerAPI) None[source]

Create directories for HTTP content

Parameters:

api – CobblerAPI

cobbler.utils.filesystem_helpers.hashfile(file_name: str, lcache: Path | None = None) str | None[source]

Returns the sha1sum of the file

Parameters:
  • file_name – The file to get the sha1sum of.

  • lcache – This is a directory where Cobbler would store its link_cache.json file to speed up the return of the hash. The hash looked up would be checked against the Cobbler internal mtime of the object.

Returns:

The sha1 sum or None if the file doesn’t exist.

Determine if it is safe to hardlink a file to the destination path.

Parameters:
  • src – The hardlink source path.

  • dst – The hardlink target path.

  • api – The api-instance to resolve needed information with.

Returns:

True if selinux is disabled, the file is on the same device, the source in not a link, and it is not a remote path. If selinux is enabled the functions still may return true if the object is a kernel or initrd. Otherwise returns False.

cobbler.utils.filesystem_helpers.linkfile(api: CobblerAPI, src: str, dst: str, symlink_ok: bool = False, cache: bool = True) None[source]

Attempt to create a link dst that points to src. Because file systems suck we attempt several different methods or bail to just copying the file.

Parameters:
  • api – This parameter is needed to check if a file can be hardlinked. This method fails if this parameter is not present.

  • src – The source file.

  • dst – The destination for the link.

  • symlink_ok – If it is okay to just use a symbolic link.

  • cache – If it is okay to use a cached file instead of the real one.

Raises:

CX – Raised in case the API is not given.

cobbler.utils.filesystem_helpers.mkdir(path: str, mode: int = 493) None[source]

Create directory with a given mode.

Parameters:
  • path – The path to create the directory at.

  • mode – The mode to create the directory with.

Raises:

CX – Raised in case creating the directory fails with something different from error code 17 (directory already exists).

cobbler.utils.filesystem_helpers.mkdirimage(path: Path, image_location: str) None[source]

Create a directory in an image.

Parameters:
  • path – The path to create the directory at.

  • image_location – The location of the image.

cobbler.utils.filesystem_helpers.path_tail(apath: str, bpath: str) str[source]

Given two paths (B is longer than A), find the part in B not in A

Parameters:
  • apath – The first path.

  • bpath – The second path.

Returns:

If the paths are not starting at the same location this function returns an empty string.

cobbler.utils.filesystem_helpers.rmfile(path: str) None[source]

Delete a single file.

Parameters:

path – The file to delete.

cobbler.utils.filesystem_helpers.rmglob_files(path: str, glob_pattern: str) None[source]

Deletes all files in path with glob_pattern with the help of rmfile().

Parameters:
  • path – The folder of the files to remove.

  • glob_pattern – The glob pattern for the files to remove in path.

cobbler.utils.filesystem_helpers.rmtree(path: str) None[source]

Delete a complete directory or just a single file.

Parameters:

path – The directory or folder to delete.

Raises:

CX – Raised in case path does not exist.

cobbler.utils.filesystem_helpers.rmtree_contents(path: str) None[source]

Delete the content of a folder with a glob pattern.

Parameters:

path – This parameter presents the glob pattern of what should be deleted.

cobbler.utils.filesystem_helpers.safe_filter(var: str | None) None[source]

This function does nothing if the argument does not find any semicolons or two points behind each other.

Parameters:

var – This parameter shall not be None or have “..”/”;” at the end.

Raises:

CX – In case any .. or / is found in var.

cobbler.utils.filesystem_helpers.sha1_file(file_path: str | Path, buffer_size: int = 65536) str[source]

This function is emulating the functionality of the sha1sum tool.

Parameters:
  • file_path – The path to the file that should be hashed.

  • buffer_size – The buffer-size that should be used to hash the file.

Returns:

The SHA1 hash as sha1sum would return it.

7.1.10.4. cobbler.utils.input_converters module

Utility functions for converting input types (string, list, dict, boolean, int) in Cobbler.

cobbler.utils.input_converters.input_boolean(value: str | bool | int) bool[source]

Convert a str to a boolean. If this is not possible or the value is false return false.

Parameters:

value – The value to convert to boolean.

Returns:

True if the value is in the following list, otherwise false: “true”, “1”, “on”, “yes”, “y” .

cobbler.utils.input_converters.input_int(value: str | int | float) int[source]

Convert a value to integer.

Parameters:

value – The value to convert.

Raises:

TypeError – In case after the attempted conversion we still don’t have an int.

Returns:

The integer if the conversion was successful.

cobbler.utils.input_converters.input_string_or_dict(options: str | List[Any] | Dict[Any, Any], allow_multiples: bool = True) str | Dict[Any, Any][source]

Older Cobbler files stored configurations in a flat way, such that all values for strings. Newer versions of Cobbler allow dictionaries. This function is used to allow loading of older value formats so new users of Cobbler aren’t broken in an upgrade.

Parameters:
  • options – The str or dict to convert.

  • allow_multiples – True (default) to allow multiple identical keys, otherwise set this false explicitly.

Returns:

A dict or the value <<inherit>> in case it is the only content of options.

Raises:

TypeError – Raised in case the input type is wrong.

cobbler.utils.input_converters.input_string_or_dict_no_inherit(options: str | List[Any] | Dict[Any, Any], allow_multiples: bool = True) Dict[Any, Any][source]

See input_string_or_dict()

cobbler.utils.input_converters.input_string_or_list(options: str | List[Any] | None) List[Any] | str[source]

Accepts a delimited list of stuff or a list, but always returns a list.

Parameters:

options – The object to split into a list.

Returns:

str when this functions get’s passed <<inherit>>. if option is delete then an empty list is returned. Otherwise, this function tries to return the arg option or tries to split it into a list.

Raises:

TypeError – In case the type of options was neither None, str or list.

cobbler.utils.input_converters.input_string_or_list_no_inherit(options: str | List[Any] | None) List[Any][source]

Accepts a delimited list of stuff or a list, but always returns a list.

Parameters:

options – The object to split into a list.

Returns:

If option is delete, None (object not literal) or an empty str, then an empty list is returned. Otherwise, this function tries to return the arg option or tries to split it into a list.

Raises:

TypeError – In case the type of options was neither None, str or list.

7.1.10.5. cobbler.utils.kernel_command_line module

Utility module to abstract the construction of the Kernel Command Line for Linux. The options available differ by version and the backported patches that fix and add functionality.

More information: https://docs.kernel.org/admin-guide/kernel-parameters.html

class cobbler.utils.kernel_command_line.KernelCommandLine(api: CobblerAPI)[source]

Bases: object

Class to interface with a given Kernel Command Line.

append_key(key: str) None[source]

Append a keyword-only argument to the Kernel Command Line.

Parameters:

key – The key of the option.

append_key_value(key: str, value: str) None[source]

Append a key-value pair to the Kernel Command Line.

Parameters:
  • key – The key of the option.

  • value – The value of the option.

append_raw(value: str) None[source]

Append a raw string to the kernel command line. This is most likely useful for initializing the “APPEND” option for GRUB.

Parameters:

value – The value of the option.

render(blended: Dict[str, Any]) str[source]

Render the Kernel Command Line with the default templating language.

Parameters:

blended – The context used for variable substitution.

Returns:

The rendered Kernel Command Line.

replace_key(key: str, condition: str, new_value: str) None[source]

Replace a given key with a given condition inside the kernel command line. This replaces all occurences, not only the first one.

Parameters:
  • key – The key of the option.

  • condition – The condition that is applied to the value of the key.

  • new_value – The value that replaces the old one.

7.1.10.6. cobbler.utils.mtab module

We cache the contents of /etc/mtab. The following module is used to keep our cache in sync.

class cobbler.utils.mtab.MntEntObj(input_data: str | None = None)[source]

Bases: object

Represents a mounted filesystem entry with its attributes parsed from a whitespace-separated string.

mnt_dir = None
mnt_freq = 0
mnt_fsname = None
mnt_opts = None
mnt_passno = 0
mnt_type = None
cobbler.utils.mtab.get_file_device_path(fname: str) Tuple[str | None, str][source]
What this function attempts to do is take a file and return:
  • the device the file is on

  • the path of the file relative to the device.

For example:

/boot/vmlinuz -> (/dev/sda3, /vmlinuz) /boot/efi/efi/redhat/elilo.conf -> (/dev/cciss0, /elilo.conf) /etc/fstab -> (/dev/sda4, /etc/fstab)

Parameters:

fname – The filename to split up.

Returns:

A tuple containing the device and relative filename.

cobbler.utils.mtab.get_mtab(mtab: str = '/etc/mtab', vfstype: bool = False) List[MntEntObj][source]

Get the list of mtab entries. If a custom mtab should be read then the location can be overridden via a parameter.

Parameters:
  • mtab – The location of the mtab. Argument can be omitted if the mtab is at its default location.

  • vfstype – If this is True, then all filesystems which are nfs are returned. Otherwise this returns all mtab entries.

Returns:

The list of requested mtab entries.

cobbler.utils.mtab.is_remote_file(file: str) bool[source]

This function is trying to detect if the file in the argument is remote or not.

Parameters:

file – The filepath to check.

Returns:

If remote True, otherwise False.

7.1.10.7. cobbler.utils.process_management module

Module for managing and restarting services using systemd, supervisord, or SysV service manager.

cobbler.utils.process_management.is_service() bool[source]

Return whether this system uses service.

This method currently checks if the path /usr/sbin/service exists.

cobbler.utils.process_management.is_supervisord() bool[source]

Return whether this system uses supervisord.

This method currently checks if there is a running supervisord instance on localhost.

cobbler.utils.process_management.is_systemd() bool[source]

Return whether this system uses systemd.

This method currently checks if the path /usr/lib/systemd/systemd exists.

cobbler.utils.process_management.service_restart(service_name: str) int[source]

Restarts a daemon service independent of the underlining process manager. Currently, supervisord, systemd and SysV are supported. Checks which manager is present is done in the order just described.

Parameters:

service_name – The name of the service

Returns:

If the system is SystemD or SysV based the return code of the restart command.

7.1.10.8. cobbler.utils.signatures module

Utility module to provide methods for working with the distro signatures JSON database file.

cobbler.utils.signatures.get_supported_distro_boot_loaders(item: Distro | Image, api_handle: CobblerAPI | None = None) List[BootLoader][source]

This is trying to return you the list of known bootloaders if all resorts fail. Otherwise this returns a list which contains only the subset of bootloaders which are available by the distro in the argument.

Parameters:
  • distro – The distro to check for.

  • api_handle – The api instance to resolve metadata and settings from.

Returns:

The list of bootloaders or a dict of well known bootloaders.

cobbler.utils.signatures.get_valid_archs() List[str][source]

Return a list of valid architectures found in the import signatures

Returns:

All architectures which are known to Cobbler according to the signature cache.

cobbler.utils.signatures.get_valid_breeds() List[str][source]

Return a list of valid breeds found in the import signatures

cobbler.utils.signatures.get_valid_os_versions() List[str][source]

Return a list of valid os-versions found in the import signatures

Returns:

All operating system versions which are known to Cobbler according to the signature cache.

cobbler.utils.signatures.get_valid_os_versions_for_breed(breed: str) List[str][source]

Return a list of valid os-versions for the given breed

Parameters:

breed – The operating system breed to check for.

Returns:

All operating system version which are known to Cobbler according to the signature cache filtered by a os-breed.

cobbler.utils.signatures.load_signatures(filename: str, cache: bool = True) None[source]

Loads the import signatures for distros.

Parameters:
  • filename – Loads the file with the given name.

  • cache – If the cache should be set with the newly read data.

7.1.10.9. cobbler.utils.thread module

This module is responsible for managing the custom common threading logic Cobbler has.

class cobbler.utils.thread.CobblerThread(event_id: str, remote: CobblerXMLRPCInterface, options: Dict[str, Any], task_name: str, api: CobblerAPI, run: Callable[[CobblerThread], None], on_done: Callable[[CobblerThread], None] | None = None)[source]

Bases: Thread

This is a custom thread that has a custom logger as well as logic to execute Cobbler triggers.

run() None[source]

Run the thread.

Returns:

The return code of the action. This may a boolean or a Linux return code.

7.1.10.10. Module contents

Misc heavy lifting functions for Cobbler

cobbler.utils.blender(api_handle: CobblerAPI, remove_dicts: bool, root_obj: BootableItem) Dict[str, Any][source]

Combine all of the data in an object tree from the perspective of that point on the tree, and produce a merged dictionary containing consolidated data.

Parameters:
  • api_handle – The api to use for collecting the information to blender the item.

  • remove_dicts – Boolean to decide whether dicts should be converted.

  • root_obj – The object which should act as the root-node object.

Returns:

A dictionary with all the information from the root node downwards.

cobbler.utils.cheetah_exc(exc: Exception) str[source]

Converts an exception thrown by Cheetah3 into a custom error message.

Parameters:

exc – The exception to convert.

Returns:

The string representation of the Cheetah3 exception.

cobbler.utils.command_existing(cmd: str) bool[source]

This takes a command which should be known to the system and checks if it is available.

Parameters:

cmd – The executable to check

Returns:

If the binary does not exist False, otherwise True.

cobbler.utils.compare_versions_gt(ver1: str, ver2: str) bool[source]

Compares versions like “0.9.3” with each other and decides if ver1 is greater than ver2.

Parameters:
  • ver1 – The first version.

  • ver2 – The second version.

Returns:

True if ver1 is greater, otherwise False.

cobbler.utils.create_files_if_not_existing(files: List[str]) None[source]

Create empty files if they don’t already exist. If they exist, do nothing.

Parameters:

files – A list of the files to create. If the base directory doesn’t exist, create it too.

raises OSError: In case the file cannot be created.

cobbler.utils.dhcp_service_name() str[source]

Determine the dhcp service which is different on various distros. This is currently a hardcoded detection.

Returns:

This will return one of the following names: “dhcp3-server”, “isc-dhcp-server”, “dhcpd”

cobbler.utils.dhcpconf_location(protocol: DHCP, filename: str = 'dhcpd.conf') str[source]

This method returns the location of the dhcpd.conf file.

Parameters:
  • protocol – The DHCP protocol version (v4/v6) that is used.

  • filename – The filename of the DHCP configuration file.

Raises:

AttributeError – If the protocol is not v4/v6.

Returns:

The path possibly used for the dhcpd.conf file.

cobbler.utils.dict_annihilate(dictionary: Dict[Any, Any]) None[source]

Annihilate entries marked for removal. This method removes all entries with key names starting with “!”. If a dictionary contains keys “!xxx” and “xxx”, then both will be removed.

Parameters:

dictionary – A dictionary to clean up.

cobbler.utils.dict_to_string(_dict: Dict[Any, Any]) str[source]

Convert a dictionary to a printable string. Used primarily in the kernel options string and for some legacy stuff where koan expects strings (though this last part should be changed to dictionaries)

A KV-Pair is joined with a “=”. Values are enclosed in single quotes.

Parameters:

_dict – The dictionary to convert to a string.

Returns:

The string which was previously a dictionary.

cobbler.utils.die(msg: str) None[source]

This method let’s Cobbler crash with an exception. Log the exception once in the per-task log or the main log if this is not a background op.

Parameters:

msg – The message to send for raising the exception

Raises:

CX – Raised in all cases with msg.

cobbler.utils.file_is_remote(file_location: str) bool[source]

Returns true if the file is remote and referenced via a protocol we support.

Parameters:

file_location – The URI to check.

Returns:

True if the URI is http, https or ftp. Otherwise false.

cobbler.utils.filelock(lock_file: str)[source]

Context manager to acquire a file lock and release it afterwards

Parameters:

lock_file – Path to the file lock to acquire

Raises:

OSError – Raised in case of unexpect error acquiring file lock.

cobbler.utils.find_highest_files(directory: str, unversioned: str, regex: Pattern[str]) str[source]

Find the highest numbered file (kernel or initrd numbering scheme) in a given directory that matches a given pattern. Used for auto-booting the latest kernel in a directory.

Parameters:
  • directory – The directory to search in.

  • unversioned – The base filename which also acts as a last resort if no numbered files are found.

  • regex – The regex to search for.

Returns:

The file with the highest number or an empty string.

cobbler.utils.find_initrd(path: str) str | None[source]

Given a directory or a filename, see if the path can be made to resolve into an intird, return that full path if possible.

Parameters:

path – The path to check for initrd files.

Returns:

None or the path to the found initrd.

cobbler.utils.find_kernel(path: str) str[source]

Given a filename, find if the path can be made to resolve into a kernel, and return that full path if possible.

Parameters:

path – The path to check for a kernel.

Returns:

path if at the specified location a possible match for a kernel was found, otherwise an empty string.

cobbler.utils.find_matching_files(directory: str, regex: Pattern[str]) List[str][source]

Find all files in a given directory that match a given regex. Can’t use glob directly as glob doesn’t take regexen. The search does not include subdirectories.

Parameters:
  • directory – The directory to search in.

  • regex – The regex to apply to the found files.

Returns:

An array of files which apply to the regex.

cobbler.utils.flatten(data: Dict[str, Any]) Dict[str, Any] | None[source]

Convert certain nested dicts to strings. This is only really done for the ones koan needs as strings this should not be done for everything

Parameters:

data – The dictionary in which various keys should be converted into a string.

Returns:

None (if data is None) or the flattened string.

cobbler.utils.get_exc(exc: Exception, full: bool = True) str[source]

This tries to analyze if an exception comes from Cobbler and potentially enriches or shortens the exception.

Parameters:
  • exc – The exception which should be analyzed.

  • full – If the full exception should be returned or only the most important information.

Returns:

The exception which has been converted into a string which then can be logged easily.

cobbler.utils.get_family() str[source]

Get family of running operating system.

Family is the base Linux distribution of a Linux distribution, with a set of common parents.

Returns:

May be “redhat”, “debian” or “suse” currently. If none of these are detected then just the distro name is returned.

cobbler.utils.get_host_ip(ip_address: str, shorten: bool = True) str[source]

Return the IP encoding needed for the TFTP boot tree.

Parameters:
  • ip_address – The IP address to pretty print.

  • shorten – Whether the IP-Address should be shortened or not.

Returns:

The IP encoded as a hexadecimal value.

cobbler.utils.get_random_mac(api_handle: CobblerAPI, virt_type: str = 'kvm') str[source]

Generate a random MAC address.

The code of this method was taken from xend/server/netif.py

Parameters:
  • api_handle – The main Cobbler api instance.

  • virt_type – The virtualization provider. Currently possible is ‘vmware’, ‘xen’, ‘qemu’, ‘kvm’.

Returns:

MAC address string

Raises:

CX – Raised in case unsupported virt_type given.

cobbler.utils.get_shared_secret() str | int[source]

The ‘web.ss’ file is regenerated each time cobblerd restarts and is used to agree on shared secret interchange between the web server and cobblerd, and also the CLI and cobblerd, when username/password access is not required. For the CLI, this enables root users to avoid entering username/pass if on the Cobbler server.

Returns:

The Cobbler secret which enables full access to Cobbler.

cobbler.utils.get_supported_system_boot_loaders() List[BootLoader][source]

Return the list of currently supported bootloaders.

Returns:

The list of currently supported bootloaders.

cobbler.utils.is_ip(strdata: str) bool[source]

Return whether the argument is an IP address.

Parameters:

strdata – The IP in a string format. This get’s passed to the IP object of Python.

cobbler.utils.is_selinux_enabled() bool[source]

This check is achieved via a subprocess call to selinuxenabled. Default return is false.

Returns:

Whether selinux is enabled or not.

cobbler.utils.is_str_float(value: str) bool[source]

Checks if the string value could be converted into a float. This is necessary since the CLI only works with strings but many methods and checks expects a float.

Parameters:

value – The value to check

Returns:

True if conversion is successful

cobbler.utils.is_str_int(value: str) bool[source]

Checks if the string value could be converted into an integer. This is necessary since the CLI only works with strings but many methods and checks expects an integer.

Parameters:

value – The value to check

Returns:

True if conversion is successful

cobbler.utils.kernel_options_to_string(options: Dict[Any, Any]) str[source]

Convert kernel options to a deterministic string representation. Options that are not order-sensitive are sorted alphabetically by key, while order-sensitive keys are appended in a defined priority (currently dud followed by console) while respecting their relative insertion order.

Parameters:

options – The kernel options to convert.

Returns:

A deterministic string representation of the kernel options.

cobbler.utils.kopts_overwrite(kopts: Dict[Any, Any], cobbler_server_hostname: str = '', distro_breed: str = '', system_name: str = '') None[source]

SUSE is not using ‘text’. Instead ‘textmode’ is used as kernel option.

Parameters:
  • kopts – The kopts of the system.

  • cobbler_server_hostname – The server setting from our Settings.

  • distro_breed – The distro for the system to change to kopts for.

  • system_name – The system to overwrite the kopts for.

cobbler.utils.local_get_cobbler_api_url() str[source]

Get the URL of the Cobbler HTTP API from the Cobbler settings file.

Returns:

The api entry point. This does not respect modifications from Loadbalancers or API-Gateways.

cobbler.utils.local_get_cobbler_xmlrpc_url() str[source]

Get the URL of the Cobbler XMLRPC API from the Cobbler settings file.

Returns:

The api entry point.

cobbler.utils.lod_sort_by_key(list_to_sort: List[Any], indexkey: Hashable) List[Any][source]

Sorts a list of dictionaries by a given key in the dictionaries.

Note: This is a destructive operation and does not sort the dictionaries.

Parameters:
  • list_to_sort – The list of dictionaries to sort.

  • indexkey – The key to index to dicts in the list.

Returns:

The sorted list.

cobbler.utils.lod_to_dod(_list: List[Any], indexkey: Hashable) Dict[Any, Any][source]

Things like get_distros() returns a list of a dictionaries. Convert this to a dict of dicts keyed off of an arbitrary field.

Example: [ { "a" : 2 }, { "a" : 3 } ] -> { "2" : { "a" : 2 }, "3" : { "a" : "3" } }

Parameters:
  • _list – The list of dictionaries to use for the conversion.

  • indexkey – The position to use as dictionary keys.

Returns:

The converted dictionary. It is not guaranteed that the same key is not used multiple times.

cobbler.utils.log_exc() None[source]

Log an exception.

cobbler.utils.merge_dicts_recursive(base_dict: Dict[str, Any], updating_dict: Dict[str, Any], str_append: bool = False) Dict[str, Any][source]

Merge updating_dict into base_config recursively.

Parameters:
  • base_dict – Base dictionary.

  • updating_dict – Updating dict, overrides base_dict.

  • str_append – Append the updating_dict String values to the base_dict with the same key instead of overwriting the original value.

Returns dict:

Merged dict

cobbler.utils.named_service_name() str[source]

Determine the named service which is normally different on various distros.

Returns:

This will return for debian/ubuntu bind9 and on other distros named-chroot or named.

cobbler.utils.namedconf_location() str[source]

This returns the location of the named.conf file.

Returns:

If the distro is Debian/Ubuntu then this returns “/etc/bind/named.conf”. Otherwise “/etc/named.conf”

cobbler.utils.os_release() Tuple[str, float][source]

Get the os version of the linux distro. If the get_family() method succeeds then the result is normalized.

Returns:

The os-name and os version.

cobbler.utils.pretty_hex(ip_address: IPAddress, length: int = 8) str[source]

Pads an IP object with leading zeroes so that the result is _length_ hex digits. Also do an upper().

Parameters:
  • ip_address – The IP address to pretty print.

  • length – The length of the resulting hexstring. If the number is smaller than the resulting hex-string then no front-padding is done.

cobbler.utils.read_file_contents(file_location: str, fetch_if_remote: bool = False) str | None[source]

Reads the contents of a file, which could be referenced locally or as a URI.

Parameters:
  • file_location – The location of the file to read.

  • fetch_if_remote – If True a remote file will be tried to read, otherwise remote files are skipped and None is returned.

Returns:

Returns None if file is remote and templating of remote files is disabled.

Raises:

FileNotFoundError – if the file does not exist at the specified location.

cobbler.utils.remote_file_exists(file_url: str) bool[source]

Return True if the remote file exists.

Parameters:

file_url – The URL to check.

Returns:

True if Cobbler can reach the specified URL, otherwise false.

cobbler.utils.remove_lines_in_file(filepath: str, remove_keywords: List[str]) None[source]

Remove any line from file at a given filepath if it is a substring of any element of the remove_keywords list.

Parameters:
  • filepath – A path of the file that you want to modify.

  • remove_keywords – A list of keywords. Any line in filepath that contains any of the keywords will be removed.

raises OSError: In case the file cannot be read or modified.

cobbler.utils.remove_yum_olddata(path: str | PathLike[str]) None[source]

Delete .olddata folders that might be present from a failed run of createrepo.

Parameters:

path – The path to check for .olddata files.

cobbler.utils.revert_strip_none(data: str | int | float | bool | List[Any] | Dict[Any, Any]) str | int | float | bool | List[Any] | Dict[Any, Any] | None[source]

Does the opposite to strip_none. If a value which represents None is detected, it replaces it with None.

Parameters:

data – The data to check.

Returns:

The data without None.

cobbler.utils.rsync_files(src: str, dst: str, args: str, quiet: bool = True) bool[source]

Sync files from src to dst. The extra arguments specified by args are appended to the command.

Parameters:
  • src – The source for the copy process.

  • dst – The destination for the copy process.

  • args – The extra arguments are appended to our standard arguments.

  • quiet – If True no progress is reported. If False then progress will be reported by rsync.

Returns:

True on success, otherwise False.

cobbler.utils.run_triggers(api: CobblerAPI, ref: ITEM | None = None, globber: str = '', additional: List[Any] | None = None) None[source]

Runs all the trigger scripts in a given directory. Example: /var/lib/cobbler/triggers/blah/*

As of Cobbler 1.5.X, this also runs Cobbler modules that match the globbing paths.

Python triggers are always run before shell triggers.

Parameters:
  • api – The api object to use for resolving the actions.

  • ref – Can be a Cobbler object, if not None, the name will be passed to the script. If ref is None, the script will be called with no arguments.

  • globber – is a wildcard expression indicating which triggers to run.

  • additional – Additional arguments to run the triggers with.

Raises:

CX – Raised in case the trigger failed.

cobbler.utils.strip_none(data: List[Any] | Dict[Any, Any] | int | str | float | None, omit_none: bool = False) List[Any] | Dict[Any, Any] | int | str | float[source]

Remove “None” entries from datastructures. Used prior to communicating with XMLRPC.

Parameters:
  • data – The data to strip None away.

  • omit_none – If the datastructure is not a single item then None items will be skipped instead of replaced if set to “True”.

Returns:

The modified data structure without any occurrence of None.

cobbler.utils.subprocess_call(cmd: str | List[str], shell: bool = False, process_input: Any = None) int[source]

A simple subprocess call with no output capturing.

Parameters:
  • cmd – The command to execute.

  • shell – Whether to use a shell or not for the execution of the command.

  • process_input – If there is any process_input needed for that command to stdin.

Returns:

The return code of the process

cobbler.utils.subprocess_get(cmd: str | List[str], shell: bool = True, process_input: Any = None) str[source]

A simple subprocess call with no return code capturing.

Parameters:
  • cmd – The command to execute.

  • shell – Whether to use a shell or not for the execution of the command.

  • process_input – If there is any process_input needed for that command to stdin.

Returns:

The data which the subprocess returns.

cobbler.utils.subprocess_sp(cmd: str | List[str], shell: bool = True, process_input: Any = None) Tuple[str, int][source]

Call a shell process and redirect the output for internal usage.

Parameters:
  • cmd – The command to execute in a subprocess call.

  • shell – Whether to use a shell or not for the execution of the command.

  • process_input – If there is any input needed for that command to stdin.

Returns:

A tuple of the output and the return code.

cobbler.utils.uniquify(seq: List[Any]) List[Any][source]

Remove duplicates from the sequence handed over in the args.

Parameters:

seq – The sequence to check for duplicates.

Returns:

The list without duplicates.