tools module

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

Bases: object

Timeout for FIFO. This does not work with threading.

handler(signum, frame)[source]

Timeout occur.

start(timeout)[source]

Start timer

stop()[source]

Stop timer before it come 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]

do the UNIX double-fork magic, see Stevens’ “Advanced Programming in the UNIX Environment” for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16

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
  • user_data – extra arguments which will be forwarded to callback function
  • filters (tuple) – Tuple of functions used to filter messages before sending them to callback
  • 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 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:returncode from command
Return type:int
class tools.OrderedSet(iterable=None)[source]

Bases: collections.abc.MutableSet

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

add(key)[source]
discard(key)[source]
pop(last=True)[source]
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]

Prepair 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 = {'e19': {'objectPath': '/org/enlightenment/wm/RemoteObject', 'interface': 'org.enlightenment.wm.Core', 'service': 'org.enlightenment.wm.service', 'method': 'Shutdown', 'bus': 'sessionbus', 'arguments': ()}, 'xfce': {'objectPath': '/org/xfce/SessionManager', 'interface': 'org.xfce.Session.Manager', 'service': 'org.xfce.SessionManager', 'method': 'Shutdown', 'bus': 'sessionbus', 'arguments': (True,)}, 'mate': {'objectPath': '/org/mate/SessionManager', 'interface': 'org.mate.SessionManager', 'service': 'org.mate.SessionManager', 'method': 'Shutdown', 'bus': 'sessionbus', 'arguments': ()}, 'kde': {'objectPath': '/KSMServer', 'interface': 'org.kde.KSMServerInterface', 'service': 'org.kde.ksmserver', 'method': 'logout', 'bus': 'sessionbus', 'arguments': (-1, 2, -1)}, 'z_freed': {'objectPath': '/org/freedesktop/login1', 'interface': 'org.freedesktop.login1.Manager', 'service': 'org.freedesktop.login1', 'method': 'PowerOff', 'bus': 'systembus', 'arguments': (True,)}, 'gnome': {'objectPath': '/org/gnome/SessionManager', 'interface': 'org.gnome.SessionManager', 'service': 'org.gnome.SessionManager', 'method': 'Shutdown', 'bus': 'sessionbus', 'arguments': ()}, 'e17': {'objectPath': '/org/enlightenment/Remote/RemoteObject', 'interface': 'org.enlightenment.Remote.Core', 'service': 'org.enlightenment.Remote.service', 'method': 'Halt', 'bus': 'sessionbus', 'arguments': ()}}
_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.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 joind 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.

Returns:True if X11 server is running
Return type:bool
tools.decodeOctalEscape(s)[source]

Decode octal-escaped characters with its ASCII dependance. 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.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.gitRevisionAndHash()[source]

Get the current Git Branch and the last HashID (shot form) if running from source.

Returns:
two items of either str instance if running from
source or None
Return type:tuple
tools.inhibitSuspend(app_id='/home/docs/checkouts/readthedocs.org/user_builds/backintime-dev/envs/latest/bin/sphinx-build', 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.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.keyringSupported()[source]
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)[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) – absolut 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 splitted 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 joind 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
  • use_mode (list) – if current mode is in this list add additional args for that mode
Returns:

SSH args for rsync

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 BackInTimes installation base path.

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 process was started with sudo
Return type:bool
tools.uuidFromDev(dev)[source]

Get the UUID for the block device dev.

Parameters:dev (str) – 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.wrapLine(msg, size=950, delimiters='\t ', new_line_indicator='CONTINUE: ')[source]

Wrap line msg into multiple lines with each shorter than size. Try to break the line on delimiters. New lines will start with new_line_indicator.

Parameters:
  • msg (str) – string that should get wrapped
  • size (int) – maximum lenght of returned strings
  • delimiters (str) – try to break msg on these characters
  • new_line_indicator (str) – start new lines with this string
Yields:

str – lines with max size lenght

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