| 1 |
# vim: set ft=python ts=4 sw=4 expandtab: |
| 2 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 3 |
# |
| 4 |
# C E D A R |
| 5 |
# S O L U T I O N S "Software done right." |
| 6 |
# S O F T W A R E |
| 7 |
# |
| 8 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 9 |
# |
| 10 |
# Copyright (c) 2004-2008,2010,2015 Kenneth J. Pronovici. |
| 11 |
# All rights reserved. |
| 12 |
# |
| 13 |
# This program is free software; you can redistribute it and/or |
| 14 |
# modify it under the terms of the GNU General Public License, |
| 15 |
# Version 2, as published by the Free Software Foundation. |
| 16 |
# |
| 17 |
# This program is distributed in the hope that it will be useful, |
| 18 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 19 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 20 |
# |
| 21 |
# Copies of the GNU General Public License are available from |
| 22 |
# the Free Software Foundation website, http://www.gnu.org/. |
| 23 |
# |
| 24 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 25 |
# |
| 26 |
# Author : Kenneth J. Pronovici <[email protected]> |
| 27 |
# Language : Python 3 |
| 28 |
# Project : Cedar Backup, release 3 |
| 29 |
# Purpose : Provides backup peer-related objects. |
| 30 |
# |
| 31 |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # |
| 32 |
|
| 33 |
######################################################################## |
| 34 |
# Module documentation |
| 35 |
######################################################################## |
| 36 |
|
| 37 |
""" |
| 38 |
Provides backup peer-related objects and utility functions. |
| 39 |
|
| 40 |
Module Attributes |
| 41 |
================= |
| 42 |
|
| 43 |
Attributes: |
| 44 |
DEF_COLLECT_INDICATOR: Name of the default collect indicator file |
| 45 |
DEF_STAGE_INDICATOR: Name of the default stage indicator file |
| 46 |
|
| 47 |
:author: Kenneth J. Pronovici <[email protected]> |
| 48 |
""" |
| 49 |
|
| 50 |
|
| 51 |
######################################################################## |
| 52 |
# Imported modules |
| 53 |
######################################################################## |
| 54 |
|
| 55 |
import logging |
| 56 |
import os |
| 57 |
import posixpath |
| 58 |
import shutil |
| 59 |
import sys |
| 60 |
|
| 61 |
from CedarBackup3.config import VALID_FAILURE_MODES |
| 62 |
from CedarBackup3.filesystem import FilesystemList |
| 63 |
from CedarBackup3.util import encodePath, executeCommand, isRunningAsRoot, pathJoin, resolveCommand, splitCommandLine |
| 64 |
|
| 65 |
######################################################################## |
| 66 |
# Module-wide constants and variables |
| 67 |
######################################################################## |
| 68 |
|
| 69 |
logger = logging.getLogger("CedarBackup3.log.peer") |
| 70 |
|
| 71 |
DEF_RCP_COMMAND = ["/usr/bin/scp", "-B", "-q", "-C"] |
| 72 |
DEF_RSH_COMMAND = ["/usr/bin/ssh"] |
| 73 |
DEF_CBACK_COMMAND = "/usr/bin/cback3" |
| 74 |
|
| 75 |
DEF_COLLECT_INDICATOR = "cback.collect" |
| 76 |
DEF_STAGE_INDICATOR = "cback.stage" |
| 77 |
|
| 78 |
SU_COMMAND = ["su"] |
| 79 |
|
| 80 |
|
| 81 |
######################################################################## |
| 82 |
# LocalPeer class definition |
| 83 |
######################################################################## |
| 84 |
|
| 85 |
|
| 86 |
class LocalPeer: |
| 87 |
###################### |
| 88 |
# Class documentation |
| 89 |
###################### |
| 90 |
|
| 91 |
""" |
| 92 |
Backup peer representing a local peer in a backup pool. |
| 93 |
|
| 94 |
This is a class representing a local (non-network) peer in a backup pool. |
| 95 |
Local peers are backed up by simple filesystem copy operations. A local |
| 96 |
peer has associated with it a name (typically, but not necessarily, a |
| 97 |
hostname) and a collect directory. |
| 98 |
|
| 99 |
The public methods other than the constructor are part of a "backup peer" |
| 100 |
interface shared with the ``RemotePeer`` class. |
| 101 |
|
| 102 |
""" |
| 103 |
|
| 104 |
############## |
| 105 |
# Constructor |
| 106 |
############## |
| 107 |
|
| 108 |
def __init__(self, name, collectDir, ignoreFailureMode=None): |
| 109 |
""" |
| 110 |
Initializes a local backup peer. |
| 111 |
|
| 112 |
Note that the collect directory must be an absolute path, but does not |
| 113 |
have to exist when the object is instantiated. We do a lazy validation |
| 114 |
on this value since we could (potentially) be creating peer objects |
| 115 |
before an ongoing backup completed. |
| 116 |
|
| 117 |
Args: |
| 118 |
name: Name of the backup peer |
| 119 |
collectDir: Path to the peer's collect directory |
| 120 |
ignoreFailureMode: Ignore failure mode for this peer, one of ``VALID_FAILURE_MODES`` |
| 121 |
Raises: |
| 122 |
ValueError: If the name is empty |
| 123 |
ValueError: If collect directory is not an absolute path |
| 124 |
""" |
| 125 |
self._name = None |
| 126 |
self._collectDir = None |
| 127 |
self._ignoreFailureMode = None |
| 128 |
self.name = name |
| 129 |
self.collectDir = collectDir |
| 130 |
self.ignoreFailureMode = ignoreFailureMode |
| 131 |
|
| 132 |
############# |
| 133 |
# Properties |
| 134 |
############# |
| 135 |
|
| 136 |
def _setName(self, value): |
| 137 |
""" |
| 138 |
Property target used to set the peer name. |
| 139 |
The value must be a non-empty string and cannot be ``None``. |
| 140 |
Raises: |
| 141 |
ValueError: If the value is an empty string or ``None`` |
| 142 |
""" |
| 143 |
if value is None or len(value) < 1: |
| 144 |
raise ValueError("Peer name must be a non-empty string.") |
| 145 |
self._name = value |
| 146 |
|
| 147 |
def _getName(self): |
| 148 |
""" |
| 149 |
Property target used to get the peer name. |
| 150 |
""" |
| 151 |
return self._name |
| 152 |
|
| 153 |
def _setCollectDir(self, value): |
| 154 |
""" |
| 155 |
Property target used to set the collect directory. |
| 156 |
The value must be an absolute path and cannot be ``None``. |
| 157 |
It does not have to exist on disk at the time of assignment. |
| 158 |
Raises: |
| 159 |
ValueError: If the value is ``None`` or is not an absolute path |
| 160 |
ValueError: If a path cannot be encoded properly |
| 161 |
""" |
| 162 |
if value is None or not ( |
| 163 |
os.path.isabs(value) or posixpath.isabs(value) |
| 164 |
): # Python 3.13+ does not treat / as absolute on Windows |
| 165 |
raise ValueError("Collect directory must be an absolute path.") |
| 166 |
self._collectDir = encodePath(value) |
| 167 |
|
| 168 |
def _getCollectDir(self): |
| 169 |
""" |
| 170 |
Property target used to get the collect directory. |
| 171 |
""" |
| 172 |
return self._collectDir |
| 173 |
|
| 174 |
def _setIgnoreFailureMode(self, value): |
| 175 |
""" |
| 176 |
Property target used to set the ignoreFailure mode. |
| 177 |
If not ``None``, the mode must be one of the values in :any:`VALID_FAILURE_MODES`. |
| 178 |
Raises: |
| 179 |
ValueError: If the value is not valid |
| 180 |
""" |
| 181 |
if value is not None: |
| 182 |
if value not in VALID_FAILURE_MODES: |
| 183 |
raise ValueError("Ignore failure mode must be one of %s." % VALID_FAILURE_MODES) |
| 184 |
self._ignoreFailureMode = value |
| 185 |
|
| 186 |
def _getIgnoreFailureMode(self): |
| 187 |
""" |
| 188 |
Property target used to get the ignoreFailure mode. |
| 189 |
""" |
| 190 |
return self._ignoreFailureMode |
| 191 |
|
| 192 |
name = property(_getName, _setName, None, "Name of the peer.") |
| 193 |
collectDir = property(_getCollectDir, _setCollectDir, None, "Path to the peer's collect directory (an absolute local path).") |
| 194 |
ignoreFailureMode = property(_getIgnoreFailureMode, _setIgnoreFailureMode, None, "Ignore failure mode for peer.") |
| 195 |
|
| 196 |
################# |
| 197 |
# Public methods |
| 198 |
################# |
| 199 |
|
| 200 |
def stagePeer(self, targetDir, ownership=None, permissions=None): |
| 201 |
""" |
| 202 |
Stages data from the peer into the indicated local target directory. |
| 203 |
|
| 204 |
The collect and target directories must both already exist before this |
| 205 |
method is called. If passed in, ownership and permissions will be |
| 206 |
applied to the files that are copied. |
| 207 |
|
| 208 |
*Note:* The caller is responsible for checking that the indicator exists, |
| 209 |
if they care. This function only stages the files within the directory. |
| 210 |
|
| 211 |
*Note:* If you have user/group as strings, call the :any:`util.getUidGid` function |
| 212 |
to get the associated uid/gid as an ownership tuple. |
| 213 |
|
| 214 |
Args: |
| 215 |
targetDir: Target directory to write data into |
| 216 |
ownership: Owner and group that files should have, tuple of numeric ``(uid, gid)`` |
| 217 |
permissions: Unix permissions mode that the staged files should have, in octal like ``0640`` |
| 218 |
Returns: |
| 219 |
Number of files copied from the source directory to the target directory |
| 220 |
|
| 221 |
Raises: |
| 222 |
ValueError: If collect directory is not a directory or does not exist |
| 223 |
ValueError: If target directory is not a directory, does not exist or is not absolute |
| 224 |
ValueError: If a path cannot be encoded properly |
| 225 |
IOError: If there were no files to stage (i.e. the directory was empty) |
| 226 |
IOError: If there is an IO error copying a file |
| 227 |
OSError: If there is an OS error copying or changing permissions on a file |
| 228 |
""" |
| 229 |
targetDir = encodePath(targetDir) |
| 230 |
if not (os.path.isabs(targetDir) or posixpath.isabs(targetDir)): # Python 3.13+ does not treat / as absolute on Windows |
| 231 |
logger.debug("Target directory [%s] not an absolute path.", targetDir) |
| 232 |
raise ValueError("Target directory must be an absolute path.") |
| 233 |
if not os.path.exists(self.collectDir) or not os.path.isdir(self.collectDir): |
| 234 |
logger.debug("Collect directory [%s] is not a directory or does not exist on disk.", self.collectDir) |
| 235 |
raise ValueError("Collect directory is not a directory or does not exist on disk.") |
| 236 |
if not os.path.exists(targetDir) or not os.path.isdir(targetDir): |
| 237 |
logger.debug("Target directory [%s] is not a directory or does not exist on disk.", targetDir) |
| 238 |
raise ValueError("Target directory is not a directory or does not exist on disk.") |
| 239 |
count = LocalPeer._copyLocalDir(self.collectDir, targetDir, ownership, permissions) |
| 240 |
if count == 0: |
| 241 |
raise OSError("Did not copy any files from local peer.") |
| 242 |
return count |
| 243 |
|
| 244 |
def checkCollectIndicator(self, collectIndicator=None): |
| 245 |
""" |
| 246 |
Checks the collect indicator in the peer's staging directory. |
| 247 |
|
| 248 |
When a peer has completed collecting its backup files, it will write an |
| 249 |
empty indicator file into its collect directory. This method checks to |
| 250 |
see whether that indicator has been written. We're "stupid" here - if |
| 251 |
the collect directory doesn't exist, you'll naturally get back ``False``. |
| 252 |
|
| 253 |
If you need to, you can override the name of the collect indicator file |
| 254 |
by passing in a different name. |
| 255 |
|
| 256 |
Args: |
| 257 |
collectIndicator: Name of the collect indicator file to check |
| 258 |
Returns: |
| 259 |
Boolean true/false depending on whether the indicator exists |
| 260 |
Raises: |
| 261 |
ValueError: If a path cannot be encoded properly |
| 262 |
""" |
| 263 |
collectIndicator = encodePath(collectIndicator) |
| 264 |
if collectIndicator is None: |
| 265 |
return os.path.exists(pathJoin(self.collectDir, DEF_COLLECT_INDICATOR)) |
| 266 |
else: |
| 267 |
return os.path.exists(pathJoin(self.collectDir, collectIndicator)) |
| 268 |
|
| 269 |
def writeStageIndicator(self, stageIndicator=None, ownership=None, permissions=None): |
| 270 |
""" |
| 271 |
Writes the stage indicator in the peer's staging directory. |
| 272 |
|
| 273 |
When the master has completed collecting its backup files, it will write |
| 274 |
an empty indicator file into the peer's collect directory. The presence |
| 275 |
of this file implies that the staging process is complete. |
| 276 |
|
| 277 |
If you need to, you can override the name of the stage indicator file by |
| 278 |
passing in a different name. |
| 279 |
|
| 280 |
*Note:* If you have user/group as strings, call the :any:`util.getUidGid` |
| 281 |
function to get the associated uid/gid as an ownership tuple. |
| 282 |
|
| 283 |
Args: |
| 284 |
stageIndicator: Name of the indicator file to write |
| 285 |
ownership: Owner and group that files should have, tuple of numeric ``(uid, gid)`` |
| 286 |
permissions: Unix permissions mode that the staged files should have, in octal like ``0640`` |
| 287 |
Raises: |
| 288 |
ValueError: If collect directory is not a directory or does not exist |
| 289 |
ValueError: If a path cannot be encoded properly |
| 290 |
IOError: If there is an IO error creating the file |
| 291 |
OSError: If there is an OS error creating or changing permissions on the file |
| 292 |
""" |
| 293 |
stageIndicator = encodePath(stageIndicator) |
| 294 |
if not os.path.exists(self.collectDir) or not os.path.isdir(self.collectDir): |
| 295 |
logger.debug("Collect directory [%s] is not a directory or does not exist on disk.", self.collectDir) |
| 296 |
raise ValueError("Collect directory is not a directory or does not exist on disk.") |
| 297 |
if stageIndicator is None: |
| 298 |
fileName = pathJoin(self.collectDir, DEF_STAGE_INDICATOR) |
| 299 |
else: |
| 300 |
fileName = pathJoin(self.collectDir, stageIndicator) |
| 301 |
LocalPeer._copyLocalFile(None, fileName, ownership, permissions) # None for sourceFile results in an empty target |
| 302 |
|
| 303 |
################## |
| 304 |
# Private methods |
| 305 |
################## |
| 306 |
|
| 307 |
@staticmethod |
| 308 |
def _copyLocalDir(sourceDir, targetDir, ownership=None, permissions=None): |
| 309 |
""" |
| 310 |
Copies files from the source directory to the target directory. |
| 311 |
|
| 312 |
This function is not recursive. Only the files in the directory will be |
| 313 |
copied. Ownership and permissions will be left at their default values |
| 314 |
if new values are not specified. The source and target directories are |
| 315 |
allowed to be soft links to a directory, but besides that soft links are |
| 316 |
ignored. |
| 317 |
|
| 318 |
*Note:* If you have user/group as strings, call the :any:`util.getUidGid` |
| 319 |
function to get the associated uid/gid as an ownership tuple. |
| 320 |
|
| 321 |
Args: |
| 322 |
sourceDir: Source directory |
| 323 |
targetDir: Target directory |
| 324 |
ownership: Owner and group that files should have, tuple of numeric ``(uid, gid)`` |
| 325 |
permissions: Unix permissions mode that the staged files should have, in octal like ``0640`` |
| 326 |
Returns: |
| 327 |
Number of files copied from the source directory to the target directory |
| 328 |
|
| 329 |
Raises: |
| 330 |
ValueError: If source or target is not a directory or does not exist |
| 331 |
ValueError: If a path cannot be encoded properly |
| 332 |
IOError: If there is an IO error copying the files |
| 333 |
OSError: If there is an OS error copying or changing permissions on a files |
| 334 |
""" |
| 335 |
filesCopied = 0 |
| 336 |
sourceDir = encodePath(sourceDir) |
| 337 |
targetDir = encodePath(targetDir) |
| 338 |
for fileName in os.listdir(sourceDir): |
| 339 |
sourceFile = pathJoin(sourceDir, fileName) |
| 340 |
targetFile = pathJoin(targetDir, fileName) |
| 341 |
LocalPeer._copyLocalFile(sourceFile, targetFile, ownership, permissions) |
| 342 |
filesCopied += 1 |
| 343 |
return filesCopied |
| 344 |
|
| 345 |
@staticmethod |
| 346 |
def _copyLocalFile(sourceFile=None, targetFile=None, ownership=None, permissions=None, overwrite=True): |
| 347 |
""" |
| 348 |
Copies a source file to a target file. |
| 349 |
|
| 350 |
If the source file is ``None`` then the target file will be created or |
| 351 |
overwritten as an empty file. If the target file is ``None``, this method |
| 352 |
is a no-op. Attempting to copy a soft link or a directory will result in |
| 353 |
an exception. |
| 354 |
|
| 355 |
*Note:* If you have user/group as strings, call the :any:`util.getUidGid` |
| 356 |
function to get the associated uid/gid as an ownership tuple. |
| 357 |
|
| 358 |
*Note:* We will not overwrite a target file that exists when this method |
| 359 |
is invoked. If the target already exists, we'll raise an exception. |
| 360 |
|
| 361 |
Args: |
| 362 |
sourceFile: Source file to copy |
| 363 |
targetFile: Target file to create |
| 364 |
ownership: Owner and group that files should have, tuple of numeric ``(uid, gid)`` |
| 365 |
permissions: Unix permissions mode that the staged files should have, in octal like ``0640`` |
| 366 |
overwrite: Indicates whether it's OK to overwrite the target file |
| 367 |
Raises: |
| 368 |
ValueError: If the passed-in source file is not a regular file |
| 369 |
ValueError: If a path cannot be encoded properly |
| 370 |
IOError: If the target file already exists |
| 371 |
IOError: If there is an IO error copying the file |
| 372 |
OSError: If there is an OS error copying or changing permissions on a file |
| 373 |
""" |
| 374 |
targetFile = encodePath(targetFile) |
| 375 |
sourceFile = encodePath(sourceFile) |
| 376 |
if targetFile is None: |
| 377 |
return |
| 378 |
if not overwrite: |
| 379 |
if os.path.exists(targetFile): |
| 380 |
raise OSError("Target file [%s] already exists." % targetFile) |
| 381 |
if sourceFile is None: |
| 382 |
with open(targetFile, "w") as f: |
| 383 |
f.write("") |
| 384 |
else: |
| 385 |
if os.path.isfile(sourceFile) and not os.path.islink(sourceFile): |
| 386 |
shutil.copy(sourceFile, targetFile) |
| 387 |
else: |
| 388 |
logger.debug("Source [%s] is not a regular file.", sourceFile) |
| 389 |
raise ValueError("Source is not a regular file.") |
| 390 |
if ownership is not None: |
| 391 |
if sys.platform != "win32": |
| 392 |
os.chown(targetFile, ownership[0], ownership[1]) |
| 393 |
if permissions is not None: |
| 394 |
os.chmod(targetFile, permissions) |
| 395 |
|
| 396 |
|
| 397 |
######################################################################## |
| 398 |
# RemotePeer class definition |
| 399 |
######################################################################## |
| 400 |
|
| 401 |
|
| 402 |
class RemotePeer: |
| 403 |
###################### |
| 404 |
# Class documentation |
| 405 |
###################### |
| 406 |
|
| 407 |
""" |
| 408 |
Backup peer representing a remote peer in a backup pool. |
| 409 |
|
| 410 |
This is a class representing a remote (networked) peer in a backup pool. |
| 411 |
Remote peers are backed up using an rcp-compatible copy command. A remote |
| 412 |
peer has associated with it a name (which must be a valid hostname), a |
| 413 |
collect directory, a working directory and a copy method (an rcp-compatible |
| 414 |
command). |
| 415 |
|
| 416 |
You can also set an optional local user value. This username will be used |
| 417 |
as the local user for any remote copies that are required. It can only be |
| 418 |
used if the root user is executing the backup. The root user will ``su`` to |
| 419 |
the local user and execute the remote copies as that user. |
| 420 |
|
| 421 |
The copy method is associated with the peer and not with the actual request |
| 422 |
to copy, because we can envision that each remote host might have a |
| 423 |
different connect method. |
| 424 |
|
| 425 |
The public methods other than the constructor are part of a "backup peer" |
| 426 |
interface shared with the ``LocalPeer`` class. |
| 427 |
|
| 428 |
""" |
| 429 |
|
| 430 |
############## |
| 431 |
# Constructor |
| 432 |
############## |
| 433 |
|
| 434 |
def __init__( |
| 435 |
self, |
| 436 |
name=None, |
| 437 |
collectDir=None, |
| 438 |
workingDir=None, |
| 439 |
remoteUser=None, |
| 440 |
rcpCommand=None, |
| 441 |
localUser=None, |
| 442 |
rshCommand=None, |
| 443 |
cbackCommand=None, |
| 444 |
ignoreFailureMode=None, |
| 445 |
): |
| 446 |
""" |
| 447 |
Initializes a remote backup peer. |
| 448 |
|
| 449 |
*Note:* If provided, each command will eventually be parsed into a list of |
| 450 |
strings suitable for passing to ``util.executeCommand`` in order to avoid |
| 451 |
security holes related to shell interpolation. This parsing will be |
| 452 |
done by the :any:`util.splitCommandLine` function. See the documentation for |
| 453 |
that function for some important notes about its limitations. |
| 454 |
|
| 455 |
Args: |
| 456 |
name: Name of the backup peer, a valid DNS name |
| 457 |
collectDir: Path to the peer's collect directory, absolute path |
| 458 |
workingDir: Working directory that can be used to create temporary files, etc, an absolute path |
| 459 |
remoteUser: Name of the Cedar Backup user on the remote peer |
| 460 |
localUser: Name of the Cedar Backup user on the current host |
| 461 |
rcpCommand: An rcp-compatible copy command to use for copying files from the peer |
| 462 |
rshCommand: An rsh-compatible copy command to use for remote shells to the peer |
| 463 |
cbackCommand: A chack-compatible command to use for executing managed actions |
| 464 |
ignoreFailureMode: Ignore failure mode for this peer, one of ``VALID_FAILURE_MODES`` |
| 465 |
Raises: |
| 466 |
ValueError: If collect directory is not an absolute path |
| 467 |
""" |
| 468 |
self._name = None |
| 469 |
self._collectDir = None |
| 470 |
self._workingDir = None |
| 471 |
self._remoteUser = None |
| 472 |
self._localUser = None |
| 473 |
self._rcpCommand = None |
| 474 |
self._rcpCommandList = None |
| 475 |
self._rshCommand = None |
| 476 |
self._rshCommandList = None |
| 477 |
self._cbackCommand = None |
| 478 |
self._ignoreFailureMode = None |
| 479 |
self.name = name |
| 480 |
self.collectDir = collectDir |
| 481 |
self.workingDir = workingDir |
| 482 |
self.remoteUser = remoteUser |
| 483 |
self.localUser = localUser |
| 484 |
self.rcpCommand = rcpCommand |
| 485 |
self.rshCommand = rshCommand |
| 486 |
self.cbackCommand = cbackCommand |
| 487 |
self.ignoreFailureMode = ignoreFailureMode |
| 488 |
|
| 489 |
############# |
| 490 |
# Properties |
| 491 |
############# |
| 492 |
|
| 493 |
def _setName(self, value): |
| 494 |
""" |
| 495 |
Property target used to set the peer name. |
| 496 |
The value must be a non-empty string and cannot be ``None``. |
| 497 |
Raises: |
| 498 |
ValueError: If the value is an empty string or ``None`` |
| 499 |
""" |
| 500 |
if value is None or len(value) < 1: |
| 501 |
raise ValueError("Peer name must be a non-empty string.") |
| 502 |
self._name = value |
| 503 |
|
| 504 |
def _getName(self): |
| 505 |
""" |
| 506 |
Property target used to get the peer name. |
| 507 |
""" |
| 508 |
return self._name |
| 509 |
|
| 510 |
def _setCollectDir(self, value): |
| 511 |
""" |
| 512 |
Property target used to set the collect directory. |
| 513 |
The value must be an absolute path and cannot be ``None``. |
| 514 |
It does not have to exist on disk at the time of assignment. |
| 515 |
Raises: |
| 516 |
ValueError: If the value is ``None`` or is not an absolute path |
| 517 |
ValueError: If the value cannot be encoded properly |
| 518 |
""" |
| 519 |
if value is not None: |
| 520 |
if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows |
| 521 |
raise ValueError("Collect directory must be an absolute path.") |
| 522 |
self._collectDir = encodePath(value) |
| 523 |
|
| 524 |
def _getCollectDir(self): |
| 525 |
""" |
| 526 |
Property target used to get the collect directory. |
| 527 |
""" |
| 528 |
return self._collectDir |
| 529 |
|
| 530 |
def _setWorkingDir(self, value): |
| 531 |
""" |
| 532 |
Property target used to set the working directory. |
| 533 |
The value must be an absolute path and cannot be ``None``. |
| 534 |
Raises: |
| 535 |
ValueError: If the value is ``None`` or is not an absolute path |
| 536 |
ValueError: If the value cannot be encoded properly |
| 537 |
""" |
| 538 |
if value is not None: |
| 539 |
if not (os.path.isabs(value) or posixpath.isabs(value)): # Python 3.13+ does not treat / as absolute on Windows |
| 540 |
raise ValueError("Working directory must be an absolute path.") |
| 541 |
self._workingDir = encodePath(value) |
| 542 |
|
| 543 |
def _getWorkingDir(self): |
| 544 |
""" |
| 545 |
Property target used to get the working directory. |
| 546 |
""" |
| 547 |
return self._workingDir |
| 548 |
|
| 549 |
def _setRemoteUser(self, value): |
| 550 |
""" |
| 551 |
Property target used to set the remote user. |
| 552 |
The value must be a non-empty string and cannot be ``None``. |
| 553 |
Raises: |
| 554 |
ValueError: If the value is an empty string or ``None`` |
| 555 |
""" |
| 556 |
if value is None or len(value) < 1: |
| 557 |
raise ValueError("Peer remote user must be a non-empty string.") |
| 558 |
self._remoteUser = value |
| 559 |
|
| 560 |
def _getRemoteUser(self): |
| 561 |
""" |
| 562 |
Property target used to get the remote user. |
| 563 |
""" |
| 564 |
return self._remoteUser |
| 565 |
|
| 566 |
def _setLocalUser(self, value): |
| 567 |
""" |
| 568 |
Property target used to set the local user. |
| 569 |
The value must be a non-empty string if it is not ``None``. |
| 570 |
Raises: |
| 571 |
ValueError: If the value is an empty string |
| 572 |
""" |
| 573 |
if value is not None: |
| 574 |
if len(value) < 1: |
| 575 |
raise ValueError("Peer local user must be a non-empty string.") |
| 576 |
self._localUser = value |
| 577 |
|
| 578 |
def _getLocalUser(self): |
| 579 |
""" |
| 580 |
Property target used to get the local user. |
| 581 |
""" |
| 582 |
return self._localUser |
| 583 |
|
| 584 |
def _setRcpCommand(self, value): |
| 585 |
""" |
| 586 |
Property target to set the rcp command. |
| 587 |
|
| 588 |
The value must be a non-empty string or ``None``. Its value is stored in |
| 589 |
the two forms: "raw" as provided by the client, and "parsed" into a list |
| 590 |
suitable for being passed to :any:`util.executeCommand` via |
| 591 |
:any:`util.splitCommandLine`. |
| 592 |
|
| 593 |
However, all the caller will ever see via the property is the actual |
| 594 |
value they set (which includes seeing ``None``, even if we translate that |
| 595 |
internally to ``DEF_RCP_COMMAND``). Internally, we should always use |
| 596 |
``self._rcpCommandList`` if we want the actual command list. |
| 597 |
|
| 598 |
Raises: |
| 599 |
ValueError: If the value is an empty string |
| 600 |
""" |
| 601 |
if value is None: |
| 602 |
self._rcpCommand = None |
| 603 |
self._rcpCommandList = DEF_RCP_COMMAND |
| 604 |
else: |
| 605 |
if len(value) >= 1: |
| 606 |
self._rcpCommand = value |
| 607 |
self._rcpCommandList = splitCommandLine(self._rcpCommand) |
| 608 |
else: |
| 609 |
raise ValueError("The rcp command must be a non-empty string.") |
| 610 |
|
| 611 |
def _getRcpCommand(self): |
| 612 |
""" |
| 613 |
Property target used to get the rcp command. |
| 614 |
""" |
| 615 |
return self._rcpCommand |
| 616 |
|
| 617 |
def _setRshCommand(self, value): |
| 618 |
""" |
| 619 |
Property target to set the rsh command. |
| 620 |
|
| 621 |
The value must be a non-empty string or ``None``. Its value is stored in |
| 622 |
the two forms: "raw" as provided by the client, and "parsed" into a list |
| 623 |
suitable for being passed to :any:`util.executeCommand` via |
| 624 |
:any:`util.splitCommandLine`. |
| 625 |
|
| 626 |
However, all the caller will ever see via the property is the actual |
| 627 |
value they set (which includes seeing ``None``, even if we translate that |
| 628 |
internally to ``DEF_RSH_COMMAND``). Internally, we should always use |
| 629 |
``self._rshCommandList`` if we want the actual command list. |
| 630 |
|
| 631 |
Raises: |
| 632 |
ValueError: If the value is an empty string |
| 633 |
""" |
| 634 |
if value is None: |
| 635 |
self._rshCommand = None |
| 636 |
self._rshCommandList = DEF_RSH_COMMAND |
| 637 |
else: |
| 638 |
if len(value) >= 1: |
| 639 |
self._rshCommand = value |
| 640 |
self._rshCommandList = splitCommandLine(self._rshCommand) |
| 641 |
else: |
| 642 |
raise ValueError("The rsh command must be a non-empty string.") |
| 643 |
|
| 644 |
def _getRshCommand(self): |
| 645 |
""" |
| 646 |
Property target used to get the rsh command. |
| 647 |
""" |
| 648 |
return self._rshCommand |
| 649 |
|
| 650 |
def _setCbackCommand(self, value): |
| 651 |
""" |
| 652 |
Property target to set the cback command. |
| 653 |
|
| 654 |
The value must be a non-empty string or ``None``. Unlike the other |
| 655 |
command, this value is only stored in the "raw" form provided by the |
| 656 |
client. |
| 657 |
|
| 658 |
Raises: |
| 659 |
ValueError: If the value is an empty string |
| 660 |
""" |
| 661 |
if value is None: |
| 662 |
self._cbackCommand = None |
| 663 |
else: |
| 664 |
if len(value) >= 1: |
| 665 |
self._cbackCommand = value |
| 666 |
else: |
| 667 |
raise ValueError("The cback command must be a non-empty string.") |
| 668 |
|
| 669 |
def _getCbackCommand(self): |
| 670 |
""" |
| 671 |
Property target used to get the cback command. |
| 672 |
""" |
| 673 |
return self._cbackCommand |
| 674 |
|
| 675 |
def _setIgnoreFailureMode(self, value): |
| 676 |
""" |
| 677 |
Property target used to set the ignoreFailure mode. |
| 678 |
If not ``None``, the mode must be one of the values in :any:`VALID_FAILURE_MODES`. |
| 679 |
Raises: |
| 680 |
ValueError: If the value is not valid |
| 681 |
""" |
| 682 |
if value is not None: |
| 683 |
if value not in VALID_FAILURE_MODES: |
| 684 |
raise ValueError("Ignore failure mode must be one of %s." % VALID_FAILURE_MODES) |
| 685 |
self._ignoreFailureMode = value |
| 686 |
|
| 687 |
def _getIgnoreFailureMode(self): |
| 688 |
""" |
| 689 |
Property target used to get the ignoreFailure mode. |
| 690 |
""" |
| 691 |
return self._ignoreFailureMode |
| 692 |
|
| 693 |
name = property(_getName, _setName, None, "Name of the peer (a valid DNS hostname).") |
| 694 |
collectDir = property(_getCollectDir, _setCollectDir, None, "Path to the peer's collect directory (an absolute local path).") |
| 695 |
workingDir = property(_getWorkingDir, _setWorkingDir, None, "Path to the peer's working directory (an absolute local path).") |
| 696 |
remoteUser = property(_getRemoteUser, _setRemoteUser, None, "Name of the Cedar Backup user on the remote peer.") |
| 697 |
localUser = property(_getLocalUser, _setLocalUser, None, "Name of the Cedar Backup user on the current host.") |
| 698 |
rcpCommand = property(_getRcpCommand, _setRcpCommand, None, "An rcp-compatible copy command to use for copying files.") |
| 699 |
rshCommand = property(_getRshCommand, _setRshCommand, None, "An rsh-compatible command to use for remote shells to the peer.") |
| 700 |
cbackCommand = property( |
| 701 |
_getCbackCommand, _setCbackCommand, None, "A chack-compatible command to use for executing managed actions." |
| 702 |
) |
| 703 |
ignoreFailureMode = property(_getIgnoreFailureMode, _setIgnoreFailureMode, None, "Ignore failure mode for peer.") |
| 704 |
|
| 705 |
################# |
| 706 |
# Public methods |
| 707 |
################# |
| 708 |
|
| 709 |
def stagePeer(self, targetDir, ownership=None, permissions=None): |
| 710 |
""" |
| 711 |
Stages data from the peer into the indicated local target directory. |
| 712 |
|
| 713 |
The target directory must already exist before this method is called. If |
| 714 |
passed in, ownership and permissions will be applied to the files that |
| 715 |
are copied. |
| 716 |
|
| 717 |
*Note:* The returned count of copied files might be inaccurate if some of |
| 718 |
the copied files already existed in the staging directory prior to the |
| 719 |
copy taking place. We don't clear the staging directory first, because |
| 720 |
some extension might also be using it. |
| 721 |
|
| 722 |
*Note:* If you have user/group as strings, call the :any:`util.getUidGid` function |
| 723 |
to get the associated uid/gid as an ownership tuple. |
| 724 |
|
| 725 |
*Note:* Unlike the local peer version of this method, an I/O error might |
| 726 |
or might not be raised if the directory is empty. Since we're using a |
| 727 |
remote copy method, we just don't have the fine-grained control over our |
| 728 |
exceptions that's available when we can look directly at the filesystem, |
| 729 |
and we can't control whether the remote copy method thinks an empty |
| 730 |
directory is an error. |
| 731 |
|
| 732 |
Args: |
| 733 |
targetDir: Target directory to write data into |
| 734 |
ownership: Owner and group that files should have, tuple of numeric ``(uid, gid)`` |
| 735 |
permissions: Unix permissions mode that the staged files should have, in octal like ``0640`` |
| 736 |
Returns: |
| 737 |
Number of files copied from the source directory to the target directory |
| 738 |
|
| 739 |
Raises: |
| 740 |
ValueError: If target directory is not a directory, does not exist or is not absolute |
| 741 |
ValueError: If a path cannot be encoded properly |
| 742 |
IOError: If there were no files to stage (i.e. the directory was empty) |
| 743 |
IOError: If there is an IO error copying a file |
| 744 |
OSError: If there is an OS error copying or changing permissions on a file |
| 745 |
""" |
| 746 |
targetDir = encodePath(targetDir) |
| 747 |
if not (os.path.isabs(targetDir) or posixpath.isabs(targetDir)): # Python 3.13+ does not treat / as absolute on Windows |
| 748 |
logger.debug("Target directory [%s] not an absolute path.", targetDir) |
| 749 |
raise ValueError("Target directory must be an absolute path.") |
| 750 |
if not os.path.exists(targetDir) or not os.path.isdir(targetDir): |
| 751 |
logger.debug("Target directory [%s] is not a directory or does not exist on disk.", targetDir) |
| 752 |
raise ValueError("Target directory is not a directory or does not exist on disk.") |
| 753 |
count = RemotePeer._copyRemoteDir( |
| 754 |
self.remoteUser, |
| 755 |
self.localUser, |
| 756 |
self.name, |
| 757 |
self._rcpCommand, |
| 758 |
self._rcpCommandList, |
| 759 |
self.collectDir, |
| 760 |
targetDir, |
| 761 |
ownership, |
| 762 |
permissions, |
| 763 |
) |
| 764 |
if count == 0: |
| 765 |
raise OSError("Did not copy any files from local peer.") |
| 766 |
return count |
| 767 |
|
| 768 |
def checkCollectIndicator(self, collectIndicator=None): |
| 769 |
""" |
| 770 |
Checks the collect indicator in the peer's staging directory. |
| 771 |
|
| 772 |
When a peer has completed collecting its backup files, it will write an |
| 773 |
empty indicator file into its collect directory. This method checks to |
| 774 |
see whether that indicator has been written. If the remote copy command |
| 775 |
fails, we return ``False`` as if the file weren't there. |
| 776 |
|
| 777 |
If you need to, you can override the name of the collect indicator file |
| 778 |
by passing in a different name. |
| 779 |
|
| 780 |
*Note:* Apparently, we can't count on all rcp-compatible implementations |
| 781 |
to return sensible errors for some error conditions. As an example, the |
| 782 |
``scp`` command in Debian 'woody' returns a zero (normal) status even when |
| 783 |
it can't find a host or if the login or path is invalid. Because of |
| 784 |
this, the implementation of this method is rather convoluted. |
| 785 |
|
| 786 |
Args: |
| 787 |
collectIndicator: Name of the collect indicator file to check |
| 788 |
Returns: |
| 789 |
Boolean true/false depending on whether the indicator exists |
| 790 |
Raises: |
| 791 |
ValueError: If a path cannot be encoded properly |
| 792 |
""" |
| 793 |
try: |
| 794 |
if collectIndicator is None: |
| 795 |
sourceFile = pathJoin(self.collectDir, DEF_COLLECT_INDICATOR) |
| 796 |
targetFile = pathJoin(self.workingDir, DEF_COLLECT_INDICATOR) |
| 797 |
else: |
| 798 |
collectIndicator = encodePath(collectIndicator) |
| 799 |
sourceFile = pathJoin(self.collectDir, collectIndicator) |
| 800 |
targetFile = pathJoin(self.workingDir, collectIndicator) |
| 801 |
logger.debug("Fetch remote [%s] into [%s].", sourceFile, targetFile) |
| 802 |
if os.path.exists(targetFile): |
| 803 |
try: |
| 804 |
os.remove(targetFile) |
| 805 |
except: |
| 806 |
raise Exception("Error: collect indicator [%s] already exists!" % targetFile) |
| 807 |
try: |
| 808 |
RemotePeer._copyRemoteFile( |
| 809 |
self.remoteUser, |
| 810 |
self.localUser, |
| 811 |
self.name, |
| 812 |
self._rcpCommand, |
| 813 |
self._rcpCommandList, |
| 814 |
sourceFile, |
| 815 |
targetFile, |
| 816 |
overwrite=False, |
| 817 |
) |
| 818 |
return os.path.exists(targetFile) |
| 819 |
except Exception as e: |
| 820 |
logger.info("Failed looking for collect indicator: %s", e) |
| 821 |
return False |
| 822 |
finally: |
| 823 |
if os.path.exists(targetFile): |
| 824 |
try: |
| 825 |
os.remove(targetFile) |
| 826 |
except: |
| 827 |
pass |
| 828 |
|
| 829 |
def writeStageIndicator(self, stageIndicator=None): |
| 830 |
""" |
| 831 |
Writes the stage indicator in the peer's staging directory. |
| 832 |
|
| 833 |
When the master has completed collecting its backup files, it will write |
| 834 |
an empty indicator file into the peer's collect directory. The presence |
| 835 |
of this file implies that the staging process is complete. |
| 836 |
|
| 837 |
If you need to, you can override the name of the stage indicator file by |
| 838 |
passing in a different name. |
| 839 |
|
| 840 |
*Note:* If you have user/group as strings, call the :any:`util.getUidGid` function |
| 841 |
to get the associated uid/gid as an ownership tuple. |
| 842 |
|
| 843 |
Args: |
| 844 |
stageIndicator: Name of the indicator file to write |
| 845 |
Raises: |
| 846 |
ValueError: If a path cannot be encoded properly |
| 847 |
IOError: If there is an IO error creating the file |
| 848 |
OSError: If there is an OS error creating or changing permissions on the file |
| 849 |
""" |
| 850 |
stageIndicator = encodePath(stageIndicator) |
| 851 |
if stageIndicator is None: |
| 852 |
sourceFile = pathJoin(self.workingDir, DEF_STAGE_INDICATOR) |
| 853 |
targetFile = pathJoin(self.collectDir, DEF_STAGE_INDICATOR) |
| 854 |
else: |
| 855 |
sourceFile = pathJoin(self.workingDir, DEF_STAGE_INDICATOR) |
| 856 |
targetFile = pathJoin(self.collectDir, stageIndicator) |
| 857 |
try: |
| 858 |
if not os.path.exists(sourceFile): |
| 859 |
with open(sourceFile, "w") as f: |
| 860 |
f.write("") |
| 861 |
RemotePeer._pushLocalFile( |
| 862 |
self.remoteUser, self.localUser, self.name, self._rcpCommand, self._rcpCommandList, sourceFile, targetFile |
| 863 |
) |
| 864 |
finally: |
| 865 |
if os.path.exists(sourceFile): |
| 866 |
try: |
| 867 |
os.remove(sourceFile) |
| 868 |
except: |
| 869 |
pass |
| 870 |
|
| 871 |
def executeRemoteCommand(self, command): |
| 872 |
""" |
| 873 |
Executes a command on the peer via remote shell. |
| 874 |
|
| 875 |
Args: |
| 876 |
command: Command to execute |
| 877 |
Raises: |
| 878 |
IOError: If there is an error executing the command on the remote peer |
| 879 |
""" |
| 880 |
RemotePeer._executeRemoteCommand( |
| 881 |
self.remoteUser, self.localUser, self.name, self._rshCommand, self._rshCommandList, command |
| 882 |
) |
| 883 |
|
| 884 |
def executeManagedAction(self, action, fullBackup): |
| 885 |
""" |
| 886 |
Executes a managed action on this peer. |
| 887 |
|
| 888 |
Args: |
| 889 |
action: Name of the action to execute |
| 890 |
fullBackup: Whether a full backup should be executed |
| 891 |
|
| 892 |
Raises: |
| 893 |
IOError: If there is an error executing the action on the remote peer |
| 894 |
""" |
| 895 |
try: |
| 896 |
command = RemotePeer._buildCbackCommand(self.cbackCommand, action, fullBackup) |
| 897 |
self.executeRemoteCommand(command) |
| 898 |
except OSError as e: |
| 899 |
logger.info(e) |
| 900 |
raise OSError("Failed to execute action [%s] on managed client [%s]." % (action, self.name)) |
| 901 |
|
| 902 |
################## |
| 903 |
# Private methods |
| 904 |
################## |
| 905 |
|
| 906 |
@staticmethod |
| 907 |
def _getDirContents(path): |
| 908 |
""" |
| 909 |
Returns the contents of a directory in terms of a Set. |
| 910 |
|
| 911 |
The directory's contents are read as a :any:`FilesystemList` containing only |
| 912 |
files, and then the list is converted into a set object for later use. |
| 913 |
|
| 914 |
Args: |
| 915 |
path: Directory path to get contents for |
| 916 |
Returns: |
| 917 |
Set of files in the directory |
| 918 |
Raises: |
| 919 |
ValueError: If path is not a directory or does not exist |
| 920 |
""" |
| 921 |
contents = FilesystemList() |
| 922 |
contents.excludeDirs = True |
| 923 |
contents.excludeLinks = True |
| 924 |
contents.addDirContents(path) |
| 925 |
return set(contents) |
| 926 |
|
| 927 |
@staticmethod |
| 928 |
def _copyRemoteDir( |
| 929 |
remoteUser, localUser, remoteHost, rcpCommand, rcpCommandList, sourceDir, targetDir, ownership=None, permissions=None |
| 930 |
): |
| 931 |
""" |
| 932 |
Copies files from the source directory to the target directory. |
| 933 |
|
| 934 |
This function is not recursive. Only the files in the directory will be |
| 935 |
copied. Ownership and permissions will be left at their default values |
| 936 |
if new values are not specified. Behavior when copying soft links from |
| 937 |
the collect directory is dependent on the behavior of the specified rcp |
| 938 |
command. |
| 939 |
|
| 940 |
*Note:* The returned count of copied files might be inaccurate if some of |
| 941 |
the copied files already existed in the staging directory prior to the |
| 942 |
copy taking place. We don't clear the staging directory first, because |
| 943 |
some extension might also be using it. |
| 944 |
|
| 945 |
*Note:* If you have user/group as strings, call the :any:`util.getUidGid` function |
| 946 |
to get the associated uid/gid as an ownership tuple. |
| 947 |
|
| 948 |
*Note:* We don't have a good way of knowing exactly what files we copied |
| 949 |
down from the remote peer, unless we want to parse the output of the rcp |
| 950 |
command (ugh). We could change permissions on everything in the target |
| 951 |
directory, but that's kind of ugly too. Instead, we use Python's set |
| 952 |
functionality to figure out what files were added while we executed the |
| 953 |
rcp command. This isn't perfect - for instance, it's not correct if |
| 954 |
someone else is messing with the directory at the same time we're doing |
| 955 |
the remote copy - but it's about as good as we're going to get. |
| 956 |
|
| 957 |
*Note:* Apparently, we can't count on all rcp-compatible implementations |
| 958 |
to return sensible errors for some error conditions. As an example, the |
| 959 |
``scp`` command in Debian 'woody' returns a zero (normal) status even |
| 960 |
when it can't find a host or if the login or path is invalid. We try |
| 961 |
to work around this by issuing ``IOError`` if we don't copy any files from |
| 962 |
the remote host. |
| 963 |
|
| 964 |
Args: |
| 965 |
remoteUser: Name of the Cedar Backup user on the remote peer |
| 966 |
localUser: Name of the Cedar Backup user on the current host |
| 967 |
remoteHost: Hostname of the remote peer |
| 968 |
rcpCommand: An rcp-compatible copy command to use for copying files from the peer |
| 969 |
rcpCommandList: An rcp-compatible copy command to use for copying files, as for :any:`util.executeCommand` |
| 970 |
sourceDir: Source directory |
| 971 |
targetDir: Target directory |
| 972 |
ownership: Owner and group that files should have, tuple of numeric ``(uid, gid)`` |
| 973 |
permissions: Unix permissions mode that the staged files should have, in octal like ``0640`` |
| 974 |
Returns: |
| 975 |
Number of files copied from the source directory to the target directory |
| 976 |
|
| 977 |
Raises: |
| 978 |
ValueError: If source or target is not a directory or does not exist |
| 979 |
IOError: If there is an IO error copying the files |
| 980 |
""" |
| 981 |
beforeSet = RemotePeer._getDirContents(targetDir) |
| 982 |
if localUser is not None: |
| 983 |
try: |
| 984 |
if not isRunningAsRoot(): |
| 985 |
raise OSError("Only root can remote copy as another user.") |
| 986 |
except AttributeError: |
| 987 |
pass |
| 988 |
actualCommand = "%s %s@%s:%s/* %s" % (rcpCommand, remoteUser, remoteHost, sourceDir, targetDir) |
| 989 |
command = resolveCommand(SU_COMMAND) |
| 990 |
result = executeCommand(command, [localUser, "-c", actualCommand])[0] |
| 991 |
if result != 0: |
| 992 |
raise OSError("Error (%d) copying files from remote host as local user [%s]." % (result, localUser)) |
| 993 |
else: |
| 994 |
copySource = "%s@%s:%s/*" % (remoteUser, remoteHost, sourceDir) |
| 995 |
command = resolveCommand(rcpCommandList) |
| 996 |
result = executeCommand(command, [copySource, targetDir])[0] |
| 997 |
if result != 0: |
| 998 |
raise OSError("Error (%d) copying files from remote host." % result) |
| 999 |
afterSet = RemotePeer._getDirContents(targetDir) |
| 1000 |
if len(afterSet) == 0: |
| 1001 |
raise OSError("Did not copy any files from remote peer.") |
| 1002 |
differenceSet = afterSet.difference(beforeSet) # files we added as part of copy |
| 1003 |
if len(differenceSet) == 0: |
| 1004 |
raise OSError("Apparently did not copy any new files from remote peer.") |
| 1005 |
for targetFile in differenceSet: |
| 1006 |
if ownership is not None: |
| 1007 |
if sys.platform != "win32": |
| 1008 |
os.chown(targetFile, ownership[0], ownership[1]) |
| 1009 |
if permissions is not None: |
| 1010 |
os.chmod(targetFile, permissions) |
| 1011 |
return len(differenceSet) |
| 1012 |
|
| 1013 |
@staticmethod |
| 1014 |
def _copyRemoteFile( |
| 1015 |
remoteUser, |
| 1016 |
localUser, |
| 1017 |
remoteHost, |
| 1018 |
rcpCommand, |
| 1019 |
rcpCommandList, |
| 1020 |
sourceFile, |
| 1021 |
targetFile, |
| 1022 |
ownership=None, |
| 1023 |
permissions=None, |
| 1024 |
overwrite=True, |
| 1025 |
): |
| 1026 |
""" |
| 1027 |
Copies a remote source file to a target file. |
| 1028 |
|
| 1029 |
*Note:* Internally, we have to go through and escape any spaces in the |
| 1030 |
source path with double-backslash, otherwise things get screwed up. It |
| 1031 |
doesn't seem to be required in the target path. I hope this is portable |
| 1032 |
to various different rcp methods, but I guess it might not be (all I have |
| 1033 |
to test with is OpenSSH). |
| 1034 |
|
| 1035 |
*Note:* If you have user/group as strings, call the :any:`util.getUidGid` function |
| 1036 |
to get the associated uid/gid as an ownership tuple. |
| 1037 |
|
| 1038 |
*Note:* We will not overwrite a target file that exists when this method |
| 1039 |
is invoked. If the target already exists, we'll raise an exception. |
| 1040 |
|
| 1041 |
*Note:* Apparently, we can't count on all rcp-compatible implementations |
| 1042 |
to return sensible errors for some error conditions. As an example, the |
| 1043 |
``scp`` command in Debian 'woody' returns a zero (normal) status even when |
| 1044 |
it can't find a host or if the login or path is invalid. We try to work |
| 1045 |
around this by issuing ``IOError`` the target file does not exist when |
| 1046 |
we're done. |
| 1047 |
|
| 1048 |
Args: |
| 1049 |
remoteUser: Name of the Cedar Backup user on the remote peer |
| 1050 |
remoteHost: Hostname of the remote peer |
| 1051 |
localUser: Name of the Cedar Backup user on the current host |
| 1052 |
rcpCommand: An rcp-compatible copy command to use for copying files from the peer |
| 1053 |
rcpCommandList: An rcp-compatible copy command to use for copying files, as for :any:`util.executeCommand` |
| 1054 |
sourceFile: Source file to copy |
| 1055 |
targetFile: Target file to create |
| 1056 |
ownership: Owner and group that files should have, tuple of numeric ``(uid, gid)`` |
| 1057 |
permissions: Unix permissions mode that the staged files should have, in octal like ``0640`` |
| 1058 |
overwrite: Indicates whether it's OK to overwrite the target file |
| 1059 |
Raises: |
| 1060 |
IOError: If the target file already exists |
| 1061 |
IOError: If there is an IO error copying the file |
| 1062 |
OSError: If there is an OS error changing permissions on the file |
| 1063 |
""" |
| 1064 |
if not overwrite: |
| 1065 |
if os.path.exists(targetFile): |
| 1066 |
raise OSError("Target file [%s] already exists." % targetFile) |
| 1067 |
if localUser is not None: |
| 1068 |
try: |
| 1069 |
if not isRunningAsRoot(): |
| 1070 |
raise OSError("Only root can remote copy as another user.") |
| 1071 |
except AttributeError: |
| 1072 |
pass |
| 1073 |
actualCommand = "%s %s@%s:%s %s" % (rcpCommand, remoteUser, remoteHost, sourceFile.replace(" ", "\\ "), targetFile) |
| 1074 |
command = resolveCommand(SU_COMMAND) |
| 1075 |
result = executeCommand(command, [localUser, "-c", actualCommand])[0] |
| 1076 |
if result != 0: |
| 1077 |
raise OSError("Error (%d) copying [%s] from remote host as local user [%s]." % (result, sourceFile, localUser)) |
| 1078 |
else: |
| 1079 |
copySource = "%s@%s:%s" % (remoteUser, remoteHost, sourceFile.replace(" ", "\\ ")) |
| 1080 |
command = resolveCommand(rcpCommandList) |
| 1081 |
result = executeCommand(command, [copySource, targetFile])[0] |
| 1082 |
if result != 0: |
| 1083 |
raise OSError("Error (%d) copying [%s] from remote host." % (result, sourceFile)) |
| 1084 |
if not os.path.exists(targetFile): |
| 1085 |
raise OSError("Apparently unable to copy file from remote host.") |
| 1086 |
if ownership is not None: |
| 1087 |
if sys.platform != "win32": |
| 1088 |
os.chown(targetFile, ownership[0], ownership[1]) |
| 1089 |
if permissions is not None: |
| 1090 |
os.chmod(targetFile, permissions) |
| 1091 |
|
| 1092 |
@staticmethod |
| 1093 |
def _pushLocalFile(remoteUser, localUser, remoteHost, rcpCommand, rcpCommandList, sourceFile, targetFile, overwrite=True): |
| 1094 |
""" |
| 1095 |
Copies a local source file to a remote host. |
| 1096 |
|
| 1097 |
*Note:* We will not overwrite a target file that exists when this method |
| 1098 |
is invoked. If the target already exists, we'll raise an exception. |
| 1099 |
|
| 1100 |
*Note:* Internally, we have to go through and escape any spaces in the |
| 1101 |
source and target paths with double-backslash, otherwise things get |
| 1102 |
screwed up. I hope this is portable to various different rcp methods, |
| 1103 |
but I guess it might not be (all I have to test with is OpenSSH). |
| 1104 |
|
| 1105 |
*Note:* If you have user/group as strings, call the :any:`util.getUidGid` function |
| 1106 |
to get the associated uid/gid as an ownership tuple. |
| 1107 |
|
| 1108 |
Args: |
| 1109 |
remoteUser: Name of the Cedar Backup user on the remote peer |
| 1110 |
localUser: Name of the Cedar Backup user on the current host |
| 1111 |
remoteHost: Hostname of the remote peer |
| 1112 |
rcpCommand: An rcp-compatible copy command to use for copying files from the peer |
| 1113 |
rcpCommandList: An rcp-compatible copy command to use for copying files, as for :any:`util.executeCommand` |
| 1114 |
sourceFile: Source file to copy |
| 1115 |
targetFile: Target file to create |
| 1116 |
overwrite: Indicates whether it's OK to overwrite the target file |
| 1117 |
Raises: |
| 1118 |
IOError: If there is an IO error copying the file |
| 1119 |
OSError: If there is an OS error changing permissions on the file |
| 1120 |
""" |
| 1121 |
if not overwrite: |
| 1122 |
if os.path.exists(targetFile): |
| 1123 |
raise OSError("Target file [%s] already exists." % targetFile) |
| 1124 |
if localUser is not None: |
| 1125 |
try: |
| 1126 |
if not isRunningAsRoot(): |
| 1127 |
raise OSError("Only root can remote copy as another user.") |
| 1128 |
except AttributeError: |
| 1129 |
pass |
| 1130 |
actualCommand = '%s "%s" "%s@%s:%s"' % (rcpCommand, sourceFile, remoteUser, remoteHost, targetFile) |
| 1131 |
command = resolveCommand(SU_COMMAND) |
| 1132 |
result = executeCommand(command, [localUser, "-c", actualCommand])[0] |
| 1133 |
if result != 0: |
| 1134 |
raise OSError("Error (%d) copying [%s] to remote host as local user [%s]." % (result, sourceFile, localUser)) |
| 1135 |
else: |
| 1136 |
copyTarget = "%s@%s:%s" % (remoteUser, remoteHost, targetFile.replace(" ", "\\ ")) |
| 1137 |
command = resolveCommand(rcpCommandList) |
| 1138 |
result = executeCommand(command, [sourceFile.replace(" ", "\\ "), copyTarget])[0] |
| 1139 |
if result != 0: |
| 1140 |
raise OSError("Error (%d) copying [%s] to remote host." % (result, sourceFile)) |
| 1141 |
|
| 1142 |
@staticmethod |
| 1143 |
def _executeRemoteCommand(remoteUser, localUser, remoteHost, rshCommand, rshCommandList, remoteCommand): |
| 1144 |
""" |
| 1145 |
Executes a command on the peer via remote shell. |
| 1146 |
|
| 1147 |
Args: |
| 1148 |
remoteUser: Name of the Cedar Backup user on the remote peer |
| 1149 |
localUser: Name of the Cedar Backup user on the current host |
| 1150 |
remoteHost: Hostname of the remote peer |
| 1151 |
rshCommand: An rsh-compatible copy command to use for remote shells to the peer |
| 1152 |
rshCommandList: An rsh-compatible copy command to use for remote shells to the peer, as for :any:`util.executeCommand` |
| 1153 |
remoteCommand: The command to be executed on the remote host, with no special shell characters |
| 1154 |
Raises: |
| 1155 |
IOError: If there is an error executing the remote command |
| 1156 |
""" |
| 1157 |
actualCommand = "%s %s@%s '%s'" % (rshCommand, remoteUser, remoteHost, remoteCommand) |
| 1158 |
if localUser is not None: |
| 1159 |
try: |
| 1160 |
if not isRunningAsRoot(): |
| 1161 |
raise OSError("Only root can remote shell as another user.") |
| 1162 |
except AttributeError: |
| 1163 |
pass |
| 1164 |
command = resolveCommand(SU_COMMAND) |
| 1165 |
result = executeCommand(command, [localUser, "-c", actualCommand])[0] |
| 1166 |
if result != 0: |
| 1167 |
raise OSError('Command failed [su -c %s "%s"]' % (localUser, actualCommand)) |
| 1168 |
else: |
| 1169 |
command = resolveCommand(rshCommandList) |
| 1170 |
result = executeCommand(command, ["%s@%s" % (remoteUser, remoteHost), "%s" % remoteCommand])[0] |
| 1171 |
if result != 0: |
| 1172 |
raise OSError("Command failed [%s]" % (actualCommand)) |
| 1173 |
|
| 1174 |
@staticmethod |
| 1175 |
def _buildCbackCommand(cbackCommand, action, fullBackup): |
| 1176 |
""" |
| 1177 |
Builds a Cedar Backup command line for the named action. |
| 1178 |
|
| 1179 |
*Note:* If the cback command is None, then DEF_CBACK_COMMAND is used. |
| 1180 |
|
| 1181 |
Args: |
| 1182 |
cbackCommand: cback command to execute, including required options |
| 1183 |
action: Name of the action to execute |
| 1184 |
fullBackup: Whether a full backup should be executed |
| 1185 |
|
| 1186 |
Returns: |
| 1187 |
String suitable for passing to :any:`_executeRemoteCommand` as remoteCommand |
| 1188 |
Raises: |
| 1189 |
ValueError: If action is None |
| 1190 |
""" |
| 1191 |
if action is None: |
| 1192 |
raise ValueError("Action cannot be None.") |
| 1193 |
if cbackCommand is None: |
| 1194 |
cbackCommand = DEF_CBACK_COMMAND |
| 1195 |
if fullBackup: |
| 1196 |
return "%s --full %s" % (cbackCommand, action) |
| 1197 |
else: |
| 1198 |
return "%s %s" % (cbackCommand, action) |