tools module

Collection of helper functions not fitting to other modules.

class tools.Alarm(callback=None, overwrite=True)[source]

Bases: object

Establish a callback function that is called after a timeout.

The implementation uses a SIGALRM signal so do not call code in the callback that does not support multi-threading (reentrance) or you may cause non-deterministic “random” RTEs.

handler(signum, frame)[source]

This method is called after the timer ran down to zero and calls the callback function of the alarm instance.

Raises:

Timeout – If no callback function was set for the alarm instance

start(timeout)[source]

Start the timer (which calls the handler function when the timer ran down).

The start is silently ignored if the current timer is still ticking and the the attribute overwrite is False.

Parameters:

timeout – timer count down in seconds

stop()[source]

Stop timer before it comes to an end

class tools.Daemon(pidfile=None, stdin='/dev/null', stdout='/dev/stdout', stderr='/dev/null', umask=18)[source]

Bases: object

A generic daemon class.

Usage: subclass the Daemon class and override the run() method

Daemon Copyright by Sander Marechal License CC BY-SA 3.0 http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/

cleanupHandler(signum, frame)[source]
daemonize()[source]

“Converts” the current process into a daemon (= process running in the background) and sends a SIGTERM signal to the current process. This is done via the UNIX double-fork magic, see Stevens’ “Advanced Programming in the UNIX Environment” for details (ISBN 0201563177) and this explanation: https://stackoverflow.com/a/6011298

reload()[source]

send SIGHUP signal to process

restart()[source]

Restart the daemon

run()[source]

You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart().

start()[source]

Start the daemon

status()[source]

return status

stop()[source]

Stop the daemon

class tools.Execute(cmd, callback=None, user_data=None, filters=(), parent=None, conv_str=True, join_stderr=True)[source]

Bases: object

Execute external commands and handle its output.

Parameters:
  • cmd (str or list) – command with arguments that should be called. Depending on if this is str or list instance the command will be called by either os.system() (deprecated) or subprocess.Popen

  • callback (method) – function which will handle output returned by command (e.g. to extract errors)

  • user_data – extra arguments which will be forwarded to callback function (e.g. a tuple - which is passed by reference in Python - to “return” results of the callback function as side effect).

  • filters (tuple) – Tuple of functions used to filter messages before sending them to the callback function

  • parent (instance) – instance of the calling method used only to proper format log messages

  • conv_str (bool) – convert output to str if True or keep it as bytes if False

  • join_stderr (bool) – join stderr to stdout

Note

Signals SIGTSTP (“keyboard stop”) and SIGCONT send to Python main process will be forwarded to the command. SIGHUP will kill the process.

kill(signum, frame)[source]

Slot which will kill the command. Is connected to signal SIGHUP.

pause(signum, frame)[source]

Slot which will send SIGSTOP to the command. Is connected to signal SIGTSTP.

resume(signum, frame)[source]

Slot which will send SIGCONT to the command. Is connected to signal SIGCONT.

run()[source]

Start the command.

Returns:

return code from the command

Return type:

int

class tools.OrderedSet(iterable=None)[source]

Bases: MutableSet

OrderedSet from Python recipe http://code.activestate.com/recipes/576694/

add(key)[source]

Add an element.

discard(key)[source]

Remove an element. Do not raise an exception if absent.

pop(last=True)[source]

Return the popped value. Raise KeyError if empty.

class tools.PathHistory(path)[source]

Bases: object

append(path)[source]
next()[source]
previous()[source]
reset(path)[source]
class tools.SetupUdev[source]

Bases: object

Setup Udev rules for starting BackInTime when a drive get connected. This is done by serviceHelper.py script (included in backintime-qt) running as root though DBus.

CONNECTION = 'net.launchpad.backintime.serviceHelper'
INTERFACE = 'net.launchpad.backintime.serviceHelper.UdevRules'
MEMBERS = ('addRule', 'save', 'delete')
OBJECT = '/UdevRules'
addRule(cmd, uuid)[source]

Prepare rules in serviceHelper.py

clean()[source]

Clean up remote cache

save()[source]

Save rules with serviceHelper.py after authentication If no rules where added before this will delete current rule.

class tools.ShutDown[source]

Bases: object

Shutdown the system after the current snapshot has finished. This should work for KDE, Gnome, Unity, Cinnamon, XFCE, Mate and E17.

DBUS_SHUTDOWN = {'e17': {'arguments': (), 'bus': 'sessionbus', 'interface': 'org.enlightenment.Remote.Core', 'method': 'Halt', 'objectPath': '/org/enlightenment/Remote/RemoteObject', 'service': 'org.enlightenment.Remote.service'}, 'e19': {'arguments': (), 'bus': 'sessionbus', 'interface': 'org.enlightenment.wm.Core', 'method': 'Shutdown', 'objectPath': '/org/enlightenment/wm/RemoteObject', 'service': 'org.enlightenment.wm.service'}, 'gnome': {'arguments': (), 'bus': 'sessionbus', 'interface': 'org.gnome.SessionManager', 'method': 'Shutdown', 'objectPath': '/org/gnome/SessionManager', 'service': 'org.gnome.SessionManager'}, 'kde': {'arguments': (-1, 2, -1), 'bus': 'sessionbus', 'interface': 'org.kde.KSMServerInterface', 'method': 'logout', 'objectPath': '/KSMServer', 'service': 'org.kde.ksmserver'}, 'mate': {'arguments': (), 'bus': 'sessionbus', 'interface': 'org.mate.SessionManager', 'method': 'Shutdown', 'objectPath': '/org/mate/SessionManager', 'service': 'org.mate.SessionManager'}, 'xfce': {'arguments': (True,), 'bus': 'sessionbus', 'interface': 'org.xfce.Session.Manager', 'method': 'Shutdown', 'objectPath': '/org/xfce/SessionManager', 'service': 'org.xfce.SessionManager'}, 'z_freed': {'arguments': (True,), 'bus': 'systembus', 'interface': 'org.freedesktop.login1.Manager', 'method': 'PowerOff', 'objectPath': '/org/freedesktop/login1', 'service': 'org.freedesktop.login1'}}
_prepair()[source]

Try to connect to the given dbus services. If successful it will return a callable dbus proxy and those arguments.

askBeforeQuit()[source]

Indicate if ShutDown is ready to fire and so the application shouldn’t be closed.

canShutdown()[source]

Indicate if a valid dbus service is available to shutdown system.

shutdown()[source]

Run ‘shutdown -h now’ if we are root or call the dbus proxy to start the shutdown.

unity7()[source]

Unity >= 7.0 doesn’t shutdown automatically. It will only show shutdown dialog and wait for user input.

class tools.UniquenessSet(dc=False, follow_symlink=False, list_equal_to='')[source]

Bases: object

Check for uniqueness or equality of files.

Parameters:
  • dc (bool) – if True use deep check which will compare files md5sums if they are of same size but no hardlinks (don’t have the same inode). If False use files size and mtime

  • follow_symlink (bool) – if True check symlinks target instead of the link

  • list_equal_to (str) – full path to file. If not empty only return equal files to the given path instead of unique files.

check(input_path)[source]

Check file input_path for either uniqueness or equality (depending on list_equal_to from constructor).

Parameters:

input_path (str) – full path to file

Returns:

True if file is unique and list_equal_to

is empty. Or True if file is equal to file in list_equal_to

Return type:

bool

checkEqual(path)[source]

Check if path is equal to the file in list_equal_to from constructor.

Parameters:

path (str) – full path to file

Returns:

True if file is equal

Return type:

bool

checkUnique(path)[source]

Check file path for uniqueness and store a unique key for path.

Parameters:

path (str) – full path to file

Returns:

True if file is unique

Return type:

bool

tools._determine_current_used_language_code(translation, language_code)[source]

Return the language code used by GNU gettext for real.

Parameters:

The used language code can differ from the one in Back In Times config file and from the current systems locale.

It is necessary because of situations where the language is not explicit setup in Back In Time config file and GNU gettext do try to find and use a language file for the current systems locale. But even this can fail and the fallback (source language “en”) is used or an alternative locale.

tools._uuidFromDev_via_blkid_command(dev)[source]

Get the UUID for the block device dev via the extern command blkid.

Hint

On most systems the blkid command is available only for the super-user (e.g. via sudo).

Parameters:

dev (pathlib.Path) – The block device path (e.g. /dev/sda1).

Returns:

The UUID or None if nothing found.

Return type:

str

tools._uuidFromDev_via_filesystem(dev)[source]

Get the UUID for the block device dev from /dev/disk/by-uuid in the filesystem.

Parameters:

dev (pathlib.Path) – The block device path (e.g. /dev/sda1).

Returns:

The UUID or None if nothing found.

Return type:

str

tools._uuidFromDev_via_udevadm_command(dev)[source]

Get the UUID for the block device dev via the extern command udevadm.

Parameters:

dev (pathlib.Path) – The block device path (e.g. /dev/sda1).

Returns:

The UUID or None if nothing found.

Return type:

str

tools.addSourceToPathEnviron()[source]

Add ‘backintime/common’ path to ‘PATH’ environ variable.

tools.backintimePath(*path)[source]

Get path inside ‘backintime’ install folder.

Parameters:

*path (str) – paths that should be joined to ‘backintime’

Returns:

‘backintime’ child path like:

/usr/share/backintime/common
/usr/share/backintime/qt

Return type:

str

tools.camelCase(s)[source]

Remove underlines and make every first char uppercase.

Parameters:

s (str) – string separated by underlines (foo_bar)

Returns:

string without underlines but uppercase chars (FooBar)

Return type:

str

tools.checkCommand(cmd)[source]

Check if command cmd is a file in ‘PATH’ environ.

Parameters:

cmd (str) – command

Returns:

True if command cmd is in ‘PATH’ environ

Return type:

bool

tools.checkCronPattern(s)[source]

Check if s is a valid cron pattern. Examples:

0,10,13,15,17,20,23
*/6
Parameters:

s (str) – pattern to check

Returns:

True if s is a valid cron pattern

Return type:

bool

tools.checkHomeEncrypt()[source]

Return True if users home is encrypted

tools.checkXServer()[source]

Check if there is a X11 server running on this system.

Use is_Qt_working instead if you want to be sure that Qt is working.

Returns:

True if X11 server is running

Return type:

bool

tools.decodeOctalEscape(s)[source]

Decode octal-escaped characters with its ASCII dependence. For example ‘ ‘ will be a space ‘ ‘

Parameters:

s (str) – string with or without octal-escaped characters

Returns:

human readable string

Return type:

str

tools.device(path)[source]

Get the device for the filesystem of path. Example:

/dev/sda1
/dev/mapper/vglinux
proc
Parameters:

path (str) – full path

Returns:

device

Return type:

str

tools.docPath()[source]

Not sure what this path is about.

tools.envLoad(f)[source]

Load environ variables from file f into current environ. Do not overwrite existing environ variables.

Parameters:

f (str) – full path to file with environ variables

tools.envSave(f)[source]

Save environ variables to file that are needed by cron to connect to keyring. This will only work if the user is logged in.

Parameters:

f (str) – full path to file for environ variables

tools.escapeIPv6Address(address)[source]

Escape IPv6 Addresses with square brackets [].

Parameters:

address (str) – address that should be escaped

Returns:

address in square brackets

Return type:

str

tools.fdDup(old, new_fd, mode='w')[source]

Duplicate file descriptor old to new_fd and closing the latter first. Used to redirect stdin, stdout and stderr from daemonized threads.

Parameters:
  • old (str) – Path to the old file (e.g. /dev/stdout)

  • new_fd (_io.TextIOWrapper) – file object for the new file

  • mode (str) – mode in which the old file should be opened

tools.filesystem(path)[source]

Get the filesystem type for the filesystem of path.

Parameters:

path (str) – full path

Returns:

filesystem

Return type:

str

tools.filesystemMountInfo()[source]

Get a dict of mount point string -> dict of filesystem info for entire system.

Returns:

{MOUNTPOINT: {‘original_uuid’: UUID}}

Return type:

dict

tools.get_available_language_codes()[source]

Return language codes available in the current installation.

The filesystem is searched for backintime.mo files and the language code is extracted from the full path of that files.

Returns:

List of language codes.

tools.get_git_repository_info(path=None, hash_length=None)[source]

Return the current branch and last commit hash.

About the length of a commit hash. There is no strict rule but it is common sense that 8 to 10 characters are enough to be unique.

Credits: https://stackoverflow.com/a/51224861/4865723

Parameters:
  • path (Path) – Path with ‘.git’ folder in (default is current working directory).

  • cut_hash (int) – Restrict length of commit hash.

Returns:

Dict with keys “branch” and “hash” if it is a git repo,

otherwise an None.

Return type:

(dict)

tools.get_language_names(language_code)[source]

Return a list with language names in three different flavors.

Language codes from get_available_language_codes() are combined with languages.language_names to prepare the list.

Parameters:

language_code (str) – Usually the current language used by Back In Time.

Returns:

A dictionary indexed by language codes with 3-item tuples as values. Each tuple contain three representations of the same language: language_code (usually the current locales language), the language itself (native) and in English (the source language); e.g. ja (Japanese) for de (German) locale is ('Japanisch', '日本語', 'Japanese').

tools.get_native_language_and_completeness(language_code)[source]

Return the language name in its native flavor and the completeness of its translation in percent.

Parameters:

language_code (str) – The language code.

Returns:

A two-entry tuple with language name as string and a percent as integer.

tools.inhibitSuspend(app_id='/home/docs/checkouts/readthedocs.org/user_builds/backintime-dev/envs/latest/lib/python3.12/site-packages/sphinx/__main__.py', toplevel_xid=None, reason='take snapshot', flags=12)[source]

Prevent machine to go to suspend or hibernate. Returns the inhibit cookie which is used to end the inhibitor.

tools.initiate_translation(language_code)[source]

Initiate Class-based API of GNU gettext.

Parameters:

language_code (str) – Language code to use (based on ISO-639).

It installs the _() (and ngettext() for plural forms) in the builtins namespace and eliminates the need to import gettext and declare _() in each module. The systems current local is used if the language code is None.

tools.isIPv6Address(address)[source]

Check if address is a valid IPv6 address.

Parameters:

address (str) – address that should get tested

Returns:

True if address is a valid IPv6 address

Return type:

bool

tools.isRoot()[source]

Check if we are root.

Returns:

True if we are root

Return type:

bool

tools.is_Qt_working(systray_required=False)[source]

Check if the Qt GUI library is working (installed and configured)

This function is contained in BiT CLI (not BiT Qt) to allow Qt diagnostics output even if the BiT Qt GUI is not installed. This function does NOT add a hard Qt dependency (just “probing”) so it is OK to be in BiT CLI.

Parameters:
  • systray_required – Set to True if the systray of the desktop

  • "working" (environment must be available too to consider Qt as)

Returns:

True Qt can create a GUI
False Qt fails (or the systray is not available

if systray_required is True)

Return type:

bool

tools.keyringSupported()[source]

Checks if a keyring (supported by BiT) is available

Returns:

True if a supported keyring could be loaded

Return type:

bool

tools.makeDirs(path)[source]

Create directories path recursive and return success.

Parameters:

path (str) – fullpath to directories that should be created

Returns:

True if successful

Return type:

bool

tools.md5sum(path)[source]

Calculate md5sum for file in path.

Parameters:

path (str) – full path to file

Returns:

md5sum of file

Return type:

str

tools.mkdir(path, mode=493, enforce_permissions=True)[source]

Create directory path.

Parameters:
  • path (str) – full path to directory that should be created

  • mode (int) – numeric permission mode

Returns:

True if successful

Return type:

bool

tools.mountArgs(path)[source]

Get all /etc/mtab args for the filesystem of path as a list. Example:

[DEVICE,      MOUNTPOINT, FILESYSTEM_TYPE, OPTIONS,    DUMP, PASS]
['/dev/sda3', '/',        'ext4',          'defaults', '0',  '0']
['/dev/sda1', '/boot',    'ext4',          'defaults', '0',  '0']
Parameters:

path (str) – full path

Returns:

mount args

Return type:

list

tools.mountpoint(path)[source]

Get the mountpoint of path. If your HOME is on a separate partition mountpoint(‘/home/user/foo’) would return ‘/home’.

Parameters:

path (str) – full path

Returns:

mountpoint of the filesystem

Return type:

str

tools.onBattery()[source]

Checks if the system is on battery power.

Returns:

True if system is running on battery

Return type:

bool

tools.password(*args)[source]
tools.patternHasNotEncryptableWildcard(pattern)[source]

Check if pattern has wildcards [ ] ? *. but return False for foo/*, foo/*/bar, */bar or **/bar

Parameters:

pattern (str) – path or pattern to check

Returns:

True if pattern has wildcards [ ] ? * but

False if wildcard look like foo/*, foo/*/bar, */bar or **/bar

Return type:

bool

tools.pids()[source]

List all PIDs currently running on the system.

Returns:

PIDs as int

Return type:

list

tools.pidsWithName(name)[source]

Get all processes currently running with name name.

Parameters:

name (str) – name of a process like ‘python3’ or ‘backintime’

Returns:

PIDs as int

Return type:

list

tools.powerStatusAvailable()[source]

Check if org.freedesktop.UPower is available so that tools.onBattery() would return the correct power status.

Returns:

True if tools.onBattery() can report power status

Return type:

bool

tools.preparePath(path)[source]

Removes trailing slash ‘/’ from path.

Parameters:

path (str) – absolute path

Returns:

path path without trailing but with leading slash

Return type:

str

tools.processAlive(pid)[source]

Check if the process with PID pid is alive.

Parameters:

pid (int) – Process Indicator

Returns:

True if the process with PID pid is alive

Return type:

bool

Raises:

ValueError – If pid is 0 because ‘kill(0, SIG)’ would send SIG to all processes

tools.processCmdline(pid)[source]

Get the cmdline (command that spawnd this process) of the process with pid.

Parameters:

pid (int) – Process Indicator

Returns:

cmdline of the process

Return type:

str

tools.processExists(name)[source]

Check if process name is currently running.

Parameters:

name (str) – name of a process like ‘python3’ or ‘backintime’

Returns:

True if there is a process running with name

Return type:

bool

tools.processName(pid)[source]

Get the name of the process with pid.

Parameters:

pid (int) – Process Indicator

Returns:

name of the process

Return type:

str

tools.processPaused(pid)[source]

Check if process pid is paused (got signal SIGSTOP).

Parameters:

pid (int) – Process Indicator

Returns:

True if process is paused

Return type:

bool

tools.processStat(pid)[source]

Get the stat’s of the process with pid.

Parameters:

pid (int) – Process Indicator

Returns:

stat from /proc/PID/stat

Return type:

str

tools.readCrontab()[source]

Read users crontab.

Returns:

crontab lines

Return type:

list

tools.readFile(path, default=None)[source]

Read the file in path or its ‘.gz’ compressed variant and return its content or default if path does not exist.

Parameters:
  • path (str) – full path to file that should be read. ‘.gz’ will be added automatically if the file is compressed

  • default (str) – default if path does not exist

Returns:

content of file in path

Return type:

str

tools.readFileLines(path, default=None)[source]

Read the file in path or its ‘.gz’ compressed variant and return its content as a list of lines or default if path does not exist.

Parameters:
  • path (str) – full path to file that should be read. ‘.gz’ will be added automatically if the file is compressed

  • default (list) – default if path does not exist

Returns:

content of file in path split by lines.

Return type:

list

tools.readTimeStamp(fname)[source]

Read date string from file fname and try to return datetime.

Parameters:

fname (str) – full path to timestamp file

Returns:

date from timestamp file

Return type:

datetime.datetime

tools.registerBackintimePath(*path)[source]

Add BackInTime path path to sys.path so subsequent imports can discover them.

Parameters:

*path (str) – paths that should be joined to ‘backintime’

Note

Duplicate in qt/qttools.py() because modules in qt folder would need this to actually import tools.

tools.rsyncCaps(data=None)[source]

Get capabilities of the installed rsync binary. This can be different from version to version and also on build arguments used when building rsync.

Parameters:

data (str) – ‘rsync –version’ output. This is just for unittests.

Returns:

List of str with rsyncs capabilities

Return type:

list

tools.rsyncPrefix(config, no_perms=True, use_mode=['ssh', 'ssh_encfs'], progress=True)[source]

Get rsync command and all args for creating a new snapshot. Args are based on current profile in config.

Parameters:
Returns:

rsync command with all args but without

–include, –exclude, source and destination

Return type:

list

tools.rsyncRemove(config, run_local=True)[source]

Get rsync command and all args for removing snapshots with rsync.

Parameters:
  • config (config.Config) – current config

  • run_local (bool) – if True and current mode is ssh or ssh_encfs this will add SSH options

Returns:

rsync command with all args

Return type:

list

tools.rsyncSshArgs(config, use_mode=['ssh', 'ssh_encfs'])[source]

Get SSH args for rsync based on current profile in config.

Parameters:
  • config (config.Config) – Current config instance.

  • use_mode (list) – If the profiles current mode is in this list add additional args.

Returns:

List of rsync args related to SSH.

Return type:

list

tools.runningFromSource()[source]

Check if BackInTime is running from source (without installing).

Returns:

True if BackInTime is running from source

Return type:

bool

tools.setPassword(*args)[source]
tools.sharePath()[source]

Get path where Back In Time is installed.

This is similar to $XDG_DATA_DIRS (XDG Base Directory Specification). If running from source return default /usr/share.

Returns:

share path like:

/usr/share
/usr/local/share
/opt/usr/share

Return type:

str

tools.splitCommands(cmds, head='', tail='', maxLength=0)[source]

Split a list of commands cmds into multiple commands with each length lower than maxLength.

Parameters:
  • cmds (list) – commands

  • head (str) – command that need to run first on every iteration of cmds

  • tail (str) – command that need to run after every iteration of cmds

  • maxLength (int) – maximum length a command could be. Don’t split if <= 0

Yields:

str – new command with length < maxLength

Example:

head cmds[0] cmds[n] tail
tools.syncfs()[source]

Sync any data buffered in memory to disk.

Returns:

True if successful

Return type:

bool

tools.tempFailureRetry(func, *args, **kwargs)[source]
tools.unInhibitSuspend(cookie, bus, dbus_props)[source]

Release inhibit.

tools.usingSudo()[source]

Check if ‘sudo’ was used to start this process.

Returns:

True if the process was started with sudo

Return type:

bool

tools.uuidFromDev(dev)[source]

Get the UUID for the block device dev.

Parameters:

dev (str, pathlib.Path) – block device path

Returns:

UUID

Return type:

str

tools.uuidFromPath(path)[source]

Get the UUID for the for the filesystem of path.

Parameters:

path (str) – full path

Returns:

UUID

Return type:

str

tools.which(cmd)[source]

Get the fullpath of executable command cmd. Works like command-line ‘which’ command.

Parameters:

cmd (str) – command

Returns:

fullpath of command cmd or None if command is

not available

Return type:

str

tools.writeCrontab(lines)[source]

Write to users crontab.

Note

This will overwrite the whole crontab. So to keep the old crontab and only add new entries you need to read it first with tools.readCrontab(), append new entries to the list and write it back.

Parameters:

lines (list, tuple) – lines that should be written to crontab

Returns:

True if successful

Return type:

bool

tools.writeTimeStamp(fname)[source]

Write current date and time into file fname.

Parameters:

fname (str) – full path to timestamp file