/usr/lib/python3/dist-packages/CedarBackup3/peer.py is in cedar-backup3 3.1.7-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 | # -*- coding: iso-8859-1 -*-
# vim: set ft=python ts=3 sw=3 expandtab:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# C E D A R
# S O L U T I O N S "Software done right."
# S O F T W A R E
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Copyright (c) 2004-2008,2010,2015 Kenneth J. Pronovici.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License,
# Version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# Copies of the GNU General Public License are available from
# the Free Software Foundation website, http://www.gnu.org/.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Author : Kenneth J. Pronovici <pronovic@ieee.org>
# Language : Python 3 (>= 3.4)
# Project : Cedar Backup, release 3
# Purpose : Provides backup peer-related objects.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
########################################################################
# Module documentation
########################################################################
"""
Provides backup peer-related objects and utility functions.
@sort: LocalPeer, RemotePeer
@var DEF_COLLECT_INDICATOR: Name of the default collect indicator file.
@var DEF_STAGE_INDICATOR: Name of the default stage indicator file.
@author: Kenneth J. Pronovici <pronovic@ieee.org>
"""
########################################################################
# Imported modules
########################################################################
# System modules
import os
import logging
import shutil
# Cedar Backup modules
from CedarBackup3.filesystem import FilesystemList
from CedarBackup3.util import resolveCommand, executeCommand, isRunningAsRoot
from CedarBackup3.util import splitCommandLine, encodePath
from CedarBackup3.config import VALID_FAILURE_MODES
########################################################################
# Module-wide constants and variables
########################################################################
logger = logging.getLogger("CedarBackup3.log.peer")
DEF_RCP_COMMAND = [ "/usr/bin/scp", "-B", "-q", "-C" ]
DEF_RSH_COMMAND = [ "/usr/bin/ssh", ]
DEF_CBACK_COMMAND = "/usr/bin/cback3"
DEF_COLLECT_INDICATOR = "cback.collect"
DEF_STAGE_INDICATOR = "cback.stage"
SU_COMMAND = [ "su" ]
########################################################################
# LocalPeer class definition
########################################################################
class LocalPeer(object):
######################
# Class documentation
######################
"""
Backup peer representing a local peer in a backup pool.
This is a class representing a local (non-network) peer in a backup pool.
Local peers are backed up by simple filesystem copy operations. A local
peer has associated with it a name (typically, but not necessarily, a
hostname) and a collect directory.
The public methods other than the constructor are part of a "backup peer"
interface shared with the C{RemotePeer} class.
@sort: __init__, stagePeer, checkCollectIndicator, writeStageIndicator,
_copyLocalDir, _copyLocalFile, name, collectDir
"""
##############
# Constructor
##############
def __init__(self, name, collectDir, ignoreFailureMode=None):
"""
Initializes a local backup peer.
Note that the collect directory must be an absolute path, but does not
have to exist when the object is instantiated. We do a lazy validation
on this value since we could (potentially) be creating peer objects
before an ongoing backup completed.
@param name: Name of the backup peer
@type name: String, typically a hostname
@param collectDir: Path to the peer's collect directory
@type collectDir: String representing an absolute local path on disk
@param ignoreFailureMode: Ignore failure mode for this peer
@type ignoreFailureMode: One of VALID_FAILURE_MODES
@raise ValueError: If the name is empty.
@raise ValueError: If collect directory is not an absolute path.
"""
self._name = None
self._collectDir = None
self._ignoreFailureMode = None
self.name = name
self.collectDir = collectDir
self.ignoreFailureMode = ignoreFailureMode
#############
# Properties
#############
def _setName(self, value):
"""
Property target used to set the peer name.
The value must be a non-empty string and cannot be C{None}.
@raise ValueError: If the value is an empty string or C{None}.
"""
if value is None or len(value) < 1:
raise ValueError("Peer name must be a non-empty string.")
self._name = value
def _getName(self):
"""
Property target used to get the peer name.
"""
return self._name
def _setCollectDir(self, value):
"""
Property target used to set the collect directory.
The value must be an absolute path and cannot be C{None}.
It does not have to exist on disk at the time of assignment.
@raise ValueError: If the value is C{None} or is not an absolute path.
@raise ValueError: If a path cannot be encoded properly.
"""
if value is None or not os.path.isabs(value):
raise ValueError("Collect directory must be an absolute path.")
self._collectDir = encodePath(value)
def _getCollectDir(self):
"""
Property target used to get the collect directory.
"""
return self._collectDir
def _setIgnoreFailureMode(self, value):
"""
Property target used to set the ignoreFailure mode.
If not C{None}, the mode must be one of the values in L{VALID_FAILURE_MODES}.
@raise ValueError: If the value is not valid.
"""
if value is not None:
if value not in VALID_FAILURE_MODES:
raise ValueError("Ignore failure mode must be one of %s." % VALID_FAILURE_MODES)
self._ignoreFailureMode = value
def _getIgnoreFailureMode(self):
"""
Property target used to get the ignoreFailure mode.
"""
return self._ignoreFailureMode
name = property(_getName, _setName, None, "Name of the peer.")
collectDir = property(_getCollectDir, _setCollectDir, None, "Path to the peer's collect directory (an absolute local path).")
ignoreFailureMode = property(_getIgnoreFailureMode, _setIgnoreFailureMode, None, "Ignore failure mode for peer.")
#################
# Public methods
#################
def stagePeer(self, targetDir, ownership=None, permissions=None):
"""
Stages data from the peer into the indicated local target directory.
The collect and target directories must both already exist before this
method is called. If passed in, ownership and permissions will be
applied to the files that are copied.
@note: The caller is responsible for checking that the indicator exists,
if they care. This function only stages the files within the directory.
@note: If you have user/group as strings, call the L{util.getUidGid} function
to get the associated uid/gid as an ownership tuple.
@param targetDir: Target directory to write data into
@type targetDir: String representing a directory on disk
@param ownership: Owner and group that the staged files should have
@type ownership: Tuple of numeric ids C{(uid, gid)}
@param permissions: Permissions that the staged files should have
@type permissions: UNIX permissions mode, specified in octal (i.e. C{0640}).
@return: Number of files copied from the source directory to the target directory.
@raise ValueError: If collect directory is not a directory or does not exist
@raise ValueError: If target directory is not a directory, does not exist or is not absolute.
@raise ValueError: If a path cannot be encoded properly.
@raise IOError: If there were no files to stage (i.e. the directory was empty)
@raise IOError: If there is an IO error copying a file.
@raise OSError: If there is an OS error copying or changing permissions on a file
"""
targetDir = encodePath(targetDir)
if not os.path.isabs(targetDir):
logger.debug("Target directory [%s] not an absolute path.", targetDir)
raise ValueError("Target directory must be an absolute path.")
if not os.path.exists(self.collectDir) or not os.path.isdir(self.collectDir):
logger.debug("Collect directory [%s] is not a directory or does not exist on disk.", self.collectDir)
raise ValueError("Collect directory is not a directory or does not exist on disk.")
if not os.path.exists(targetDir) or not os.path.isdir(targetDir):
logger.debug("Target directory [%s] is not a directory or does not exist on disk.", targetDir)
raise ValueError("Target directory is not a directory or does not exist on disk.")
count = LocalPeer._copyLocalDir(self.collectDir, targetDir, ownership, permissions)
if count == 0:
raise IOError("Did not copy any files from local peer.")
return count
def checkCollectIndicator(self, collectIndicator=None):
"""
Checks the collect indicator in the peer's staging directory.
When a peer has completed collecting its backup files, it will write an
empty indicator file into its collect directory. This method checks to
see whether that indicator has been written. We're "stupid" here - if
the collect directory doesn't exist, you'll naturally get back C{False}.
If you need to, you can override the name of the collect indicator file
by passing in a different name.
@param collectIndicator: Name of the collect indicator file to check
@type collectIndicator: String representing name of a file in the collect directory
@return: Boolean true/false depending on whether the indicator exists.
@raise ValueError: If a path cannot be encoded properly.
"""
collectIndicator = encodePath(collectIndicator)
if collectIndicator is None:
return os.path.exists(os.path.join(self.collectDir, DEF_COLLECT_INDICATOR))
else:
return os.path.exists(os.path.join(self.collectDir, collectIndicator))
def writeStageIndicator(self, stageIndicator=None, ownership=None, permissions=None):
"""
Writes the stage indicator in the peer's staging directory.
When the master has completed collecting its backup files, it will write
an empty indicator file into the peer's collect directory. The presence
of this file implies that the staging process is complete.
If you need to, you can override the name of the stage indicator file by
passing in a different name.
@note: If you have user/group as strings, call the L{util.getUidGid}
function to get the associated uid/gid as an ownership tuple.
@param stageIndicator: Name of the indicator file to write
@type stageIndicator: String representing name of a file in the collect directory
@param ownership: Owner and group that the indicator file should have
@type ownership: Tuple of numeric ids C{(uid, gid)}
@param permissions: Permissions that the indicator file should have
@type permissions: UNIX permissions mode, specified in octal (i.e. C{0640}).
@raise ValueError: If collect directory is not a directory or does not exist
@raise ValueError: If a path cannot be encoded properly.
@raise IOError: If there is an IO error creating the file.
@raise OSError: If there is an OS error creating or changing permissions on the file
"""
stageIndicator = encodePath(stageIndicator)
if not os.path.exists(self.collectDir) or not os.path.isdir(self.collectDir):
logger.debug("Collect directory [%s] is not a directory or does not exist on disk.", self.collectDir)
raise ValueError("Collect directory is not a directory or does not exist on disk.")
if stageIndicator is None:
fileName = os.path.join(self.collectDir, DEF_STAGE_INDICATOR)
else:
fileName = os.path.join(self.collectDir, stageIndicator)
LocalPeer._copyLocalFile(None, fileName, ownership, permissions) # None for sourceFile results in an empty target
##################
# Private methods
##################
@staticmethod
def _copyLocalDir(sourceDir, targetDir, ownership=None, permissions=None):
"""
Copies files from the source directory to the target directory.
This function is not recursive. Only the files in the directory will be
copied. Ownership and permissions will be left at their default values
if new values are not specified. The source and target directories are
allowed to be soft links to a directory, but besides that soft links are
ignored.
@note: If you have user/group as strings, call the L{util.getUidGid}
function to get the associated uid/gid as an ownership tuple.
@param sourceDir: Source directory
@type sourceDir: String representing a directory on disk
@param targetDir: Target directory
@type targetDir: String representing a directory on disk
@param ownership: Owner and group that the copied files should have
@type ownership: Tuple of numeric ids C{(uid, gid)}
@param permissions: Permissions that the staged files should have
@type permissions: UNIX permissions mode, specified in octal (i.e. C{0640}).
@return: Number of files copied from the source directory to the target directory.
@raise ValueError: If source or target is not a directory or does not exist.
@raise ValueError: If a path cannot be encoded properly.
@raise IOError: If there is an IO error copying the files.
@raise OSError: If there is an OS error copying or changing permissions on a files
"""
filesCopied = 0
sourceDir = encodePath(sourceDir)
targetDir = encodePath(targetDir)
for fileName in os.listdir(sourceDir):
sourceFile = os.path.join(sourceDir, fileName)
targetFile = os.path.join(targetDir, fileName)
LocalPeer._copyLocalFile(sourceFile, targetFile, ownership, permissions)
filesCopied += 1
return filesCopied
@staticmethod
def _copyLocalFile(sourceFile=None, targetFile=None, ownership=None, permissions=None, overwrite=True):
"""
Copies a source file to a target file.
If the source file is C{None} then the target file will be created or
overwritten as an empty file. If the target file is C{None}, this method
is a no-op. Attempting to copy a soft link or a directory will result in
an exception.
@note: If you have user/group as strings, call the L{util.getUidGid}
function to get the associated uid/gid as an ownership tuple.
@note: We will not overwrite a target file that exists when this method
is invoked. If the target already exists, we'll raise an exception.
@param sourceFile: Source file to copy
@type sourceFile: String representing a file on disk, as an absolute path
@param targetFile: Target file to create
@type targetFile: String representing a file on disk, as an absolute path
@param ownership: Owner and group that the copied should have
@type ownership: Tuple of numeric ids C{(uid, gid)}
@param permissions: Permissions that the staged files should have
@type permissions: UNIX permissions mode, specified in octal (i.e. C{0640}).
@param overwrite: Indicates whether it's OK to overwrite the target file.
@type overwrite: Boolean true/false.
@raise ValueError: If the passed-in source file is not a regular file.
@raise ValueError: If a path cannot be encoded properly.
@raise IOError: If the target file already exists.
@raise IOError: If there is an IO error copying the file
@raise OSError: If there is an OS error copying or changing permissions on a file
"""
targetFile = encodePath(targetFile)
sourceFile = encodePath(sourceFile)
if targetFile is None:
return
if not overwrite:
if os.path.exists(targetFile):
raise IOError("Target file [%s] already exists." % targetFile)
if sourceFile is None:
with open(targetFile, "w") as f:
f.write("")
else:
if os.path.isfile(sourceFile) and not os.path.islink(sourceFile):
shutil.copy(sourceFile, targetFile)
else:
logger.debug("Source [%s] is not a regular file.", sourceFile)
raise ValueError("Source is not a regular file.")
if ownership is not None:
os.chown(targetFile, ownership[0], ownership[1])
if permissions is not None:
os.chmod(targetFile, permissions)
########################################################################
# RemotePeer class definition
########################################################################
class RemotePeer(object):
######################
# Class documentation
######################
"""
Backup peer representing a remote peer in a backup pool.
This is a class representing a remote (networked) peer in a backup pool.
Remote peers are backed up using an rcp-compatible copy command. A remote
peer has associated with it a name (which must be a valid hostname), a
collect directory, a working directory and a copy method (an rcp-compatible
command).
You can also set an optional local user value. This username will be used
as the local user for any remote copies that are required. It can only be
used if the root user is executing the backup. The root user will C{su} to
the local user and execute the remote copies as that user.
The copy method is associated with the peer and not with the actual request
to copy, because we can envision that each remote host might have a
different connect method.
The public methods other than the constructor are part of a "backup peer"
interface shared with the C{LocalPeer} class.
@sort: __init__, stagePeer, checkCollectIndicator, writeStageIndicator,
executeRemoteCommand, executeManagedAction, _getDirContents,
_copyRemoteDir, _copyRemoteFile, _pushLocalFile, name, collectDir,
remoteUser, rcpCommand, rshCommand, cbackCommand
"""
##############
# Constructor
##############
def __init__(self, name=None, collectDir=None, workingDir=None, remoteUser=None,
rcpCommand=None, localUser=None, rshCommand=None, cbackCommand=None,
ignoreFailureMode=None):
"""
Initializes a remote backup peer.
@note: If provided, each command will eventually be parsed into a list of
strings suitable for passing to C{util.executeCommand} in order to avoid
security holes related to shell interpolation. This parsing will be
done by the L{util.splitCommandLine} function. See the documentation for
that function for some important notes about its limitations.
@param name: Name of the backup peer
@type name: String, must be a valid DNS hostname
@param collectDir: Path to the peer's collect directory
@type collectDir: String representing an absolute path on the remote peer
@param workingDir: Working directory that can be used to create temporary files, etc.
@type workingDir: String representing an absolute path on the current host.
@param remoteUser: Name of the Cedar Backup user on the remote peer
@type remoteUser: String representing a username, valid via remote shell to the peer
@param localUser: Name of the Cedar Backup user on the current host
@type localUser: String representing a username, valid on the current host
@param rcpCommand: An rcp-compatible copy command to use for copying files from the peer
@type rcpCommand: String representing a system command including required arguments
@param rshCommand: An rsh-compatible copy command to use for remote shells to the peer
@type rshCommand: String representing a system command including required arguments
@param cbackCommand: A chack-compatible command to use for executing managed actions
@type cbackCommand: String representing a system command including required arguments
@param ignoreFailureMode: Ignore failure mode for this peer
@type ignoreFailureMode: One of VALID_FAILURE_MODES
@raise ValueError: If collect directory is not an absolute path
"""
self._name = None
self._collectDir = None
self._workingDir = None
self._remoteUser = None
self._localUser = None
self._rcpCommand = None
self._rcpCommandList = None
self._rshCommand = None
self._rshCommandList = None
self._cbackCommand = None
self._ignoreFailureMode = None
self.name = name
self.collectDir = collectDir
self.workingDir = workingDir
self.remoteUser = remoteUser
self.localUser = localUser
self.rcpCommand = rcpCommand
self.rshCommand = rshCommand
self.cbackCommand = cbackCommand
self.ignoreFailureMode = ignoreFailureMode
#############
# Properties
#############
def _setName(self, value):
"""
Property target used to set the peer name.
The value must be a non-empty string and cannot be C{None}.
@raise ValueError: If the value is an empty string or C{None}.
"""
if value is None or len(value) < 1:
raise ValueError("Peer name must be a non-empty string.")
self._name = value
def _getName(self):
"""
Property target used to get the peer name.
"""
return self._name
def _setCollectDir(self, value):
"""
Property target used to set the collect directory.
The value must be an absolute path and cannot be C{None}.
It does not have to exist on disk at the time of assignment.
@raise ValueError: If the value is C{None} or is not an absolute path.
@raise ValueError: If the value cannot be encoded properly.
"""
if value is not None:
if not os.path.isabs(value):
raise ValueError("Collect directory must be an absolute path.")
self._collectDir = encodePath(value)
def _getCollectDir(self):
"""
Property target used to get the collect directory.
"""
return self._collectDir
def _setWorkingDir(self, value):
"""
Property target used to set the working directory.
The value must be an absolute path and cannot be C{None}.
@raise ValueError: If the value is C{None} or is not an absolute path.
@raise ValueError: If the value cannot be encoded properly.
"""
if value is not None:
if not os.path.isabs(value):
raise ValueError("Working directory must be an absolute path.")
self._workingDir = encodePath(value)
def _getWorkingDir(self):
"""
Property target used to get the working directory.
"""
return self._workingDir
def _setRemoteUser(self, value):
"""
Property target used to set the remote user.
The value must be a non-empty string and cannot be C{None}.
@raise ValueError: If the value is an empty string or C{None}.
"""
if value is None or len(value) < 1:
raise ValueError("Peer remote user must be a non-empty string.")
self._remoteUser = value
def _getRemoteUser(self):
"""
Property target used to get the remote user.
"""
return self._remoteUser
def _setLocalUser(self, value):
"""
Property target used to set the local user.
The value must be a non-empty string if it is not C{None}.
@raise ValueError: If the value is an empty string.
"""
if value is not None:
if len(value) < 1:
raise ValueError("Peer local user must be a non-empty string.")
self._localUser = value
def _getLocalUser(self):
"""
Property target used to get the local user.
"""
return self._localUser
def _setRcpCommand(self, value):
"""
Property target to set the rcp command.
The value must be a non-empty string or C{None}. Its value is stored in
the two forms: "raw" as provided by the client, and "parsed" into a list
suitable for being passed to L{util.executeCommand} via
L{util.splitCommandLine}.
However, all the caller will ever see via the property is the actual
value they set (which includes seeing C{None}, even if we translate that
internally to C{DEF_RCP_COMMAND}). Internally, we should always use
C{self._rcpCommandList} if we want the actual command list.
@raise ValueError: If the value is an empty string.
"""
if value is None:
self._rcpCommand = None
self._rcpCommandList = DEF_RCP_COMMAND
else:
if len(value) >= 1:
self._rcpCommand = value
self._rcpCommandList = splitCommandLine(self._rcpCommand)
else:
raise ValueError("The rcp command must be a non-empty string.")
def _getRcpCommand(self):
"""
Property target used to get the rcp command.
"""
return self._rcpCommand
def _setRshCommand(self, value):
"""
Property target to set the rsh command.
The value must be a non-empty string or C{None}. Its value is stored in
the two forms: "raw" as provided by the client, and "parsed" into a list
suitable for being passed to L{util.executeCommand} via
L{util.splitCommandLine}.
However, all the caller will ever see via the property is the actual
value they set (which includes seeing C{None}, even if we translate that
internally to C{DEF_RSH_COMMAND}). Internally, we should always use
C{self._rshCommandList} if we want the actual command list.
@raise ValueError: If the value is an empty string.
"""
if value is None:
self._rshCommand = None
self._rshCommandList = DEF_RSH_COMMAND
else:
if len(value) >= 1:
self._rshCommand = value
self._rshCommandList = splitCommandLine(self._rshCommand)
else:
raise ValueError("The rsh command must be a non-empty string.")
def _getRshCommand(self):
"""
Property target used to get the rsh command.
"""
return self._rshCommand
def _setCbackCommand(self, value):
"""
Property target to set the cback command.
The value must be a non-empty string or C{None}. Unlike the other
command, this value is only stored in the "raw" form provided by the
client.
@raise ValueError: If the value is an empty string.
"""
if value is None:
self._cbackCommand = None
else:
if len(value) >= 1:
self._cbackCommand = value
else:
raise ValueError("The cback command must be a non-empty string.")
def _getCbackCommand(self):
"""
Property target used to get the cback command.
"""
return self._cbackCommand
def _setIgnoreFailureMode(self, value):
"""
Property target used to set the ignoreFailure mode.
If not C{None}, the mode must be one of the values in L{VALID_FAILURE_MODES}.
@raise ValueError: If the value is not valid.
"""
if value is not None:
if value not in VALID_FAILURE_MODES:
raise ValueError("Ignore failure mode must be one of %s." % VALID_FAILURE_MODES)
self._ignoreFailureMode = value
def _getIgnoreFailureMode(self):
"""
Property target used to get the ignoreFailure mode.
"""
return self._ignoreFailureMode
name = property(_getName, _setName, None, "Name of the peer (a valid DNS hostname).")
collectDir = property(_getCollectDir, _setCollectDir, None, "Path to the peer's collect directory (an absolute local path).")
workingDir = property(_getWorkingDir, _setWorkingDir, None, "Path to the peer's working directory (an absolute local path).")
remoteUser = property(_getRemoteUser, _setRemoteUser, None, "Name of the Cedar Backup user on the remote peer.")
localUser = property(_getLocalUser, _setLocalUser, None, "Name of the Cedar Backup user on the current host.")
rcpCommand = property(_getRcpCommand, _setRcpCommand, None, "An rcp-compatible copy command to use for copying files.")
rshCommand = property(_getRshCommand, _setRshCommand, None, "An rsh-compatible command to use for remote shells to the peer.")
cbackCommand = property(_getCbackCommand, _setCbackCommand, None, "A chack-compatible command to use for executing managed actions.")
ignoreFailureMode = property(_getIgnoreFailureMode, _setIgnoreFailureMode, None, "Ignore failure mode for peer.")
#################
# Public methods
#################
def stagePeer(self, targetDir, ownership=None, permissions=None):
"""
Stages data from the peer into the indicated local target directory.
The target directory must already exist before this method is called. If
passed in, ownership and permissions will be applied to the files that
are copied.
@note: The returned count of copied files might be inaccurate if some of
the copied files already existed in the staging directory prior to the
copy taking place. We don't clear the staging directory first, because
some extension might also be using it.
@note: If you have user/group as strings, call the L{util.getUidGid} function
to get the associated uid/gid as an ownership tuple.
@note: Unlike the local peer version of this method, an I/O error might
or might not be raised if the directory is empty. Since we're using a
remote copy method, we just don't have the fine-grained control over our
exceptions that's available when we can look directly at the filesystem,
and we can't control whether the remote copy method thinks an empty
directory is an error.
@param targetDir: Target directory to write data into
@type targetDir: String representing a directory on disk
@param ownership: Owner and group that the staged files should have
@type ownership: Tuple of numeric ids C{(uid, gid)}
@param permissions: Permissions that the staged files should have
@type permissions: UNIX permissions mode, specified in octal (i.e. C{0640}).
@return: Number of files copied from the source directory to the target directory.
@raise ValueError: If target directory is not a directory, does not exist or is not absolute.
@raise ValueError: If a path cannot be encoded properly.
@raise IOError: If there were no files to stage (i.e. the directory was empty)
@raise IOError: If there is an IO error copying a file.
@raise OSError: If there is an OS error copying or changing permissions on a file
"""
targetDir = encodePath(targetDir)
if not os.path.isabs(targetDir):
logger.debug("Target directory [%s] not an absolute path.", targetDir)
raise ValueError("Target directory must be an absolute path.")
if not os.path.exists(targetDir) or not os.path.isdir(targetDir):
logger.debug("Target directory [%s] is not a directory or does not exist on disk.", targetDir)
raise ValueError("Target directory is not a directory or does not exist on disk.")
count = RemotePeer._copyRemoteDir(self.remoteUser, self.localUser, self.name,
self._rcpCommand, self._rcpCommandList,
self.collectDir, targetDir,
ownership, permissions)
if count == 0:
raise IOError("Did not copy any files from local peer.")
return count
def checkCollectIndicator(self, collectIndicator=None):
"""
Checks the collect indicator in the peer's staging directory.
When a peer has completed collecting its backup files, it will write an
empty indicator file into its collect directory. This method checks to
see whether that indicator has been written. If the remote copy command
fails, we return C{False} as if the file weren't there.
If you need to, you can override the name of the collect indicator file
by passing in a different name.
@note: Apparently, we can't count on all rcp-compatible implementations
to return sensible errors for some error conditions. As an example, the
C{scp} command in Debian 'woody' returns a zero (normal) status even when
it can't find a host or if the login or path is invalid. Because of
this, the implementation of this method is rather convoluted.
@param collectIndicator: Name of the collect indicator file to check
@type collectIndicator: String representing name of a file in the collect directory
@return: Boolean true/false depending on whether the indicator exists.
@raise ValueError: If a path cannot be encoded properly.
"""
try:
if collectIndicator is None:
sourceFile = os.path.join(self.collectDir, DEF_COLLECT_INDICATOR)
targetFile = os.path.join(self.workingDir, DEF_COLLECT_INDICATOR)
else:
collectIndicator = encodePath(collectIndicator)
sourceFile = os.path.join(self.collectDir, collectIndicator)
targetFile = os.path.join(self.workingDir, collectIndicator)
logger.debug("Fetch remote [%s] into [%s].", sourceFile, targetFile)
if os.path.exists(targetFile):
try:
os.remove(targetFile)
except:
raise Exception("Error: collect indicator [%s] already exists!" % targetFile)
try:
RemotePeer._copyRemoteFile(self.remoteUser, self.localUser, self.name,
self._rcpCommand, self._rcpCommandList,
sourceFile, targetFile,
overwrite=False)
if os.path.exists(targetFile):
return True
else:
return False
except Exception as e:
logger.info("Failed looking for collect indicator: %s", e)
return False
finally:
if os.path.exists(targetFile):
try:
os.remove(targetFile)
except: pass
def writeStageIndicator(self, stageIndicator=None):
"""
Writes the stage indicator in the peer's staging directory.
When the master has completed collecting its backup files, it will write
an empty indicator file into the peer's collect directory. The presence
of this file implies that the staging process is complete.
If you need to, you can override the name of the stage indicator file by
passing in a different name.
@note: If you have user/group as strings, call the L{util.getUidGid} function
to get the associated uid/gid as an ownership tuple.
@param stageIndicator: Name of the indicator file to write
@type stageIndicator: String representing name of a file in the collect directory
@raise ValueError: If a path cannot be encoded properly.
@raise IOError: If there is an IO error creating the file.
@raise OSError: If there is an OS error creating or changing permissions on the file
"""
stageIndicator = encodePath(stageIndicator)
if stageIndicator is None:
sourceFile = os.path.join(self.workingDir, DEF_STAGE_INDICATOR)
targetFile = os.path.join(self.collectDir, DEF_STAGE_INDICATOR)
else:
sourceFile = os.path.join(self.workingDir, DEF_STAGE_INDICATOR)
targetFile = os.path.join(self.collectDir, stageIndicator)
try:
if not os.path.exists(sourceFile):
with open(sourceFile, "w") as f:
f.write("")
RemotePeer._pushLocalFile(self.remoteUser, self.localUser, self.name,
self._rcpCommand, self._rcpCommandList,
sourceFile, targetFile)
finally:
if os.path.exists(sourceFile):
try:
os.remove(sourceFile)
except: pass
def executeRemoteCommand(self, command):
"""
Executes a command on the peer via remote shell.
@param command: Command to execute
@type command: String command-line suitable for use with rsh.
@raise IOError: If there is an error executing the command on the remote peer.
"""
RemotePeer._executeRemoteCommand(self.remoteUser, self.localUser,
self.name, self._rshCommand,
self._rshCommandList, command)
def executeManagedAction(self, action, fullBackup):
"""
Executes a managed action on this peer.
@param action: Name of the action to execute.
@param fullBackup: Whether a full backup should be executed.
@raise IOError: If there is an error executing the action on the remote peer.
"""
try:
command = RemotePeer._buildCbackCommand(self.cbackCommand, action, fullBackup)
self.executeRemoteCommand(command)
except IOError as e:
logger.info(e)
raise IOError("Failed to execute action [%s] on managed client [%s]." % (action, self.name))
##################
# Private methods
##################
@staticmethod
def _getDirContents(path):
"""
Returns the contents of a directory in terms of a Set.
The directory's contents are read as a L{FilesystemList} containing only
files, and then the list is converted into a set object for later use.
@param path: Directory path to get contents for
@type path: String representing a path on disk
@return: Set of files in the directory
@raise ValueError: If path is not a directory or does not exist.
"""
contents = FilesystemList()
contents.excludeDirs = True
contents.excludeLinks = True
contents.addDirContents(path)
return set(contents)
@staticmethod
def _copyRemoteDir(remoteUser, localUser, remoteHost, rcpCommand, rcpCommandList,
sourceDir, targetDir, ownership=None, permissions=None):
"""
Copies files from the source directory to the target directory.
This function is not recursive. Only the files in the directory will be
copied. Ownership and permissions will be left at their default values
if new values are not specified. Behavior when copying soft links from
the collect directory is dependent on the behavior of the specified rcp
command.
@note: The returned count of copied files might be inaccurate if some of
the copied files already existed in the staging directory prior to the
copy taking place. We don't clear the staging directory first, because
some extension might also be using it.
@note: If you have user/group as strings, call the L{util.getUidGid} function
to get the associated uid/gid as an ownership tuple.
@note: We don't have a good way of knowing exactly what files we copied
down from the remote peer, unless we want to parse the output of the rcp
command (ugh). We could change permissions on everything in the target
directory, but that's kind of ugly too. Instead, we use Python's set
functionality to figure out what files were added while we executed the
rcp command. This isn't perfect - for instance, it's not correct if
someone else is messing with the directory at the same time we're doing
the remote copy - but it's about as good as we're going to get.
@note: Apparently, we can't count on all rcp-compatible implementations
to return sensible errors for some error conditions. As an example, the
C{scp} command in Debian 'woody' returns a zero (normal) status even
when it can't find a host or if the login or path is invalid. We try
to work around this by issuing C{IOError} if we don't copy any files from
the remote host.
@param remoteUser: Name of the Cedar Backup user on the remote peer
@type remoteUser: String representing a username, valid via the copy command
@param localUser: Name of the Cedar Backup user on the current host
@type localUser: String representing a username, valid on the current host
@param remoteHost: Hostname of the remote peer
@type remoteHost: String representing a hostname, accessible via the copy command
@param rcpCommand: An rcp-compatible copy command to use for copying files from the peer
@type rcpCommand: String representing a system command including required arguments
@param rcpCommandList: An rcp-compatible copy command to use for copying files
@type rcpCommandList: Command as a list to be passed to L{util.executeCommand}
@param sourceDir: Source directory
@type sourceDir: String representing a directory on disk
@param targetDir: Target directory
@type targetDir: String representing a directory on disk
@param ownership: Owner and group that the copied files should have
@type ownership: Tuple of numeric ids C{(uid, gid)}
@param permissions: Permissions that the staged files should have
@type permissions: UNIX permissions mode, specified in octal (i.e. C{0640}).
@return: Number of files copied from the source directory to the target directory.
@raise ValueError: If source or target is not a directory or does not exist.
@raise IOError: If there is an IO error copying the files.
"""
beforeSet = RemotePeer._getDirContents(targetDir)
if localUser is not None:
try:
if not isRunningAsRoot():
raise IOError("Only root can remote copy as another user.")
except AttributeError: pass
actualCommand = "%s %s@%s:%s/* %s" % (rcpCommand, remoteUser, remoteHost, sourceDir, targetDir)
command = resolveCommand(SU_COMMAND)
result = executeCommand(command, [localUser, "-c", actualCommand])[0]
if result != 0:
raise IOError("Error (%d) copying files from remote host as local user [%s]." % (result, localUser))
else:
copySource = "%s@%s:%s/*" % (remoteUser, remoteHost, sourceDir)
command = resolveCommand(rcpCommandList)
result = executeCommand(command, [copySource, targetDir])[0]
if result != 0:
raise IOError("Error (%d) copying files from remote host." % result)
afterSet = RemotePeer._getDirContents(targetDir)
if len(afterSet) == 0:
raise IOError("Did not copy any files from remote peer.")
differenceSet = afterSet.difference(beforeSet) # files we added as part of copy
if len(differenceSet) == 0:
raise IOError("Apparently did not copy any new files from remote peer.")
for targetFile in differenceSet:
if ownership is not None:
os.chown(targetFile, ownership[0], ownership[1])
if permissions is not None:
os.chmod(targetFile, permissions)
return len(differenceSet)
@staticmethod
def _copyRemoteFile(remoteUser, localUser, remoteHost,
rcpCommand, rcpCommandList,
sourceFile, targetFile, ownership=None,
permissions=None, overwrite=True):
"""
Copies a remote source file to a target file.
@note: Internally, we have to go through and escape any spaces in the
source path with double-backslash, otherwise things get screwed up. It
doesn't seem to be required in the target path. I hope this is portable
to various different rcp methods, but I guess it might not be (all I have
to test with is OpenSSH).
@note: If you have user/group as strings, call the L{util.getUidGid} function
to get the associated uid/gid as an ownership tuple.
@note: We will not overwrite a target file that exists when this method
is invoked. If the target already exists, we'll raise an exception.
@note: Apparently, we can't count on all rcp-compatible implementations
to return sensible errors for some error conditions. As an example, the
C{scp} command in Debian 'woody' returns a zero (normal) status even when
it can't find a host or if the login or path is invalid. We try to work
around this by issuing C{IOError} the target file does not exist when
we're done.
@param remoteUser: Name of the Cedar Backup user on the remote peer
@type remoteUser: String representing a username, valid via the copy command
@param remoteHost: Hostname of the remote peer
@type remoteHost: String representing a hostname, accessible via the copy command
@param localUser: Name of the Cedar Backup user on the current host
@type localUser: String representing a username, valid on the current host
@param rcpCommand: An rcp-compatible copy command to use for copying files from the peer
@type rcpCommand: String representing a system command including required arguments
@param rcpCommandList: An rcp-compatible copy command to use for copying files
@type rcpCommandList: Command as a list to be passed to L{util.executeCommand}
@param sourceFile: Source file to copy
@type sourceFile: String representing a file on disk, as an absolute path
@param targetFile: Target file to create
@type targetFile: String representing a file on disk, as an absolute path
@param ownership: Owner and group that the copied should have
@type ownership: Tuple of numeric ids C{(uid, gid)}
@param permissions: Permissions that the staged files should have
@type permissions: UNIX permissions mode, specified in octal (i.e. C{0640}).
@param overwrite: Indicates whether it's OK to overwrite the target file.
@type overwrite: Boolean true/false.
@raise IOError: If the target file already exists.
@raise IOError: If there is an IO error copying the file
@raise OSError: If there is an OS error changing permissions on the file
"""
if not overwrite:
if os.path.exists(targetFile):
raise IOError("Target file [%s] already exists." % targetFile)
if localUser is not None:
try:
if not isRunningAsRoot():
raise IOError("Only root can remote copy as another user.")
except AttributeError: pass
actualCommand = "%s %s@%s:%s %s" % (rcpCommand, remoteUser, remoteHost, sourceFile.replace(" ", "\\ "), targetFile)
command = resolveCommand(SU_COMMAND)
result = executeCommand(command, [localUser, "-c", actualCommand])[0]
if result != 0:
raise IOError("Error (%d) copying [%s] from remote host as local user [%s]." % (result, sourceFile, localUser))
else:
copySource = "%s@%s:%s" % (remoteUser, remoteHost, sourceFile.replace(" ", "\\ "))
command = resolveCommand(rcpCommandList)
result = executeCommand(command, [copySource, targetFile])[0]
if result != 0:
raise IOError("Error (%d) copying [%s] from remote host." % (result, sourceFile))
if not os.path.exists(targetFile):
raise IOError("Apparently unable to copy file from remote host.")
if ownership is not None:
os.chown(targetFile, ownership[0], ownership[1])
if permissions is not None:
os.chmod(targetFile, permissions)
@staticmethod
def _pushLocalFile(remoteUser, localUser, remoteHost,
rcpCommand, rcpCommandList,
sourceFile, targetFile, overwrite=True):
"""
Copies a local source file to a remote host.
@note: We will not overwrite a target file that exists when this method
is invoked. If the target already exists, we'll raise an exception.
@note: Internally, we have to go through and escape any spaces in the
source and target paths with double-backslash, otherwise things get
screwed up. I hope this is portable to various different rcp methods,
but I guess it might not be (all I have to test with is OpenSSH).
@note: If you have user/group as strings, call the L{util.getUidGid} function
to get the associated uid/gid as an ownership tuple.
@param remoteUser: Name of the Cedar Backup user on the remote peer
@type remoteUser: String representing a username, valid via the copy command
@param localUser: Name of the Cedar Backup user on the current host
@type localUser: String representing a username, valid on the current host
@param remoteHost: Hostname of the remote peer
@type remoteHost: String representing a hostname, accessible via the copy command
@param rcpCommand: An rcp-compatible copy command to use for copying files from the peer
@type rcpCommand: String representing a system command including required arguments
@param rcpCommandList: An rcp-compatible copy command to use for copying files
@type rcpCommandList: Command as a list to be passed to L{util.executeCommand}
@param sourceFile: Source file to copy
@type sourceFile: String representing a file on disk, as an absolute path
@param targetFile: Target file to create
@type targetFile: String representing a file on disk, as an absolute path
@param overwrite: Indicates whether it's OK to overwrite the target file.
@type overwrite: Boolean true/false.
@raise IOError: If there is an IO error copying the file
@raise OSError: If there is an OS error changing permissions on the file
"""
if not overwrite:
if os.path.exists(targetFile):
raise IOError("Target file [%s] already exists." % targetFile)
if localUser is not None:
try:
if not isRunningAsRoot():
raise IOError("Only root can remote copy as another user.")
except AttributeError: pass
actualCommand = '%s "%s" "%s@%s:%s"' % (rcpCommand, sourceFile, remoteUser, remoteHost, targetFile)
command = resolveCommand(SU_COMMAND)
result = executeCommand(command, [localUser, "-c", actualCommand])[0]
if result != 0:
raise IOError("Error (%d) copying [%s] to remote host as local user [%s]." % (result, sourceFile, localUser))
else:
copyTarget = "%s@%s:%s" % (remoteUser, remoteHost, targetFile.replace(" ", "\\ "))
command = resolveCommand(rcpCommandList)
result = executeCommand(command, [sourceFile.replace(" ", "\\ "), copyTarget])[0]
if result != 0:
raise IOError("Error (%d) copying [%s] to remote host." % (result, sourceFile))
@staticmethod
def _executeRemoteCommand(remoteUser, localUser, remoteHost, rshCommand, rshCommandList, remoteCommand):
"""
Executes a command on the peer via remote shell.
@param remoteUser: Name of the Cedar Backup user on the remote peer
@type remoteUser: String representing a username, valid on the remote host
@param localUser: Name of the Cedar Backup user on the current host
@type localUser: String representing a username, valid on the current host
@param remoteHost: Hostname of the remote peer
@type remoteHost: String representing a hostname, accessible via the copy command
@param rshCommand: An rsh-compatible copy command to use for remote shells to the peer
@type rshCommand: String representing a system command including required arguments
@param rshCommandList: An rsh-compatible copy command to use for remote shells to the peer
@type rshCommandList: Command as a list to be passed to L{util.executeCommand}
@param remoteCommand: The command to be executed on the remote host
@type remoteCommand: String command-line, with no special shell characters ($, <, etc.)
@raise IOError: If there is an error executing the remote command
"""
actualCommand = "%s %s@%s '%s'" % (rshCommand, remoteUser, remoteHost, remoteCommand)
if localUser is not None:
try:
if not isRunningAsRoot():
raise IOError("Only root can remote shell as another user.")
except AttributeError: pass
command = resolveCommand(SU_COMMAND)
result = executeCommand(command, [localUser, "-c", actualCommand])[0]
if result != 0:
raise IOError("Command failed [su -c %s \"%s\"]" % (localUser, actualCommand))
else:
command = resolveCommand(rshCommandList)
result = executeCommand(command, ["%s@%s" % (remoteUser, remoteHost), "%s" % remoteCommand])[0]
if result != 0:
raise IOError("Command failed [%s]" % (actualCommand))
@staticmethod
def _buildCbackCommand(cbackCommand, action, fullBackup):
"""
Builds a Cedar Backup command line for the named action.
@note: If the cback command is None, then DEF_CBACK_COMMAND is used.
@param cbackCommand: cback command to execute, including required options
@param action: Name of the action to execute.
@param fullBackup: Whether a full backup should be executed.
@return: String suitable for passing to L{_executeRemoteCommand} as remoteCommand.
@raise ValueError: If action is None.
"""
if action is None:
raise ValueError("Action cannot be None.")
if cbackCommand is None:
cbackCommand = DEF_CBACK_COMMAND
if fullBackup:
return "%s --full %s" % (cbackCommand, action)
else:
return "%s %s" % (cbackCommand, action)
|