protogeni.py 120 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 elasticslice.util.exceptions as exc
53
import json as JSON
54

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

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):
83 84 85 86
    """
    :param timestring: a GENI time string (UTC)
    :return: a local UNIX time stamp
    """
87 88 89 90 91 92 93 94
    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):
95 96 97 98
    """
    :param timestring: a local UNIX time stamp
    :return: a GENI time string (UTC)
    """
99 100 101
    utctt = time.mktime(ts + __UTC_OFFSET)
    return time.strftime("%Y-%m-%dT%H:%M:%S",utctt) + "Z"

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

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
##
## 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:
135
        LOG.exception("direct mail send failed, trying sendmail")
136 137 138 139 140 141 142 143 144
        pass
    
    if not sent:
        try:
            stdin = os.popen("sendmail '%s'" % (To,),'w')
            stdin.write(smsg.as_string())
            stdin.close()
            sent = True
        except:
145
            LOG.exception("sendmail send failed")
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
            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:
170
            LOG.exception('Error reading passphrase file %s' % (passphrasefile,))
171
    else:
172
        LOG.warning('passphrase file %s does not exist' % (passphrasefile,))
173 174 175 176 177 178 179 180
    # Prompt user if passphrasefile does not exist or could not be read.
    from M2Crypto.util import passphrase_callback
    return passphrase_callback(v, prompt1, prompt2)

##
## Some useful codes that ProtoGeni API Servers can return.
##
class ProtoGeniClientDefs:
181 182 183
    """
    XMLRPC/HTTP return codes from a ProtoGeni server.
    """
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    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):
222
        LOG.debug("Using NoHostChecker")
223
        val = M2Crypto.SSL.Checker.Checker.__call__(self,peerCert,None)
224
        LOG.debug("Used NoHostChecker: %s" % str(val))
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
        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",
}

256 257 258 259
RPC_CERT_CN_REMAPS = {
    "www.apt.emulab.net" : "boss.apt.emulab.net",
}

260
def parse_cm_list(cmliststr):
261 262
    if str is None:
        return
263 264 265 266 267 268 269 270 271 272
    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

273
def parse_bool(str):
274 275
    if str is None:
        return
276 277 278 279 280
    str = str.lstrip(' ').rstrip(' ')
    if str in ['True','TRUE','true','1','yes','YES','Yes']:
        return Truef
    return False

281 282 283 284 285 286 287 288 289 290 291 292
def parse_bool_or_int(str):
    if str is None:
        return
    str = str.lstrip(' ').rstrip(' ')
    if str in ['True','TRUE','true','T','t','yes','YES','Yes','Y','y']:
        return True
    elif str in ['False','FALSE','false','F','f','no','NO','No','N','n']:
        return False
    else:
        return int(str)
    pass

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

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
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
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    
def parse_safe_eval(value):
    retval = None
    try:
        retval = eval(value)
        return retval
    except:
        LOG.exception("Argument must be Python code")
        raise Exception("Argument must be Python code")
    pass
    
def parse_safe_list_or_eval(value):
    retval = None
    try:
        retval = eval(value)
        return retval
    except:
        pass
    try:
        _list = value.split(',')
        return _list
    except:
        pass
    raise Exception("Argument must be Python code, or a list of strings")
340

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
#
# 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,
359
             'SliverStatus' : 1 * MINUTE,
360 361 362
        }
    }

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
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

417
@ApplicableClass()
418
class ProtoGeniServer(object):
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    """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).
    """
    
458 459
    def __init__(self,config=None,
                 cert=CERTIFICATE,passphrasefile=PASSPHRASEFILE,
460 461 462 463
                 cacert=None,noCertHostChecking=False,
                 endpoints={},devuser=None,slicename=None,sliceurn=None,
                 cms=DEFAULT_CMS,default_cm='emulab',cmuri=None,sauri=None,
                 speaksforcredential=None,
464
                 fscache=True,fscachedir=None,
465 466
                 cache_times=DEFAULT_METHOD_CACHE_TIMES,nolock=False):
        """
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
        :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.
485
        """
486 487 488

        super(ProtoGeniServer,self).__init__()

489 490 491 492 493 494 495 496
        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
497
        if self.cacert is not None and self.cacert[0] == '~':
498 499
            self.cacert = HOME + "/" + self.cacert[1:]
        self.noCertHostChecking = (config and config.nocerthostchecking) or noCertHostChecking
500
        self.endpoints = endpoints
501 502
        self.devuser = (config and config.devuser) or devuser
        self.slicename = (config and config.slicename) or slicename
503
        if not self.slicename:
504
            raise exc.InvalidArgumentError("no default slicename specified!")
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
        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
530 531
        self.default_cm = (config and config.default_cm) or default_cm
        self.cmuri = (config and config.cmuri) or cmuri
532 533 534 535 536 537 538
        if cmuri is not None:
            self.default_cm = 'custom'
            if cms is None:
                self.cms = {}
                pass
            self.cms['custom'] = self.cmuri
            pass
539
        self.sauri = (config and config.sauri) or sauri
540 541 542 543 544 545 546 547 548 549
        
        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
        
550
        if self.default_cm and not cms.has_key(self.default_cm):
551
            raise exc.InvalidArgumentError("cannot specify a default cm not in cms!")
552
        if self.cmuri is not None and self.default_cm is not None:
553
            raise exc.InvalidArgumentError("cannot specify both a custom CM URI and a default cm!")
554
        
555 556 557 558 559 560
        self.selfcredential = None
        self.selfcredential_expiration = None
        self.selfcredential_expiration_str = None
        
        self.cache = {}
        self.cache_times = cache_times
561
        self.fscache = (config and config.fscache) or fscache
David Johnson's avatar
David Johnson committed
562
        self.fscachedir = (config and config.fscachedir) or fscachedir
563 564 565
        if not self.fscachedir:
            self.fscachedir = os.getenv('HOME') + '/.protogeni/cache'
            pass
566 567 568 569 570 571 572 573
        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
574 575 576 577 578 579 580 581 582 583 584
            pass
        
        self.speaksforcredential = speaksforcredential

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

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

        #
        # 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)
618 619
                if host in RPC_CERT_CN_REMAPS:
                    host = RPC_CERT_CN_REMAPS[host]
620 621 622
                self.endpoints["default"] = { "host":host,"port":port,
                                              "path":path }
            except LookupError, err:
623 624
                LOG.exception("Error while loading certificate %s to get"
                              " default endpoint" % (self.cert,))
625 626 627
                pass

            if "default" not in self.endpoints and cert is not None:
628 629 630 631
                dhost = cert.get_issuer().CN
                if dhost in RPC_CERT_CN_REMAPS:
                    dhost = RPC_CERT_CN_REMAPS[dhost]
                self.endpoints["default"] = { "host":dhost,
632 633 634 635
                                              "port":443,
                                              "path":"/protogeni/xmlrpc", }
                pass
            
636
            LOG.debug("Default endpoint: %s" % (str(self.endpoints["default"]),))
637
            LOG.debug("All endpoints: %s" % (str(self.endpoints),))
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
            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
    
669
    def __cache_get(self,key,accept_stale=False,max_age=None):
670 671 672
        self.__get_lock()
        
        value = None
673
        cur_time = None
674 675
        if self.cache.has_key(key):
            cur_time = time.time()
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
            # If there is a max_age, and the value is under it, set it up
            # for return (but NB: we check accept_stale below separately).
            if not max_age == None:
                if type(max_age) == int and \
                  (cur_time - self.cache[key]['ctime']) <= max_age:
                    value = self.cache[key]
                else:
                    # We had a max_age and the value was over it, so don't
                    # return anything.
                    value = None
                pass
            else:
                # We aren't checking a max_age or are under it; now we just
                # need to set value so that the staleness/expiration check
                # below is handled correctly.
691 692
                value = self.cache[key]
                pass
693 694 695 696 697 698 699
            
            # NB: check accept_stale separately from max_age: if we
            # don't accept stale values, and it's expired, don't return
            # even if there was an acceptable max_age!
            if not accept_stale and (self.cache[key]['xtime'] <= cur_time):
                value = None
                pass
700 701 702 703
            pass
        
        self.__put_lock()

704
        if value:
705 706 707 708
            LOG.debug("CACHE: found %s (%s %s) (expires=%f,added=%f,age=%f)"
                      % (key,str(accept_stale),str(max_age),
                         value['xtime'],value['ctime'],
                         (cur_time - value['ctime'])))
709
        else:
710 711
            LOG.debug("CACHE: did not find %s (%s %s)"
                      % (key,str(accept_stale),str(max_age)))
712 713 714 715 716
            pass
        
        return value
    
    def _cache_get(self,uri,module,method,version,params,accept_stale=False,
717
                   max_age=None,cache_notifier=None):
718 719 720 721 722 723 724
        # 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
        
725
        value = self.__cache_get(key,accept_stale=accept_stale,max_age=max_age)
726 727 728 729 730 731 732
        if cache_notifier:
            cache_notifier.reset()
            if not value:
                cache_notifier.cached = False
            else:
                cache_notifier.cached = True
                cache_notifier.expires = value['xtime']
733
                cache_notifier.added = value['ctime']
734 735
                cache_notifier.key = key
                cache_notifier.updated = False
736
                LOG.debug("CACHE: %s" % (str(cache_notifier),))
737 738 739 740 741 742 743 744
                pass
            pass
        
        if value:
            value = value['value']
        
        return value
    
745
    def __cache_add(self,key,value,ctime=None,xtime=None,
746 747 748
                    cache_notifier=None):
        self.__get_lock()
        
David Johnson's avatar
David Johnson committed
749 750 751 752 753
        updated = False
        if key in self.cache:
            updated = True
            pass
        
754 755 756 757 758 759 760 761 762
        # Make sure we have a synchronous timestamp so we can use the
        # same ctime for both ctime and for computing xtime.
        __ctime = None
        if not ctime or not xtime:
            __ctime = time.time()
            pass
        
        if not ctime:
            ctime = __ctime
763
        if not xtime:
764
            xtime = __ctime + DEFAULT_METHOD_CACHE_INTERVAL
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
            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
789
            cache_notifier.added = ctime
790
            cache_notifier.key = key
David Johnson's avatar
David Johnson committed
791
            cache_notifier.updated = updated
792 793 794 795
            pass
        
        self.__put_lock()
        
796 797 798 799
        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))
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
        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
        
David Johnson's avatar
David Johnson committed
839 840
        LOG.debug("CACHE: deleting items matching keys %s" % (str(dkeys),))
        
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
        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:
David Johnson's avatar
David Johnson committed
859
            LOG.debug("CACHE: deleting matching key %s" % (dk,))
860 861 862 863 864 865 866 867 868 869 870
            del self.cache[dk]
            pass
        
        self.__put_lock()
        
        pass
    
    def _cache_load(self):
        if not self.fscache:
            return None
        
871
        cn = self.get_cache_notifier()
872
        
873
        LOG.debug("CACHE: loading cache...")
874 875 876 877 878 879
        cur_time = time.time()
        if not self.fscache:
            return None
        dls = dircache.listdir(self.fscachedir)
        if not dls:
            return
880
        LOG.debug("CACHE: files %s" % (" ".join(dls),))
881 882 883 884
        for filename in dls:
            try:
                if not filename.endswith(".ctime"):
                    continue
885
                LOG.debug("CACHE: considering file %s" % filename,)
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
                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:
902
                    LOG.debug("CACHE: removing stale file %s" % (filename,))
903 904 905 906 907 908 909
                    # Delete stale entries
                    unlink(vf.name)
                    unlink(cf.name)
                    unlink(xf.name)
                    unlink(kf.name)
                    pass
                else:
910
                    LOG.debug("CACHE: adding file %s" % (filename,))
911 912 913 914 915 916 917 918 919 920 921 922 923 924
                    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:
925
            LOG.exception("could not load cache dir %s:" % (self.fscachedir,))
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
            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):
961 962 963
            """
            :param server: The :class:`ProtoGeniServer` instance object this CacheNotifier belongs to.
            """
964
            self.server = server
965
            """The :class:`ProtoGeniServer` instance object this CacheNotifier belongs to."""
966
            self.key = None
967
            """The key for this cached value."""
968
            self.cached = False
969
            """True if this value was cached; False if not."""
970
            self.updated = False
971
            """True if this value was updated as a result of the operation associated with this CacheNotifier; False if not."""
972
            self.expires = None
973
            """The expiration timestamp of this cached value."""
974 975
            self.added = None
            """The add/update timestamp (ctime) of this cached value."""
976 977 978
            pass
        
        def reset(self):
979 980 981 982 983
            """
            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)
            """
984 985 986 987
            self.key = None
            self.cached = False
            self.updated = False
            self.expires = None
988
            self.added = None
989
            return self
990
        
991
        def __repr__(self):
992 993
            s = super(ProtoGeniServer.CacheNotifier,self).__repr__()
            s += "<%s::::cached=%r,updated=%r,expires=%f,added=%f>" \
994 995 996
              % (self.key,self.cached,self.updated,self.expires,self.added)
            return s
        
997 998 999
        pass

            
1000
    def get_cache_notifier(self):
1001
        """
1002 1003 1004 1005 1006
        :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.
1007 1008 1009
        """
        return ProtoGeniServer.CacheNotifier(self)
    
1010
    def do_method(self,module,method,params,URI=None,project=None,quiet=False,version=None,
1011 1012 1013
                  response_handler=None,cm=None,
                  force=False,cache=False,cache_accept_stale=False,
                  cache_add_params=[],cache_destroy_params=[],
1014
                  cache_destroy_extra=[],cache_replace_info=None,
1015 1016 1017
                  cache_notifier=None,cache_expire_func=None):
        """
        Invoke an RPC.
1018 1019 1020 1021 1022
        
        :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.
1023
        :param project: If this is a Project URN (i.e. for ProtoGENI/Cloudlab), this is the project we need to stick into URLs for some SA calls (i.e. Register, RenewSlice).
1024 1025
        :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.
1026
        :param force: If True, don't simply return a cached value even if a valid, unexpired value exists in the cache; call the method on the server.  Otherwise, if a non-zero, positive integer, if the value is cached and the result is older than `force` seconds, also call the method on the server.
1027 1028 1029
        :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.
1030
        :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 DeleteSliver 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.
1031 1032 1033
        :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.
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 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 1096 1097 1098 1099 1100 1101 1102 1103
        """
                  
        #
        # 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)

1104 1105 1106 1107
        if project is not None and url.path.endswith("/sa"):
            upath = url.path.replace("/sa","/project/%s/sa" % (str(project),))
            url = url._replace(path=upath)

1108
        LOG.debug("URL: %s || %s" % (str(url),method))
1109 1110 1111 1112
        
        #
        # Maybe get the value from the cache
        #
1113 1114 1115 1116 1117 1118
        if cache and (not force or type(force) == int and force > 0):
            if type(force) == int and force > 0:
                max_age = force
            else:
                max_age = None
                pass
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
            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,
1132
                                    max_age=max_age,
1133 1134 1135 1136 1137 1138 1139
                                    cache_notifier=cache_notifier)
            if value is not None:
                return value
            pass

        if url.scheme == "https":
            if not os.path.exists(self.cert):
1140
                LOG.error("missing emulab certificate: %s" % (self.cert,))
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
                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. 
        #
1182 1183 1184 1185 1186 1187 1188 1189
        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
1190 1191 1192 1193 1194 1195
        while True:
            try:
                server.request("POST",url.path,xmlrpclib.dumps((params,),method),
                               headers=headers)
                response = server.getresponse()
                if response.status == 503:
1196
                    LOG.warning("Status 503; will try again in a few seconds...")
1197 1198 1199
                    time.sleep(5.0)
                    continue
                elif response.status != 200:
1200 1201
                    LOG.warning("Status %d: %s"
                                % (response.status,response.reason))
1202 1203 1204 1205
                    return (-1,None)
                response = xmlrpclib.loads(response.read())[ 0 ][ 0 ]
                break
            except httplib.HTTPException, e:
1206
                LOG.exception("http error")
1207 1208 1209
                return (-1, None)
            except xmlrpclib.Fault, e:
                if e.faultCode == 503:
1210
                    LOG.error("HTTP %s, retrying" % (e.faultString,))
1211
                    time.sleep(5.0)
1212 1213
                    continue
                LOG.error("HTTP %s, aborting" % (e.faultString,))
1214 1215
                return (-1, None)
            except M2Crypto.SSL.Checker.WrongHost, e:
1216
                LOG.exception("certificate host name mismatch (consult http://www.protogeni.net/trac/protogeni/wiki/HostNameMismatch)")
1217 1218 1219 1220 1221 1222 1223
                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. 
        # 
1224
        if response["code"] and len(response["output"]):
1225 1226
            LOG.log(logging.DEBUG - 1,
                    "RESPONSE: %s, %s"
1227
                      % (str(response['code']),response['output']))
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
            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 \
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
            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']
1297
                    pass
1298 1299 1300 1301 1302 1303 1304
                if cde.has_key('module'):
                    if cde['module'] is None:
                        d_module = module
                    else:
                        d_module = cde['module']
                        pass
                    del cparams['module']
1305
                    pass
1306 1307 1308 1309 1310 1311 1312 1313
                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']
1314
                    pass
1315 1316 1317 1318 1319 1320 1321
                if cde.has_key('version'):
                    if cde['version'] is None:
                        d_version = version
                    else:
                        d_version = cde['version']
                        pass
                    del cparams['version']
1322 1323
                    pass
            
1324 1325
                self._cache_delete(d_uri,d_module,d_method,d_version,cparams)
                pass
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 1380 1381
            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)

1382
    def do_method_retry(self,module,method,params,URI=None,project=None,retries=200,
1383 1384 1385
                        quiet=False,version=None,response_handler=None,cm=None,
                        force=False,cache=False,cache_accept_stale=False,
                        cache_add_params=[],cache_destroy_params=[],
1386
                        cache_destroy_extra=[],cache_replace_info=None,
1387 1388 1389 1390 1391 1392
                        cache_notifier=None,cache_expire_func=None):
        """
        Retries the RPC @retries times (default 200).
        """
        count = retries
        rval, response = \
1393
            self.do_method(module,method,params,URI=URI,project=project,quiet=quiet,cm=cm,
1394 1395 1396 1397 1398 1399
                           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,
1400
                           cache_destroy_extra=cache_destroy_extra,
1401 1402 1403 1404
                           cache_notifier=cache_notifier,
                           cache_expire_func=cache_expire_func)
        while count > 0 and response and response["code"] == 14:
            count = count - 1
1405
            LOG.debug("Will try again in a few seconds (%s)" % (str(response),))
1406 1407
            time.sleep(5.0)
            rval, response = \
1408
                self.do_method(module,method,params,URI=URI,project=project,quiet=quiet,cm=cm,
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
                               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
    
1429 1430
    @staticmethod
    def __get_cred_expire_str(credential):
1431 1432 1433 1434
        try:
            from lxml import etree as ET
            cx = ET.fromstring(credential)
            #r = ET.parse(path)
1435
            return cx.find("credential/expires").text
1436
        except:
1437
            LOG.exception("error getting cred timestamp")
1438
            return None
1439
        pass
1440 1441 1442 1443 1444
    
    def __get_cred_expire_local_timestamp(self,response):
        credential = response['value']
        # grab expiration
        LOG.debug("CACHE: cache-checking credential expiration time")
1445
        expstr = ProtoGeniServer.__get_cred_expire_str(credential)
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
        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
    
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
    @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
        """
1478
        if remaining is True:
1479 1480
            es = ProtoGeniServer.__get_cred_expire_str(result)
            return GeniTimeStringToLocalTimeStamp(es) - time.time()
1481
        elif expirestr is True:
1482
            return ProtoGeniServer.__get_cred_expire_str(result)
1483
        elif expirestamp is True:
1484 1485
            es = ProtoGeniServer.__get_cred_expire_str(result)
            return GeniTimeStringToLocalTimeStamp(es)
1486
        else:
1487
            return get_default_formatter()(result,text=text,json=json)
1488 1489 1490
        pass
    
    @ApplicableMethod(
1491
        kwargs=[dict(name='force',type=parse_bool_or_int)],
1492 1493
        excluded=['cache_notifier'],
        formatter=_cred_formatter)
1494 1495
    def get_self_credential(self,force=False,cache_notifier=None):
        """
1496 1497
        Gets a self credential (SA::GetCredential).
        
1498
        :param force: If True, or if nonzero, positive integer and the cached value has been cached greater than `force` seconds --- bypass the cache.  Otherwise, might return a cached value.
1499 1500 1501
        """
        self.__get_lock()
        
1502
        LOG.debug("Refreshing self credential from SA (force=%s)" % (str(force),))
1503 1504 1505 1506 1507 1508 1509
        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()
1510
            raise exc.RPCError("sa::GetCredential",rval,response,
1511
                           "could not get self credential")
1512 1513 1514 1515 1516
        selfcredential = response["value"]
        
        self.__put_lock()
        
        return selfcredential
1517

1518
    
1519
    @ApplicableMethod(
1520
        excluded=['slice','selfcredential','cache_notifier'],
1521
        kwargs=[dict(name='force',type=parse_bool_or_int)],
1522
        formatter=_cred_formatter)
1523
    def get_slice_credential(self,slice=None,slicename=None,selfcredential=None,
1524 1525
                             force=False,cache_notifier=None):
        """
1526 1527 1528
        Get a slice credential (SA::GetCredential).
        
        :param slicename: Specify a slice URN
1529
        :param force: If True, or if nonzero, positive integer and the cached value has been cached greater than `force` seconds --- bypass the cache.  Otherwise, might return a cached value.
1530 1531 1532 1533
        """
        self.__get_lock()
        
        if not slice:
1534 1535 1536 1537
            if not slicename:
                slicename = self.slicename
                pass
            slice = self.resolve_slice(slicename=slicename,selfcredential=selfcredential,force=force)
1538 1539
            if not slice:
                raise exc.NonexistentSliceError(slicename)
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
            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
1554
        LOG.debug("Refreshing slice credential from SA (%s)" % (slice_id,))
1555 1556 1557 1558 1559 1560 1561 1562
        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()
1563
            raise exc.RPCError("sa::GetCredential",rval,response,
1564
                           "could not get slice credential")
1565 1566 1567 1568 1569
        
        self.__put_lock()
            
        return response['value']

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
    
    @ApplicableMethod(
        excluded=['selfcredential','cache_notifier'],
        kwargs=[dict(name='force',type=parse_bool_or_int)],
        formatter=_cred_formatter)
    def get_sliver_credential(self,slicename=None,selfcredential=None,
                             force=False,cache_notifier=None):
        """
        Get a sliver credential (CM::GetSliver()).
        
        :param slicename: Specify a slice URN
        :param force: If True, or if nonzero, positive integer and the cached value has been cached greater than `force` seconds --- bypass the cache.  Otherwise, might return a cached value.
        """
        self.__get_lock()
        
        myslice = self.resolve_slice(slicename=slicename)
        slicecred = self.get_slice_credential(
            slicename=slicename,selfcredential=selfcredential,force=force)
        
        params = {}
        params["slice_urn"] = myslice['urn']
        params["credentials"] = (slicecred,)
        LOG.debug("Refreshing sliver credential from CM")
        rval,response = \
            self.do_method_retry("cm","GetSliver",params,version="2.0",
                                 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()
            raise exc.RPCError("cm::GetSliver",rval,response,
                           "could not get sliver credential")
        
        self.__put_lock()
            
        return response['value']

1608

1609
    @ApplicableMethod(
1610
        excluded=['selfcredential','cache_notifier'],
1611
        kwargs=[dict(name='force',type=parse_bool_or_int)])
1612
    def resolve_slice(self,slicename=None,selfcredential=None,force=False,
1613 1614
                      cache_notifier=None):
        """
1615 1616 1617
        Resolve a slice (SA::Resolve(type=slice)).
        
        :param slicename: Specify a slice URN
1618
        :param force: If True, or if nonzero, positive integer and the cached value has been cached greater than `force` seconds --- bypass the cache.  Otherwise, might return a cached value.
1619 1620 1621 1622 1623
        """
        self.__get_lock()

        if not selfcredential:
            selfcredential = self.get_self_credential()
1624 1625
        if not slicename:
            slicename = self.slicename
1626 1627 1628 1629

        params = {}
        params["credential"] = selfcredential
        params["type"]       = "Slice"
1630
        if slicename.startswith("urn:"):
1631
            pname = "urn"
1632
            params["urn"]       = slicename
1633 1634
        else:
            pname = "hrn"
1635
            params["hrn"]       = slicename
1636 1637 1638 1639 1640
            pass
        
        while True:
            rval,response = \
                self.do_method_retry("sa","Resolve",params,version="2.0",
1641
                                     force=force,
1642 1643 1644
                                     cache=True,cache_add_params=["type",pname],
                                     cache_notifier=cache_notifier)
            if rval:
1645
                LOG.debug("Resolve: %s" % (str(rval)))
1646 1647 1648 1649 1650 1651 1652 1653 1654
                self.__put_lock()
                return None
            else:
                break
            pass

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

1656
    @ApplicableMethod(
1657
        excluded=['selfcredential'],
1658
        help="Get expiration time for slice",
1659
        kwargs=[dict(name='force',type=parse_bool_or_int)])
1660
    def get_slice_expiration(self,slicename=None,selfcredential=None,force=False):
1661
        """
1662 1663 1664
        Get the slice expiration as a local UNIX timestamp (SA::Resolve).

        :param slicename: Specify a slice URN
1665
        :param force: If True, or if nonzero, positive integer and the cached value has been cached greater than `force` seconds --- bypass the cache.  Otherwise, might return a cached value.
1666 1667 1668 1669 1670
        """
        self.__get_lock()
        
        if not selfcredential:
            selfcredential = self.get_self_credential()
1671 1672
        if not slicename:
            slicename = self.slicename
1673
        
1674
        slice = self.resolve_slice(slicename=slicename,selfcredential=selfcredential,
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
                                   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
1689

1690
    @ApplicableMethod(
1691
        excluded=['selfcredential','cache_notifier'])
1692 1693
    def resolve_user(self,urn=None,selfcredential=None,cache_notifier=None):
        """
1694 1695 1696
        Resolve a GENI user (SA::Resolve(type=user).
        
        :param urn: Specify a user URN
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
        """
        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()
1720
            LOG.error("could not resolve user at SA!")
1721 1722
            return None
        myuser = response["value"]
1723
        LOG.debug("Got user: %s (%s)" % (str(rval),str(response),))
1724 1725
        self.__put_lock()
        return myuser
1726

1727
    @ApplicableMethod()
1728
    def get_user_urn(self):
1729 1730 1731
        """
        Get your user URN.
        """
1732 1733 1734 1735 1736 1737 1738
        if self.user_urn:
            return self.user_urn
        else:
            myslice = self.resolve_slice()
            return myslice['creator_urn']
        pass
    
1739
    @ApplicableMethod()
1740
    def get_user_email(self):
1741 1742 1743
        """
        Get your user email.
        """
1744 1745 1746 1747 1748 1749 1750
        if self.user_email:
            return self.user_email
        else:
            myuser = self.resolve_user()
            return myuser['email']
        pass
    
1751
    @ApplicableMethod()
1752
    def get_user_uid(self):
1753 1754 1755
        """
        Get your user uid.
        """
1756 1757
        myuser = self.resolve_user()
        return myuser['uid']
1758

1759 1760
    @ApplicableMethod(
        excluded=['selfcredential','cache_notifier'])
1761
    def get_keys(self,selfcredential=None,