/usr/share/pyshared/buildbot/steps/transfer.py is in buildbot 0.8.6p1-1.
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 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# 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. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os.path, tarfile, tempfile
try:
from cStringIO import StringIO
assert StringIO
except ImportError:
from StringIO import StringIO
from twisted.internet import reactor
from twisted.spread import pb
from twisted.python import log
from buildbot.process.buildstep import RemoteCommand, BuildStep
from buildbot.process.buildstep import SUCCESS, FAILURE, SKIPPED
from buildbot.interfaces import BuildSlaveTooOldError
from buildbot.util import json
from buildbot import config
class _FileWriter(pb.Referenceable):
"""
Helper class that acts as a file-object with write access
"""
def __init__(self, destfile, maxsize, mode):
# Create missing directories.
destfile = os.path.abspath(destfile)
dirname = os.path.dirname(destfile)
if not os.path.exists(dirname):
os.makedirs(dirname)
self.destfile = destfile
self.mode = mode
fd, self.tmpname = tempfile.mkstemp(dir=dirname)
self.fp = os.fdopen(fd, 'wb')
self.remaining = maxsize
def remote_write(self, data):
"""
Called from remote slave to write L{data} to L{fp} within boundaries
of L{maxsize}
@type data: C{string}
@param data: String of data to write
"""
if self.remaining is not None:
if len(data) > self.remaining:
data = data[:self.remaining]
self.fp.write(data)
self.remaining = self.remaining - len(data)
else:
self.fp.write(data)
def remote_utime(self, accessed_modified):
os.utime(self.destfile,accessed_modified)
def remote_close(self):
"""
Called by remote slave to state that no more data will be transfered
"""
self.fp.close()
self.fp = None
# on windows, os.rename does not automatically unlink, so do it manually
if os.path.exists(self.destfile):
os.unlink(self.destfile)
os.rename(self.tmpname, self.destfile)
self.tmpname = None
if self.mode is not None:
os.chmod(self.destfile, self.mode)
def cancel(self):
# unclean shutdown, the file is probably truncated, so delete it
# altogether rather than deliver a corrupted file
fp = getattr(self, "fp", None)
if fp:
fp.close()
os.unlink(self.destfile)
if self.tmpname and os.path.exists(self.tmpname):
os.unlink(self.tmpname)
def _extractall(self, path=".", members=None):
"""Fallback extractall method for TarFile, in case it doesn't have its own."""
import copy
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 0700
self.extract(tarinfo, path)
# Reverse sort directories.
directories.sort(lambda a, b: cmp(a.name, b.name))
directories.reverse()
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except tarfile.ExtractError, e:
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
class _DirectoryWriter(_FileWriter):
"""
A DirectoryWriter is implemented as a FileWriter, with an added post-processing
step to unpack the archive, once the transfer has completed.
"""
def __init__(self, destroot, maxsize, compress, mode):
self.destroot = destroot
self.compress = compress
self.fd, self.tarname = tempfile.mkstemp()
os.close(self.fd)
_FileWriter.__init__(self, self.tarname, maxsize, mode)
def remote_unpack(self):
"""
Called by remote slave to state that no more data will be transfered
"""
# Make sure remote_close is called, otherwise atomic rename wont happen
self.remote_close()
# Map configured compression to a TarFile setting
if self.compress == 'bz2':
mode='r|bz2'
elif self.compress == 'gz':
mode='r|gz'
else:
mode = 'r'
# Support old python
if not hasattr(tarfile.TarFile, 'extractall'):
tarfile.TarFile.extractall = _extractall
# Unpack archive and clean up after self
archive = tarfile.open(name=self.tarname, mode=mode)
archive.extractall(path=self.destroot)
archive.close()
os.remove(self.tarname)
class StatusRemoteCommand(RemoteCommand):
def __init__(self, step, remote_command, args):
RemoteCommand.__init__(self, remote_command, args)
callback = lambda arg: step.step_status.addLog('stdio')
self.useLogDelayed('stdio', callback, True)
class _TransferBuildStep(BuildStep):
"""
Base class for FileUpload and FileDownload to factor out common
functionality.
"""
DEFAULT_WORKDIR = "build" # is this redundant?
renderables = [ 'workdir' ]
haltOnFailure = True
flunkOnFailure = True
def setDefaultWorkdir(self, workdir):
if self.workdir is None:
self.workdir = workdir
def _getWorkdir(self):
if self.workdir is None:
workdir = self.DEFAULT_WORKDIR
else:
workdir = self.workdir
return workdir
def interrupt(self, reason):
self.addCompleteLog('interrupt', str(reason))
if self.cmd:
d = self.cmd.interrupt(reason)
return d
def finished(self, result):
# Subclasses may choose to skip a transfer. In those cases, self.cmd
# will be None, and we should just let BuildStep.finished() handle
# the rest
if result == SKIPPED:
return BuildStep.finished(self, SKIPPED)
if self.cmd.rc is None or self.cmd.rc == 0:
return BuildStep.finished(self, SUCCESS)
return BuildStep.finished(self, FAILURE)
class FileUpload(_TransferBuildStep):
name = 'upload'
renderables = [ 'slavesrc', 'masterdest', 'url' ]
def __init__(self, slavesrc, masterdest,
workdir=None, maxsize=None, blocksize=16*1024, mode=None,
keepstamp=False, url=None,
**buildstep_kwargs):
BuildStep.__init__(self, **buildstep_kwargs)
self.addFactoryArguments(slavesrc=slavesrc,
masterdest=masterdest,
workdir=workdir,
maxsize=maxsize,
blocksize=blocksize,
mode=mode,
keepstamp=keepstamp,
url=url,
)
self.slavesrc = slavesrc
self.masterdest = masterdest
self.workdir = workdir
self.maxsize = maxsize
self.blocksize = blocksize
if not isinstance(mode, (int, type(None))):
config.error(
'mode must be an integer or None')
self.mode = mode
self.keepstamp = keepstamp
self.url = url
def start(self):
version = self.slaveVersion("uploadFile")
if not version:
m = "slave is too old, does not know about uploadFile"
raise BuildSlaveTooOldError(m)
source = self.slavesrc
masterdest = self.masterdest
# we rely upon the fact that the buildmaster runs chdir'ed into its
# basedir to make sure that relative paths in masterdest are expanded
# properly. TODO: maybe pass the master's basedir all the way down
# into the BuildStep so we can do this better.
masterdest = os.path.expanduser(masterdest)
log.msg("FileUpload started, from slave %r to master %r"
% (source, masterdest))
self.step_status.setText(['uploading', os.path.basename(source)])
if self.url is not None:
self.addURL(os.path.basename(masterdest), self.url)
# we use maxsize to limit the amount of data on both sides
fileWriter = _FileWriter(masterdest, self.maxsize, self.mode)
if self.keepstamp and self.slaveVersionIsOlderThan("uploadFile","2.13"):
m = ("This buildslave (%s) does not support preserving timestamps. "
"Please upgrade the buildslave." % self.build.slavename )
raise BuildSlaveTooOldError(m)
# default arguments
args = {
'slavesrc': source,
'workdir': self._getWorkdir(),
'writer': fileWriter,
'maxsize': self.maxsize,
'blocksize': self.blocksize,
'keepstamp': self.keepstamp,
}
self.cmd = StatusRemoteCommand(self, 'uploadFile', args)
d = self.runCommand(self.cmd)
@d.addErrback
def cancel(res):
fileWriter.cancel()
return res
d.addCallback(self.finished).addErrback(self.failed)
class DirectoryUpload(_TransferBuildStep):
name = 'upload'
renderables = [ 'slavesrc', 'masterdest', 'url' ]
def __init__(self, slavesrc, masterdest,
workdir=None, maxsize=None, blocksize=16*1024,
compress=None, url=None, **buildstep_kwargs):
BuildStep.__init__(self, **buildstep_kwargs)
self.addFactoryArguments(slavesrc=slavesrc,
masterdest=masterdest,
workdir=workdir,
maxsize=maxsize,
blocksize=blocksize,
compress=compress,
url=url,
)
self.slavesrc = slavesrc
self.masterdest = masterdest
self.workdir = workdir
self.maxsize = maxsize
self.blocksize = blocksize
if compress not in (None, 'gz', 'bz2'):
config.error(
"'compress' must be one of None, 'gz', or 'bz2'")
self.compress = compress
self.url = url
def start(self):
version = self.slaveVersion("uploadDirectory")
if not version:
m = "slave is too old, does not know about uploadDirectory"
raise BuildSlaveTooOldError(m)
source = self.slavesrc
masterdest = self.masterdest
# we rely upon the fact that the buildmaster runs chdir'ed into its
# basedir to make sure that relative paths in masterdest are expanded
# properly. TODO: maybe pass the master's basedir all the way down
# into the BuildStep so we can do this better.
masterdest = os.path.expanduser(masterdest)
log.msg("DirectoryUpload started, from slave %r to master %r"
% (source, masterdest))
self.step_status.setText(['uploading', os.path.basename(source)])
if self.url is not None:
self.addURL(os.path.basename(masterdest), self.url)
# we use maxsize to limit the amount of data on both sides
dirWriter = _DirectoryWriter(masterdest, self.maxsize, self.compress, 0600)
# default arguments
args = {
'slavesrc': source,
'workdir': self._getWorkdir(),
'writer': dirWriter,
'maxsize': self.maxsize,
'blocksize': self.blocksize,
'compress': self.compress
}
self.cmd = StatusRemoteCommand(self, 'uploadDirectory', args)
d = self.runCommand(self.cmd)
@d.addErrback
def cancel(res):
dirWriter.cancel()
return res
d.addCallback(self.finished).addErrback(self.failed)
def finished(self, result):
# Subclasses may choose to skip a transfer. In those cases, self.cmd
# will be None, and we should just let BuildStep.finished() handle
# the rest
if result == SKIPPED:
return BuildStep.finished(self, SKIPPED)
if self.cmd.rc is None or self.cmd.rc == 0:
return BuildStep.finished(self, SUCCESS)
return BuildStep.finished(self, FAILURE)
class _FileReader(pb.Referenceable):
"""
Helper class that acts as a file-object with read access
"""
def __init__(self, fp):
self.fp = fp
def remote_read(self, maxlength):
"""
Called from remote slave to read at most L{maxlength} bytes of data
@type maxlength: C{integer}
@param maxlength: Maximum number of data bytes that can be returned
@return: Data read from L{fp}
@rtype: C{string} of bytes read from file
"""
if self.fp is None:
return ''
data = self.fp.read(maxlength)
return data
def remote_close(self):
"""
Called by remote slave to state that no more data will be transfered
"""
if self.fp is not None:
self.fp.close()
self.fp = None
class FileDownload(_TransferBuildStep):
name = 'download'
renderables = [ 'mastersrc', 'slavedest' ]
def __init__(self, mastersrc, slavedest,
workdir=None, maxsize=None, blocksize=16*1024, mode=None,
**buildstep_kwargs):
BuildStep.__init__(self, **buildstep_kwargs)
self.addFactoryArguments(mastersrc=mastersrc,
slavedest=slavedest,
workdir=workdir,
maxsize=maxsize,
blocksize=blocksize,
mode=mode,
)
self.mastersrc = mastersrc
self.slavedest = slavedest
self.workdir = workdir
self.maxsize = maxsize
self.blocksize = blocksize
if not isinstance(mode, (int, type(None))):
config.error(
'mode must be an integer or None')
self.mode = mode
def start(self):
version = self.slaveVersion("downloadFile")
if not version:
m = "slave is too old, does not know about downloadFile"
raise BuildSlaveTooOldError(m)
# we are currently in the buildmaster's basedir, so any non-absolute
# paths will be interpreted relative to that
source = os.path.expanduser(self.mastersrc)
slavedest = self.slavedest
log.msg("FileDownload started, from master %r to slave %r" %
(source, slavedest))
self.step_status.setText(['downloading', "to",
os.path.basename(slavedest)])
# setup structures for reading the file
try:
fp = open(source, 'rb')
except IOError:
# if file does not exist, bail out with an error
self.addCompleteLog('stderr',
'File %r not available at master' % source)
# TODO: once BuildStep.start() gets rewritten to use
# maybeDeferred, just re-raise the exception here.
reactor.callLater(0, BuildStep.finished, self, FAILURE)
return
fileReader = _FileReader(fp)
# default arguments
args = {
'slavedest': slavedest,
'maxsize': self.maxsize,
'reader': fileReader,
'blocksize': self.blocksize,
'workdir': self._getWorkdir(),
'mode': self.mode,
}
self.cmd = StatusRemoteCommand(self, 'downloadFile', args)
d = self.runCommand(self.cmd)
d.addCallback(self.finished).addErrback(self.failed)
class StringDownload(_TransferBuildStep):
name = 'string_download'
renderables = [ 'slavedest', 's' ]
def __init__(self, s, slavedest,
workdir=None, maxsize=None, blocksize=16*1024, mode=None,
**buildstep_kwargs):
BuildStep.__init__(self, **buildstep_kwargs)
self.addFactoryArguments(s=s,
slavedest=slavedest,
workdir=workdir,
maxsize=maxsize,
blocksize=blocksize,
mode=mode,
)
self.s = s
self.slavedest = slavedest
self.workdir = workdir
self.maxsize = maxsize
self.blocksize = blocksize
if not isinstance(mode, (int, type(None))):
config.error(
'mode must be an integer or None')
self.mode = mode
def start(self):
version = self.slaveVersion("downloadFile")
if not version:
m = "slave is too old, does not know about downloadFile"
raise BuildSlaveTooOldError(m)
# we are currently in the buildmaster's basedir, so any non-absolute
# paths will be interpreted relative to that
slavedest = self.slavedest
log.msg("StringDownload started, from master to slave %r" % slavedest)
self.step_status.setText(['downloading', "to",
os.path.basename(slavedest)])
# setup structures for reading the file
fp = StringIO(self.s)
fileReader = _FileReader(fp)
# default arguments
args = {
'slavedest': slavedest,
'maxsize': self.maxsize,
'reader': fileReader,
'blocksize': self.blocksize,
'workdir': self._getWorkdir(),
'mode': self.mode,
}
self.cmd = StatusRemoteCommand(self, 'downloadFile', args)
d = self.runCommand(self.cmd)
d.addCallback(self.finished).addErrback(self.failed)
class JSONStringDownload(StringDownload):
name = "json_download"
def __init__(self, o, slavedest, **buildstep_kwargs):
if 's' in buildstep_kwargs:
del buildstep_kwargs['s']
s = json.dumps(o)
StringDownload.__init__(self, s=s, slavedest=slavedest, **buildstep_kwargs)
self.addFactoryArguments(o=o)
class JSONPropertiesDownload(StringDownload):
name = "json_properties_download"
def __init__(self, slavedest, **buildstep_kwargs):
self.super_class = StringDownload
if 's' in buildstep_kwargs:
del buildstep_kwargs['s']
StringDownload.__init__(self, s=None, slavedest=slavedest, **buildstep_kwargs)
def start(self):
properties = self.build.getProperties()
props = {}
for key, value, source in properties.asList():
props[key] = value
self.s = json.dumps(dict(
properties=props,
sourcestamp=self.build.getSourceStamp().asDict(),
),
)
return self.super_class.start(self)
|