All new accounts created on Gitlab now require administrator approval. If you invite any collaborators, please let Flux staff know so they can approve the accounts.

loghole.in 50.6 KB
Newer Older
Timothy Stack's avatar
 
Timothy Stack committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#! /usr/bin/env python

#
# EMULAB-COPYRIGHT
# Copyright (c) 2004, 2005 University of Utah and the Flux Group.
# All rights reserved.
#

import re
import pwd
import sys
import sets
import stat
import time
import getopt
import socket
import zipfile
import cStringIO
Timothy Stack's avatar
 
Timothy Stack committed
19
import threading
Timothy Stack's avatar
 
Timothy Stack committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
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

PACKAGE_VERSION = 0.1

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

RSYNC = "@RSYNC@"
Timothy Stack's avatar
 
Timothy Stack committed
38
ACCEPTABLE_RSYNC_STATUS = [ 0 ]
Timothy Stack's avatar
 
Timothy Stack committed
39 40 41 42 43 44 45 46

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

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

Timothy Stack's avatar
 
Timothy Stack committed
47 48
GLOBAL_LOGS = [
    "event-sched.log", "feedback.log", "../tbdata/feedback_data.tcl",
Timothy Stack's avatar
 
Timothy Stack committed
49
    "digest.out", "report.mail", "../tbdata/%(EID)s.report"
Timothy Stack's avatar
 
Timothy Stack committed
50
    ]
Timothy Stack's avatar
 
Timothy Stack committed
51

Timothy Stack's avatar
 
Timothy Stack committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65
EXTENSIONS = [ ".zip" ]

LINK_DUMP_FMT = [ "%s.xmit", "%s.recv" ]

DOT_LOGHOLES = """+ /var/
+ /var/emulab/
+ /var/emulab/logs/
+ /var/emulab/logs/**
+ /local/
+ /local/logs/
+ /local/logs/**
- *
"""

Timothy Stack's avatar
 
Timothy Stack committed
66 67 68
PID = None
EID = None

Timothy Stack's avatar
 
Timothy Stack committed
69 70 71 72
try:
    pw = pwd.getpwuid(os.getuid())
    pass
except KeyError:
Timothy Stack's avatar
 
Timothy Stack committed
73 74 75 76
    sys.stderr.write("error: unknown user id %d" % os.getuid())
    sys.exit(2)
    pass

Timothy Stack's avatar
 
Timothy Stack committed
77 78
USER = pw.pw_name
HOME = pw.pw_dir
Timothy Stack's avatar
 
Timothy Stack committed
79 80 81

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

Timothy Stack's avatar
 
Timothy Stack committed
82 83
PARALLELIZATION = 10

Timothy Stack's avatar
 
Timothy Stack committed
84 85 86 87 88 89 90 91 92
DEBUG = 0

VERBOSITY_MACHINE = 1
VERBOSITY_HUMAN = 2

VERBOSITY = VERBOSITY_HUMAN

SERVER = None

Timothy Stack's avatar
 
Timothy Stack committed
93 94
OSIDS = {}

Timothy Stack's avatar
 
Timothy Stack committed
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
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

##
# 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():
Timothy Stack's avatar
 
Timothy Stack committed
170
    print "Usage: loghole [-hV] [-e pid/eid|-a] [OPTIONS] <action> [...]"
Timothy Stack's avatar
 
Timothy Stack committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    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."
Timothy Stack's avatar
 
Timothy Stack committed
193
    print "  change    Change the metadata of an existing archive."
Timothy Stack's avatar
 
Timothy Stack committed
194 195 196 197
    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."
Timothy Stack's avatar
 
Timothy Stack committed
198 199 200
    #print "  validate  Validate the contents of an archive."
    print "  clean     Clean the experiment log directory and node local"
    print "            directories."
Timothy Stack's avatar
 
Timothy Stack committed
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
    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():
    print "Usage: loghole sync [node1 ...]"
    print
    print "Synchronize the experiment's log holes with the experiment's log"
    print "directory."
    print
    print "Optional arguments:"
    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."
    print "  -d, --delete           Delete the files in the log directory"
    print "                         after producing the archive."
    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

Timothy Stack's avatar
 
Timothy Stack committed
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
##
# 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():
    print "Usage: loghole validate <archive-name>"
    print
    print "Validate the contents of an archive."
    print
    print "Required arguments:"
    print "  archive-name  The name of the archive to validate."
    print
    print "Examples:"
    print "  $ loghole validate foobar.0"
    return

Timothy Stack's avatar
 
Timothy Stack committed
380 381 382 383
##
# Print the usage statement for the "clean" action.
#
def clean_usage():
Timothy Stack's avatar
 
Timothy Stack committed
384 385 386 387 388
    print "Usage: loghole clean [-fne] [node1 ...]"
    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."
Timothy Stack's avatar
 
Timothy Stack committed
389
    print
Timothy Stack's avatar
 
Timothy Stack committed
390 391 392 393
    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."
Timothy Stack's avatar
 
Timothy Stack committed
394 395 396 397 398
    print
    print "Examples:"
    print "  $ loghole clean"
    return

Timothy Stack's avatar
 
Timothy Stack committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
##
# 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:"
Timothy Stack's avatar
 
Timothy Stack committed
415
    print "  $ loghole gc -n -m 1"
Timothy Stack's avatar
 
Timothy Stack committed
416 417 418
    print "  Reclaimed 3421 bytes from foo/bar."
    print "  52434 bytes are still in foo/bar."
    print
Timothy Stack's avatar
 
Timothy Stack committed
419
    print "  $ loghole -q gc -m 1"
Timothy Stack's avatar
 
Timothy Stack committed
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
    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)
        if ((len(dirs) < 6) or not
            ((DIRS["proj"] in dirs and
              "exp" in dirs[dirs.index(DIRS["proj"]):]) or
             (len(dirs) >= 6 and
              (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.
#
Timothy Stack's avatar
 
Timothy Stack committed
464
def open_loghole(path, mode='r'):
Timothy Stack's avatar
 
Timothy Stack committed
465 466
    retval = None, None
    if zipfile.is_zipfile(path):
Timothy Stack's avatar
 
Timothy Stack committed
467
        zf = zipfile.ZipFile(path, mode)
Timothy Stack's avatar
 
Timothy Stack committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
        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:
Timothy Stack's avatar
 
Timothy Stack committed
717 718 719
        formatted_log = log % { "PID" : PID, "EID" : EID }
        if os.path.exists(formatted_log):
            zf.write(formatted_log)
Timothy Stack's avatar
 
Timothy Stack committed
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
            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:
        for entry in os.listdir(logdir):
            if os.path.isdir(entry):
                os.rmdir(entry)
                pass
            pass
        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"))
Timothy Stack's avatar
 
Timothy Stack committed
807 808 809 810
                if "report.mail" in lh.namelist():
                    print "Report:"
                    print lh.read("report.mail")
                    pass
Timothy Stack's avatar
 
Timothy Stack committed
811 812 813 814 815 816 817 818 819
                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
Timothy Stack's avatar
 
Timothy Stack committed
820 821 822 823 824
                try:
                    lh.printdir()
                    pass
                except IOError:
                    pass
Timothy Stack's avatar
 
Timothy Stack committed
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
                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.
#
def rsync(host, base, *args):
    global RSYNC, HOME, DEBUG
    
    retval = 0
    for path in args:
        fullpath = os.path.join("", base, path[1:], "")
        try:
            os.makedirs(fullpath)
            pass
        except OSError:
            pass
Timothy Stack's avatar
 
Timothy Stack committed
852 853 854 855
        cmd = [RSYNC,
               "-rptgoDlz",
               "--copy-unsafe-links",
               "--include-from=" + os.path.join(base, os.pardir, ".logholes")]
Timothy Stack's avatar
 
Timothy Stack committed
856
        if VERBOSITY > VERBOSITY_HUMAN:
Timothy Stack's avatar
 
Timothy Stack committed
857
            cmd.append("-v")
Timothy Stack's avatar
 
Timothy Stack committed
858
            pass
Timothy Stack's avatar
 
Timothy Stack committed
859 860 861 862 863
        cmd.extend([("--rsh=ssh -o StrictHostKeyChecking=no "
                     + "-o UserKnownHostsFile="
                     + os.path.join(HOME, ".ssh", "emulab_known_hosts")),
                    host + ":" + path,
                    fullpath])
Timothy Stack's avatar
 
Timothy Stack committed
864
        if DEBUG:
Timothy Stack's avatar
 
Timothy Stack committed
865 866
            print `cmd`
            retval = -1
Timothy Stack's avatar
 
Timothy Stack committed
867 868
            pass
        else:
Timothy Stack's avatar
 
Timothy Stack committed
869 870 871 872 873 874 875 876
            retval = os.fork()
            if retval != 0:
                # Parent
                pass
            else:
                os.execve(RSYNC, cmd, os.environ)
                os._exit(127)
                pass
Timothy Stack's avatar
 
Timothy Stack committed
877 878 879 880 881
            pass
        pass
    
    return retval

Timothy Stack's avatar
 
Timothy Stack committed
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
def rmstar(host, *args):
    global HOME, DEBUG

    retval = 0
    for path in args:
        cmd = ["/usr/bin/ssh",
               "-o", "StrictHostKeyChecking=no",
               "-o", ("UserKnownHostsFile=" +
                      os.path.join(HOME, ".ssh", "emulab_known_hosts")),
               host,
               "rm",
               "-rf",
               path]
        if DEBUG:
            print `cmd`
            retval = -1
            pass
        else:
            retval = os.fork()
            if retval != 0:
                # Parent
                pass
            else:
                os.execve("/usr/bin/ssh", cmd, os.environ)
                os._exit(127)
                pass
            pass
        pass
    
    return retval
    

Timothy Stack's avatar
 
Timothy Stack committed
914 915 916 917 918 919
##
# Performs the "sync" action, which synchronizes the logholes for a group of
# nodes.
#
# @param args Action-specific command line arguments.
#
Timothy Stack's avatar
 
Timothy Stack committed
920
def do_sync(args, mode="pull", must_be_active=1):
Timothy Stack's avatar
 
Timothy Stack committed
921
    from emulabclient import RESPONSE_SUCCESS
Timothy Stack's avatar
 
Timothy Stack committed
922
    global OSIDS, SERVER
Timothy Stack's avatar
 
Timothy Stack committed
923 924 925 926 927 928
    
    retval = 0

    init_server()
    
    state_method = getattr(SERVER, "experiment.state")
Timothy Stack's avatar
 
Timothy Stack committed
929 930 931 932 933 934 935
    
    logdir = os.path.join(EXPDIR_FMT % { "PID" : PID, "EID" : EID }, "logs")

    fp = open(os.path.join(logdir, ".logholes"), "w")
    os.chmod(fp.name, 0664)
    fp.write(DOT_LOGHOLES)
    fp.close()
Timothy Stack's avatar
 
Timothy Stack committed
936 937 938 939 940 941 942

    state = state_method(PACKAGE_VERSION, { "proj" : PID, "exp" : EID })
    if state["code"] != RESPONSE_SUCCESS:
        sys.stderr.write("error: " + state["output"] + "\n")
        retval = 1
        pass
    elif state["value"] != "active":
Timothy Stack's avatar
 
Timothy Stack committed
943 944 945 946 947 948 949 950
        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
Timothy Stack's avatar
 
Timothy Stack committed
951 952 953
        pass
    else:
        info_method = getattr(SERVER, "experiment.info")
Timothy Stack's avatar
 
Timothy Stack committed
954 955
        osinfo_method = getattr(SERVER, "osid.info")

Timothy Stack's avatar
 
Timothy Stack committed
956 957 958 959 960
        physical = info_method(PACKAGE_VERSION, {
            "proj" : PID,
            "exp" : EID,
            "aspect" : "mapping",
            })
Timothy Stack's avatar
 
Timothy Stack committed
961 962 963 964 965 966

        delays = info_method(PACKAGE_VERSION, {
            "proj" : PID,
            "exp" : EID,
            "aspect" : "delays",
            })
Timothy Stack's avatar
 
Timothy Stack committed
967
        
Timothy Stack's avatar
 
Timothy Stack committed
968 969
        if ((physical["code"] != RESPONSE_SUCCESS) or
            (delays["code"] != RESPONSE_SUCCESS)):
Timothy Stack's avatar
 
Timothy Stack committed
970 971 972 973 974 975
            sys.stderr.write("error: xmlrpc failed - %s\n" %
                             (physical["output"],))
            retval = 1
            pass
        else:
            physical = physical["value"]
Timothy Stack's avatar
 
Timothy Stack committed
976 977
            delays = delays["value"]
            
Timothy Stack's avatar
 
Timothy Stack committed
978
            hosts = [(x["node"], x["name"]) for x in physical.values()
Timothy Stack's avatar
 
Timothy Stack committed
979 980 981
                     if ((x["erole"] == "virthost" or
                          x["erole"] == "node" or
                          x["erole"] == "delaynode") and
Timothy Stack's avatar
 
Timothy Stack committed
982 983 984 985 986 987 988 989 990 991 992
                         (x["status"] == "up" and x["eventstatus"] == "ISUP"))]

            phosts = sets.Set([x[0] for x in hosts])
            vhosts = sets.Set([x[1] for x in hosts])
            if len(args) == 0:
                args = vhosts
                pass

            known_nodes = sets.Set(args) & (phosts | vhosts)
            unknown_nodes = known_nodes ^ sets.Set(args)

Timothy Stack's avatar
 
Timothy Stack committed
993 994
            jobs = {}
            hoststatus = {}
Timothy Stack's avatar
 
Timothy Stack committed
995 996
            for phost, vhost in hosts:
                if (vhost in args) or (phost in args):
Timothy Stack's avatar
 
Timothy Stack committed
997 998 999
                    osid = physical[vhost]["osid"]
                    if osid not in OSIDS:
                        oi = osinfo_method(PACKAGE_VERSION, {
1000
                            "osid" : osid })
Timothy Stack's avatar
 
Timothy Stack committed
1001 1002 1003 1004 1005
                        if oi["code"] == RESPONSE_SUCCESS:
                            OSIDS[osid] = oi["value"]
                            pass
                        else:
                            OSIDS[osid] = None
Timothy Stack's avatar
 
Timothy Stack committed
1006 1007
                            pass
                        pass
1008

Timothy Stack's avatar
 
Timothy Stack committed
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
                    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"]]
                        if "ssh" not in vos["osfeatures"]:
                            if VERBOSITY > VERBOSITY_HUMAN:
                                sys.stderr.write("warning: %s OS, %s, does "
                                                 "not support ssh, skipping\n"
                                                 % (vhost, vos["osname"]))
                                pass
                            continue
                        pass

                    if mode == "pull":
                        pid = rsync(phost, os.path.join(logdir, vhost), "/")
                        pass
                    elif mode == "clean":
                        pid = rmstar(phost, "/local/logs/*")
                        pass
                    else:
                        assert 0
                    
                    jobs[pid] = vhost

                    try:
                        while len(jobs) == PARALLELIZATION:
                            pid, sts = os.waitpid(0, 0)
                            if pid in jobs:
                                hoststatus[jobs[pid]] = sts
                                del jobs[pid]
                                pass
                            pass
                        pass
                    except OSError:
                        pass
Timothy Stack's avatar
 
Timothy Stack committed
1046 1047 1048
                    pass
                pass

Timothy Stack's avatar
 
Timothy Stack committed
1049 1050 1051 1052 1053
            try:
                for job in jobs:
                    pid, sts = os.waitpid(job, 0)
                    hoststatus[jobs[pid]] = sts
                    pass
Timothy Stack's avatar
 
Timothy Stack committed
1054
                pass
Timothy Stack's avatar
 
Timothy Stack committed
1055 1056 1057
            except OSError:
                pass

Timothy Stack's avatar
 
Timothy Stack committed
1058 1059 1060 1061 1062 1063
            if len(unknown_nodes) > 0:
                for vhost in unknown_nodes:
                    sys.stderr.write("error: unknown node - %s\n" % vhost)
                    pass
                retval = 2
                pass
Timothy Stack's avatar
 
Timothy Stack committed
1064 1065 1066 1067 1068 1069 1070 1071 1072

            for vhost, sts in hoststatus.items():
                if sts not in ACCEPTABLE_RSYNC_STATUS:
                    sys.stderr.write("error: failed to sync with node '%s'\n" %
                                     vhost)
                    retval = 3
                    pass
                pass
            
Timothy Stack's avatar
 
Timothy Stack committed
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
            pass
        pass

    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
    
Timothy Stack's avatar
 
Timothy Stack committed
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
    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 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
            pass
        
        if len(args) == 0:
            raise getopt.error(
                'error: not enough arguments for "change" action.')
        pass
    except getopt.error, e:
        print e.args[0]
        change_usage()
        return 2

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

    for archive_name in args:
        if os.path.exists(archive_name):
            full_archive_name = archive_name
            pass
        else:
            full_archive_name = os.path.join(logdir, archive_name)
            pass
        if (not archive_name.endswith(".zip") and
            not os.path.exists(full_archive_name)):
            for ext in EXTENSIONS:
                tmp_name = full_archive_name + ext
                if os.path.exists(tmp_name):
                    full_archive_name = tmp_name
                    break
                pass
            if full_archive_name != tmp_name:
                print "error: bad archive name - " + archive_name
                continue
            pass

        lh, cp = open_loghole(full_archive_name, mode='a')

        if not lh:
            sys.stderr.write("error: %s is not a loghole archive\n" %
                             (archive_name,))
            continue

        try:
            lh.infolist().remove(lh.getinfo("loghole.cfg"))
            pass
        except:
            sys.stderr.write("warning: loghole.cfg is missing from %s\n" %
                             (archive_name,))
            pass

        # Change the meta-data.
        if keep_until:
            cp.set("MAIN", "keep-until", keep_until)
            pass
        if keep_atleast:
            cp.set("MAIN", "keep-atleast", keep_atleast)
            pass

        if keep_until or 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"
            
            lh.writestr(loghole_zi, cio.getvalue())
            pass
        
        # Add any comments.
        ct = time.localtime(time.time())
        for comment in comments:
            loghole_zi = zipfile.ZipInfo()
            loghole_zi.filename = uniquish_name(
                "loghole-comment",
                "txt",
                [x.filename for x in lh.infolist()])
            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"
            
            lh.writestr(loghole_zi, comment)
            pass
    
        if DEBUG:
            try:
                lh.printdir()
                pass
            except IOError:
                pass
            pass
    
        lh.close()
        
        if VERBOSITY >= VERBOSITY_HUMAN:
            print "Changed log hole archive: " + archive_name
            pass
        pass
    
    return retval

##
# Performs the "validate" action, which XXX
#
# @param args Action-specific command line arguments.
#
def do_validate(args):
    retval = 0

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

    

Timothy Stack's avatar
 
Timothy Stack committed
1380 1381
    return retval

Timothy Stack's avatar
 
Timothy Stack committed
1382 1383 1384 1385 1386 1387 1388 1389 1390
##
# Performs the "clean" action, which deletes logs from the experiment
# directory.
#
# @param args Action-specific command line arguments.
#
def do_clean(args):
    retval = 0

Timothy Stack's avatar
 
Timothy Stack committed
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
    force = 0
    do_nodes = 1
    do_experiment = 1
    confirm_msg = "Are you sure you want to remove ALL log files? [y/N] "

    # Parse action-specific options and arguments.
    try:
        opts, args = getopt.getopt(args, "fne", [
            "force", "nodes", "experiment", ])
        for opt, val in opts:
            if opt in ("-f", "--force"):
                force = 1
                pass
            elif opt in ("-n", "--nodes"):
                do_nodes = 1
                do_experiment = 0
                confirm_msg = ("Are you sure you want to remove log files on "
                               "the nodes? [y/N] ")
                pass
            elif opt in ("-e", "--experiment"):
                do_nodes = 0
                do_experiment = 1
                confirm_msg = ("Are you sure you want to remove log files "
                               "from the experiment log directory? [y/N] ")
                pass
            pass
        pass
    except getopt.error, e:
        print e.args[0]
        archive_usage()
        return 2

    if not force:
        line = raw_input(confirm_msg)
        if not (line.startswith("y") or line.startswith("Y")):
            return 0
        pass
    
Timothy Stack's avatar
 
Timothy Stack committed
1429 1430 1431
    logdir = os.path.join(EXPDIR_FMT % { "PID" : PID, "EID" : EID }, "logs")
    os.chdir(logdir)

1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    if do_experiment:
        for entry in os.listdir(logdir):
            entry = os.path.join(logdir, entry)
            if os.path.isdir(entry):
                for root, dirs, files in os.walk(entry, topdown=False):
                    for name in files:
                        os.remove(os.path.join(root, name))
                        pass
                    for name in dirs:
                        os.rmdir(os.path.join(root, name))
                        pass
Timothy Stack's avatar
 
Timothy Stack committed
1443
                    pass
1444
                os.rmdir(entry)
Timothy Stack's avatar
 
Timothy Stack committed
1445 1446 1447
                pass
            pass
        pass
1448 1449 1450 1451
    
    if do_nodes:
        do_sync(args, mode="clean", must_be_active=0)
        pass
Timothy Stack's avatar
 
Timothy Stack committed
1452

Timothy Stack's avatar
 
Timothy Stack committed
1453 1454
    return retval

Timothy Stack's avatar
 
Timothy Stack committed
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
##
# Performs the "gc" action, which garbage collects old/extra log files.
#
# @param args Action-specific command line arguments.
#
def do_gc(args):
    retval = 0

    keep_atmost = 100
    keep_size = 3.0
    dry_run = False
    
    try:
        opts, args = getopt.getopt(args, "nm:s:", [
            "dry-run", "keep-atmost=", "keep-size="
            ])
        for opt, val in opts:
            if 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
            elif opt in ("-n", "--dry-run"):
                dry_run = True
                pass
            pass
        
        if len(args) > 0:
            raise getopt.error(
                'error: too many arguments passed to "gc" action')
        pass
    except getopt.error, e:
        print e.args[0]
        gc_usage()
        return 2

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

    sa = sort_archives(keep_atmost, keep_size)

    if not dry_run:
        for file in sa["del"]:
            os.remove(file)
            pass
        pass

    if VERBOSITY == VERBOSITY_MACHINE:
        print "%s %s" % (str(reclaimed_size), str(inuse_size))
        pass
    elif VERBOSITY >= VERBOSITY_HUMAN:
        print ("Reclaimed %d bytes from %s/%s." %
               (sa["reclaimed-size"], PID, EID))
        print "%d bytes are still in %s/%s." % (sa["inuse-size"], PID, EID)
        pass
    
    return retval

def notimplemented():
    raise "loghole: not implemented yet"

ACTIONS = {
    "get" : (do_sync, sync_usage),
    "sync" : (do_sync, sync_usage),
    "archive" : (do_archive, archive_usage),
    "list" : (do_list, list_usage),
    "show" : (do_show, show_usage),
Timothy Stack's avatar
 
Timothy Stack committed
1535
    "change" : (do_change, change_usage),
Timothy Stack's avatar
 
Timothy Stack committed
1536
    "clean" : (do_clean, clean_usage),
Timothy Stack's avatar
 
Timothy Stack committed
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
    "gc" : (do_gc, gc_usage),
    }

exp_list = []

try:
    action = None
    all_experiments = False
    
    opts, req_args = getopt.getopt(sys.argv[1:],
                                   "hVdqve:aP:s:",
                                   [ "help",
                                     "version",
                                     "debug",
                                     "quiet",
                                     "verbose",
                                     "experiment=",
                                     "all",
                                     "port=",
                                     "server=", ])
    if len(req_args) > 0:
        action = req_args[0].lower()
        pass
    
    for opt, val in opts:
        if opt in ("-h", "--help"):
            if action in ACTIONS:
                ACTIONS[action][1]()
                pass
            else:
                usage()
                pass
            sys.exit()
            pass
        elif opt in ("-V", "--version"):
            print PACKAGE_VERSION
            sys.exit()
            pass
        elif opt in ("-d", "--debug"):
            DEBUG = DEBUG + 1
            pass
        elif opt in ("-q", "--quiet"):
            VERBOSITY = VERBOSITY - 1
            pass
        elif opt in ("-v", "--verbose"):
            VERBOSITY = VERBOSITY + 1
            pass
        elif opt in ("-e", "--experiment"):
            pair = val.split('/')
            if len(pair) == 2 and len(pair[0]) > 0 and len(pair[1]) > 0:
                exp_list.append(pair)
                pass
            else:
                raise getopt.error('error: -e argument is of the form pid/eid')
            pass
        elif opt in ("-a", "--all"):
            all_experiments = True
            pass
        elif opt in ("-P", "--port"):
            XMLRPC_PORT = int(val)
            pass
        elif opt in ("-s", "--server"):
            XMLRPC_SERVER = val
            pass
        else:
            assert False
            pass
        pass

    if len(req_args) < 1:
        raise getopt.error('error: too few arguments')

    action = req_args[0].lower()
    if action not in ACTIONS:
        raise getopt.error('error: unknown action - ' + req_args[0] + '\n'
                           'error: action must be one of: '
                           + str(ACTIONS.keys()))

    if all_experiments:
        exp_list.extend(get_explist())
        pass
    
    if len(exp_list) == 0:
        exp_list.append(infer_pid_eid(sys.argv[0], os.getcwd()))
        if not exp_list[0][0]:
            raise getopt.error(
                'error: -e argument was not given and the current directory\n'
                'error: is not in an experiment directory.')
        pass
    pass
except getopt.error, e:
    print e.args[0]
    usage()
    sys.exit(2)
    pass

for PID, EID in exp_list:
    if DEBUG:
        sys.stderr.write("loghole: pid/eid - " + PID + "/" + EID + "\n")
        pass
    
    rc = ACTIONS[action][0](req_args[1:])
    if rc != 0:
        sys.exit(rc)
        pass
    pass