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
- 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/
- 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
- 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
orlist
) – command with arguments that should be called. Depending on if this isstr
orlist
instance the command will be called by eitheros.system()
(deprecated) orsubprocess.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
functionparent (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 asbytes
if Falsejoin_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.
- pause(signum, frame)[source]
Slot which will send
SIGSTOP
to the command. Is connected to signalSIGTSTP
.
- class tools.OrderedSet(iterable=None)[source]
Bases:
MutableSet
OrderedSet from Python recipe http://code.activestate.com/recipes/576694/
- 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'
- 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.
- 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). IfFalse
use files size and mtimefollow_symlink (bool) – if
True
check symlinks target instead of the linklist_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 onlist_equal_to
from constructor).
- tools._determine_current_used_language_code(translation, language_code)[source]
Return the language code used by GNU gettext for real.
- Parameters:
translation (gettext.NullTranslations) – The translation installed.
language_code (str) – Configured language code.
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 commandblkid
.Hint
On most systems the
blkid
command is available only for the super-user (e.g. viasudo
).- Parameters:
dev (pathlib.Path) – The block device path (e.g.
/dev/sda1
).- Returns:
The UUID or
None
if nothing found.- Return type:
- 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:
- tools._uuidFromDev_via_udevadm_command(dev)[source]
Get the UUID for the block device
dev
via the extern commandudevadm
.- Parameters:
dev (pathlib.Path) – The block device path (e.g.
/dev/sda1
).- Returns:
The UUID or
None
if nothing found.- Return type:
- tools.checkCronPattern(s)[source]
Check if
s
is a valid cron pattern. Examples:0,10,13,15,17,20,23 */6
- 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:
- tools.decodeOctalEscape(s)[source]
Decode octal-escaped characters with its ASCII dependence. For example ‘ ‘ will be a space ‘ ‘
- tools.device(path)[source]
Get the device for the filesystem of
path
. Example:/dev/sda1 /dev/mapper/vglinux proc
- 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.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.
- tools.filesystemMountInfo()[source]
Get a dict of mount point string -> dict of filesystem info for entire system.
- Returns:
{MOUNTPOINT: {‘original_uuid’: UUID}}
- Return type:
- 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.
- 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) forde
(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
_()
(andngettext()
for plural forms) in thebuiltins
namespace and eliminates the need toimport gettext
and declare_()
in each module. The systems current local is used if the language code is None.
- 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 GUIFalse
Qt fails (or the systray is not availableif
systray_required
isTrue
)
- Return type:
- tools.keyringSupported()[source]
Checks if a keyring (supported by BiT) is available
- Returns:
True
if a supported keyring could be loaded- Return type:
- 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']
- tools.mountpoint(path)[source]
Get the mountpoint of
path
. If your HOME is on a separate partition mountpoint(‘/home/user/foo’) would return ‘/home’.
- tools.onBattery()[source]
Checks if the system is on battery power.
- Returns:
True
if system is running on battery- Return type:
- tools.patternHasNotEncryptableWildcard(pattern)[source]
Check if
pattern
has wildcards[ ] ? *
. but returnFalse
forfoo/*
,foo/*/bar
,*/bar
or**/bar
- tools.pids()[source]
List all PIDs currently running on the system.
- Returns:
PIDs as int
- Return type:
- tools.powerStatusAvailable()[source]
Check if org.freedesktop.UPower is available so that
tools.onBattery()
would return the correct power status.- Returns:
True
iftools.onBattery()
can report power status- Return type:
- tools.processAlive(pid)[source]
Check if the process with PID
pid
is alive.- Parameters:
pid (int) – Process Indicator
- Returns:
True
if the process with PIDpid
is alive- Return type:
- 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
.
- tools.readFile(path, default=None)[source]
Read the file in
path
or its ‘.gz’ compressed variant and return its content ordefault
ifpath
does not exist.
- 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 ordefault
ifpath
does not exist.
- 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:
- tools.registerBackintimePath(*path)[source]
Add BackInTime path
path
tosys.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 importtools
.
- 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.
- 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:
config (config.Config) – current config
no_perms (bool) – don’t sync permissions (–no-p –no-g –no-o) if
True
.config.Config.preserveAcl()
==True
orconfig.Config.preserveXattr()
==True
will overwrite this toFalse
use_mode (list) – if current mode is in this list add additional args for that mode
progress (bool) – add ‘–info=progress2’ to show progress
- Returns:
- rsync command with all args but without
–include, –exclude, source and destination
- Return type:
- 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
orssh_encfs
this will add SSH options
- Returns:
rsync command with all args
- Return type:
- 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:
- tools.runningFromSource()[source]
Check if BackInTime is running from source (without installing).
- Returns:
True
if BackInTime is running from source- Return type:
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:
- tools.splitCommands(cmds, head='', tail='', maxLength=0)[source]
Split a list of commands
cmds
into multiple commands with each length lower thanmaxLength
.- Parameters:
- 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:
- tools.usingSudo()[source]
Check if ‘sudo’ was used to start this process.
- Returns:
True
if the process was started with sudo- Return type:
- tools.uuidFromDev(dev)[source]
Get the UUID for the block device
dev
.- Parameters:
dev (str, pathlib.Path) – block device path
- Returns:
UUID
- Return type:
- tools.which(cmd)[source]
Get the fullpath of executable command
cmd
. Works like command-line ‘which’ command.
- 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.