1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
|
# SPDX-FileCopyrightText: © 2008-2022 Oprea Dan
# SPDX-FileCopyrightText: © 2008-2022 Bart de Koning
# SPDX-FileCopyrightText: © 2008-2022 Richard Bailey
# SPDX-FileCopyrightText: © 2008-2022 Germar Reitze
# SPDX-FileCopyrightText: © 2025 Christian Buhtz <c.buhtz@posteo.jp>
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This file is part of the program "Back In Time" which is released under GNU
# General Public License v2 (GPLv2). See LICENSES directory or go to
# <https://spdx.org/licenses/GPL-2.0-or-later.html>.
#
# Split from backintime.py
"""Module about CLI commands"""
import sys
import argparse
from datetime import datetime
from time import sleep
import tools
# Workaround for situations where startApp() is not invoked.
# E.g. when using --diagnostics and other argparse.Action
tools.initiate_translation(None)
import logger
import snapshots
import sshtools
import password
import encfstools
import cli
import config
import bitbase
import mount
from exceptions import MountException
from applicationinstance import ApplicationInstance
from shutdownagent import ShutdownAgent
def _deprecation_msg(cmd_flag: str, replacement: str) -> str:
if not replacement:
replacement = 'A replacement is not planned.'
kind = 'flag' if cmd_flag[0] == '-' else 'command'
return (
f'The {kind} "{cmd_flag}" is deprecated and will be removed from Back '
f'In Time in the foreseeable future. {replacement} Feel free to '
'contact the project team if you have any questions or suggestions.')
def show_deprecation_message(cmd_flag: str):
"""Centralize management of deprecation message regarding CLI commands and
flags.
As an exception the deprecation messages for flag-aliases (e.g. '--backup'
for 'backup') are managed in `cliargument.alias_parser()`.
"""
# 'None' means no replacement planned.
replacement = {
'benchmark-cipher': None,
'snapshots-path': None,
'snapshots-list': 'Use "show" instead.',
'snapshots-list-path': 'Use "show --path" instead.',
'last-snapshot': 'Use "show --last" instead.',
'last-snapshot-path': 'Use "show --last --path" instead.',
'backup-job': 'Use "backup --background" instead.',
'smart-remove': 'Use "prune" instead.',
'remove-and-do-not-ask-again':
'Use "remove --skip-confirmation" instead.',
'--profile-id': 'Use "--profile" instead.',
'--share-path': None,
'decode': None,
}[cmd_flag]
msg = _deprecation_msg(cmd_flag, replacement)
# ToDo: Switch this later to ERROR
logger.warning(msg)
def _get_config(args: argparse.Namespace) -> config.Config:
"""A dirty little helper. Feel free to refactor."""
return cli.get_config_and_select_profile(
config_path=args.config,
data_path=args.share_path,
profile=args.profile,
checksum=getattr(args, 'checksum', None)
)
def backup(args: argparse.Namespace, force: bool = True):
"""
Command for force taking a new snapshot.
Args:
args (argparse.Namespace):
previously parsed arguments
force (bool): take the snapshot even if it wouldn't need to or would
be prevented (e.g. running on battery)
Raises:
SystemExit: 0 if successful, 1 if not
"""
# Run backup in background?
if args.background:
# "Force" will be False
cli.BackupJobDaemon(_do_backup, args).start()
else:
_do_backup(args, force)
def _do_backup(args: argparse.Namespace, force: bool):
"""
Command for force taking a new snapshot.
Args:
args (argparse.Namespace):
previously parsed arguments
force (bool): take the snapshot even if it wouldn't need to or would
be prevented (e.g. running on battery)
Raises:
SystemExit: 0 if successful, 1 if not
"""
cli.set_quiet(args)
cli.print_header()
cfg = _get_config(args)
tools.envLoad(cfg.cronEnvFile())
ret = snapshots.Snapshots(cfg).backup(force)
sys.exit(int(ret))
def backup_job(args: argparse.Namespace):
"""
Command for taking a new snapshot in background. Mainly used for cronjobs.
This will run the snapshot inside a daemon and detach from it. It will
return immediately back to commandline.
Args:
args: Previously parsed arguments
Raises:
SystemExit: 0
"""
show_deprecation_message('backup-job')
args.background = True
backup(args)
def benchmark_cipher(args: argparse.Namespace):
"""
Command for transferring a file with scp to remote host with all
available ciphers and print its speed and time.
Args:
args: Previously parsed arguments.
Raises:
SystemExit: 0
"""
show_deprecation_message('benchmark-cipher')
cli.set_quiet(args)
cli.print_header()
cfg = _get_config(args)
if cfg.snapshotsMode() in ('ssh', 'ssh_encfs'):
ssh = sshtools.SSH(cfg)
ssh.benchmarkCipher(args.FILE_SIZE)
sys.exit(bitbase.RETURN_OK)
# else
logger.error(
f"SSH is not configured for profile '{cfg.profileName()}'!")
sys.exit(bitbase.RETURN_ERR)
def check_config(args: argparse.Namespace):
"""Check the config file.
In case of no errors application exists with 0, otherwise 1.
Args:
args: Previously parsed arguments.
Raises:
SystemExit: 0 if config is okay, 1 if not.
"""
force_stdout = cli.set_quiet(args)
cli.print_header()
cfg = _get_config(args)
msg = f'\nConfig {cfg._LOCAL_CONFIG_PATH} profile ' \
f"'{cfg.profileName()}'"
if cli.checkConfig(cfg, crontab=not args.no_crontab):
print(f'{msg} is fine.', file=force_stdout)
sys.exit(bitbase.RETURN_OK)
# else
print(f'{msg} has errors.', file=force_stdout)
sys.exit(bitbase.RETURN_ERR)
def decode(args: argparse.Namespace):
"""Decoding paths given paths with 'encfsctl'.
Will listen on stdin if no path was given.
Args:
args: Previously parsed arguments
Raises:
SystemExit: 0
"""
show_deprecation_message('decode')
force_stdout = cli.set_quiet(args)
cfg = _get_config(args)
if cfg.snapshotsMode() not in ('local_encfs', 'ssh_encfs'):
logger.error(f"Profile '{cfg.profileName()}' is not encrypted.")
sys.exit(bitbase.RETURN_ERR)
_mount(cfg)
decoder = encfstools.Decode(cfg)
if not args.PATH:
while True:
try:
path = input()
except EOFError:
break
if not path:
break
print(decoder.path(path), file=force_stdout)
else:
print('\n'.join(decoder.list(args.PATH)), file=force_stdout)
decoder.close()
_umount(cfg)
sys.exit(bitbase.RETURN_OK)
def _last_snapshot_base(args: argparse.Namespace, path_info: bool):
"""Print info about the very last (youngest) snapshot in current profile.
Args:
args: Previously parsed arguments
Raises:
SystemExit: 0
"""
force_stdout = cli.set_quiet(args)
cfg = _get_config(args)
_mount(cfg)
sid = snapshots.lastSnapshot(cfg)
if sid:
# Path or ID
label = 'SnapshotPath' if path_info else 'SnapshotID'
data = sid.path() if path_info else sid
msg = f'{data}' if args.quiet else f'{label}: {data}'
print(msg, file=force_stdout)
else:
logger.error(f"There are no snapshots in '{cfg.profileName()}'")
if not getattr(args, 'keep_mount', None):
_umount(cfg)
sys.exit(bitbase.RETURN_OK)
def last_snapshot(args: argparse.Namespace):
"""Print the very last (youngest) snapshot in current profile.
Args:
args: Previously parsed arguments
Raises:
SystemExit: 0
"""
show_deprecation_message('last-snapshot')
_last_snapshot_base(args=args, path_info=False)
def last_snapshot_path(args: argparse.Namespace):
"""Print the path of the very last (youngest) snapshot in
current profile.
Args:
args: Previously parsed arguments.
Raises:
SystemExit: 0
"""
show_deprecation_message('last-snapshot-path')
_last_snapshot_base(args=args, path_info=True)
def pw_cache(args: argparse.Namespace):
"""Startpassword cache daemon.
Args:
args: Previously parsed arguments
Raises:
SystemExit: 0 if daemon is running, 1 if not.
"""
force_stdout = cli.set_quiet(args)
cli.print_header()
cfg = _get_config(args)
ret = bitbase.RETURN_OK
daemon = password.Password_Cache(cfg)
if args.ACTION and args.ACTION != 'status':
# call action method
getattr(daemon, args.ACTION)()
elif args.ACTION == 'status':
print(f'{cfg.APP_NAME} Password Cache: ', end=' ', file=force_stdout)
if daemon.status():
print(f'{cli.bcolors.OKGREEN}running{cli.bcolors.ENDC}',
file=force_stdout)
ret = bitbase.RETURN_OK
else:
print(f'{cli.bcolors.FAIL}not running{cli.bcolors.ENDC}',
file=force_stdout)
ret = bitbase.RETURN_ERR
else:
daemon.run()
sys.exit(ret)
def remove(args: argparse.Namespace):
"""Remove snapshots.
Args:
args: Previously parsed arguments.
Raises:
SystemExit: 0
"""
cli.set_quiet(args)
cli.print_header()
cfg = _get_config(args)
_mount(cfg)
cli.remove(
cfg=cfg,
snapshot_ids=args.BACKUP_ID,
force=args.skip_confirmation)
_umount(cfg)
sys.exit(bitbase.RETURN_OK)
def remove_and_donot_ask_again(args):
"""Removing snapshots without asking (BE CAREFUL!).
Args:
args: Previously parsed arguments.
Raises:
SystemExit: 0
"""
show_deprecation_message('remove-and-do-not-ask-again')
args.skip_confirmation = True
remove(args=args)
def restore(args: argparse.Namespace):
"""Restore files from snapshots.
Args:
args: Previously parsed arguments.
Raises:
SystemExit: 0
"""
cli.set_quiet(args)
cli.print_header()
cfg = _get_config(args)
_mount(cfg)
if cfg.backupOnRestore() and not args.no_local_backup:
isbackup = True
else:
isbackup = args.local_backup
cli.restore(cfg,
args.BACKUP_ID,
args.WHAT,
args.WHERE,
delete=args.delete,
backup=isbackup,
only_new=args.only_new)
_umount(cfg)
sys.exit(bitbase.RETURN_OK)
def shutdown(args: argparse.Namespace):
"""Shut down the computer after the current snapshot has
finished.
Args:
args: Previously parsed arguments
Raises:
SystemExit: 0 if successful; 1 if it failed either because there is no
active snapshot for this profile or shutdown is not supported.
"""
cli.set_quiet(args)
cli.print_header()
cfg = _get_config(args)
sd = ShutdownAgent()
if not sd.can_shutdown():
logger.warning('Shutdown is not supported.')
sys.exit(bitbase.RETURN_ERR)
instance = ApplicationInstance(cfg.takeSnapshotInstanceFile(), False)
profile = '='.join((cfg.currentProfile(), cfg.profileName()))
if not instance.busy():
logger.info('Skip shutdown because there is no active bacukp '
f'for profile {profile}.')
sys.exit(bitbase.RETURN_ERR)
print(f'Shutdown is waiting for the running backup in profile {profile} '
'to end.\nPress CTRL+C to interrupt shutdown.\n')
sd.activate_shutdown = True
try:
while instance.busy():
logger.debug('Backup is still active. Wait for shutdown.')
sleep(5)
except KeyboardInterrupt:
print('Shutdown interrupted.')
else:
logger.info('Shuting down now.')
sd.shutdown()
sys.exit(bitbase.RETURN_OK)
def snapshots_path(args: argparse.Namespace):
"""Print the full snapshot path of current profile.
Args:
args: Previously parsed arguments.
Raises:
SystemExit: 0
"""
show_deprecation_message('snapshots-path')
force_stdout = cli.set_quiet(args)
cfg = _get_config(args)
if args.keep_mount:
_mount(cfg)
msg = '{}' if args.quiet else 'SnapshotsPath: {}'
print(msg.format(cfg.snapshotsFullPath()), file=force_stdout)
sys.exit(bitbase.RETURN_OK)
def _snapshots_list_base(args: argparse.Namespace, path_info: bool):
"""Print infos about a list of all snapshots in current profile.
Args:
args: Ppreviously parsed arguments
Raises:
SystemExit: 0
"""
force_stdout = cli.set_quiet(args)
cfg = _get_config(args)
_mount(cfg)
if path_info:
msg = '{}' if args.quiet else 'SnapshotPath: {}'
else:
msg = '{}' if args.quiet else 'SnapshotID: {}'
# Use snapshots.listSnapshots instead of iterSnapshots because of sorting
if path_info:
data = [
sid.path() for sid in snapshots.listSnapshots(cfg, reverse=False)]
else:
data = list(snapshots.listSnapshots(cfg, reverse=False))
for sid_info in data:
print(msg.format(sid_info), file=force_stdout)
if not data:
logger.error(f"There are no snapshots in '{cfg.profileName()}'")
if not args.keep_mount:
_umount(cfg)
sys.exit(bitbase.RETURN_OK)
def snapshots_list(args: argparse.Namespace):
"""Print a list of all snapshots in current profile.
Args:
args: Ppreviously parsed arguments
Raises:
SystemExit: 0
"""
show_deprecation_message('snapshots-list')
_snapshots_list_base(args=args, path_info=False)
def snapshots_list_path(args: argparse.Namespace):
"""Print a list of all snapshots paths in current profile.
Args:
args: Previously parsed arguments.
Raises:
SystemExit: 0
"""
show_deprecation_message('snapshots-list-path')
_snapshots_list_base(args=args, path_info=True)
def show_backups(args: argparse.Namespace):
"""Command 'show'.
Args:
args: Parsed command-line arguments.
Raises:
SystemExit: With errors or no backups available
`bitbase.RETURN_ERR` (1), otherwise `bitbase.RETURN_OK' (0).
"""
cfg = _get_config(args)
_mount(cfg)
# raw data
backups = snapshots.get_backup_ids_and_paths(
cfg=cfg, descending=True, include_new=False)
if args.last:
backups = backups[-1:]
if args.path:
# Path
def _element(e):
return str(e[1])
else:
# ID
def _element(e):
return e[0]
# one line for each ID/Path
result = '\n'.join(
map(_element, backups)
)
print(result)
_umount(cfg)
if not backups:
logger.error(f'No backups in profile "{cfg.profileName()}"')
sys.exit(bitbase.RETURN_ERR)
sys.exit(bitbase.RETURN_OK)
def smart_remove(args: argparse.Namespace):
show_deprecation_message('smart-remove')
prune(args)
def prune(args: argparse.Namespace):
"""Run Remove & Retention (aka Smart-Removal).
Args:
args: Previously parsed arguments.
Raises:
SystemExit: 0 if okay. 2 if Remove & Retention is not configured.
"""
cli.set_quiet(args)
cli.print_header()
cfg = _get_config(args)
sn = snapshots.Snapshots(cfg)
enabled, \
keep_all, \
keep_one_per_day, \
keep_one_per_week, \
keep_one_per_month = cfg.smartRemove()
if enabled:
_mount(cfg)
del_snapshots = sn.smartRemoveList(datetime.today(),
keep_all,
keep_one_per_day,
keep_one_per_week,
keep_one_per_month)
logger.info(f'{len(del_snapshots)} backups are marked for removal.')
sn.smartRemove(del_snapshots, log=logger.info)
_umount(cfg)
sys.exit(bitbase.RETURN_OK)
# else
logger.error('Remove & Retention is not configured.')
sys.exit(bitbase.RETURN_NO_CFG)
def unmount(args):
"""Unmount all filesystems.
Args:
args: Previously parsed arguments
Raises:
SystemExit: 0
"""
cli.set_quiet(args)
cfg = _get_config(args)
_mount(cfg)
_umount(cfg)
sys.exit(bitbase.RETURN_OK)
def _mount(cfg: config.Config):
"""Mount external filesystems of current selected profile.
Args:
cfg: Config to identify the current profile.
"""
try:
hash_id = mount.Mount(cfg=cfg).mount()
except MountException as ex:
logger.error(str(ex))
sys.exit(bitbase.RETURN_ERR)
else:
cfg.setCurrentHashId(hash_id)
def _umount(cfg: config.Config):
"""Unmount external filesystems of current selected profile.
Args:
cfg: Config to identify the current profile.
"""
try:
mount.Mount(cfg=cfg).umount(cfg.current_hash_id)
except MountException as ex:
logger.error(str(ex))
|