예제 #1
0
파일: Shutdown.py 프로젝트: gnogueras/sfa
class Shutdown(Method):
    """
    Perform an emergency shut down of a sliver. This operation is intended for administrative use. 
    The sliver is shut down but remains available for further forensics.

    @param slice_urn (string) URN of slice to renew
    @param credentials ([string]) of credentials    
    """
    interfaces = ['aggregate', 'slicemgr']
    accepts = [
        Parameter(str, "Slice URN"),
        Parameter(type([dict]), "Credentials"),
    ]
    returns = Parameter(bool, "Success or Failure")

    def call(self, xrn, creds):

        valid_creds = self.api.auth.checkCredentials(
            creds,
            'stopslice',
            xrn,
            check_sliver_callback=self.api.driver.check_sliver_credentials)
        #log the call
        origin_hrn = Credential(cred=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info(
            "interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s" %
            (self.api.interface, origin_hrn, xrn, self.name))

        return self.api.manager.Shutdown(self.api, xrn, creds)
예제 #2
0
파일: Status.py 프로젝트: gnogueras/sfa
class Status(Method):
    """
    Get the status of a sliver
    
    @param slice_urn (string) URN of slice to allocate to
    
    """
    interfaces = ['aggregate', 'slicemgr', 'component']
    accepts = [
        Parameter(type([str]), "Slice or sliver URNs"),
        Parameter(type([dict]), "credentials"),
        Parameter(dict, "Options")
    ]
    returns = Parameter(dict, "Status details")

    def call(self, xrns, creds, options):
        (speaking_for, _) = urn_to_hrn(options.get('geni_speaking_for'))
        valid_creds = self.api.auth.checkCredentials(
            creds,
            'sliverstatus',
            xrns,
            check_sliver_callback=self.api.driver.check_sliver_credentials,
            speaking_for_hrn=speaking_for)

        self.api.logger.info("interface: %s\ttarget-hrn: %s\tmethod-name: %s" %
                             (self.api.interface, xrns, self.name))
        return self.api.manager.Status(self.api, xrns, creds, options)
예제 #3
0
class List(Method):
    """
    List the records in an authority. 

    @param cred credential string specifying the rights of the caller
    @param hrn human readable name of authority to list (hrn or urn)
    @return list of record dictionaries         
    """
    interfaces = ['registry']

    accepts = [
        Parameter(str, "Human readable name (hrn or urn)"),
        Mixed(Parameter(str, "Credential string"),
              Parameter(type([str]), "List of credentials")),
    ]

    # xxx used to be [SfaRecord]
    returns = [Parameter(dict, "registry record")]

    def call(self, xrn, creds, options={}):
        hrn, type = urn_to_hrn(xrn)
        valid_creds = self.api.auth.checkCredentials(creds, 'list')

        #log the call
        origin_hrn = Credential(
            string=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info(
            "interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s" %
            (self.api.interface, origin_hrn, hrn, self.name))

        return self.api.manager.List(self.api, xrn, options=options)
예제 #4
0
class get_trusted_certs(Method):
    """
    @param cred credential string specifying the rights of the caller
    @return list of gid strings  
    """

    interfaces = ['registry', 'aggregate', 'slicemgr']

    accepts = [
        Mixed(Parameter(str, "Credential string"),
              Parameter(None, "Credential not specified"))
    ]

    returns = Parameter(type([str]), "List of GID strings")

    def call(self, cred=None):
        # If cred is not specified just return the gid for this interface.
        # This is true when when a peer is attempting to initiate federation
        # with this interface
        self.api.logger.debug("get_trusted_certs: %r" % cred)
        if not cred:
            gid_strings = []
            for gid in self.api.auth.trusted_cert_list:
                if gid.get_hrn() == self.api.config.SFA_INTERFACE_HRN:
                    gid_strings.append(gid.save_to_string(save_parents=True))
            return gid_strings

        # authenticate the cred
        self.api.auth.check(cred, 'gettrustedcerts')
        gid_strings = [gid.save_to_string(save_parents=True) for \
                                gid in self.api.auth.trusted_cert_list]

        return gid_strings
예제 #5
0
class ListResources(Method):
    """
    Returns information about available resources
    @param credential list
    @param options dictionary
    @return string
    """
    interfaces = ['aggregate', 'slicemgr']
    accepts = [
        Mixed(Parameter(str, "Credential string"),
              Parameter(type([str]), "List of credentials")),
        Parameter(dict, "Options")
    ]
    returns = Parameter(str, "List of resources")

    def call(self, creds, options):
        self.api.logger.info("interface: %s\tmethod-name: %s" %
                             (self.api.interface, self.name))

        # client must specify a version
        if not options.get('geni_rspec_version'):
            if options.get('rspec_version'):
                options['geni_rspec_version'] = options['rspec_version']
            else:
                raise SfaInvalidArgument(
                    'Must specify an rspec version option. geni_rspec_version cannot be null'
                )

        (speaking_for, _) = urn_to_hrn(options.get('geni_speaking_for'))

        # Find the valid credentials
        valid_creds = self.api.auth.checkCredentials(
            creds, 'listnodes', speaking_for_hrn=speaking_for)

        # get hrn of the original caller
        origin_hrn = options.get('origin_hrn', None)
        if not origin_hrn:
            origin_hrn = Credential(
                cred=valid_creds[0]).get_gid_caller().get_hrn()
        rspec = self.api.manager.ListResources(self.api, creds, options)

        # filter rspec through sfatables
        if self.api.interface in ['aggregate']:
            chain_name = 'OUTGOING'
        elif self.api.interface in ['slicemgr']:
            chain_name = 'FORWARD-OUTGOING'
        self.api.logger.debug("ListResources: sfatables on chain %s" %
                              chain_name)
        filtered_rspec = run_sfatables(chain_name, '', origin_hrn, rspec)

        if options.has_key(
                'geni_compressed') and options['geni_compressed'] == True:
            filtered_rspec = zlib.compress(filtered_rspec).encode('base64')

        return filtered_rspec
예제 #6
0
파일: Describe.py 프로젝트: gnogueras/sfa
class Describe(Method):
    """
    Retrieve a manifest RSpec describing the resources contained by the 
    named entities, e.g. a single slice or a set of the slivers in a 
    slice. This listing and description should be sufficiently 
    descriptive to allow experimenters to use the resources.    
    @param credential list
    @param options dictionary
    @return dict
    """
    interfaces = ['aggregate', 'slicemgr']
    accepts = [
        Parameter(type([str]), "List of URNs"),
        Mixed(Parameter(str, "Credential string"), 
              Parameter(type([str]), "List of credentials")),
        Parameter(dict, "Options")
        ]
    returns = Parameter(str, "List of resources")

    def call(self, urns, creds, options):
        self.api.logger.info("interface: %s\tmethod-name: %s" % (self.api.interface, self.name))
       
        # client must specify a version
        if not options.get('geni_rspec_version'):
            if options.get('rspec_version'):
                options['geni_rspec_version'] = options['rspec_version']
            else:
                raise SfaInvalidArgument('Must specify an rspec version option. geni_rspec_version cannot be null')
        (speaking_for, _) = urn_to_hrn(options.get('geni_speaking_for'))
        valid_creds = self.api.auth.checkCredentials(creds, 'listnodes', urns, \
                      check_sliver_callback = self.api.driver.check_sliver_credentials,
                      speaking_for_hrn=speaking_for)

        # get hrn of the original caller 
        origin_hrn = options.get('origin_hrn', None)
        if not origin_hrn:
            origin_hrn = Credential(cred=valid_creds[0]).get_gid_caller().get_hrn()
        desc = self.api.manager.Describe(self.api, creds, urns, options)

        # filter rspec through sfatables 
        if self.api.interface in ['aggregate']:
            chain_name = 'OUTGOING'
        elif self.api.interface in ['slicemgr']: 
            chain_name = 'FORWARD-OUTGOING'
        self.api.logger.debug("ListResources: sfatables on chain %s"%chain_name)
        desc['geni_rspec'] = run_sfatables(chain_name, '', origin_hrn, desc['geni_rspec']) 
 
        if options.has_key('geni_compressed') and options['geni_compressed'] == True:
            desc['geni_rspec'] = zlib.compress(desc['geni_rspec']).encode('base64')

        return desc  
예제 #7
0
class GetVersion(Method):
    """
    Returns this GENI Aggregate Manager's Version Information
    @return version
    """
    interfaces = ['registry', 'aggregate', 'slicemgr', 'component']
    accepts = [Parameter(dict, "Options")]
    returns = Parameter(dict, "Version information")

    # API v2 specifies options is optional, so..
    def call(self, options={}):
        self.api.logger.info("interface: %s\tmethod-name: %s" %
                             (self.api.interface, self.name))
        return self.api.manager.GetVersion(self.api, options)
예제 #8
0
class ResolveGENI(Method):
    """
    Lookup a URN and return information about the corresponding object.
    @param urn
    """

    interfaces = ['registry']
    accepts = [
        Parameter(str, "URN"),
        Parameter(type([str]), "List of credentials"),
    ]
    returns = Parameter(bool, "Success or Failure")

    def call(self, xrn):
        return self.api.manager.Resolve(self.api, xrn, '')
예제 #9
0
class PerformOperationalAction(Method):
    """
    Request that the named geni_allocated slivers be made 
    geni_provisioned, instantiating or otherwise realizing the 
    resources, such that they have a valid geni_operational_status 
    and may possibly be made geni_ready for experimenter use. This 
    operation is synchronous, but may start a longer process, such 
    as creating and imaging a virtual machine

    @param slice urns ([string]) URNs of slivers to provision to
    @param credentials (dict) of credentials
    @param options (dict) options
    
    """
    interfaces = ['aggregate', 'slicemgr']
    accepts = [
        Parameter(type([str]), "URNs"),
        Parameter(type([dict]), "Credentials"),
        Parameter(str, "Action"),
        Parameter(dict, "Options"),
    ]
    returns = Parameter(dict, "Provisioned Resources")

    def call(self, xrns, creds, action, options):
        self.api.logger.info("interface: %s\ttarget-hrn: %s\tmethod-name: %s" %
                             (self.api.interface, xrns, self.name))

        (speaking_for, _) = urn_to_hrn(options.get('geni_speaking_for'))

        # Find the valid credentials
        valid_creds = self.api.auth.checkCredentials(
            creds,
            'createsliver',
            xrns,
            check_sliver_callback=self.api.driver.check_sliver_credentials,
            speaking_for_hrn=speaking_for)
        origin_hrn = Credential(cred=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info(
            "interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s" %
            (self.api.interface, origin_hrn, xrns, self.name))
        result = self.api.manager.PerformOperationalAction(
            self.api, xrns, creds, action, options)
        return result
예제 #10
0
파일: CreateGid.py 프로젝트: gnogueras/sfa
class CreateGid(Method):
    """
    Create a signed credential for the object with the registry. In addition to being stored in the
    SFA database, the appropriate records will also be created in the
    PLC databases
    
    @param cred credential string
    @param xrn urn or hrn of certificate owner
    @param cert caller's certificate
    
    @return gid string representation
    """

    interfaces = ['registry']

    accepts = [
        Mixed(Parameter(str, "Credential string"),
              Parameter(type([str]), "List of credentials")),
        Parameter(str, "URN or HRN of certificate owner"),
        Parameter(str, "Certificate string"),
    ]

    returns = Parameter(int, "String representation of gid object")

    def call(self, creds, xrn, cert=None):
        # TODO: is there a better right to check for or is 'update good enough?
        valid_creds = self.api.auth.checkCredentials(creds, 'update')

        # verify permissions
        hrn, type = urn_to_hrn(xrn)
        self.api.auth.verify_object_permission(hrn)

        #log the call
        origin_hrn = Credential(
            string=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info(
            "interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s" %
            (self.api.interface, origin_hrn, xrn, self.name))

        return self.api.manager.CreateGid(self.api, xrn, cert)
예제 #11
0
파일: Renew.py 프로젝트: gnogueras/sfa
class Renew(Method):
    """
    Renews the resources in the specified slice or slivers by 
    extending the lifetime.
    
    @param surn ([string]) List of URNs of to renew
    @param credentials ([string]) of credentials
    @param expiration_time (string) requested time of expiration
    @param options (dict) options
    """
    interfaces = ['aggregate', 'slicemgr']
    accepts = [
        Parameter(type([str]), "Slice URN"),
        Parameter(type([str]), "List of credentials"),
        Parameter(str, "Expiration time in RFC 3339 format"),
        Parameter(dict, "Options"),
        ]
    returns = Parameter(bool, "Success or Failure")

    def call(self, urns, creds, expiration_time, options):

        self.api.logger.info("interface: %s\ttarget-hrn: %s\tcaller-creds: %s\tmethod-name: %s"%(self.api.interface, urns, creds, self.name))

        (speaking_for, _) = urn_to_hrn(options.get('geni_speaking_for'))
    
        # Find the valid credentials
        valid_creds = self.api.auth.checkCredentials(creds, 'renewsliver', urns,
                      check_sliver_callback = self.api.driver.check_sliver_credentials,
                      speaking_for_hrn=speaking_for)

        # Validate that the time does not go beyond the credential's expiration time
        requested_time = utcparse(expiration_time)
        max_renew_days = int(self.api.config.SFA_MAX_SLICE_RENEW)
        if requested_time > Credential(cred=valid_creds[0]).get_expiration():
            raise InsufficientRights('Renewsliver: Credential expires before requested expiration time')
        if requested_time > datetime.datetime.utcnow() + datetime.timedelta(days=max_renew_days):
            raise Exception('Cannot renew > %s days from now' % max_renew_days)
        return self.api.manager.Renew(self.api, urns, creds, expiration_time, options)
예제 #12
0
파일: GetGids.py 프로젝트: gnogueras/sfa
class GetGids(Method):
    """
    Get a list of record information (hrn, gid and type) for 
    the specified hrns.

    @param cred credential string 
    @param cert certificate string 
    @return    
    """

    interfaces = ['registry']
    
    accepts = [
        Mixed(Parameter(str, "Human readable name (hrn or xrn)"), 
              Parameter(type([str]), "List of Human readable names (hrn or xrn)")),
        Mixed(Parameter(str, "Credential string"),
              Parameter(type([str]), "List of credentials")), 
        ]

    returns = [Parameter(dict, "Dictionary of gids keyed on hrn")]
    
    def call(self, xrns, creds):
        # validate the credential
        valid_creds = self.api.auth.checkCredentials(creds, 'getgids')
        # xxxpylintxxx origin_hrn is unused..
        origin_hrn = Credential(string=valid_creds[0]).get_gid_caller().get_hrn()
        
        # resolve the record
        records = self.api.manager.Resolve(self.api, xrns, details = False)
        if not records:
            raise RecordNotFound(xrns)

        allowed_fields =  ['hrn', 'type', 'gid']
        for record in records:
            for key in record.keys():
                if key not in allowed_fields:
                    del(record[key])
        return records    
예제 #13
0
class Register(Method):
    """
    Register an object with the registry. In addition to being stored in the
    SFA database, the appropriate records will also be created in the
    PLC databases
    
    @param cred credential string
    @param record_dict dictionary containing record fields
    
    @return gid string representation
    """

    interfaces = ['registry']

    accepts = [
        Parameter(dict, "Record dictionary containing record fields"),
        Mixed(Parameter(str, "Credential string"),
              Parameter(type([str]), "List of credentials")),
    ]

    returns = Parameter(int, "String representation of gid object")

    def call(self, record, creds):
        # validate cred
        valid_creds = self.api.auth.checkCredentials(creds, 'register')

        # verify permissions
        hrn = record.get('hrn', '')
        self.api.auth.verify_object_permission(hrn)

        #log the call
        origin_hrn = Credential(
            string=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info(
            "interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s" %
            (self.api.interface, origin_hrn, hrn, self.name))

        return self.api.manager.Register(self.api, record)
예제 #14
0
class Update(Method):
    """
    Update an object in the registry. Currently, this only updates the
    PLC information associated with the record. The SFA fields (name, type,
    GID) are fixed.
    
    @param cred credential string specifying rights of the caller
    @param record a record dictionary to be updated

    @return 1 if successful, faults otherwise 
    """

    interfaces = ['registry']

    accepts = [
        Parameter(dict, "Record dictionary to be updated"),
        Parameter(str, "Credential string"),
    ]

    returns = Parameter(int, "1 if successful")

    def call(self, record_dict, creds):
        # validate the cred
        valid_creds = self.api.auth.checkCredentials(creds, "update")

        # verify permissions
        hrn = record_dict.get('hrn', '')
        self.api.auth.verify_object_permission(hrn)

        # log
        origin_hrn = Credential(
            string=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info(
            "interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s" %
            (self.api.interface, origin_hrn, hrn, self.name))

        return self.api.manager.Update(self.api, record_dict)
예제 #15
0
파일: Delete.py 프로젝트: gnogueras/sfa
class Delete(Method):
    """
    Remove the slice or slivers and free the allocated resources        

    @param xrns human readable name of slice to instantiate (hrn or urn)
    @param creds credential string specifying the rights of the caller
    @return 1 is successful, faults otherwise  
    """

    interfaces = ['aggregate', 'slicemgr', 'component']

    accepts = [
        Parameter(type([str]),
                  "Human readable name of slice to delete (hrn or urn)"),
        Parameter(type([dict]), "Credentials"),
        Parameter(dict, "options"),
    ]

    returns = Parameter(int, "1 if successful")

    def call(self, xrns, creds, options):
        (speaking_for, _) = urn_to_hrn(options.get('geni_speaking_for'))
        valid_creds = self.api.auth.checkCredentials(
            creds,
            'deletesliver',
            xrns,
            check_sliver_callback=self.api.driver.check_sliver_credentials,
            speaking_for_hrn=speaking_for)

        #log the call
        origin_hrn = Credential(cred=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info(
            "interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s" %
            (self.api.interface, origin_hrn, xrns, self.name))

        return self.api.manager.Delete(self.api, xrns, creds, options)
예제 #16
0
class get_key_from_incoming_ip(Method):
    """
    Generate a new keypair and gid for requesting caller (component/node).     
    This is a myplc-specific API call used by component manager
    @return 1 If successful  
    """

    interfaces = ['registry']

    accepts = []

    returns = Parameter(int, "1 if successful, faults otherwise")

    def call(self):
        if hasattr(self.api.manager, 'get_key_from_incoming_ip'):
            return self.api.manager.get_key_from_incoming_ip(api)
        else:
            logger.warning(
                "get_key_from_incoming_ip not supported by registry manager")
            return 0
예제 #17
0
class Resolve(Method):
    """
    Resolve a record.

    @param cred credential string authorizing the caller
    @param hrn human readable name to resolve (hrn or urn) 
    @return a list of record dictionaries or empty list     
    """

    interfaces = ['registry']
    
    # should we not accept an optional 'details' argument ?
    accepts = [
        Mixed(Parameter(str, "Human readable name (hrn or urn)"),
              Parameter(list, "List of Human readable names ([hrn])")),
        Mixed(Parameter(str, "Credential string"),
              Parameter(list, "List of credentials)")),
        Parameter(dict, "options"),
        ]

    # xxx used to be [SfaRecord]
    returns = [Parameter(dict, "registry record")]
    
    def call(self, xrns, creds, options={}):
        # use details=False by default, only when explicitly specified do we want 
        # to mess with the testbed details
        if 'details' in options: details=options['details']
        else:                    details=False
        type = None
        if not isinstance(xrns, types.ListType):
            type = Xrn(xrns).get_type()
            xrns=[xrns]
        hrns = [urn_to_hrn(xrn)[0] for xrn in xrns]
        #find valid credentials
        valid_creds = self.api.auth.checkCredentials(creds, 'resolve')

        #log the call
        origin_hrn = Credential(string=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, origin_hrn, hrns, self.name))
 
        # send the call to the right manager
        return self.api.manager.Resolve(self.api, xrns, type, details=details)
            
예제 #18
0
파일: Remove.py 프로젝트: gnogueras/sfa
class Remove(Method):
    """
    Remove an object from the registry. If the object represents a PLC object,
    then the PLC records will also be removed.
    
    @param cred credential string
    @param type record type
    @param xrn human readable name of record to remove (hrn or urn)

    @return 1 if successful, faults otherwise 
    """

    interfaces = ['registry']

    accepts = [
        Parameter(str,
                  "Human readable name of slice to instantiate (hrn or urn)"),
        Mixed(Parameter(str, "Credential string"),
              Parameter(type([str]), "List of credentials")),
        Mixed(Parameter(str, "Record type"),
              Parameter(None, "Type not specified")),
    ]

    returns = Parameter(int, "1 if successful")

    def call(self, xrn, creds, type):
        xrn = Xrn(xrn, type=type)

        # validate the cred
        valid_creds = self.api.auth.checkCredentials(creds, "remove")
        self.api.auth.verify_object_permission(xrn.get_hrn())

        #log the call
        origin_hrn = Credential(
            string=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info(
            "interface: %s\tmethod-name: %s\tcaller-hrn: %s\ttarget-urn: %s" %
            (self.api.interface, self.name, origin_hrn, xrn.get_urn()))

        return self.api.manager.Remove(self.api, xrn)
예제 #19
0
class GetCredential(Method):
    """
    Retrive a credential for an object
    If cred == None then the behavior reverts to GetSelfCredential

    @param hrn human readable name of object (hrn or urn)
    @param cred credential object specifying rights of the caller
    @param type type of object (user | slice | node | authority )

    @return the string representation of a credential object  
    """

    interfaces = ['registry']
    
    accepts = [
        Mixed(Parameter(str, "Credential string"),
              Parameter(type([str]), "List of credentials")), 
        Parameter(str, "Human readable name (hrn or urn)"),
        Mixed(Parameter(str, "Record type"),
              Parameter(None, "Type not specified")),
        ]

    returns = Parameter(str, "String representation of a credential object")

    def call(self, creds, xrn, type):
    
        if type:
            hrn = urn_to_hrn(xrn)[0]
        else:
            hrn, type = urn_to_hrn(xrn)

        # check creds
        valid_creds = self.api.auth.checkCredentials(creds, 'getcredential')
        self.api.auth.verify_object_belongs_to_me(hrn)

        #log the call
        origin_hrn = Credential(string=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, origin_hrn, hrn, self.name))	

        return self.api.manager.GetCredential(self.api, xrn, type, self.api.auth.client_gid.get_urn())
예제 #20
0
class Allocate(Method):
    """
    Allocate resources as described in a request RSpec argument 
    to a slice with the named URN. On success, one or more slivers 
    are allocated, containing resources satisfying the request, and 
    assigned to the given slice. This method returns a listing and 
    description of the resources reserved for the slice by this 
    operation, in the form of a manifest RSpec. Allocated slivers 
    are held for an aggregate-determined period. Clients must Renew 
    or Provision slivers before the expiration time (given in the 
    return struct), or the aggregate will automatically Delete them.

    @param slice_urn (string) URN of slice to allocate to
    @param credentials (dict) of credentials
    @param rspec (string) rspec to allocate
    
    """
    interfaces = ['aggregate', 'slicemgr']
    accepts = [
        Parameter(str, "Slice URN"),
        Parameter(type([dict]), "List of credentials"),
        Parameter(str, "RSpec"),
        Parameter(dict, "options"),
    ]
    returns = Parameter(str, "Allocated RSpec")

    def call(self, xrn, creds, rspec, options):
        xrn = Xrn(xrn, type='slice')
        self.api.logger.info("interface: %s\ttarget-hrn: %s\tmethod-name: %s" %
                             (self.api.interface, xrn.get_hrn(), self.name))
        (speaking_for, _) = urn_to_hrn(options.get('geni_speaking_for'))

        # Find the valid credentials
        valid_creds = self.api.auth.checkCredentials(
            creds,
            'createsliver',
            xrn.get_hrn(),
            speaking_for_hrn=speaking_for)
        # use the expiration from the first valid credential to determine when
        # the slivers should expire.
        expiration = datetime_to_string(
            Credential(cred=valid_creds[0]).expiration)

        # make sure request is not empty
        slivers = RSpec(rspec).version.get_nodes_with_slivers()
        if not slivers:
            raise InvalidRSpec(
                "Missing <sliver_type> or <sliver> element. Request rspec must explicitly allocate slivers"
            )

        # flter rspec through sfatables
        if self.api.interface in ['aggregate']:
            chain_name = 'INCOMING'
        elif self.api.interface in ['slicemgr']:
            chain_name = 'FORWARD-INCOMING'
        self.api.logger.debug("Allocate: sfatables on chain %s" % chain_name)
        origin_hrn = Credential(cred=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info(
            "interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s" %
            (self.api.interface, origin_hrn, xrn, self.name))
        rspec = run_sfatables(chain_name, xrn.get_hrn(), origin_hrn, rspec)
        slivers = RSpec(rspec).version.get_nodes_with_slivers()
        if not slivers:
            raise SfatablesRejected(slice_xrn)

        result = self.api.manager.Allocate(self.api, xrn.get_urn(), creds,
                                           rspec, expiration, options)
        return result
예제 #21
0
class GetSelfCredential(Method):
    """
    Retrive a credential for an object
    @param cert certificate string 
    @param type type of object (user | slice | sa | ma | node)
    @param hrn human readable name of object (hrn or urn)

    @return the string representation of a credential object  
    """

    interfaces = ['registry']

    accepts = [
        Parameter(str, "certificate"),
        Parameter(str, "Human readable name (hrn or urn)"),
        Mixed(Parameter(str, "Record type"),
              Parameter(None, "Type not specified")),
    ]

    returns = Parameter(str, "String representation of a credential object")

    def call(self, cert, xrn, type):
        """
        GetSelfCredential a degenerate version of GetCredential used by a client
        to get his initial credential when de doesnt have one. This is the same as
        GetCredential(..., cred = None, ...)

        The registry ensures that the client is the principal that is named by
        (type, name) by comparing the public key in the record's  GID to the
        private key used to encrypt the client side of the HTTPS connection. Thus
        it is impossible for one principal to retrieve another principal's
        credential without having the appropriate private key.

        @param type type of object (user | slice | sa | ma | node)
        @param hrn human readable name of authority to list
        @return string representation of a credential object
        """
        if type:
            hrn = urn_to_hrn(xrn)[0]
        else:
            hrn, type = urn_to_hrn(xrn)
        self.api.auth.verify_object_belongs_to_me(hrn)

        origin_hrn = Certificate(string=cert).get_subject()
        self.api.logger.info(
            "interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s" %
            (self.api.interface, origin_hrn, hrn, self.name))

        ### authenticate the gid
        # import here so we can load this module at build-time for sfa2wsdl
        #from sfa.storage.alchemy import dbsession
        from sfa.storage.model import RegRecord

        # xxx-local - the current code runs Resolve, which would forward to
        # another registry if needed
        # I wonder if this is truly the intention, or shouldn't we instead
        # only look in the local db ?
        records = self.api.manager.Resolve(self.api, xrn, type, details=False)
        if not records:
            raise RecordNotFound(hrn)

        record_obj = RegRecord(dict=records[0])
        # xxx-local the local-only version would read
        #record_obj = dbsession.query(RegRecord).filter_by(hrn=hrn).first()
        #if not record_obj: raise RecordNotFound(hrn)
        gid = record_obj.get_gid_object()
        gid_str = gid.save_to_string(save_parents=True)
        self.api.auth.authenticateGid(gid_str, [cert, type, hrn])
        # authenticate the certificate against the gid in the db
        certificate = Certificate(string=cert)
        if not certificate.is_pubkey(gid.get_pubkey()):
            for (obj, name) in [
                (certificate, "CERT"),
                (gid, "GID"),
            ]:
                self.api.logger.debug(
                    "ConnectionKeyGIDMismatch, %s pubkey: %s" %
                    (name, obj.get_pubkey().get_pubkey_string()))
                self.api.logger.debug("ConnectionKeyGIDMismatch, %s dump: %s" %
                                      (name, obj.dump_string()))
                if hasattr(obj, 'filename'):
                    self.api.logger.debug(
                        "ConnectionKeyGIDMismatch, %s filename: %s" %
                        (name, obj.filename))
            raise ConnectionKeyGIDMismatch(gid.get_subject())

        return self.api.manager.GetCredential(self.api, xrn, type)