protogeni.py 111 KB
Newer Older
1 2
#!/usr/bin/env python

3 4 5 6 7 8 9 10 11 12 13 14
"""
:mod:`elasticslice.rpc.protogeni` contains an object-based
implementation of the basic ProtoGeni test client-side python code, plus
several more useful classes for building client-side (i.e., slice- and
experiment-managing) ProtoGENI programs.  It requires geni-lib (i.e.,
the geni.* modules imported below).  Cloudlab maintains its own copy of
this repository which has the latest Cloudlab additions that may not
have made it upstream yet.  This library doesn't currently require those
additions; just FYI.  The Cloudlab repository can be found at
https://bitbucket.org/emulab/geni-lib/ ; the main repository is
https://bitbucket.org/barnstorm/geni-lib .
"""
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

import sys
import getopt
import os, os.path
import dircache
import pwd
import traceback
import syslog
import string
import BaseHTTPServer
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
import M2Crypto
from M2Crypto import SSL
from M2Crypto.SSL import SSLError
import base64
import threading
from urlparse import urlsplit, urlunsplit
from urllib import splitport
import httplib
import xmlrpclib
import zlib
import re
import threading
import select
import smtplib
from email.mime.text import MIMEText
import time
import socket
import hashlib
import pickle
45
import logging
46 47
import geni.rspec.pgmanifest
from geni.rspec.pgmanifest import Manifest as PGManifest
48
import geni.rspec.pgad as RSpecAd
49
from elasticslice.util.applicable \
50 51
  import ApplicableClass,ApplicableMethod,ApplicableFormatter, \
    get_default_formatter
52
import json as JSON
53

54
LOG = logging.getLogger(__name__)
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

HOME = os.getenv('HOME')
if HOME:
    CERTIFICATE     = HOME + "/.ssl/encrypted.pem"
    PASSPHRASEFILE  = HOME + "/.ssl/password"
    CACERTIFICATE     = HOME + "/.ssl/emulab-cacert.pem"
else:
    CERTIFICATE     = None
    PASSPHRASEFILE  = None
    CACERTIFICATE     = None
    
    import smtplib

SECOND = 1
MINUTE = SECOND * 60
HOUR   = MINUTE * 60
DAY    = HOUR * 24
MONTH  = DAY * 31
YEAR   = DAY * 365

# Ever tried time zones in python?  It sucks cause there's no zoneinfo
# by default.  And dateutil/pytz/whatever isn't everywhere.  So hack it.
____now = time.time()
__UTC_OFFSET = time.mktime(time.gmtime(____now)) \
                   - time.mktime(time.localtime(____now))

def GeniTimeStringToLocalTimeStamp(timestring):
82 83 84 85
    """
    :param timestring: a GENI time string (UTC)
    :return: a local UNIX time stamp
    """
86 87 88 89 90 91 92 93
    if timestring[-1] == 'Z':
        timestring = timestring[:-1]
        pass
    ts = time.strptime(timestring,"%Y-%m-%dT%H:%M:%S")
    utcstamp = time.mktime(ts)
    return utcstamp - __UTC_OFFSET

def LocalTimeStampToGeniTimeString(ts):
94 95 96 97
    """
    :param timestring: a local UNIX time stamp
    :return: a GENI time string (UTC)
    """
98 99 100
    utctt = time.mktime(ts + __UTC_OFFSET)
    return time.strftime("%Y-%m-%dT%H:%M:%S",utctt) + "Z"

101
def GeniTimeStampToLocalTimeStamp(ts):
102 103 104 105
    """
    :param timestring: a GENI (UTC) UNIX time stamp
    :return: a local UNIX time stamp
    """
106 107
    return ts - __UTC_OFFSET

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
##
## A utility function to send email to someone.
##
def SENDMAIL(To,Subject,Msg,From=None,headers=None):
    smsg = MIMEText(Msg)
    smsg['Subject'] = Subject
    if not From:
        smsg['From'] = os.getlogin() + "@" + socket.gethostname()
    else:
        smsg['From'] = From
    smsg['To'] = To
    if headers and len(headers.keys()) > 0:
        for (k,v) in headers.iteritems():
            smsg[k] = v
            pass
        pass
    
    sent = False
    try:
        # Send the message via our own SMTP server, but don't include the
        # envelope header.
        s = smtplib.SMTP('localhost')
        s.sendmail(smsg['From'],[smsg['To'],],smsg.as_string())
        s.quit()
        sent = True
    except:
134
        LOG.exception("direct mail send failed, trying sendmail")
135 136 137 138 139 140 141 142 143
        pass
    
    if not sent:
        try:
            stdin = os.popen("sendmail '%s'" % (To,),'w')
            stdin.write(smsg.as_string())
            stdin.close()
            sent = True
        except:
144
            LOG.exception("sendmail send failed")
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
            pass
        pass

    return True

##
## A helper function to read the passphrase for a private key.
##
def PassPhraseCB(v, prompt1='Enter passphrase:', prompt2='Verify passphrase:',
                 passphrasefile=PASSPHRASEFILE):
    """Acquire the encrypted certificate passphrase by reading a file
    or prompting the user.

    This is an M2Crypto callback. If the passphrase file exists and is
    readable, use it. If the passphrase file does not exist or is not
    readable, delegate to the standard M2Crypto passphrase
    callback. Return the passphrase.
    """
    if os.path.exists(passphrasefile):
        try:
            passphrase = open(passphrasefile).readline()
            passphrase = passphrase.strip()
            return passphrase
        except IOError, e:
169
            LOG.exception('Error reading passphrase file %s' % (passphrasefile,))
170
    else:
171
        LOG.warning('passphrase file %s does not exist' % (passphrasefile,))
172 173 174 175
    # Prompt user if passphrasefile does not exist or could not be read.
    from M2Crypto.util import passphrase_callback
    return passphrase_callback(v, prompt1, prompt2)

176 177 178 179
class InvalidArgumentError(Exception):
    pass

class RPCError(Exception):
180 181 182 183
    """
    Raised as an exception on XMLRPC method errors.  Encapsulates error
    information.
    """
184 185 186 187 188 189
    def __init__(self,rpcname,rval,response,msg=None):
        s = "Server returned error code %s while executing %s (%s)" \
            % (str(rval),rpcname,str(response))
        if msg:
            s += ": " + msg
            pass
190
        super(RPCError,self).__init__(s)
191 192 193 194 195
        self.rval = rval
        self.response = response
        pass
    pass

196 197 198 199
##
## Some useful codes that ProtoGeni API Servers can return.
##
class ProtoGeniClientDefs:
200 201 202
    """
    XMLRPC/HTTP return codes from a ProtoGeni server.
    """
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
    RESPONSE_SUCCESS        = 0
    RESPONSE_BADARGS        = 1
    RESPONSE_ERROR          = 2
    RESPONSE_FORBIDDEN      = 3
    RESPONSE_BADVERSION     = 4
    RESPONSE_SERVERERROR    = 5
    RESPONSE_TOOBIG         = 6
    RESPONSE_REFUSED        = 7  # Emulab is down, try again later.
    RESPONSE_TIMEDOUT       = 8
    RESPONSE_DBERROR        = 9
    RESPONSE_RPCERROR       = 10
    RESPONSE_UNAVAILABLE    = 11
    RESPONSE_SEARCHFAILED   = 12
    RESPONSE_UNSUPPORTED    = 13
    RESPONSE_BUSY           = 14
    RESPONSE_EXPIRED        = 15
    RESPONSE_INPROGRESS     = 16
    RESPONSE_ALREADYEXISTS  = 17
    RESPONSE_VLAN_UNAVAILABLE = 24
    RESPONSE_INSUFFICIENT_BANDWIDTH  = 25
    RESPONSE_INSUFFICIENT_NODES      = 26
    RESPONSE_INSUFFICIENT_MEMORY     = 27
    RESPONSE_NO_MAPPING              = 28
    RESPONSE_NOT_IMPLEMENTED         = 100
    RESPONSE_SERVER_UNAVAILABLE = 503
    pass

##
## Hacks for better control over cert validation in M2Crypto.  We have
## this unusual situation, where the protogeni client has a server (to
## which protogeni daemons might call RPCs on, i.e. to notify), but is
## not a real server.  They've only got their user cert, and the ca cert
## of the SA (Emulab).  This user cert uses the CN for user info, not
## hostname info.  So we have to elide that check.  M2Crypto does not
## make this easy to do properly, so we hack.
##
class NoHostChecker(M2Crypto.SSL.Checker.Checker):
    def __call__(self, peerCert, host=None):
241
        LOG.debug("Using NoHostChecker")
242
        val = M2Crypto.SSL.Checker.Checker.__call__(self,peerCert,None)
243
        LOG.debug("Used NoHostChecker: %s" % str(val))
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
        return val
    pass

class NoHostCheckHTTPSConnection(M2Crypto.httpslib.HTTPSConnection):
    #
    # Have to change out the cert checker after the Connection is created but
    # before .connect() happens!  Ugh, this is sick.  So, steal the code, but
    # replace the checker in the Connection object.
    #
    def connect(self):
        self.sock = M2Crypto.SSL.Connection(self.ssl_ctx)
        self.sock.clientPostConnectionCheck = NoHostChecker()
        if self.session:
            self.sock.set_session(self.session)
        self.sock.connect((self.host, self.port))
        pass
    pass

##
## These are the default Component Managers we know about.  You can
## extend or replace this list when you construct a ProtoGeniClient
## object.
##
DEFAULT_CMS = {
    "apt" : "https://boss.apt.emulab.net:12369/protogeni/xmlrpc",
    "clutah" : "https://www.utah.cloudlab.us:12369/protogeni/xmlrpc",
    "clemson" : "https://www.clemson.cloudlab.us:12369/protogeni/xmlrpc",
    "wisc" : "https://www.wisc.cloudlab.us:12369/protogeni/xmlrpc",
    "emulab" : "https://www.emulab.net:12369/protogeni/xmlrpc",
}

275
def parse_cm_list(cmliststr):
276 277
    if str is None:
        return
278 279 280 281 282 283 284 285 286 287
    retval = []
    cmlist = cmliststr.split(',')
    for cm in cmlist:
        if not cm in DEFAULT_CMS:
            raise Exception("cm %s not in DEFAULT_CMS (%s)"
                            % (cm,DEFAULT_CMS))
        retval.append(cm)
        pass
    return retval

288
def parse_bool(str):
289 290
    if str is None:
        return
291 292 293 294 295
    str = str.lstrip(' ').rstrip(' ')
    if str in ['True','TRUE','true','1','yes','YES','Yes']:
        return Truef
    return False

296 297 298 299 300 301 302 303
def parse_str_list(str):
    if str is None:
        return
    str = str.lstrip(' ').rstrip(' ')
    if str == '':
        return []
    return str.split(',')

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
def parse_rspec_arg(_rspec):
    try:
        from lxml import etree as ET
        ET.fromstring(_rspec)
        return _rspec
    except:
        pass
    try:
        f = open(_rspec,'r')
        return f.read()
    except:
        LOG.warn("rspec argument does not appear to be XML nor a file;"
                 " but assuming it is indeed XML!")
        return _rspec
    pass

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
#
# By default, adjust our credential caching time by this much to give a
# little slop to make sure we can renew the credential.
#
DEFAULT_CREDENTIAL_EXPIRATION_BUFFER = 6 * HOUR
#
# If we're caching a method result, but we don't have a more specific
# cache time or cache expiration function, use this time.
#
DEFAULT_METHOD_CACHE_INTERVAL = 5 * MINUTE
DEFAULT_METHOD_CACHE_TIMES = {
    'sa' : { 'Resolve' : HOUR,
             'GetKeys' : YEAR,
             'GetCredential' : 5 * MINUTE, # credential_cache_func,
             'DiscoverResources' : HOUR,
        },
    'cm' : { 'Resolve' : HOUR,
             'DiscoverResources' : 10 * MINUTE,
             'SliverStatus' : 2 * MINUTE,
        }
    }

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
class Credential(object):
    def __init__(self,credential):
        self.credential = credential
        pass
    pass

class SelfCredential(Credential):
    def __init__(self,credential):
        super(SelfCredential,self).__init__(credential)
        pass
    pass

class SliceCredential(Credential):
    def __init__(self,credential):
        super(SliceCredential,self).__init__(credential)
        pass
    pass

class SelfCredential(Credential):
    def __init__(self,credential):
        super(SelfCredential,self).__init__(credential)
        pass
    pass


class Slice(object):
    def __init__(self,urn,uuid,creator_uuid,creator_urn,gid,
                 component_managers):
        self.urn = urn
        self.uuid = uuid
        self.creator_uuid = creator_uuid
        self.creator_urn = creator_urn
        self.gid = gid
        self.component_managers = component_managers
        pass
    pass

class Sliver(object):
    def __init__(self,):

        pass
    pass

class User(object):
    def __init__(self,uid,hrn,uuid,email,gid,name):
        self.uid = uid
        self.hrn = hrn
        self.uuid = uuid
        self.email = email
        self.gid = gid
        self.name = name
        pass
    pass

396
@ApplicableClass()
397
class ProtoGeniServer(object):
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    """A ProtoGeniServer is a class that provides a client user with the
    ability to call RPCs at ProtoGENI SA (slice authority) and CM
    (component manager) (aka AM -- aggregate manager) servers.  In the
    Cloudlab/PG world, Emulab central is the SA, and the various
    clusters are CM/AMs.  This client helps you create a slice at an SA
    (defaults to Emulab, or whomever issued your certificate), then
    create slivers at one or more CM/AMs by submitting an RSpec to each
    cluster.  An RSpec describes the resources you want allocated and
    how they're configured/connected.
  
    It is a generic class that lets you directly invoke PG/GENI methods
    on a CH, SA, AM, CM; but it also provides wrappers for key functions
    on ProtoGENI's SA and CM interfaces.  It creates an XMLRPC
    connection for each RPC you invoke, although it attempts to cache
    credentials and state from your previous RPCs, and only renew those
    things as necessary.
    
    Some of the methods cache results for you.  Some RPCs are very
    heavyweight (i.e. DiscoverResources), and you just don't need to
    refresh the resource list all that often.  However, you may want to
    review the information it contains more regularly, and only refresh
    periodically or in exceptional cases.  The caching infrastructure
    helps with this pattern.  Generally speaking, the rule is that any
    RPCs that modify resources or state on the server are not cached;
    whereas requests for information *are* cached.  Any method that
    caches an RPC's result has several keyword args (i.e., force,
    cache_notifier) that help you interact with the cache usefully.
    Finally, the cache persists itself by default to
    HOME/.protogeni/cache .
    
    Finally, this server stub can be multithreaded; it locks itself to
    prevent parallel invocation of certain methods.  Right now it uses
    one big lock; this should be broken out into a cache lock, and locks
    for each RPC endpoint URI.  This may seem stupid, but we really want
    to reduce weird things happening (i.e., two parallel CM.AddNodes
    calls on the same slice, or two parallel CM.SliverStatus calls that
    duplicate work).
    """
    
437 438
    def __init__(self,config=None,
                 cert=CERTIFICATE,passphrasefile=PASSPHRASEFILE,
439 440 441 442
                 cacert=None,noCertHostChecking=False,
                 endpoints={},devuser=None,slicename=None,sliceurn=None,
                 cms=DEFAULT_CMS,default_cm='emulab',cmuri=None,sauri=None,
                 speaksforcredential=None,
443
                 fscache=True,fscachedir=None,
444 445
                 cache_times=DEFAULT_METHOD_CACHE_TIMES,nolock=False):
        """
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        :param cert: Your GENI user certificate.  It should be encrypted, and you'll need to supply a passphrase.  Defaults to ~/.ssl/encrypted.pem .
        :param passphrasefile: If you place your certificate passphrase into a file and tell the constructor, you won't be prompted to enter your password all the time.
        :param cacert: The certificate authority who issued your cert.  Defaults to ~/.ssl/@<default_cm>-cacert.pem .
        :param default_cm: The CM to use by default (if none is specified to any of the CM API wrapper functions via cm= keyword arg)
        :param noCertHostChecking: Usually, when certs are verified during SSL session establishment, the CN field is checked for a matching hostname.  This should only be disabled if you're trying to talk to a server that doesn't have a real certificate -- or a server that is using a GENI identity cert as its certificate.
        :param endpoints: A dictionary of endpoint types to endpoint URL information. This is useful if you would like to use a non-default SA, CH, etc.
        :param devuser: If you want to invoke RPCs through an Emulab developer's development tree, provide the dev's loginuid here, and it will get added to RPC URLs in the right way.
        :param slicename: The HRN of the "default" slice that will be used in any RPCs for which a slicename is required and not supplied in that call.
        :param sliceurn: The URN of the "default" slice that will be used in any RPCs for which a slicename is required and not supplied in that call.
        :param cms: A dict of known CMs; defaults to protogeniclientlib.DEFAULT_CMS.
        :param default_cm: The default cm to use for CM RPCs when one isn't specified as a method argument.  Must be a key in @cms.
        :param cmuri: Provide a custom CM URI here instead of filling out cms.  If this is set, it will become your @default_cm (with a name of "custom").
        :param sauri: Provide a custom SA URI here.
        :param speaksforcredential: A credential of a GENI user on whose behalf you are invoking RPCs.
        :param fscache: Should we cache method results to the filesystem; True or False
        :param fscachedir: The location of the fscache; defaults to HOME/.protogeni/cache
        :param cache_times: A dict of SA/CM RPCs to cache times in seconds; defaults to DEFAULT_METHOD_CACHE_TIMES.
        :param nolock: Set this to true if you don't want any locking.
464
        """
465 466 467

        super(ProtoGeniServer,self).__init__()

468 469 470 471 472 473 474 475 476 477 478
        self.config = config
        self.cert = (config and config.cert) or cert
        if self.cert[0] == '~':
            self.cert = HOME + "/" + self.cert[1:]
        self.passphrasefile = (config and config.passphrasefile) or passphrasefile
        if self.passphrasefile[0] == '~':
            self.passphrasefile = HOME + "/" + self.passphrasefile[1:]
        self.cacert = (config and config.cacert) or cacert
        if self.cacert[0] == '~':
            self.cacert = HOME + "/" + self.cacert[1:]
        self.noCertHostChecking = (config and config.nocerthostchecking) or noCertHostChecking
479
        self.endpoints = endpoints
480 481
        self.devuser = (config and config.devuser) or devuser
        self.slicename = (config and config.slicename) or slicename
482 483
        if not self.slicename:
            raise InvalidArgumentError("no default slicename specified!")
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
        self.sliceurn = sliceurn
        
        self.user_urn = None
        self.user_email = None
        self.cert_x509 = M2Crypto.X509.load_cert(self.cert)
        subject_alt_name = self.cert_x509.get_ext('subjectAltName').get_value()
        ss = subject_alt_name.find("urn:")
        if ss >= 0:
            sc = subject_alt_name[ss:].find(',')
            if sc >= 0:
                self.user_urn = subject_alt_name[ss:(ss+sc)]
            else:
                self.user_urn = subject_alt_name[ss:]
            pass
        ss = subject_alt_name.find("email:")
        if ss >= 0:
            ss += 6
            sc = subject_alt_name[ss:].find(',')
            if sc >= 0:
                self.user_email = subject_alt_name[ss:(ss+sc)]
            else:
                self.user_email = subject_alt_name[ss:]
            pass

        self.cms = cms
509 510
        self.default_cm = (config and config.default_cm) or default_cm
        self.cmuri = (config and config.cmuri) or cmuri
511 512 513 514 515 516 517
        if cmuri is not None:
            self.default_cm = 'custom'
            if cms is None:
                self.cms = {}
                pass
            self.cms['custom'] = self.cmuri
            pass
518
        self.sauri = (config and config.sauri) or sauri
519 520 521 522 523 524 525 526 527 528
        
        if not self.cacert:
            if not self.default_cm:
                self.cacert = CACERTIFICATE
            elif HOME:
                self.cacert = HOME + "/.ssl/%s-cacert.pem" % (self.default_cm,)
            else:
                self.cacert = None
            pass
        
529
        if self.default_cm and not cms.has_key(self.default_cm):
530
            raise InvalidArgumentError("cannot specify a default cm not in cms!")
531
        if self.cmuri is not None and self.default_cm is not None:
532
            raise InvalidArgumentError("cannot specify both a custom CM URI and a default cm!")
533
        
534 535 536 537 538 539 540 541 542 543 544
        self.selfcredential = None
        self.selfcredential_expiration = None
        self.selfcredential_expiration_str = None
        
        self.cache = {}
        self.cache_times = cache_times
        self.fscache = fscache
        self.fscachedir = fscachedir
        if not self.fscachedir:
            self.fscachedir = os.getenv('HOME') + '/.protogeni/cache'
            pass
545 546 547 548 549 550 551 552
        elif self.fscachedir[0] == '~':
            self.fscachedir = HOME + "/" + self.fscachedir[1:]
        if not os.path.exists(self.fscachedir):
            try:
                os.makedirs(self.fscachedir)
            except:
                LOG.exception("could not create cache dir %s" % (self.fscachedir))
                pass
553 554 555 556 557 558 559 560 561 562 563
            pass
        
        self.speaksforcredential = speaksforcredential

        self.locking = not nolock
        if self.locking:
            self.lock = threading.RLock()
        else:
            self.lock = None
            pass

564
        LOG.debug("default_cm = %s" % (self.default_cm,))
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

        #
        # Configure our endpoints.  By default, we assume this is a client of
        # a ProtoGENI/GENI server, although even the default config tries to
        # learn from the user's cert.
        #
        if not endpoints or len(endpoints.keys()) == 0:
            self.endpoints = {}
            # XMLRPC server: use www.emulab.net for the clearinghouse.
            self.endpoints['ch'] = { "host":"www.emulab.net",
                                     "port":12369,"path":"/protogeni/xmlrpc" }
            self.endpoints["sr"] = { "host" : "www.emulab.net","port":12370,
                                     "path":"/protogeni/pubxmlrpc" }
            pass
        else:
            self.endpoints = {}
            pass

        if not self.endpoints.has_key("default"):
            try:
                cert = M2Crypto.X509.load_cert(self.cert)
                extension = cert.get_ext("authorityInfoAccess")
                val = extension.get_value()
                if val.find('URI:') > 0:
                    url = val[val.find('URI:')+4:]
                url = url.rstrip()
                # strip trailing sa
                if url.endswith('/sa') > 0:
                    url = url[:-3]
                    pass
                scheme, netloc, path, query, fragment = urlsplit(url)
                host,port = splitport(netloc)
                self.endpoints["default"] = { "host":host,"port":port,
                                              "path":path }
            except LookupError, err:
600 601
                LOG.exception("Error while loading certificate %s to get"
                              " default endpoint" % (self.cert,))
602 603 604 605 606 607 608 609
                pass

            if "default" not in self.endpoints and cert is not None:
                self.endpoints["default"] = { "host":cert.get_issuer().CN,
                                              "port":443,
                                              "path":"/protogeni/xmlrpc", }
                pass
            
610
            LOG.debug("Default endpoint: %s" % (str(self.endpoints["default"]),))
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
            pass
        
        #
        # Try to build our slice URN
        #
        if not self.sliceurn and self.slicename:
            if "sa" in self.endpoints and "host" in self.endpoints["sa"]:
                hn = self.endpoints["sa"]["host"]
            elif "default" in self.endpoints and "host" in self.endpoints["default"]:
                hn = self.endpoints["default"]["host"]
            else:
                hn = None
                pass
            if hn:
                domain = hn[hn.find('.')+1:]
                self.sliceurn = "urn:publicid:IDN+" + domain + "+slice+" + self.slicename
                pass
            pass
        
        pass
    
    def __get_lock(self):
        if self.locking:
            self.lock.acquire()
        pass
    
    def __put_lock(self):
        if self.locking:
            self.lock.release()
        pass
    
    def __cache_get(self,key,accept_stale=False):
        self.__get_lock()
        
        value = None
        if self.cache.has_key(key):
            cur_time = time.time()
            if accept_stale \
                or self.cache[key]['xtime'] > cur_time:
                # This version returns the whole thing
                value = self.cache[key]
                pass
            pass
        
        self.__put_lock()

657 658 659 660
        if value:
            LOG.debug("CACHE: found %s" % (key,))
        else:
            LOG.debug("CACHE: did not find %s" % (key,))
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
            pass
        
        return value
    
    def _cache_get(self,uri,module,method,version,params,accept_stale=False,
                   cache_notifier=None):
        # Set up the key for lookup
        key = "|uri=%s||module=%s||method=%s|version=%s|" \
            % (str(uri),str(module),str(method),str(version),)
        for (k,v) in params.iteritems():
            key += "|%s=%s|" % (str(k),str(v),)
            pass
        
        value = self.__cache_get(key,accept_stale=accept_stale)
        if cache_notifier:
            cache_notifier.reset()
            if not value:
                cache_notifier.cached = False
            else:
                cache_notifier.cached = True
                cache_notifier.expires = value['xtime']
                cache_notifier.key = key
                cache_notifier.updated = False
                pass
            pass
        
        if value:
            value = value['value']
        
        return value
    
    def __cache_add(self,key,value,ctime=time.time(),xtime=None,
                    cache_notifier=None):
        self.__get_lock()
        
David Johnson's avatar
David Johnson committed
696 697 698 699 700
        updated = False
        if key in self.cache:
            updated = True
            pass
        
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
        if not xtime:
            xtime = time.time() + DEFAULT_METHOD_CACHE_INTERVAL
            pass
        
        self.cache[key] = { 'value':value,'ctime':ctime,'xtime':xtime }
        
        if self.fscache:
            h = hashlib.md5(key).hexdigest()
            kf = file("%s/%s.key" % (self.fscachedir,h),'w')
            vf = file("%s/%s.value" % (self.fscachedir,h),'w')
            cf = file("%s/%s.ctime" % (self.fscachedir,h),'w')
            xf = file("%s/%s.xtime" % (self.fscachedir,h),'w')
            cf.write(str(ctime))
            cf.close()
            xf.write(str(xtime))
            xf.close()
            kf.write(key)
            kf.close()
            pickle.dump(value,vf)
            vf.close()
            pass
        
        if cache_notifier:
            cache_notifier.reset()
            cache_notifier.cached = False
            cache_notifier.expires = xtime
            cache_notifier.key = key
David Johnson's avatar
David Johnson committed
728
            cache_notifier.updated = updated
729 730 731 732
            pass
        
        self.__put_lock()
        
733 734 735 736
        LOG.debug("CACHE: added key %s at %s (expires %s, duration %.4f hrs,"
                  " remaining %.4f hrs)"
                  % (key,str(ctime),str(xtime),(xtime - ctime)/HOUR,
                     (xtime - time.time())/HOUR))
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
        pass
    
    def _cache_add(self,uri,module,method,version,params,value,
                   ctime=time.time(),xtime=None,cache_notifier=None):
        key = "|uri=%s||module=%s||method=%s|version=%s|" \
            % (str(uri),str(module),str(method),str(version),)
        for (k,v) in params.iteritems():
            key += "|%s=%s|" % (str(k),str(v),)
            pass
        
        if not xtime:
            xtime = ctime + DEFAULT_METHOD_CACHE_INTERVAL
            if self.cache_times.has_key(module) \
                and self.cache_times[module].has_key(method):
                xtime = ctime + self.cache_times[module][method]
                pass
            pass
        
        self.__cache_add(key,value,ctime,xtime,cache_notifier=cache_notifier)
        pass
    
    def _cache_delete(self,uri,module,method,version,params):
        # Assemble a list of cache key tags to filter over; all have to
        # be matched for a particular key to be deleted.
        dkeys = []
        if uri:
            dkeys.append("|uri=%s|" % (str(uri),))
        if module:
            dkeys.append("|module=%s|" % (str(module),))
        if method:
            dkeys.append("|method=%s|" % (str(method),))
        if version:
            dkeys.append("|version%s|" % (str(version),))
        if params:
            for (k,v) in params.iteritems():
                dkeys.append("|%s=%s|" % (str(k),str(v),))
                pass
            pass
        
        self.__get_lock()

        # Assemble a list of matching cache keys.
        deletes = []
        for k in self.cache.keys():
            allfound = True
            for dk in dkeys:
                if k.find(dk) < 0:
                    allfound = False
                    break
                pass
            if not allfound:
                deletes.append(k)
                pass
            pass
        
        # Delete the matching cache keys.
        for dk in deletes:
            del self.cache[dk]
            pass
        
        self.__put_lock()
        
        pass
    
    def _cache_load(self):
        if not self.fscache:
            return None
        
805
        cn = self.get_cache_notifier()
806
        
807
        LOG.debug("CACHE: loading cache...")
808 809 810 811 812 813
        cur_time = time.time()
        if not self.fscache:
            return None
        dls = dircache.listdir(self.fscachedir)
        if not dls:
            return
814
        LOG.debug("CACHE: files %s" % (" ".join(dls),))
815 816 817 818
        for filename in dls:
            try:
                if not filename.endswith(".ctime"):
                    continue
819
                LOG.debug("CACHE: considering file %s" % filename,)
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
                idx = filename.rfind('.')
                h = filename[:idx]
                kf = open("%s/%s.key" % (self.fscachedir,h))
                vf = open("%s/%s.value" % (self.fscachedir,h))
                cf = open("%s/%s.ctime" % (self.fscachedir,h))
                xf = open("%s/%s.xtime" % (self.fscachedir,h))
                key = kf.read()
                kf.close()
                value = pickle.load(vf)
                vf.close()
                ctime = float(cf.read())
                cf.close()
                xtime = float(xf.read())
                xf.close()
                
                if cur_time > xtime:
836
                    LOG.debug("CACHE: removing stale file %s" % (filename,))
837 838 839 840 841 842 843
                    # Delete stale entries
                    unlink(vf.name)
                    unlink(cf.name)
                    unlink(xf.name)
                    unlink(kf.name)
                    pass
                else:
844
                    LOG.debug("CACHE: adding file %s" % (filename,))
845 846 847 848 849 850 851 852 853 854 855 856 857 858
                    self.__cache_add(key,value,ctime,xtime)
                    pass
            except:
                pass
            pass
        pass
    
    def loadCache(self):
        """
        Loads the persistent disk cache of RPC results; removes expired values.
        """
        try:
            return self._cache_load()
        except:
859
            LOG.exception("could not load cache dir %s:" % (self.fscachedir,))
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
            return None
        pass
    
    def geni_am_response_handler(method, method_args):
        """
        Handles the GENI AM responses, which are different from the
        ProtoGENI responses. ProtoGENI always returns a dict with three
        keys (code, value, and output. GENI AM operations return the
        value, or an XML RPC Fault if there was a problem.
        """
        return apply(method, method_args)

    def geni_sr_response_handler(method, method_args):
        """
        Handles the GENI SR responses, which are different from the
        ProtoGENI responses. ProtoGENI always returns a dict with three
        keys (code, value, and output). GENI SR operations return the
        value, or an XML RPC Fault if there was a problem.
        """
        return apply(method, method_args)
    
    def _passphrase_callback(self,v,prompt1=None,prompt2=None):
        args = { 'passphrasefile':self.passphrasefile }
        if prompt1:
            args["prompt1"] = prompt1
        if prompt2:
            args["prompt2"] = prompt2
        return PassPhraseCB(v,**args)
    
    class CacheNotifier(object):
        """
        A simple cache notifier object, to tell the caller (if it cares)
        whether the return value is cached, is new, and when it expires.
        """
        def __init__(self,server):
895 896 897
            """
            :param server: The :class:`ProtoGeniServer` instance object this CacheNotifier belongs to.
            """
898
            self.server = server
899
            """The :class:`ProtoGeniServer` instance object this CacheNotifier belongs to."""
900
            self.key = None
901
            """The key for this cached value."""
902
            self.cached = False
903
            """True if this value was cached; False if not."""
904
            self.updated = False
905
            """True if this value was updated as a result of the operation associated with this CacheNotifier; False if not."""
906
            self.expires = None
907
            """The expiration timestamp of this cached value."""
908 909 910
            pass
        
        def reset(self):
911 912 913 914 915
            """
            Resets all fields (except `server`) to constructor defaults.

            :return: `self` (a convenience so you can reuse the object trivially by passing ``cache_notifier=notifier.reset()`` to a caching :class:`ProtoGeniServer` method)
            """
916 917 918 919
            self.key = None
            self.cached = False
            self.updated = False
            self.expires = None
920
            return self
921 922 923 924
        
        pass

            
925
    def get_cache_notifier(self):
926
        """
927 928 929 930 931
        :return: a :class:`ProtoGeniServer.CacheNotifier` object that
        can be passed to any :class:`ProtoGeniServer` method that takes
        a `cache_notifier` parameter, to be notified if the return value
        was cached (if not cached, it's new), and when it expires from
        the cache.
932 933 934 935 936 937 938
        """
        return ProtoGeniServer.CacheNotifier(self)
    
    def do_method(self,module,method,params,URI=None,quiet=False,version=None,
                  response_handler=None,cm=None,
                  force=False,cache=False,cache_accept_stale=False,
                  cache_add_params=[],cache_destroy_params=[],
939
                  cache_destroy_extra=[],cache_replace_info=None,
940 941 942
                  cache_notifier=None,cache_expire_func=None):
        """
        Invoke an RPC.
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
        
        :param module: The RPC server module to invoke `method` within; sa, cm, dynslice, etc.
        :param method: The RPC method to invoke.
        :param params: A dict of params to pass to the method invocation.
        :param URI: A custom URI to use; if not supplied, the full URI is constructed based on the specified @module and @cm.
        :param version: Specify the version of the module/method being invoked (i.e., a str like "2.0"
        :param cm: Call this method on a specific CM; defaults to self.default_cm.
        :param force: Don't simply return a cached value even if a valid, unexpired value exists in the cache; call the method on the server.
        :param cache: True if the caller of do_method wants the result cached.  This is typically used by our method wrappers below to cache values.
        :param cache_accept_stale: True if the caller will accept a stale value.
        :param cache_notifier: A CacheNotifier object; caller can set this to find out if the response was already cached; if it was updated; and when it expires; these metadata are useful in the caller's decision of when to next call a particular method.
        :param cache_add_params,cache_destroy_params,cache_destroy_extra,cache_replace_info: These all control how the value is cached, uncached, or if it triggers destruction or replacement of other cached values.  For instance, calling DeleteSlice at a CM should remove the result of any prior SliverStatus call.  This is complicated to use and should only be used by this class's wrapper functions.
        :param cache_expire_func: A function that is applied to the response from the RPC server to determine its expiration time.  For instance, we use this to extract the expiration time of credentials so that we can age them out in accordance with their expiration time.  Like the arguments above, this should only be called by wrapper functions in this class.
        
        :returns: An (rval,response) tuple.  The rval is a ProtoGeniClientDefs response code; the response is a dict containing a 'value' key/value, whose value is the output from the RPC.
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
        """
                  
        #
        # Add speaksforcredential for credentials list.
        #
        if "credentials" in params and self.speaksforcredential:
            if 1 or type(params["credentials"]) is tuple:
                params["credentials"] = list(params["credentials"])
                pass
            params["credentials"].append(self.speaksforcredential);
            pass
        
        if URI == None and (module == "cm" or module == "cmv2"
                            or module == 'dynslice'):
            if cm:
                URI = self.cms[cm]
            else:
                URI = self.cms[self.default_cm]
                pass
        elif URI == None and self.sauri and module == "sa":
            URI = self.sauri

        # Save the cache URI -- it's the URI without the module/version
        # info.
        cache_uri = URI
        
        userstr = None
        if URI == None:
            if module in self.endpoints and "host" in self.endpoints[module]:
                addr = self.endpoints[module]["host"]
            else:
                addr = self.endpoints["default"]["host"]
            if module in self.endpoints and "port" in self.endpoints[module]:
                port = self.endpoints[module]["port"]
            else:
                port = self.endpoints["default"]["port"]
            if module in self.endpoints and "path" in self.endpoints[module]:
                path = self.endpoints[module]["path"]
            else:
                path = self.endpoints["default"]["path"]
                
            if module in self.endpoints \
                and "user" in self.endpoints[module] \
                and "pass" in self.endpoints[module]:
                userstr = "%s:%s" % (self.endpoints[module]["user"],
                                      self.endpoints[module]["pass"],)
            elif "user" in self.endpoints["default"] \
                and "pass" in self.endpoints["default"]:
                userstr = "%s:%s" % (self.endpoints["default"]["user"],
                                     self.endpoints["default"]["pass"],)
                pass

            URI = "https://" + addr + ":" + str(port) + path
            cache_uri = URI
            URI += "/" + module
        elif module:
            URI = URI + "/" + module
            pass

        if version:
            URI = URI + "/" + version
            pass

        url = urlsplit(URI, "https")
    
        if self.devuser and url.path.startswith("/protogeni/"):
            upath = url.path.replace("/protogeni/",
                                     "/protogeni/" + self.devuser + "/")
            url = url._replace(path=upath)

1028
        LOG.debug("URL: %s || %s" % (str(url),method))
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
        
        #
        # Maybe get the value from the cache
        #
        if cache and not force:
            if len(cache_add_params) == 0:
                cparams = params
            else:
                # Filter according to the specific cache params
                cparams = {}           
                for p in params.keys():
                    if p in cache_add_params:
                        cparams[p] = params[p]
                        pass
                    pass
                pass
            value = self._cache_get(cache_uri,module,method,version,cparams,
                                    accept_stale=cache_accept_stale,
                                    cache_notifier=cache_notifier)
            if value is not None:
                return value
            pass

        if url.scheme == "https":
            if not os.path.exists(self.cert):
1054
                LOG.error("missing emulab certificate: %s" % (self.cert,))
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
                return (-1, None)

            port = url.port if url.port else 443

            ctx = M2Crypto.SSL.Context("sslv23")
            ctx.load_cert_chain(self.cert,self.cert,self._passphrase_callback)
            #ctx.load_client_CA(self.cacert)
            #ctx.load_verify_info(self.cacert)
            #ctx.load_verify_info(cert) #,callback=PassPhraseCB)
            #ctx.set_verify(SSL.verify_fail_if_no_peer_cert | SSL.verify_peer, 16)
            #ctx.set_verify(M2Crypto.SSL.verify_none, 16)
            ctx.set_allow_unknown_ca(0)
    
            if self.noCertHostChecking:
                server = NoHostCheckHTTPSConnection(url.hostname,port,
                                                    ssl_context=ctx)
            else:
                server = M2Crypto.httpslib.HTTPSConnection(url.hostname,port,
                                                           ssl_context=ctx)
                pass
        elif url.scheme == "http":
            port = url.port if url.port else 80
            server = httplib.HTTPConnection(url.hostname,port)
            
        headers = {}
        if userstr:
            headers["Authorization"] = "Basic %s" % (base64.b64encode(userstr).decode("ascii"),)
            pass
        
        if response_handler:
            # If a response handler was passed, use it and return the result.
            # This is the case when running the GENI AM.
            def am_helper(server, path, body):
                server.request("POST", path, body)
                return xmlrpclib.loads(server.getresponse().read())[ 0 ][ 0 ]
            
            return response_handler((lambda *x: am_helper(server, url.path, xmlrpclib.dumps(x, method))), params)

        #
        # Make the call. 
        #
1096 1097 1098 1099 1100 1101 1102 1103
        if LOG.isEnabledFor(logging.DEBUG):
            lparams = dict(params)
            if 'credential' in lparams and len(lparams['credential']) > 64:
                lparams['credential'] = lparams['credential'][:32] + "<<<...>>>" + lparams['credential'][-32:]
            if 'credentials' in lparams and len(str(lparams['credentials'])) > 64:
                lparams['credentials'] = str(lparams['credentials'])[:32] + "<<<...>>>" + str(lparams['credentials'])[-32:]
            LOG.debug("REQUEST: %s %s(%s)" % (str(url),str(method),str(lparams)))
            pass
1104 1105 1106 1107 1108 1109
        while True:
            try:
                server.request("POST",url.path,xmlrpclib.dumps((params,),method),
                               headers=headers)
                response = server.getresponse()
                if response.status == 503:
1110
                    LOG.warning("Status 503; will try again in a few seconds...")
1111 1112 1113
                    time.sleep(5.0)
                    continue
                elif response.status != 200:
1114 1115
                    LOG.warning("Status %d: %s"
                                % (response.status,response.reason))
1116 1117 1118 1119
                    return (-1,None)
                response = xmlrpclib.loads(response.read())[ 0 ][ 0 ]
                break
            except httplib.HTTPException, e:
1120
                LOG.exception("http error")
1121 1122 1123
                return (-1, None)
            except xmlrpclib.Fault, e:
                if e.faultCode == 503:
1124
                    LOG.error("HTTP %s, retrying" % (e.faultString,))
1125
                    time.sleep(5.0)
1126 1127
                    continue
                LOG.error("HTTP %s, aborting" % (e.faultString,))
1128 1129
                return (-1, None)
            except M2Crypto.SSL.Checker.WrongHost, e:
1130
                LOG.exception("certificate host name mismatch (consult http://www.protogeni.net/trac/protogeni/wiki/HostNameMismatch)")
1131 1132 1133 1134 1135 1136 1137
                return (-1, None)

        #
        # Parse the Response, which is a Dictionary. See EmulabResponse in the
        # emulabclient.py module. The XML standard converts classes to a plain
        # Dictionary, hence the code below. 
        # 
1138
        if response["code"] and len(response["output"]):
1139 1140
            LOG.log(logging.DEBUG - 1,
                    "RESPONSE: %s, %s"
1141
                      % (str(response['code']),response['output']))
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
            pass

        rval = response["code"]

        #
        # If the code indicates failure, look for a "value". Use that as the
        # return value instead of the code. 
        # 
        if rval:
            if response["value"]:
                rval = response["value"]
                pass
            pass
        
        #
        # If the return code indicates success and we have cache destroy
        # stuff, destroy matching cache items!  Note, for
        # cache_destroy_params, we look for a few specific ones
        # (uri,module,method); if the user sets those, we also set
        # delete to filter on those values.  IF THE USER DOESN'T SET
        # THOSE, they are wildcards for the delete.
        #
        if not rval and cache_destroy_params and len(cache_destroy_params) > 0:
            d_uri = None
            d_module = None
            d_method = None
            d_version = None
            if 'uri' in cache_destroy_params:
                d_uri = cache_uri
            if 'module' in cache_destroy_params:
                d_module = module
            if 'method' in cache_destroy_params:
                d_method = method
                d_version = version
                pass
            
            # Filter according to the specific cache params
            cparams = {}           
            for p in params.keys():
                if p in cache_destroy_params:
                    cparams[p] = params[p]
                    pass
                pass
            self._cache_delete(d_uri,d_module,d_method,d_version,cparams)
            pass
        
        #
        # If the return code indicates success and we have extra cache
        # destroy stuff, destroy matching cache items!  Note, for
        # cache_destroy_extra, we look for a few specific ones
        # (uri,module,method); if the user sets those, we also set
        # delete to filter on those values.  IF THE USER DOESN'T SET
        # THOSE, they are wildcards for the delete.
        #
        if not rval \
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
            and cache_destroy_extra and len(cache_destroy_extra) > 0:
            for cde in cache_destroy_extra:
                cparams = dict(cde)
                d_uri = None
                d_module = None
                d_method = None
                d_version = None
                if cde.has_key('uri'):
                    if cde['uri'] is None:
                        d_uri = cache_uri
                    else:
                        d_uri = cde['uri']
                        pass
                    del cparams['uri']
1211
                    pass
1212 1213 1214 1215 1216 1217 1218
                if cde.has_key('module'):
                    if cde['module'] is None:
                        d_module = module
                    else:
                        d_module = cde['module']
                        pass
                    del cparams['module']
1219
                    pass
1220 1221 1222 1223 1224 1225 1226 1227
                if cde.has_key('method'):
                    if cde['method'] is None:
                        d_method = method
                        d_version = version
                    else:
                        d_method = cde['method']
                        pass
                    del cparams['method']
1228
                    pass
1229 1230 1231 1232 1233 1234 1235
                if cde.has_key('version'):
                    if cde['version'] is None:
                        d_version = version
                    else:
                        d_version = cde['version']
                        pass
                    del cparams['version']
1236 1237
                    pass
            
1238 1239
                self._cache_delete(d_uri,d_module,d_method,d_version,cparams)
                pass
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
            pass
        
        xtime = None
        if cache_expire_func is not None:
            xtime = cache_expire_func(response)
            pass
        
        #
        # If the output from this is supposed to replace some other cached
        # entry, do that.
        #
        if not rval and cache_replace_info is not None:
            _r_module = module
            if cache_replace_info.has_key('module'):
                _r_module = cache_replace_info['module']
            _r_method = method
            if cache_replace_info.has_key('method'):
                _r_method = cache_replace_info['method']
            _r_version = version
            if cache_replace_info.has_key('version'):
                _r_version = cache_replace_info['version']
            _r_params = {}
            if cache_replace_info.has_key('params'):
                _r_params = cache_replace_info['params']
                
            self._cache_add(cache_uri,_r_module,_r_method,_r_version,_r_params,
                            (rval,response),xtime=xtime,
                            cache_notifier=cache_notifier)
            pass
        
        #
        # If the return code indicates success and we're caching, add it
        # to the cache!
        #
        if not rval and cache:
            if cache_expire_func is not None:
                xtime = cache_expire_func(response)
                pass
            if len(cache_add_params) == 0:
                cparams = params
            else:
                # Filter according to the specific cache params
                cparams = {}           
                for p in params.keys():
                    if p in cache_add_params:
                        cparams[p] = params[p]
                        pass
                    pass
                pass
            self._cache_add(cache_uri,module,method,version,cparams,
                            (rval,response),xtime=xtime,
                            cache_notifier=cache_notifier)
            pass
        
        return (rval, response)

    def do_method_retry(self,module,method,params,URI=None,retries=200,
                        quiet=False,version=None,response_handler=None,cm=None,
                        force=False,cache=False,cache_accept_stale=False,
                        cache_add_params=[],cache_destroy_params=[],
1300
                        cache_destroy_extra=[],cache_replace_info=None,
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
                        cache_notifier=None,cache_expire_func=None):
        """
        Retries the RPC @retries times (default 200).
        """
        count = retries
        rval, response = \
            self.do_method(module,method,params,URI=URI,quiet=quiet,cm=cm,
                           version=version,response_handler=response_handler,
                           force=force,cache=cache,
                           cache_accept_stale=cache_accept_stale,
                           cache_add_params=cache_add_params,
                           cache_destroy_params=cache_destroy_params,
                           cache_replace_info=cache_replace_info,
1314
                           cache_destroy_extra=cache_destroy_extra,
1315 1316 1317 1318
                           cache_notifier=cache_notifier,
                           cache_expire_func=cache_expire_func)
        while count > 0 and response and response["code"] == 14:
            count = count - 1
1319
            LOG.debug("Will try again in a few seconds")
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
            time.sleep(5.0)
            rval, response = \
                self.do_method(module,method,params,URI=URI,quiet=quiet,cm=cm,
                               version=version,response_handler=response_handler,
                               force=force,cache=cache,
                               cache_accept_stale=cache_accept_stale,
                               cache_add_params=cache_add_params,
                               cache_destroy_params=cache_destroy_params,
                               cache_replace_info=cache_replace_info,
                               cache_destroy_extra=cache_destroy_extra,
                               cache_notifier=cache_notifier,
                               cache_expire_func=cache_expire_func)
        return (rval, response)

    def _expires_within(self,time_tuple,seconds=0):
        tt_exp = time.mktime(time_tuple)
        cgmtime = time.mktime(time.gmtime())
        if (cgmtime + seconds) > tt_exp:
            return True
        else:
            return False
        pass
    
1343 1344
    @staticmethod
    def __get_cred_expire_str(credential):
1345 1346 1347 1348
        try:
            from lxml import etree as ET
            cx = ET.fromstring(credential)
            #r = ET.parse(path)
1349
            return cx.find("credential/expires").text
1350
        except:
1351
            LOG.exception("error getting cred timestamp")
1352
            return None
1353
        pass
1354 1355 1356 1357 1358
    
    def __get_cred_expire_local_timestamp(self,response):
        credential = response['value']
        # grab expiration
        LOG.debug("CACHE: cache-checking credential expiration time")
1359
        expstr = ProtoGeniServer.__get_cred_expire_str(credential)
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
        if expstr is None:
            return None
        
        lts = GeniTimeStringToLocalTimeStamp(expstr)
        LOG.debug("CACHE: expstr %s -> %f" % (expstr,lts))
        
        if DEFAULT_CREDENTIAL_EXPIRATION_BUFFER > 0:
            lts -= DEFAULT_CREDENTIAL_EXPIRATION_BUFFER
            LOG.debug("CACHE: giving credential a bit less time to expire"
                      " (%.4f hrs less)"
                      % (DEFAULT_CREDENTIAL_EXPIRATION_BUFFER/float(HOUR),))
            pass
        return lts
    
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    @ApplicableFormatter(
        kwargs=[dict(name='text',action='store_true'),
                dict(name='json',action='store_true'),
                dict(name='expirestr',action='store_true'),
                dict(name='expirestamp',parser_largs=['-E','--expirestamp'],
                     action='store_true'),
                dict(name='remaining',action='store_true')])
    def _cred_formatter(result,text=None,json=None,
                        expirestr=None,expirestamp=None,remaining=None):
        """
        Format a credential or its expiration time as a string, modulo arguments.
        
        :param text: display credential as plaintext
        :param json: display credential as a JSON object
        :param expirestr: display expiration string
        :param expirestamp: display expiration as local UNIX timestamp
        :param remaining: display seconds remaining until credential expires
        """
1392
        if remaining is True:
1393 1394
            es = ProtoGeniServer.__get_cred_expire_str(result)
            return GeniTimeStringToLocalTimeStamp(es) - time.time()
1395
        elif expirestr is True:
1396
            return ProtoGeniServer.__get_cred_expire_str(result)
1397
        elif expirestamp is True:
1398 1399
            es = ProtoGeniServer.__get_cred_expire_str(result)
            return GeniTimeStringToLocalTimeStamp(es)
1400
        else:
1401
            return get_default_formatter()(result,text=text,json=json)
1402 1403 1404
        pass
    
    @ApplicableMethod(
1405 1406 1407
        kwargs=[dict(name='force',action='store_true')],
        excluded=['cache_notifier'],
        formatter=_cred_formatter)
1408 1409
    def get_self_credential(self,force=False,cache_notifier=None):
        """
1410 1411 1412
        Gets a self credential (SA::GetCredential).
        
        :param force: Bypass the cache if True
1413 1414 1415
        """
        self.__get_lock()
        
1416
        LOG.debug("Refreshing self credential from SA (force=%s)" % (str(force),))
1417 1418 1419 1420 1421 1422 1423
        params = {}
        rval,response = \
            self.do_method_retry("sa","GetCredential",params,force=force,
                                 cache=True,cache_notifier=cache_notifier,
                                 cache_expire_func=self.__get_cred_expire_local_timestamp)
        if rval:
            self.__put_lock()
1424 1425
            raise RPCError("sa::GetCredential",rval,response,
                           "could not get self credential")
1426 1427 1428 1429 1430
        selfcredential = response["value"]
        
        self.__put_lock()
        
        return selfcredential
1431

1432
    
1433
    @ApplicableMethod(
1434 1435 1436
        excluded=['slice','selfcredential','cache_notifier'],
        kwargs=[dict(name='force',action='store_true')],
        formatter=_cred_formatter)
1437
    def get_slice_credential(self,slice=None,slicename=None,selfcredential=None,
1438 1439
                             force=False,cache_notifier=None):
        """
1440 1441 1442 1443
        Get a slice credential (SA::GetCredential).
        
        :param slicename: Specify a slice URN
        :param force: Bypass the cache if True
1444 1445 1446 1447
        """
        self.__get_lock()
        
        if not slice:
1448 1449 1450 1451
            if not slicename:
                slicename = self.slicename
                pass
            slice = self.resolve_slice(slicename=slicename,selfcredential=selfcredential,force=force)
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
            pass
        
        if not selfcredential:
            selfcredential = self.get_self_credential()
        params = {}
        params["credential"] = selfcredential
        params["type"]       = "Slice"
        if "urn" in slice:
            params["urn"] = slice["urn"]
            slice_id = slice['urn']
        else:
            params["uuid"] = slice["uuid"]
            slice_id = slice['uuid']
            pass
1466
        LOG.debug("Refreshing slice credential from SA (%s)" % (slice_id,))
1467 1468 1469 1470 1471 1472 1473 1474
        rval,response = \
            self.do_method_retry("sa","GetCredential",params,
                                 force=force,cache=True,
                                 cache_add_params=['type','urn','uuid'],
                                 cache_notifier=cache_notifier,
                                 cache_expire_func=self.__get_cred_expire_local_timestamp)
        if rval:
            self.__put_lock()
1475 1476
            raise RPCError("sa::GetCredential",rval,response,
                           "could not get slice credential")
1477 1478 1479 1480 1481
        
        self.__put_lock()
            
        return response['value']

1482

1483
    @ApplicableMethod(
1484 1485
        excluded=['selfcredential','cache_notifier'],
        kwargs=[dict(name='force',action='store_true')])
1486
    def resolve_slice(self,slicename=None,selfcredential=None,force=False,
1487 1488
                      cache_notifier=None):
        """
1489 1490 1491 1492
        Resolve a slice (SA::Resolve(type=slice)).
        
        :param slicename: Specify a slice URN
        :param force: Bypass the cache if True
1493 1494 1495 1496 1497
        """
        self.__get_lock()

        if not selfcredential:
            selfcredential = self.get_self_credential()
1498 1499
        if not slicename:
            slicename = self.slicename
1500 1501 1502 1503

        params = {}
        params["credential"] = selfcredential
        params["type"]       = "Slice"
1504
        if slicename.startswith("urn:"):
1505
            pname = "urn"
1506
            params["urn"]       = slicename
1507 1508
        else:
            pname = "hrn"
1509
            params["hrn"]       = slicename
1510 1511 1512 1513 1514
            pass
        
        while True:
            rval,response = \
                self.do_method_retry("sa","Resolve",params,version="2.0",
1515
                                     force=force,
1516 1517 1518
                                     cache=True,cache_add_params=["type",pname],
                                     cache_notifier=cache_notifier)
            if rval:
1519
                LOG.debug("Resolve: %s" % (str(rval)))
1520 1521 1522 1523 1524 1525 1526 1527 1528
                self.__put_lock()
                return None
            else:
                break
            pass

        self.__put_lock()
        
        return response["value"]
1529

1530
    @ApplicableMethod(
1531
        excluded=['selfcredential'],
1532
        help="Get expiration time for slice",
1533
        kwargs=[dict(name='force',action='store_true')])
1534
    def get_slice_expiration(self,slicename=None,selfcredential=None,force=False):
1535
        """
1536 1537 1538 1539
        Get the slice expiration as a local UNIX timestamp (SA::Resolve).

        :param slicename: Specify a slice URN
        :param force: Bypass the cache
1540 1541 1542 1543 1544
        """
        self.__get_lock()
        
        if not selfcredential:
            selfcredential = self.get_self_credential()
1545 1546
        if not slicename:
            slicename = self.slicename
1547
        
1548
        slice = self.resolve_slice(slicename=slicename,selfcredential=selfcredential,
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
                                   force=force)
        
        slicecredential = self.get_slice_credential(slice,force=force)
        
        try:
            from lxml import etree as ET
            cx = ET.fromstring(slicecredential)
            expstr = cx.find("credential/expires").text
            self.__put_lock()
            return GeniTimeStringToLocalTimeStamp(expstr)
        except:
            self.__put_lock()
            return None
        pass
1563

1564
    @ApplicableMethod(
1565
        excluded=['selfcredential','cache_notifier'])
1566 1567
    def resolve_user(self,urn=None,selfcredential=None,cache_notifier=None):
        """
1568 1569 1570
        Resolve a GENI user (SA::Resolve(type=user).
        
        :param urn: Specify a user URN
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
        """
        self.__get_lock()
        if not selfcredential:
            selfcredential = self.get_self_credential()
        
        if not urn:
            if self.user_urn:
                urn = self.user_urn
            else:
                myslice = self.resolve_slice(selfcredential=selfcredential)
                urn = myslice['creator_urn']
                pass
            pass

        params = {}
        params["credential"] = selfcredential
        params["urn"] = urn
        params["type"] = 'User'
        rval,response = self.do_method("sa","Resolve",params,version="2.0",
                                       cache=True,cache_add_params=["urn","type"],
                                       cache_notifier=cache_notifier)
        if rval:
            self.__put_lock()
1594
            LOG.error("could not resolve user at SA!")
1595 1596
            return None
        myuser = response["value"]
1597
        LOG.debug("Got user: %s (%s)" % (str(rval),str(response),))
1598 1599
        self.__put_lock()
        return myuser
1600

1601
    @ApplicableMethod()
1602
    def get_user_urn(self):
1603 1604 1605
        """
        Get your user URN.
        """
1606 1607 1608 1609 1610 1611 1612
        if self.user_urn:
            return self.user_urn
        else:
            myslice = self.resolve_slice()
            return myslice['creator_urn']
        pass
    
1613
    @ApplicableMethod()
1614
    def get_user_email(self):
1615 1616 1617
        """
        Get your user email.
        """
1618 1619 1620 1621 1622 1623 1624
        if self.user_email:
            return self.user_email
        else:
            myuser = self.resolve_user()
            return myuser['email']
        pass
    
1625
    @ApplicableMethod()
1626
    def get_user_uid(self):
1627 1628 1629
        """
        Get your user uid.
        """
1630 1631
        myuser = self.resolve_user()
        return myuser['uid']
1632

1633 1634
    @ApplicableMethod(
        excluded=['selfcredential','cache_notifier'])
1635
    def get_keys(self,selfcredential=None,cache_notifier=None):
1636 1637 1638
        """
        Get user's keys from the SA (SA:GetKeys).
        """
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
        self.__get_lock()
        if not selfcredential:
            selfcredential = self.get_self_credential()

        params = {}
        params["credential"] = selfcredential
        rval,response = self.do_method("sa","GetKeys",params,
                                       cache=True,cache_notifier=cache_notifier)
        if rval:
            self.__put_lock()
1649
            LOG.error("could not get keys from SA!")
1650 1651
            return None
        keys = response["value"]
1652
        LOG.debug("Got keys: %s (%s)" % (str(rval),str(response),))
1653 1654 1655
        self.__put_lock()
        return keys

1656
    @ApplicableMethod(
1657
        excluded=['selfcredential'])
1658
    def create_slice(self,slicename=None,valid_until=None,selfcredential=None):
1659 1660 1661 1662 1663 1664
        """
        Create a slice.
        
        :param slicename: Specify a slice URN
        :param valid_until: Specify a slice expiration time (as a GMT time string)
        """
1665 1666 1667
        self.__get_lock()
        if not selfcredential:
            selfcredential = self.get_self_credential()
1668 1669
        if not slicename:
            slicename = self.slicename
1670 1671 1672 1673 1674 1675 1676
        if not valid_until:
            valid_until = time.strftime("%Y%m%dT%H:%M:%S",
                                        time.gmtime(time.time() + 60*60*24))

        params = {}
        params["credential"] = selfcredential
        params["type"]       = "Slice"
1677 1678
        if slicename.startswith("urn:"):
            params["urn"]       = slicename
1679
        else:
1680
            params["hrn"]       = slicename
1681 1682 1683 1684 1685 1686
            pass
        params["expiration"] = valid_until
        
        rval,response = self.do_method("sa", "Register", params)
        if rval:
            self.__put_lock()
1687
            raise RPCError("sa::Register",rval,response,
1688
                           "could not register slice %s" % (slicename,))
1689
        myslice = response["value"]
1690
        LOG.debug("Created slice %s: %s (%s)" % (slicename,str(rval),str(response),))
1691 1692 1693
        self.__put_lock()
        return myslice

1694
    @ApplicableMethod(
1695 1696
        excluded=['selfcredential'],
        kwargs=[dict(name='cmlist',type=parse_cm_list)])
1697
    def delete_slice(self,slicename=None,cmlist=None,selfcredential=None):
1698 1699 1700 1701 1702 1703
        """
        Delete a slice.
        
        :param slicename: Specify a slice URN
        :param cmlist: A comma-separated list of CMs to delete slivers at; defaults to the default CM if unspecified.
        """
1704 1705 1706 1707
        self.__get_lock()
        
        if not selfcredential:
            selfcredential = self.get_self_credential()
1708 1709
        if not slicename:
            slicename = self.slicename
1710 1711 1712 1713 1714
            pass
        if not cmlist or len(cmlist) < 1:
            cmlist = [self.default_cm,]
            pass
        
1715
        myslice = self.resolve_slice(slicename=slicename)
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
        slicecredential = self.get_slice_credential(myslice,
                                                    selfcredential=selfcredential)
        
        if cmlist and len(cmlist) > 0:
            #
            # Delete at CMs too.
            #
            for cm in cmlist:
                params = {}
                params["slice_urn"]   = myslice['urn']
                params["credentials"] = (slicecredential,)
                rval,response = self.do_method_retry("cm","DeleteSlice",params,cm=cm,
                                               version="2.0")
                if rval:
1730 1731 1732 1733
                    LOG.error("DeleteSlice(%s,%s): %s, %s"
                      % (myslice['urn'],cm,str(rval),str(response),))
                else:
                    LOG.debug("Deleted slice %s at CM %s" % (myslice['urn'],cm))
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
                pass
            pass
        
        params = {}
        params['type']  = 'Slice'
        params["urn"]   = myslice['urn']
        params["credentials"] = (selfcredential,)
        rval,response = self.do_method_retry("sa","Remove",params,version="2.0")
        if rval:
            self.__put_lock()
1744 1745
            raise RPCError("sa::Remove",rval,response,
                           "could not delete slice")
1746
        LOG.debug("Deleted slice %s" % (myslice['urn'],))
1747 1748
        self.__put_lock()
        return response["value"]
1749 1750

    @ApplicableMethod(
1751 1752 1753
        excluded=['selfcredential'],
        kwargs=[dict(name='additional_seconds',type=int),
                dict(name='cmlist',type=parse_cm_list)])
1754
    def renew_slice(self,slicename=None,additional_seconds=None,expiration_time=None,
1755
                    cmlist=None,selfcredential=None):
1756 1757 1758 1759 1760 1761 1762 1763
        """
        Renew a slice (and possibly its slivers).
        
        :param slicename: Specify a slice URN
        :param expiration_time: Specify an expiration time string, in GMT
        :param additional_seconds: If expiration_time is not set, and this is, <additional_seconds> will be added to your slice\'s current expiration time.
        :param cmlist: A comma-separated list of CMs to renew slivers at; defaults to the default CM if unspecified.
        """
1764
        self.__get_lock()
1765 1766
        if not slicename:
            slicename = self.slicename
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
            pass
        if expiration_time:
            expiration = time.strftime("%Y%m%dT%H:%M:%S",
                                       time.gmtime(expiration_time))
        else:
            if not additional_seconds:
                additional_seconds = DAY
            expiration_time = time.gmtime(time.time() + additional_seconds)
            expiration = time.strftime("%Y%m%dT%H:%M:%S",expiration_time)
            pass
        
1778
        myslice = self.resolve_slice(slicename=slicename)
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
        slicecredential = self.get_slice_credential(myslice,
                                                    selfcredential=selfcredential)

        slice_id = None
        if 'urn' in myslice:
            slice_id = myslice['urn']
        else:
            slice_id = myslice['uuid']
        
        params = {}
        params["slice_urn"]   = myslice['urn']
        params["credentials"] = (slicecredential,)
        params["expiration"] = expiration
        crd = { 'method':'GetCredential','params':{ 'urn':myslice['urn'],
                                                    'type':'Slice' } }
        #
        # NB: the output of this function replaces our current slice credential
        # from GetCredential, so replace it in the cache too.
        #
        rval,response = \
            self.do_method_retry("sa","RenewSlice",params,
                                 cache=False,cache_replace_info=crd,
                                 cache_expire_func=self.__get_cred_expire_local_timestamp)
        if rval:
            self.__put_lock()
1804 1805
            raise RPCError("sa::RenewSlice",rval,response,
                           "could not renew slice")
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 1832
        
        slicecredential = response['value']

        # grab expiration
        try:
            from lxml import etree as ET
            cx = ET.fromstring(response['value'])
            #r = ET.parse(path)
            expstr = cx.find("credential/expires").text
        except:
            expstr = expiration
            pass
        
        if cmlist and len(cmlist) > 0:
            #
            # Renew at CMs too.
            #
            for cm in cmlist:
                params = {}
                params["slice_urn"]   = myslice['urn']
                params["credentials"] = (slicecredential,)
                params["expiration"] = expstr
                rval,response = \
                    self.do_method_retry("cm","RenewSlice",params,cm=cm,
                                         version="2.0")
                if rval:
                    self.__put_lock()
1833 1834
                    raise RPCError("cm::RenewSlice",rval,response,
                                   "could not renew sliver")
1835 1836 1837 1838 1839 1840
                pass
            pass
        
        self.__put_lock()

        return slicecredential
1841 1842

    @ApplicableMethod(
1843
        excluded=['selfcredential'],
1844 1845
        largs=[dict(name='rspec',type=parse_rspec_arg,
                     help='An RSpec XML string or a file containing an RSpec')],
1846 1847
        kwargs=[dict(name='dokeys',type=parse_bool),
                dict(name='gen_random_key',action='store_true')])