loghole.in 77 KB
Newer Older
1 2 3
#! /usr/bin/env python

#
4
# Copyright (c) 2004-2012 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file 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 Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
24 25 26 27 28
#

import re
import pwd
import sys
29
import glob
30 31 32 33 34 35
import sets
import stat
import time
import getopt
import socket
import zipfile
36
import tempfile
37
import cStringIO
38
import threading
39 40 41 42 43 44 45 46 47 48 49
import xmlrpclib
import os, os.path
import ConfigParser

prefix = "@prefix@"

TBPATH = os.path.join(prefix, "lib")
if TBPATH not in sys.path:
    sys.path.append(TBPATH)
    pass

50 51
from tbevent import *

52 53 54 55 56 57 58
PACKAGE_VERSION = 0.1

# Default server
XMLRPC_SERVER = "@BOSSNODE@"
XMLRPC_PORT   = 3069

RSYNC = "@RSYNC@"
59
ACCEPTABLE_RSYNC_STATUS = [ 0 ]
60
NONRETRIABLE_RSYNC_STATUS = [ 0, 1, 2, 4 ]
61 62 63 64 65 66 67 68

DIRS = {
    "proj" : "proj",
    "groups" : "groups",
    }

EXPDIR_FMT = os.path.join("/", DIRS["proj"], "%(PID)s", "exp", "%(EID)s")

69 70
GLOBAL_LOGS = [
    "event-sched.log", "feedback.log", "../tbdata/feedback_data.tcl",
71
    "digest.out", "report.mail", "../tbdata/%(EID)s.report"
72
    ]
73

74 75
EXTENSIONS = [ ".zip" ]

76
LINK_DUMP_FMT = [ "trace_%s-%s.xmit", "trace_%s-%s.recv" ]
77

78 79
CLEANFILE = ".cleanonsync"

80 81 82
DOT_LOGHOLES = ""

DEFAULT_LOGHOLES = ["/var/emulab/logs", "/local/logs"]
83

84 85
DELAYLOG2XPLOT = os.path.join(prefix, "bin", "delaylog2xplot")

86 87
MERGECAP = "/usr/X11R6/bin/mergecap"
TCPTRACE = "/usr/local/bin/tcptrace"
88
TEVC     = os.path.join(prefix, "bin", "tevc")
89

90 91 92
PID = None
EID = None

93 94 95
COLLAB_PW = None
DPDBNAME  = None

96 97 98 99
try:
    pw = pwd.getpwuid(os.getuid())
    pass
except KeyError:
100 101 102 103
    sys.stderr.write("error: unknown user id %d" % os.getuid())
    sys.exit(2)
    pass

104 105
USER = pw.pw_name
HOME = pw.pw_dir
106 107 108

CERTIFICATE = os.path.join(HOME, ".ssl", "emulab.pem")

109
PARALLELIZATION = 25
110

111 112 113 114 115 116 117 118 119
DEBUG = 0

VERBOSITY_MACHINE = 1
VERBOSITY_HUMAN = 2

VERBOSITY = VERBOSITY_HUMAN

SERVER = None

120 121 122 123 124
# For compressfile stuff
COMPRESSFILE_THRESHOLD  = 512 * 1024
COMPRESSFILE_EXTENSIONS = [ ".zip", ".gz", ".bz2" ]
COMPRESSFILE_PROGRAM    = "/usr/bin/gzip"

125 126
OSIDS = {}

127 128 129 130
JOB_TRIES = 3
JOB_PROGRESS = [ "-", "\\", "|", "/" ]
JOB_PROGRESS_INDEX = 0

131 132 133 134 135 136 137 138 139 140
if len(XMLRPC_SERVER) == 0:
    sys.stderr.write("internal error: XMLRPC_SERVER is empty\n")
    sys.exit(2)
    pass

if len(RSYNC) == 0:
    sys.stderr.write("internal error: RSYNC is empty\n")
    sys.exit(2)
    pass

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
def loghole_include(path):
    retval = ""

    prefix = "/"
    for comp in path.split("/"):
        if comp != "":
            prefix = prefix + comp + "/"
            retval = retval + "+ " + prefix + "\n"
            pass
        pass

    retval = retval + "+ " + prefix + "**\n"
    
    return retval

for path in DEFAULT_LOGHOLES:
    DOT_LOGHOLES += loghole_include(path)
    pass

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
##
# Initialize the XML-RPC server proxy, if it has not already been done.  After
# returning, the SERVER variable will hold the proxy object.
#
def init_server():
    global SERVER

    if not SERVER:
        if not os.path.exists(CERTIFICATE):
            sys.stderr.write("error: missing emulab certificate: %s\n" %
                             CERTIFICATE)
            sys.exit(2)
            pass
        
        from M2Crypto.m2xmlrpclib import SSL_Transport
        from M2Crypto import SSL
        
        URI = "https://" + XMLRPC_SERVER + ":" + str(XMLRPC_PORT) + prefix
        
        ctx = SSL.Context("sslv23")
        ctx.load_cert(CERTIFICATE, CERTIFICATE)
        ctx.set_verify(SSL.verify_none, 16)
        ctx.set_allow_unknown_ca(0)
        
        SERVER = xmlrpclib.ServerProxy(URI, SSL_Transport(ctx))
        pass
    return

##
# Download the user's experiment list from the XML-RPC server.
#
# @return A list of (pid, eid) pairs for each experiment created by the user.
#
def get_explist():
    global SERVER

    from emulabclient import RESPONSE_SUCCESS
    
    retval = []
    
    init_server()
    
    list_method = getattr(SERVER, "experiment.getlist")
    elist = list_method(PACKAGE_VERSION, {})
    
    if elist["code"] != RESPONSE_SUCCESS:
        sys.stderr.write("error: " + elist["output"] + "\n")
        sys.exit(1)
        pass
    else:
        for project in elist["value"]:
            for group in elist["value"][project]:
                for exp in elist["value"][project][group]:
                    retval.append((project, exp))
                    pass
                pass
            pass
        pass
    
    return retval

##
# Print the top level usage statement for the whole tool.
#
def usage():
225
    print "Usage: loghole [-hV] [-e pid/eid|-a] [OPTIONS] <action> [...]"
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    print
    print "Manage an experiment's log hole."
    print
    print "Optional arguments:"
    print "  -h, --help                Print this message, or the action's"
    print "                            usage message."
    print "  -V, --version             Print version information."
    print "  -d, --debug               Turn on debugging messages."
    print "  -q, --quiet               Be less verbose."
    print "  -v, --verbose             Be more verbose."
    print "  -e, --experiment=PID/EID  Specify the experiment to manage."
    print "  -a, --all                 Perform the action on all of your "
    print "                            experiments."
    print "  -s, --server=SERVER       Specify the XML-RPC server to use."
    print "                            (Default: %s)" % XMLRPC_SERVER
    print "  -P, --port=PORT           Specify the XML-RPC server port."
    print "                            (Default: %d)" % XMLRPC_PORT
    print
    print "Actions:"
    print "  sync      Synchronize the experiment's log holes with the"
    print "            experiment's log directory."
    print "  archive   Archive the contents of the experiment's log directory."
248
    print "  change    Change the metadata of an existing archive."
249 250 251 252
    print "  list      Print a brief listing of the archives in the"
    print "            experiment's log directory."
    print "  show      Show a detailed listing of the archive(s) in the"
    print "            experiment directory."
253
    print "  validate  Validate the experiment logs."
254 255
    print "  clean     Clean the experiment log directory and node local"
    print "            directories."
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    print "  gc        Garbage collect old archives."
    print
    print "Environment:"
    print "  cwd       The project and experiment ID will be inferred from the"
    print "            current working directory, if it is inside the"
    print "            experiment's directory (e.g. /proj/foo/exp/bar)."
    print
    print "Examples:"
    print "  $ loghole -e foo/bar sync"
    print "  $ loghole -e foo/bar list"
    return

##
# Print the usage statement for the "sync" action.
#
def sync_usage():
272
    print "Usage: loghole sync [-nPsR] [-r remotedir] [-l localdir] [node1 ...]"
273
    print
274
    print "Synchronize the experiment's log holes with a local directory."
275 276
    print
    print "Optional arguments:"
277 278 279 280 281 282 283 284 285 286 287
    print "  -r, --remote=REMOTEDIR"
    print "               An additional remote directory to sync.  This option"
    print "               is additive, so you can download several additional"
    print "               directories."
    print "  -l, --local=LOCALDIR"
    print "               The local directory to store the downloaded files."
    print "               This defaults to the experiment's log directory."
    print "  -n, --no-standard"
    print "               Flag that indicates that the standard logholes"
    print "               (i.e. '/var/emulab/logs', '/local/logs') should not"
    print "               be downloaded."
288 289
    print "  -P, --no-post"
    print "               Do not do any additional post processing."
290 291
    print "  -s, --snapshot"
    print "               Send a SNAPSHOT event to any link trace agents."
292 293
    print "  -R, --root"
    print "               Use sudo on remote nodes to read files as root."
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
    print "  node1 ...    The names of the virtual or physical nodes that "
    print "               should be synced.  The default behavior is to sync "
    print "               all of the nodes in an experiment."
    print
    print "Files:"
    print "  /proj/<pid>/exp/<eid>/logs/<node>/<loghole>"
    print "               The location of the log hole for a particular node."
    print
    print "Examples:"
    print "  $ loghole sync"
    return

##
# Print the usage statement for the "archive" action.
#
def archive_usage():
    print ("Usage: loghole archive [-k (i-delete|space-is-needed)] "
           "[-a days] [-c comment] [-d] [archive-name]")
    print
    print "Archive the contents of the experiment's log directory.  The"
    print "archive will be a zip file containing all of the directories"
    print "under the experiment's log directory, any extra log files"
    print "at the top (e.g. event-sched.log), and some metadata."
    print
    print "Optional arguments:"
    print "  -k, --keep-until=(i-delete|space-is-needed)"
    print "                         Keep the archive until you decide to"
    print "                         delete it manually or space is needed."
    print "                         (Default: space-is-needed)"
    print "  -a, --keep-atleast=N   Keep the archive atleast N days after"
    print "                         creation.  This value keeps the archive "
    print "                         from being garbage collected when more "
    print "                         space is needed. (Default: 3 days)"
    print "  -c, --comment=COMMENT  Add a comment to the archive. This comment"
    print "                         will be displayed in the listing generated"
    print "                         by the 'show' action.  Use a single dash "
    print "                         (-) to read the comment from standard in."
331 332
    print "  -d, --delete           Mark the experiment as clean-on-sync to"
    print "                         remove stale data before another sync."
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
    print
    print "Required arguments:"
    print "  archive-name  The name of the archive to create."
    print "                (Default: The experiment name)"
    print
    print "Files:"
    print "  /proj/<pid>/exp/<eid>/logs/<archive-name>.<instance>.zip"
    print
    print "Examples:"
    print "  $ loghole archive foobar"
    return

##
# Print the usage statement for the "list" action.
#
def list_usage():
    print "Usage: loghole list [-O1!Xo] [-m atmost] [-s megabytes]"
    print
    print "Print a brief listing of the archives in the experiment's log"
    print "directory.  The listing can be helpful in getting an idea of"
    print "what archives are in your experiment and when they are likely"
    print "to be garbage collected."
    print
    print "Optional arguments:"
    print "  -O                    Only list archives that are marked as 'keep"
    print "                        until \"i-delete\"'."
    print "  -1                    Only list archives that are a day from"
    print "                        their keep-atleast date."
    print "  -!                    Only list archives that are past their"
    print "                        keep-atleast date."
    print "  -X                    Only list archives that are ready to be"
    print "                        garbage collected."
    print "  -o                    List archives that do not match the above"
    print "                        flags."
    print "  -m, --keep-atmost=N   Keep at most N archives in the experiment."
    print "                        (Default: 100)"
    print "  -s, --keep-size=N     Keep at N megabytes of archives."
    print "                        (Default: 3.0 MB)"
    print
    print "Examples:"
    print "  $ loghole list"
    print "  GC  Name             Date"
    print
    print "  [ ] foobar.1.zip     10/15"
    print "  [!] foobar.0.zip     10/13"
    print "  ..."
    print
    print "  $ loghole -q list -!"
    print "  foobar.0.zip"
    return

##
# Print the usage statement for the "show" action.
#
def show_usage():
    print "Usage: loghole show [archive-name]"
    print
    print "Show a detailed listing of the archive(s) in the experiment"
    print "directory.  The listing shows all of the metadata for the archive,"
    print "comments, and the file listing."
    print
    print "Example:"
    print "  $ loghole show foobar"
    print "  Archive: foobar.0.zip"
    print "    Creator:\t\t%s" % USER
    print "    ..."
    print "  Archive: foobar.1.zip"
    print "    ..."
    return

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
##
# Print the usage statement for the "change" action.
#
def change_usage():
    print ("Usage: loghole change [-k (i-delete|space-is-needed)] "
           "[-a days] [-c comment] <archive-name1> [archive-name2 ...]")
    print
    print "Change the metadata of an existing archive."
    print
    print "Optional arguments:"
    print "  -k, --keep-until=(i-delete|space-is-needed)"
    print "                         Keep the archive until you decide to"
    print "                         delete it manually or space is needed."
    print "                         (Default: space-is-needed)"
    print "  -a, --keep-atleast=N   Keep the archive atleast N days after"
    print "                         creation.  This value keeps the archive "
    print "                         from being garbage collected when more "
    print "                         space is needed. (Default: 3 days)"
    print "  -c, --comment=COMMENT  Add a comment to the archive. This comment"
    print "                         will be displayed in the listing generated"
    print "                         by the 'show' action.  Use a single dash "
    print "                         (-) to read the comment from standard in."
    print
    print "Required arguments:"
    print "  archive-name  The name of the archive to change."
    print
    print "Files:"
    print "  /proj/<pid>/exp/<eid>/logs/<archive-name>.<instance>.zip"
    print
    print "Examples:"
    print "  $ loghole change -c 'Results bad...' foobar"
    return

##
# Print the usage statement for the "validate" action.
#
def validate_usage():
440
    print "Usage: loghole validate"
441
    print
442
    print "Validate the experiment logs.  Currently, this action will:"
443
    print
444 445 446
    print "  1. Examine the log files from individual logs from the "
    print "     program-agent to verify that the files are intact."
    print "  2. Check that the referent of any soft-links exist."
447 448
    print
    print "Examples:"
449
    print "  $ loghole validate"
450 451
    return

452 453 454 455
##
# Print the usage statement for the "clean" action.
#
def clean_usage():
456
    print "Usage: loghole clean [-fneR] [node1 ...]"
457 458 459 460
    print
    print "Clean the experiment log directory by removing any subdirectories"
    print "and/or clean the log holes on the nodes.  The default behavior is"
    print "to clean both."
461
    print
462 463 464 465
    print "Optional arguments:"
    print "  -f, --force         Do not ask for confirmation."
    print "  -n, --nodes         Clean only the nodes log directories."
    print "  -e, --experiment    Clean only the experiment log directory."
466
    print "  -R, --root          Use sudo to clean nodes as root."
467 468 469 470 471
    print
    print "Examples:"
    print "  $ loghole clean"
    return

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
##
# Print the usage statement for the "gc" action.
#
def gc_usage():
    print "Usage: loghole gc [-n] [-m atmost] [-s megabytes]"
    print
    print "Garbage collect old log archives."
    print
    print "Optional arguments:"
    print "  -n, --dry-run         Perform a dry run, do not delete any files."
    print "  -m, --keep-atmost=N   Keep at most N archives in the experiment."
    print "                        (Default: 100)"
    print "  -s, --keep-size=N     Keep at N megabytes of archives."
    print "                        (Default: 3.0 MB)"
    print
    print "Examples:"
488
    print "  $ loghole gc -n -m 1"
489 490 491
    print "  Reclaimed 3421 bytes from foo/bar."
    print "  52434 bytes are still in foo/bar."
    print
492
    print "  $ loghole -q gc -m 1"
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
    print "  3421 52434"
    return

##
# Infer the project and experiment IDs from the given list of directories.
#
# @param *args The list of directories to check for likely PID/EID values.
# @return A pair containing the project and experiment IDs, which will be None
# if the IDs could not be inferred.
#
def infer_pid_eid(*args):
    pid = None
    eid = None
    for path in args:
        dirs = path.split(os.path.sep)
508
        if ((len(dirs) < 5) or not
509 510
            ((DIRS["proj"] in dirs and
              "exp" in dirs[dirs.index(DIRS["proj"]):]) or
511
             (len(dirs) >= 5 and
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
              (DIRS["groups"] in dirs and
               "exp" in dirs[dirs.index(DIRS["groups"]):])))):
            # No match...
            pass
        else:
            if DIRS["proj"] in dirs:
                pid = dirs[dirs.index(DIRS["proj"]) + 1]
                pass
            else:
                pid = dirs[dirs.index(DIRS["groups"]) + 1]
                pass
            eid = dirs[dirs.index("exp") + 1]
            pass
        pass

    return pid, eid

##
# Attempt to open a loghole archive located at the given path.  An archive
# must be a zip file with a "loghole.cfg" file stored in the root directory.
#
# @param path The path to the loghole archive.
# @return A pair containing the ZipFile object referring to the archive and a
# ConfigParser object that contains the archive's metadata.
#
537
def open_loghole(path, mode='r'):
538 539
    retval = None, None
    if zipfile.is_zipfile(path):
540
        zf = zipfile.ZipFile(path, mode)
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
        if "loghole.cfg" in zf.namelist():
            cio = cStringIO.StringIO(zf.read("loghole.cfg"))
            cp = ConfigParser.ConfigParser()
            cp.readfp(cio)
            retval = zf, cp
            zf = None
            pass
        if zf:
            zf.close()
            pass
        pass
    
    return retval

##
# Generate a name that is unique in the context of the given list of entries.
#
# @param base The base of the file name.
# @param ext The file name extension.
# @param entries An iterable containing any existing file names.
# @return A string of the form "<base>.<unique #>.<ext>".
#
def uniquish_name(base, ext, entries):
    retval = None
    lpc = 0
    while not retval:
        name = base + "." + str(lpc) + "." + ext
        if name not in entries:
            retval = name
            pass
        lpc = lpc + 1
        pass
    
    return retval

##
# Callback for os.walk() that writes files to the ZipFile.
#
# @param zf The ZipFile object that files should be added to.
# @param dirname The current directory name.
# @param names The list of files in the current directory.
#
def file_archiver(zf, dirname, names):
    for entry in names:
        entry = os.path.join(dirname, entry)
        if os.path.isfile(entry):
            zf.write(entry)
            pass
        pass

    return

##
# Sort the list of log archives in the current directory based on when they
# should be garbage collected.
#
# @param keep_atmost The maximum number of archives that should be kept, any
# extras are marked as collectable.
# @param keep_size The number of megabytes of archives to keep.
# @return A dictionary containing: "del", a list of archives that will be
# deleted at the next GC; "safe", a list of archives that are marked "keep
# until 'i-delete'"; "soon", the remaining archives; "reclaimed-size", the
# amount of data that will be reclaimed at the next GC; and "inuse-size", the
# amount of data that will remain after the next GC.
#
def sort_archives(keep_atmost, keep_size):
    
    keep_size = keep_size * 1024 * 1024

    reclaimed_size = 0
    inuse_size = 0 # In-use size for non-gc'able archives
    inuse_gc_size = 0 # In-use size for gc'able archives
    
    current_time = time.time()
    
    retval_del = []
    retval_safe = []
    retval_soon = []
    exp_logholes = []

    # Walk the directory collecting archives and sorting them into "safe" and
    # to-be-determined lists.
    for entry in os.listdir(os.curdir):
        st = os.stat(entry)
        lh, cp = open_loghole(entry)
        if lh:
            keep_until = cp.get("MAIN", "keep-until")
            if keep_until == "i-delete":
                if DEBUG:
                    print "loghole: ignoring - " + entry
                    pass

                retval_safe.append(entry)
                inuse_size = inuse_size + st[stat.ST_SIZE]
                pass
            else:
                created = time.mktime(time.strptime(cp.get("MAIN", "created")))
                keep_atleast = (cp.getint("MAIN", "keep-atleast") *
                                60 * 60 * 24)

                inuse_gc_size = inuse_gc_size + st[stat.ST_SIZE]
                exp_logholes.append((entry, st, created + keep_atleast))
                pass
            lh.close()
            pass
        pass

    # Sort the archives from oldest keep-atleast time to newest, then
    exp_logholes.sort(lambda x, y: cmp(x[2], y[2]))

    # ... divide them between the del list and the soon list depending on
    # whether or not space is needed.
    for entry, st, expiration in exp_logholes:
        if inuse_gc_size > keep_size:
            if DEBUG:
                print "loghole: stale entry - " + entry
                pass

            retval_del.append(entry)
            inuse_gc_size = inuse_gc_size - st[stat.ST_SIZE]
            reclaimed_size = reclaimed_size + st[stat.ST_SIZE]
            pass
        else:
            retval_soon.append(entry)
            pass
        pass

    # Resort the list in the reverse direction for keep-atleast time.
    exp_logholes = [x for x in exp_logholes if x[0] in retval_soon]
    exp_logholes.sort(lambda x, y: cmp(y[2], x[2]))

    # Update the inuse_size for the archives below the keep-atmost value, then
    for entry, st, expiration in exp_logholes[0:keep_atmost]:
        if DEBUG:
            print ("loghole: keeping '"
                   + entry
                   + "' until "
                   + time.ctime(expiration))
            pass

        inuse_size = inuse_size + st[stat.ST_SIZE]
        pass

    # ... move the rest to the "del" list and
    for entry, st, expiration in exp_logholes[keep_atmost:]:
        if DEBUG:
            print "loghole: excess entry - " + entry
            pass

        retval_soon.remove(entry)
        retval_del.append(entry)
        reclaimed_size = reclaimed_size + st[stat.ST_SIZE]
        pass

    # ... drop the end of the array.
    del retval_soon[keep_atmost:]

    return {
        "del" : retval_del,
        "safe" : retval_safe,
        "soon" : retval_soon,
        "reclaimed-size" : reclaimed_size,
        "inuse-size" : inuse_size,
        }

##
# Performs the "archive" action, which involves building a zip file containing
# all of the logs.
#
# @param args Action-specific command line arguments.
#
def do_archive(args):
    retval = 0

    keep_until = "space-is-needed"
    keep_atleast = 3
    comments = []
    delete_dir = False

    # Parse action-specific options and arguments.
    try:
        opts, args = getopt.getopt(args, "k:a:c:d", [
            "keep-until=", "keep-atleast=", "comment=", "delete" ])
        for opt, val in opts:
            if opt in ("-k", "--keep-until"):
                if val == "i-delete" or val == "space-is-needed":
                    keep_until = val
                    pass
                else:
                    raise getopt.error(
                        'error: expecting "i-delete" or "space-is-needed" for '
                        'keep until value, got - ' + val)
                pass
            elif opt in ("-a", "--keep-atleast"):
                try:
                    keep_atleast = int(val)
                    pass
                except:
                    raise getopt.error(
                        'error: expecting integer for keep atleast value, '
                        'got - ' + val)
                pass
            elif opt in ("-c", "--comment"):
                if val == "-":
                    comments.append(sys.stdin.read())
                    pass
                else:
                    comments.append(val)
                    pass
                pass
            elif opt in ("-d", "--delete"):
                delete_dir = True
                pass
            pass
        
        if len(args) > 1:
            raise getopt.error(
                'error: too many arguments for "archive" action.')
        pass
    except getopt.error, e:
        print e.args[0]
        archive_usage()
        return 2

    if len(args) < 1:
        archive_base = EID
        pass
    else:
        archive_base = args[0]
        pass

    logdir = os.path.join(EXPDIR_FMT % { "PID" : PID, "EID" : EID }, "logs")
    os.chdir(logdir)

    # Figure out a unique name for the archive,
    archive_name = uniquish_name(archive_base, 'zip', os.listdir(logdir))

    # ... create a new zip file,
    zf = zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED)

    # ... fill it up with the node log holes, and
    for entry in os.listdir(logdir):
        if os.path.isdir(entry):
            os.path.walk(entry, file_archiver, zf)
            pass
        pass

    # ... any global log files (e.g. event-sched.log).
    for log in GLOBAL_LOGS:
790 791 792
        formatted_log = log % { "PID" : PID, "EID" : EID }
        if os.path.exists(formatted_log):
            zf.write(formatted_log)
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
            pass
        pass

    # Construct the meta-data.
    cp = ConfigParser.ConfigParser()
    cp.add_section("MAIN")
    cp.set("MAIN", "created", time.ctime(time.time()))
    cp.set("MAIN", "creator", USER)
    cp.set("MAIN", "project", PID)
    cp.set("MAIN", "experiment", EID)
    cp.set("MAIN", "keep-until", keep_until)
    cp.set("MAIN", "keep-atleast", keep_atleast)
    
    cio = cStringIO.StringIO()
    cp.write(cio)

    loghole_zi = zipfile.ZipInfo()
    loghole_zi.filename = "loghole.cfg"
    ct = time.localtime(time.time())
    loghole_zi.date_time = (ct[0], ct[1], ct[2], ct[3], ct[4], ct[5])
    loghole_zi.compress_type = zipfile.ZIP_STORED
    loghole_zi.comment = "Log hole meta-data"
    
    zf.writestr(loghole_zi, cio.getvalue())

    # Add any comments.
    ct = time.localtime(time.time())
    lpc = 0
    for comment in comments:
        loghole_zi = zipfile.ZipInfo()
        loghole_zi.filename = "loghole-comment.%d.txt" % lpc
        loghole_zi.date_time = (ct[0], ct[1], ct[2], ct[3], ct[4], ct[5])
        loghole_zi.compress_type = zipfile.ZIP_DEFLATED
        loghole_zi.comment = "Loghole comment #%d" % lpc

        zf.writestr(loghole_zi, comment)

        lpc = lpc + 1
        pass
    
    if DEBUG:
        zf.printdir()
        pass
    
    zf.close()

    if delete_dir:
840
        open(CLEANFILE, 'w')
841
        os.chmod(CLEANFILE, 0664)
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
        pass

    if VERBOSITY == VERBOSITY_MACHINE:
        print archive_name
        pass
    elif VERBOSITY >= VERBOSITY_HUMAN:
        print "Created log hole archive: " + archive_name
        pass
    
    return retval

##
# Performs the "show" action, which shows a detailed listing of a log archive.
#
# @param args Action-specific command line arguments.
#
def do_show(args):
    retval = 0

    logdir = os.path.join(EXPDIR_FMT % { "PID" : PID, "EID" : EID }, "logs")
    os.chdir(logdir)
    
    for entry in os.listdir(logdir):
        if len(args) == 0 or entry.startswith(args[0]):
            lh, cp = open_loghole(entry)
            if lh:
                print "Archive: " + entry
                print ("  Project/Experiment:\t%s/%s" %
                       (cp.get("MAIN", "project"),
                        cp.get("MAIN", "experiment")))
                print "  Creator:\t\t%s" % cp.get("MAIN", "creator")
                print "  Created:\t\t%s" % cp.get("MAIN", "created")
                print "  Keep-until:\t\t%s" % cp.get("MAIN", "keep-until")
                print ("  Keep-atleast:\t\t%s days" %
                       cp.get("MAIN", "keep-atleast"))
877 878 879 880
                if "report.mail" in lh.namelist():
                    print "Report:"
                    print lh.read("report.mail")
                    pass
881 882 883 884 885 886 887 888 889
                for name in lh.namelist():
                    if re.match(r'loghole-comment.*\.txt', name):
                        before = 38 - (len(name) / 2)
                        after = 77 - before - len(name)
                        print "%s %s %s" % ("-" * before, name, "-" * after)
                        print lh.read(name)
                        pass
                    pass
                print "=" * 79
890 891 892 893 894
                try:
                    lh.printdir()
                    pass
                except IOError:
                    pass
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
                lh.close()
                print
                pass
            pass
        pass
    
    return retval

##
# Run rsync for a given host and list of files.
#
# @param host The host to sync against.
# @param base The local directory where the downloaded files should be placed.
# @param *args The list of directories to sync.
# @retval The exit status of the rsync command-line.
#
911 912
def rsync(host, base, dlpath = None, paths = ["/"], port = None,
          output = False, delay = 0, as_root = False, relative = True):
913 914 915
    global RSYNC, HOME, DEBUG
    
    retval = 0
916
    for path in paths:
917 918 919 920 921
        if relative == True:
            fullpath = os.path.join("", base, path[1:], "")
        else:
            fullpath = base
            pass
922 923 924 925 926
        try:
            os.makedirs(fullpath)
            pass
        except OSError:
            pass
927
        cmd = [RSYNC,
928 929
               "-rtgoDl",
               "-z", # rsync compression, ssh compression turned off below
930
               "-v", # XXX
931 932 933 934
               "--copy-unsafe-links"]
        if dlpath != None:
            cmd.append("--include-from=" + dlpath)
            pass
935
        if VERBOSITY > VERBOSITY_HUMAN:
936
            cmd.append("-v")
937
            pass
938
        ssh_args = ("ssh -o BatchMode=yes -o StrictHostKeyChecking=no "
939
                    + "-o Compression=no "
940 941 942 943 944
                    + "-o UserKnownHostsFile="
                    + os.path.join(HOME, ".ssh", "emulab_known_hosts"))
        if port:
            ssh_args += " -p " + str(port)
            pass
945 946 947
        if as_root:
            cmd.append("--rsync-path=sudo rsync")
            pass
948
        cmd.extend([("--rsh=" + ssh_args),
949 950
                    host + ":" + path,
                    fullpath])
951
        if DEBUG:
952 953
            print `cmd`
            retval = -1
954 955
            pass
        else:
956 957 958 959 960
            retval = os.fork()
            if retval != 0:
                # Parent
                pass
            else:
961
                try:
962 963 964
                    if delay > 0:
                        time.sleep(delay)
                        pass
965 966 967 968 969 970 971 972 973
                    os.close(0)
                    os.open("/dev/null", os.O_RDONLY)
                    if output:
                        os.close(1)
                        fd = os.open(os.path.join(base, ".rsync.out"),
                                     os.O_CREAT|os.O_TRUNC|os.O_WRONLY,
                                     0664)
                        os.dup2(fd, 2)
                        pass
974 975 976 977 978 979 980 981
                    try:
                        os.execve(RSYNC, cmd, os.environ)
                    except OSError, e:
                        sys.stderr.write(
                            "error: unable to exec '%s' - %s\n"
                            "error: args=%s\n"
                            % (RSYNC, e.strerror, `cmd`))
                        pass
982 983 984 985 986
                    os._exit(127)
                    pass
                except:
                    sys.exit(1)
                    pass
987
                pass
988 989 990 991 992
            pass
        pass
    
    return retval

993
def rmstar(host, port, delay, as_root, *args):
994 995 996 997 998
    global HOME, DEBUG

    retval = 0
    for path in args:
        cmd = ["/usr/bin/ssh",
999
               "-o", "BatchMode=yes",
1000 1001
               "-o", "StrictHostKeyChecking=no",
               "-o", ("UserKnownHostsFile=" +
1002 1003 1004 1005
                      os.path.join(HOME, ".ssh", "emulab_known_hosts"))]
        if port:
            cmd.extend([ "-p", str(port) ])
            pass
1006 1007 1008 1009
        cmd.extend([ host ])
        if as_root:
            cmd.extend(["sudo"])
        cmd.extend(["rm", "-rf", path ])
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
        if DEBUG:
            print `cmd`
            retval = -1
            pass
        else:
            retval = os.fork()
            if retval != 0:
                # Parent
                pass
            else:
1020 1021 1022
                if delay > 0:
                    time.sleep(delay)
                    pass
1023 1024 1025 1026 1027 1028 1029
                os.execve("/usr/bin/ssh", cmd, os.environ)
                os._exit(127)
                pass
            pass
        pass
    
    return retval
1030

1031 1032 1033 1034 1035 1036 1037 1038 1039
def print_status(msg):
    if not sys.stdout.isatty() or VERBOSITY < VERBOSITY_HUMAN:
        return
    
    sys.stdout.write(msg)
    sys.stdout.flush()
    
    return

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
#
# Compress a file. Return False if file is skipped for whatever reason.
#
def compressfile(root, file, threshold):
    pathname = os.path.join(root, file)
    if not os.path.exists(pathname):
        return False
    statinfo = os.stat(pathname)
    mode     = statinfo[stat.ST_MODE]
    size     = statinfo[stat.ST_SIZE]
    # Only regular files
    if not stat.S_ISREG(mode):
        return False
    # Only files greater then threshold
    if not size >= threshold:
        return False
    first, last = os.path.splitext(pathname)
    # Try to avoid compressing things that are already compressed.
    if last in COMPRESSFILE_EXTENSIONS:
        return False
    # Lets be careful of foo and foo.gz, which is from a previous run.
    if os.path.exists(pathname + ".gz"):
        os.unlink(pathname + ".gz")
        pass
    print_status("Compressing " + pathname + " --> " + pathname + ".gz\n")
    exitval = os.system(COMPRESSFILE_PROGRAM + " %s " % (pathname,))
    if exitval != 0:
        return False
    return True

1070
def print_job_status(mode, hosts, jobs, hoststatus, hoststart):
1071 1072
    if not sys.stdout.isatty() or VERBOSITY < VERBOSITY_HUMAN:
        return
1073
    
1074
    lmsg = "nodes todo/doing/done %d/%d/%d "
1075
    rmsg = mode + " time min/avg/max: %.2f/%.2f/%.2f secs"
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095

    hosttimes = map(lambda x:
                    hoststatus.get(x, (time.time(),))[0] - hoststart[x],
                    hoststart.keys())
    
    if len(hosttimes) == 0:
        hosttimes = [0]
        avg = 0.0
        pass
    else:
        avg = sum(hosttimes) / len(hosttimes)
        pass
    lmsg = lmsg % (
        len(hosts) - len(hoststatus) - len(jobs),
        len(jobs),
        len(hoststatus))
    rmsg = rmsg % (
        min(hosttimes),
        avg,
        max(hosttimes))
1096
    line_len = len(lmsg) + len(rmsg) + 2
1097 1098 1099
    if line_len < 79:
        lmsg += " " * (79 - line_len)
        pass
1100 1101
    print_status(lmsg + rmsg + " "
                 + JOB_PROGRESS[JOB_PROGRESS_INDEX % len(JOB_PROGRESS)] + "\r")
1102 1103

    return
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
##
# Detect changes in the rsync log file sizes.
#
# @param jobs The hashtable of jobs
# @param logsize The hashtable of previous log file sizes.
# @param logdir The root directory for log files.
# @return True if the size of any of the log files has changed.
#
def making_progress(jobs, logsize, logdir):
    retval = False
    for pid in jobs:
        phost, vhost = jobs[pid]
        try:
            st = os.stat(os.path.join(logdir, vhost, ".rsync.out"))
            if st[stat.ST_SIZE] > logsize[pid]:
                retval = True
                logsize[pid] = st[stat.ST_SIZE]
                pass
            pass
        except OSError:
            pass
        pass
    
    return retval

1130 1131 1132 1133 1134 1135
##
# Trace preprocessing.
#
# @param traces Sequence of dictionaries describing the active link tracers.
#
def trace_pre(traces):
1136 1137
    if len(traces) == 0:
        return;
1138
    
1139 1140 1141 1142
    rc = os.system(TEVC + " -w -t 30 -e %s/%s now __all_tracemon snapshot" %
                   (PID, EID))
    if rc != 0:
        print "Could not SNAPSHOT the trace agents!";
1143 1144 1145 1146 1147 1148 1149 1150 1151
        pass
    return

##
# Trace post processing
#
# @param link2trace Dictionary containing the link names that map to a sequence
# of dictionaries containing individual trace information.
#
1152 1153
def trace_post(link2trace):
    lpc = 1
Leigh Stoller's avatar
Leigh Stoller committed
1154 1155
    sql = []
    
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
    for linkvname in link2trace.keys():
        print_status("linktrace post processing %d/%d  " %
                     (lpc, len(link2trace)))
        args = {}
        os.chdir(linkvname)
        for filename in glob.glob("*.recv*"):
            base, ext = os.path.splitext(filename)
            if base.startswith("__") or ext == ".recv":
                continue
            al = args.get(ext, [])
            al.append(filename)
            args[ext] = al
1168 1169 1170 1171 1172 1173

            stuff = base.split(".");
            trace_db = link2trace[linkvname][stuff[0]]["trace_db"]
            if trace_db != "0":
                sql.append(linkvname + "/" + filename)
                pass
1174 1175 1176 1177 1178 1179
            pass
        for ext in args.keys():
            if ext == ".recv":
                continue
            dst = "__all.recv%s" % (ext,)
            print_status(".")
1180 1181 1182
            if os.path.exists(MERGECAP):
                os.system(MERGECAP + " -w %s %s" % (dst, " ".join(args[ext])))
                pass
1183
            print_status(".")
1184 1185 1186 1187 1188 1189 1190
            if ext != ".0":
                if not os.path.exists(ext[1:]):
                    os.mkdir(ext[1:])
                    pass
                os.chdir(ext[1:])
                dst = os.path.join(os.path.pardir, dst)
                pass
1191 1192 1193
            if os.path.exists(TCPTRACE):
                os.system(TCPTRACE + " -y -G %s > .tcptrace.out" % (dst,))
                pass
1194 1195 1196
            if ext != ".0":
                os.chdir(os.path.pardir)
                pass
1197
            pass
1198
        print_status("\r")
1199 1200 1201 1202 1203 1204 1205
        os.chdir(os.path.pardir)
        lpc += 1
        pass

    if len(link2trace.keys()):
        print_status("\n")
        pass
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
    # Now do the DB enters.
    if len(sql) != 0:
        SNORTCONF  = ".snort.conf"
        SNORTOUT   = ".snort.out"
        USERRULES  = "snort.rules"
        
        print_status("Entering trace data into mysql DB %s" % DPDBNAME)

        # snort needs a config file to do anything useful
        os.system("/bin/rm -f %s %s" % (SNORTCONF, SNORTOUT))
        
        fp = open(SNORTCONF, 'w')
        os.chmod(SNORTCONF, 0600)
1220 1221
        fp.write("output database: log, mysql, user=%s dbname=%s password=%s\n" %
                 (USER, DPDBNAME, COLLAB_PW))
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233

        # Allow user to override default rules.
        if os.path.exists(USERRULES):
            fp.write("include ./%s" % (USERRULES,))
            pass
        else:
            fp.write("log ip any any -> any any\n")
            pass
        fp.close()
        
        for filename in sql:
            print_status(".")
1234
            os.system("snort -k none -l ./ -c ./%s -r %s > %s 2>&1" %
1235 1236 1237 1238
                      (SNORTCONF, filename, SNORTOUT))
            print_status(".")
            pass
        print_status("\n")
1239
        os.system("/bin/rm -f %s" % (SNORTCONF,))
1240 1241
        pass
    
1242 1243
    return

1244 1245 1246 1247
##
# Performs the "sync" action, which synchronizes the logholes for a group of
# nodes.
#
1248 1249
# XXX This method is in dire need of a rewrite.
#
1250 1251
# @param args Action-specific command line arguments.
#
1252
def do_sync(args, mode="sync", must_be_active=1, as_root=False):
1253
    from emulabclient import RESPONSE_SUCCESS
1254
    global OSIDS, SERVER, DOT_LOGHOLES, JOB_PROGRESS_INDEX
1255
    global DPDBNAME, COLLAB_PW
1256 1257
    
    retval = 0
1258
    delete_dir = False
1259

1260
    logdir = os.path.join(EXPDIR_FMT % { "PID" : PID, "EID" : EID }, "logs")
1261 1262
    # Special dir for local program agent (or other stuff).
    opsdir = os.path.join(EXPDIR_FMT % { "PID" : PID, "EID" : EID }, "ops")
1263 1264

    standard_logholes = True
1265
    snapshot_traces = False
1266
    post_process = True
1267
    compress = False
1268 1269 1270
    extra_logholes = []

    try:
1271 1272
        opts, node_list = getopt.getopt(args, "nl:r:PsdcR", [
            "no-standard", "local=", "remote=", "delete", "compress", "root"])
1273 1274 1275 1276
        for opt, val in opts:
            if opt in ("-n", "--no-standard"):
                standard_logholes = False
                pass
1277 1278 1279
            elif opt in ("-P", "--no-post"):
                post_process = False
                pass
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
            elif opt in ("-l", "--local"):
                logdir = os.path.abspath(val)
                if not os.path.isdir(logdir):
                    raise getopt.error(
                        'error: local directory does not exist - '
                        + logdir)
                pass
            elif opt in ("-r", "--remote"):
                extra_logholes.append(val)
                pass
1290 1291 1292
            elif opt in ("-s", "--snapshot"):
                snapshot_traces = True
                pass
1293 1294 1295
            elif opt in ("-d", "--delete"):
                delete_dir = True
                pass
1296 1297
            elif opt in ("-c", "--compress"):
                compress = True
1298 1299
            elif opt in ("-R", "--root"):
                as_root = True
1300
                pass
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
            pass
        pass
    except getopt.error, e:
        print e.args[0]
        sync_usage()
        return 2

    if not standard_logholes:
        DOT_LOGHOLES = ""
        pass
    
    for path in extra_logholes:
        DOT_LOGHOLES += loghole_include(path)
        pass

    DOT_LOGHOLES += "- *\n"
    
1318 1319 1320
    init_server()
    
    state_method = getattr(SERVER, "experiment.state")
1321
    
1322
    os.chdir(logdir)
1323 1324
    
    if standard_logholes and os.path.exists(CLEANFILE):
1325 1326 1327 1328
        do_clean(["-f", "-e"])
        os.unlink(CLEANFILE)
        pass

1329 1330 1331
    dlhandle = tempfile.NamedTemporaryFile(prefix=".logholes")
    dlhandle.write(DOT_LOGHOLES)
    dlhandle.flush()
1332 1333 1334 1335 1336 1337

    state = state_method(PACKAGE_VERSION, { "proj" : PID, "exp" : EID })
    if state["code"] != RESPONSE_SUCCESS:
        sys.stderr.write("error: " + state["output"] + "\n")
        retval = 1
        pass
1338 1339 1340
    elif (state["value"] != "active" and
          state["value"] != "activating" and
          state["value"] != "modify_reswap"):
1341 1342 1343 1344 1345 1346 1347 1348
        if must_be_active:
            sys.stderr.write("error: %s/%s is not an active experiment!\n" %
                             (PID, EID))
            retval = 2
            pass
        else:
            retval = 0
            pass
1349 1350 1351
        pass
    else:
        info_method = getattr(SERVER, "experiment.info")
1352
        osinfo_method = getattr(SERVER, "osid.info")
1353
        ssh_method = getattr(SERVER, "node.sshdescription")
1354 1355
        collabpw_method = getattr(SERVER, "user.collabpassword")
        dpinfo_method = getattr(SERVER, "experiment.dpinfo")
1356

1357
        # Get any bits of information we need from the RPC server.
1358 1359 1360 1361 1362
        physical = info_method(PACKAGE_VERSION, {
            "proj" : PID,
            "exp" : EID,
            "aspect" : "mapping",
            })
1363

1364
        traces = info_method(PACKAGE_VERSION, {
1365 1366
            "proj" : PID,
            "exp" : EID,
1367
            "aspect" : "traces",
1368
            })
1369 1370 1371 1372 1373

        ssh_data = ssh_method(PACKAGE_VERSION, {
            "proj" : PID,
            "exp" : EID
            })
1374 1375 1376 1377

        collab_data = collabpw_method(PACKAGE_VERSION, { })
        dpinfo_data = dpinfo_method(PACKAGE_VERSION, { "proj" : PID,
                                                       "exp" : EID, })
1378
        
1379
        if ((physical["code"] != RESPONSE_SUCCESS) or
1380
            (traces["code"] != RESPONSE_SUCCESS) or
1381 1382
            (collab_data["code"] != RESPONSE_SUCCESS) or
            (dpinfo_data["code"] != RESPONSE_SUCCESS) or
1383
            (ssh_data["code"] != RESPONSE_SUCCESS)):
1384 1385 1386 1387 1388 1389
            sys.stderr.write("error: xmlrpc failed - %s\n" %
                             (physical["output"],))
            retval = 1
            pass
        else:
            physical = physical["value"]
1390
            traces = traces["value"]
1391
            ssh_data = ssh_data["value"]
1392 1393
            COLLAB_PW = collab_data["value"]
            DPDBNAME  = dpinfo_data["value"]["dbname"]
1394 1395 1396 1397

            if snapshot_traces:
                trace_pre(traces)
                pass
1398 1399

            # Separate the nodes into those that are up
1400
            hosts = [(x["node"], x["name"]) for x in physical.values()
1401 1402 1403
                     if ((x["erole"] == "virthost" or
                          x["erole"] == "node" or
                          x["erole"] == "delaynode") and
1404 1405
                         (x["status"] == "up" and x["eventstatus"] == "ISUP"))]

1406
            # ... or down.
1407 1408 1409 1410 1411 1412
            downhosts = [(x["node"], x["name"]) for x in physical.values()
                     if ((x["erole"] == "virthost" or
                          x["erole"] == "node" or
                          x["erole"] == "delaynode") and
                         (x["status"] != "up" or x["eventstatus"] != "ISUP"))]

1413 1414
            phosts = sets.Set([x[0] for x in hosts])
            vhosts = sets.Set([x[1] for x in hosts])
1415 1416
            dphosts = sets.Set([x[0] for x in downhosts])
            dvhosts = sets.Set([x[1] for x in downhosts])
1417 1418
            if len(node_list) == 0:
                node_list = vhosts
1419 1420 1421 1422 1423
                
                for host in downhosts:
                    sys.stderr.write("warning: '%s' is down, its logs will "
                                     "not be retrieved\n" % (host[1],))
                    pass
1424 1425
                pass

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
            #
            # Do the local ops directory first.
            #
            if os.path.exists(opsdir):
                if mode == "sync":
                    pid = rsync("localhost", logdir,
                                paths = [opsdir], output = True,
                                relative = False)
                    pass
                elif mode == "clean":
                    pid = rmstar("localhost", None, 0, False, opsdir + "/*")
                    pass
                else:
                    assert 0
                pass

1442 1443
            known_nodes = sets.Set(node_list) & (phosts | vhosts)
            unknown_nodes = known_nodes ^ sets.Set(node_list)
1444

1445 1446
            jobs = {}
            hoststatus = {}
1447
            hoststart = {}
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
            hosttries = {}
            logsize = {}
            while len(hosts) > 0 or len(jobs) > 0:
                if len(hosts) > 0:
                    ht = hosts.pop()
                    phost, vhost = ht
                    pass
                else:
                    phost = ""
                    vhost = ""
                    pass
1459
                if (vhost in node_list) or (phost in node_list):
1460
                    # Start a job for the next host.
1461 1462 1463
                    osid = physical[vhost]["osid"]
                    if osid not in OSIDS:
                        oi = osinfo_method(PACKAGE_VERSION, {
1464
                            "osid" : osid })
1465 1466 1467 1468 1469
                        if oi["code"] == RESPONSE_SUCCESS:
                            OSIDS[osid] = oi["value"]
                            pass
                        else:
                            OSIDS[osid] = None
1470 1471
                            pass
                        pass
1472

1473
                    # Make sure we can talk to it.
1474 1475 1476 1477 1478 1479
                    if not OSIDS[osid]:
                        sys.stderr.write("warning: unknown OSID %s for %s\n" %
                                         (physical[vhost]["osid"], vhost))
                        continue
                    else:
                        vos = OSIDS[physical[vhost]["osid"]]
1480 1481 1482
                        if ("osfeatures" not in vos or
                            not vos["osfeatures"] or
                            "ssh" not in vos["osfeatures"]):
1483 1484 1485 1486 1487 1488 1489 1490
                            if VERBOSITY > VERBOSITY_HUMAN:
                                sys.stderr.write("warning: %s OS, %s, does "
                                                 "not support ssh, skipping\n"
                                                 % (vhost, vos["osname"]))
                                pass
                            continue
                        pass

1491 1492 1493 1494 1495 1496 1497
                    # Start the job.
                    if ht in hosttries:
                        delay = 3
                        pass
                    else:
                        delay = 0
                        pass
1498
                    if mode == "sync":
1499
                        pid = rsync(phost, os.path.join(logdir, vhost),
1500
                                    dlpath = dlhandle.name,
1501
                                    port = ssh_data[phost].get("port", None),
1502
                                    output = True,
1503 1504
                                    delay = delay,
                                    as_root = as_root)
1505 1506
                        pass
                    elif mode == "clean":
1507 1508 1509
                        pid = rmstar(phost,
                                     ssh_data[phost].get("port", None),
                                     delay,
1510
                                     as_root,
1511
                                     "/local/logs/*")
1512 1513 1514 1515
                        pass
                    else:
                        assert 0
                    
1516 1517 1518
                    jobs[pid] = ht
                    logsize[pid] = 0
                    hoststart[ht] = time.time()
1519

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
                    if ht not in hosttries:
                        hosttries[ht] = 0
                        pass
                    hosttries[ht] += 1
                    pass
                
                try:
                    # Wait for the children and update the status.
                    while len(jobs) == PARALLELIZATION or len(hosts) == 0:
                        print_job_status(mode, node_list, jobs,
                                         hoststatus, hoststart)
                        # Check for any changes in the log files.
                        if (mode == "sync" and
                            making_progress(jobs, logsize, logdir)):
                            JOB_PROGRESS_INDEX += 1
                            pass
                        # Check for processes that have ended.
                        pid, sts = os.waitpid(0, os.WNOHANG)
                        if pid in jobs:
                            # Retry on some errors 
                            if (mode == "clean" and sts == 255 and
                                hosttries[jobs[pid]] <= JOB_TRIES):
                                hosts.append(jobs[pid])
                                pass
                            elif (mode == "sync" and
                                  sts not in NONRETRIABLE_RSYNC_STATUS and
                                  hosttries[jobs[pid]] <= JOB_TRIES):
                                hosts.append(jobs[pid])
                                pass
                            else:
1550
                                hoststatus[jobs[pid]] = (time.time(), sts)
1551
                                pass
1552
                            del jobs[pid]
1553
                            pass
1554

1555 1556 1557
                        if len(jobs) == PARALLELIZATION or len(hosts) == 0:
                            time.sleep(0.5)
                            pass
1558
                        pass
1559
                    pass
1560 1561
                except OSError:
                    pass
1562 1563
                pass

1564 1565
            sys.stdout.write("\n")

1566 1567
            # Clue the user in if there were nodes that they specified nodes
            # we don't know about.
1568 1569
            if len(unknown_nodes) > 0:
                for vhost in unknown_nodes:
1570 1571 1572 1573 1574 1575 1576 1577
                    if vhost in dvhosts or vhost in dphosts:
                        sys.stderr.write("error: node '%s' is down\n" %
                                         (vhost,))
                        pass
                    else:
                        sys.stderr.write("error: unknown node - %s\n" %
                                         (vhost,))
                        pass
1578 1579 1580
                    pass
                retval = 2
                pass
1581

1582 1583 1584
            # Check the status of the jobs and dump logs for any that failed.
            for ht, (etime, sts) in hoststatus.items():
                phost, vhost = ht
1585
                if VERBOSITY > VERBOSITY_HUMAN:
1586
                    print "info: %s - %.2f" % (vhost, etime - hoststart[ht])
1587
                    pass
1588 1589
                if mode == "clean":
                    continue
1590
                if sts not in ACCEPTABLE_RSYNC_STATUS:
1591 1592
                    sys.stderr.write("error: failed to %s node '%s'\n" %
                                     (mode, vhost))
1593 1594 1595 1596 1597
                    eout = open(os.path.join(logdir, vhost, ".rsync.out"),
                                "r").read()
                    sys.stderr.write(
                        vhost + ": " + re.sub(r'\n',
                                              "\n" + vhost + ": ",
1598
                                              eout[:-1]) + eout[-1])
1599 1600
                    retval = 3
                    pass
1601
                else:
1602 1603 1604 1605 1606
                    # Post process the delay-agent log files, if there are any.
                    vdir = os.path.join(vhost, "var", "emulab", "logs")
                    if (os.path.exists(vdir) and
                        os.path.exists("delayagent.debug")):
                        os.chdir(vdir)
1607 1608 1609 1610 1611
                        os.system("%s %s" %
                                  (DELAYLOG2XPLOT, "delayagent.debug"))
                        pass
                    os.chdir(logdir)
                    pass
1612
                pass
1613 1614

            # Add symbolic links to the trace files.
1615
            link2trace = {}
1616
            for trace in traces:
1617 1618
                if trace["trace_type"] == "monitor":
                    continue
1619 1620 1621

                tl = link2trace.get(trace["linkvname"], {})
                tl[trace["vnode"]] = trace
1622 1623
                link2trace[trace["linkvname"]] = tl
                
1624 1625 1626 1627 1628 1629 1630 1631
                fullpath = os.path.join(logdir, trace["linkvname"])
                try:
                    os.makedirs(fullpath)
                    pass
                except OSError:
                    pass
                for fmt in LINK_DUMP_FMT:
                    src = os.path.join(trace["delayvname"],
1632 1633
                                       "local",
                                       "logs",
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
                                       fmt % (trace["vnode"],
                                              trace["linkvname"]))
                    for filename in glob.glob(src + "*"):
                        dst = os.path.split(filename)
                        dst = dst[len(dst) - 1].split('.')
                        comp = [trace["vnode"]]
                        comp.extend(dst[1:])
                        dst = ".".join(comp)
                        dst = os.path.join(fullpath, dst)
                        try:
                            os.unlink(dst)
                            pass
                        except OSError:
                            pass
                        os.symlink(os.path.join(os.pardir, filename), dst)
                        pass
                    pass
1651

1652 1653
                # Add some links to the xplot log files created by
                # delaylog2xplot
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
                src = os.path.join(trace["delayvname"],
                                   "var", "emulab", "logs",
                                   "%s-%s-*.xpl" % (trace["linkvname"],
                                                    trace["vnode"]))
                for filename in glob.glob(src):
                    aspect = filename.split("-")[2].split(".")[0]
                    dst = "%s-%s.xpl" % (trace["vnode"], aspect)
                    dst = os.path.join(fullpath, dst)
                    try:
                        os.unlink(dst)
                        pass
                    except OSError:
                        pass
                    os.symlink(os.path.join(os.pardir, filename), dst)
                    pass
1669
                pass
1670 1671 1672 1673

            if post_process:
                trace_post(link2trace)
                pass
1674
            
1675 1676
            pass
        pass
1677 1678 1679 1680 1681

    # Do compression
    if compress:
        do_compress("", as_root = as_root)
        pass
1682
    
1683 1684 1685 1686 1687 1688 1689
    # Schedule clean
    if delete_dir:
        os.chdir(logdir)
        open(CLEANFILE, 'w')
        os.chmod(CLEANFILE, 0664)
        pass

1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
    return retval

##
# Performs the "archive" action, which displays a brief summary of the log
# files in the experiment.
#
# @param args Action-specific command line arguments.
#
def do_list(args):
    retval = 0

    keep_atmost = 100
    keep_size = 3.0

    list_gc = ""
    
    try:
        opts, args = getopt.getopt(args, "O1!Xom:s:", [
            "keep-atmost=", "keep-size="
            ])
        for opt, val in opts:
            if opt in ("-O", "-1", "-!", "-X"):
                list_gc = list_gc + opt[1]
                pass
            elif opt in ("-o"):
                list_gc = list_gc + ' '
                pass
            elif opt in ("-m", "--keep-atmost"):
                try:
                    keep_atmost = int(val)
                    pass
                except:
                    raise getopt.error(
                        'error: expecting integer for keep atmost value, '
                        'got - ' + val)
                pass
            elif opt in ("-s", "--keep-size"):
                try:
                    keep_size = float(val)
                    pass
                except:
                    raise getopt.error(
                        'error: expecting float for keep size value, '
                        'got - ' + val)
                pass
            pass
        
        if len(args) > 0:
            raise getopt.error(
                'error: too many arguments passed to "list" action')
        pass
    except getopt.error, e:
        print e.args[0]
        list_usage()
        return 2

    if len(list_gc) == 0:
        list_gc = "O1!X "
        pass
    
    logdir = os.path.join(EXPDIR_FMT % { "PID" : PID, "EID" : EID }, "logs")
    os.chdir(logdir)

    sa = sort_archives(keep_atmost, keep_size)

    exp_logholes = []
    for entry in os.listdir(logdir):
        lh, cp = open_loghole(entry)
        if lh:
            created = time.mktime(time.strptime(cp.get("MAIN", "created")))
            exp_logholes.append((entry, cp, created))
            pass
        pass

    current_time = time.time()
    tomorrow_time = current_time + (60 * 60 * 24)
    
    if len(exp_logholes) > 0:
        max_entry_len = max([len(x[0]) for x in exp_logholes])

        if VERBOSITY >= VERBOSITY_HUMAN:
            print "GC  Name%sDate" % (" " * (max_entry_len - 4 + 5))
            print
            pass
        
        exp_logholes.sort(lambda x, y: cmp(y[2], x[2]))
        for entry, cp, created in exp_logholes:
            keep_until = cp.get("MAIN", "keep-until")
            keep_atleast = (cp.getint("MAIN", "keep-atleast") * 60 * 60 * 24)
            created = time.mktime(time.strptime(cp.get("MAIN", "created")))
            created_str = time.strftime("%m/%d", time.localtime(created))
            if keep_until == "i-delete":
                ball = "O"
                pass
            elif entry in sa["del"]:
                ball = "X"
                pass
            elif entry in sa["soon"]:
                if current_time > keep_atleast:
                    ball = "!"
                    pass
                elif (tomorrow_time - created) > keep_atleast:
                    ball = "1"
                    pass
                else:
                    ball = " "
                    pass
                pass

            if ball in list_gc:
                if VERBOSITY == VERBOSITY_MACHINE:
                    print entry
                    pass
                elif VERBOSITY >= VERBOSITY_HUMAN:
                    gap = " " * (max_entry_len - len(entry) + 5)
                    print "[%s] %s%s%s" % (ball, entry, gap, created_str)
                    pass
                pass
            pass
        if len(exp_logholes) == 0:
            if VERBOSITY >= VERBOSITY_HUMAN:
                print "  <No log holes found in %s/%s>" % (PID, EID)
                pass
            pass

        if VERBOSITY == VERBOSITY_MACHINE:
            pass
        elif VERBOSITY >= VERBOSITY_HUMAN:
            print
            print "%d bytes are in use." % (sa["inuse-size"],)
            print ("%d bytes will be reclaimed at the next gc." %
                   (sa["reclaimed-size"],))
            print
            print "GC Legend:"
            print "  O - Archive will not be deleted automatically."
            print "  1 - Archive is one day away from its keep-until date."
            print "  ! - Archive is past its keep-until date and will be"
            print "      deleted when space is needed."
            print "  X - Archive is ready to be garbage collected."
            pass
        pass
    
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
    return retval

##
# Performs the "change" action, which involves updating the metadata for an
# existing archive.
#
# @param args Action-specific command line arguments.
#
def do_change(args):
    retval = 0

    keep_until = None
    keep_atleast = None
    comments = []

    # Parse action-specific options and arguments.
    try:
        opts, args = getopt.getopt(args, "k:a:c:", [
            "keep-until=", "keep-atleast=", "comment=", ])
        for opt, val in opts:
            if opt in ("-k", "--keep-until"):
                if val == "i-delete" or val == "space-is-needed":
                    keep_until = val
                    pass
                else:
                    raise getopt.error(
                        'error: expecting "i-delete" or "space-is-needed" for '
                        'keep until value, got - ' + val)
                pass
            elif opt