Esempio n. 1
0
 def authorize(self, method, caller, creds, args, opts,
               requested_allocation_state):
     if self._logger:
         caller_urn = gid.GID(string=caller).get_urn()
         template = "Authorizing %s %s #Creds = %s Args = %s Opts =%s"
         self._logger.info(template % \
                               (method, caller_urn, len(creds), \
                                    args.keys(), opts.keys()))
Esempio n. 2
0
def exercise_am(ch_server, am_server, certfile):

    # Get UUID out of certfile
    user_certstr = file(certfile, 'r').read()
    user_gid = gid.GID(string=user_certstr)
    user_uuid = str(uuid.UUID(int=user_gid.get_uuid()));

    # Create a project at the clearinghouse
    project_name = "Proj-" + str(uuid.uuid4());
    lead_id = user_uuid; 
    project_purpose = "DUMMY";
    project_result = ch_server.CreateProject(project_name, 
                                             lead_id, project_purpose);
    if(project_result['code'] != 0):
        print "Failed to create project " + str(project_result);
        return

    project_id = project_result['value'];
    print("PROJECT_RESULT = " + str(project_id));

    # Create a slice at the clearinghouse
    slice_name = "Slice-" + str(uuid.uuid4());
    slice_name = slice_name[:15]; # Can't have slice names too big
    slice_result = ch_server.CreateSlice(slice_name, project_id, user_uuid)
    if (slice_result['code'] != 0):
        print "Failed to create slice " + str(slice_result);
        return;
    slice_info = slice_result['value']
    slice_id = slice_info['slice_id']

    slice_credential_result = ch_server.GetSliceCredential(slice_id, user_certstr)
    if(slice_credential_result['code'] != 0):
        print "Failed to get slice credential " + str(slice_credential_result);
        return

    slice_cred_string = slice_credential_result['value']['slice_credential']
    slice_credential = cred.Credential(string=slice_cred_string)
    slice_gid = slice_credential.get_gid_object()
    slice_urn = slice_gid.get_urn()
    print 'Slice Creation SUCCESS: URN = %s' % (slice_urn)
    
    # Set up the array of credentials as just the slice credential
    credentials = [slice_cred_string]

    test_get_version(am_server)
    dom = test_list_resources(am_server, credentials)
    test_create_sliver(am_server, slice_urn, credentials, dom)
    test_sliver_status(am_server, slice_urn, credentials)
    test_list_resources(am_server, credentials, slice_urn=slice_urn)
    
    expiration = datetime.datetime.utcnow() + datetime.timedelta(days=1)
    test_renew_sliver(am_server, slice_urn, credentials, expiration)
    
    test_delete_sliver(am_server, slice_urn, credentials)
    
    # Test compression on list resources
    dom = test_list_resources(am_server, credentials, compressed=True,
                              available=False)

    # Now create a slice and shut it down instead of deleting it.
    slice_name = "Slice-" + str(uuid.uuid4());
    slice_name = slice_name[:15]; # Can't have slice names too big
    slice_result = ch_server.CreateSlice(slice_name, project_id, user_uuid)
    if(slice_result['code'] != 0):
        print "Failed to create slice " + str(slice_result);
        return

    slice_info = slice_result['value'];
    sllice_id = slice_info['slice_id']
    slice_credential_result = ch_server.GetSliceCredential(slice_id, user_certstr)
    if(slice_credential_result['code'] != 0):
        print "Failed to get slice credential " + str(slice_credential_result)
        return

    slice_cred_string = slice_credential_result['value']['slice_credential']
    slice_credential = cred.Credential(string=slice_cred_string)
    slice_gid = slice_credential.get_gid_object()
    slice_urn = slice_gid.get_urn()
    print 'Second Slice URN = %s' % (slice_urn)
    credentials = [slice_cred_string]
    dom = test_list_resources(am_server, credentials)
    test_create_sliver(am_server, slice_urn, credentials, dom)
    test_shutdown(am_server, slice_urn, credentials)
Esempio n. 3
0
    def Resolve(self, client_cert, args):
        # Omni uses this, Flack may not need it

        # ID may be a uuid, hrn, or urn
        #   Omni uses hrn for type=User, urn for type=Slice
        # type is Slice or User
        # args: credential, hrn, urn, uuid, type
        # Return is dict:
        #When the type is Slice:
        #
        #{
        #  "urn"  : "URN of the slice",
        #  "uuid" : "rfc4122 universally unique identifier",
        #  "creator_uuid" : "UUID of the user who created the slice",
        #  "creator_urn" : "URN of the user who created the slice",
        #  "gid"  : "ProtoGENI Identifier (an x509 certificate)",
        #  "component_managers" : "List of CM URNs which are known to contain slivers or tickets in this slice. May be stale"
        #}
        #When the type is User:
        #
        #{
        #  "uid"  : "login (Emulab) ID of the user.",
        #  "hrn"  : "Human Readable Name (HRN)",
        #  "uuid" : "rfc4122 universally unique identifier",
        #  "email": "registered email address",
        #  "gid"  : "ProtoGENI Identifier (an x509 certificate)",
        #  "name" : "common name",
        #}

        user_email = get_email_from_cert(client_cert)
        type = None
        if 'type' in args:
            type = args['type'].lower()
        if type not in ('slice', 'user'):
            raise CHAPIv1ArgumentError("Unknown type for PGH.Resolve: %s" %
                                       str(type))

        uuid = None
        if 'uuid' in args:
            uuid = args['uuid']

        urn = None
        if 'urn' in args:
            urn = args['urn']

        hrn = None
        if 'hrn' in args:
            hrn = args['hrn']

        if not hrn and not urn and not uuid:
            raise CHAPIv1ArgumentError(
                "No UUID, URN or HRN identifier provided")

        if hrn and not urn:
            urn = gcf.sfa.util.xrn.hrn_to_urn(hrn, type)

        if type == 'user':
            # User
            ma = self._ma_handler
            match_clause = {'MEMBER_URN': urn}
            if not urn:
                match_clause = {'MEMBER_UID': uuid}
            public_filter_clause = [
                'MEMBER_UID', 'MEMBER_URN', 'MEMBER_USERNAME',
                '_GENI_MEMBER_SSL_CERTIFICATE'
            ]
            public_options = {
                "match": match_clause,
                "filter": public_filter_clause
            }
            creds = []
            lookup_public_return = \
                ma.lookup_public_member_info(creds, public_options)
            if lookup_public_return['code'] != NO_ERROR:
                return lookup_public_return
            public_info = lookup_public_return['value']
            if not public_info or len(public_info.keys()) == 0 or \
                    (urn and not public_info.has_key(urn)):
                # no user by that urn or uuid
                msg = ""
                if urn:
                    msg = "User requested not found: %s" % urn
                else:
                    msg = "User requested not found: %s" % uuid

                chapi_info(PGCH_LOG_PREFIX, msg, {'user': user_email})
                # Return an error with this message
                return {'code': ARGUMENT_ERROR, 'value': {}, 'output': msg}

            this_urn = public_info.keys()[0]
            public_info = public_info[this_urn]

            # to get a proper display name we need the following
            identifying_filter_clause = [
                'MEMBER_EMAIL', '_GENI_MEMBER_DISPLAYNAME', 'MEMBER_FIRSTNAME',
                'MEMBER_LASTNAME'
            ]
            identifying_options = {
                'match': match_clause,
                'filter': identifying_filter_clause
            }
            lookup_identifying_return = \
                ma.lookup_identifying_member_info(creds,
                                                  identifying_options)
            if lookup_identifying_return['code'] != NO_ERROR:
                return lookup_identifying_return
            identifying_info = lookup_identifying_return['value']
            identifying_info = identifying_info[this_urn]

            member_uid = public_info['MEMBER_USERNAME']
            member_hrn = gcf.sfa.util.xrn.urn_to_hrn(
                public_info['MEMBER_URN'])[0]
            member_uuid = public_info['MEMBER_UID']
            member_email = identifying_info['MEMBER_EMAIL']
            member_gid = None
            if public_info.has_key('_GENI_MEMBER_SSL_CERTIFICATE'):
                member_gid = public_info['_GENI_MEMBER_SSL_CERTIFICATE']
            member_name = get_member_display_name(identifying_info,
                                                  public_info['MEMBER_URN'])

            # Slices
            sa = self._sa_handler
            lookup_slices_return = sa.lookup_slices_for_member(urn, [], {})
            if lookup_slices_return['code'] != NO_ERROR:
                return lookup_slices_return
            slice_info = lookup_slices_return['value']
            slices = []
            for s in slice_info:
                if s['EXPIRED'] == True:
                    continue
                slices.append(s['SLICE_URN'])

            resolve = {'uid' : member_uid,  # login(Emulab) ID of user \
                           'hrn' : member_hrn, \
                           'uuid' : member_uuid, \
                           'email' : member_email, \
                           'gid' : member_gid,
                       'name' : member_name,  # Common Name
                       'slices' : slices
                       }
        else:
            # Slice
            match_clause = {'SLICE_URN': urn, 'SLICE_EXPIRED': 'f'}
            if not urn:
                match_clause = {'SLICE_UID': uuid}
            filter_clause = ["SLICE_UID", "SLICE_URN", "SLICE_NAME", \
                                 "_GENI_SLICE_OWNER"]
            options = {'match': match_clause, 'filter': filter_clause}
            creds = []
            lookup_slices_return = \
                self._sa_handler.lookup_slices(creds, options)

            if lookup_slices_return['code'] != NO_ERROR:
                if lookup_slices_return['code'] == AUTHORIZATION_ERROR:
                    # Only slice members or operators can look up a
                    # slice
                    # So this might mean you are not in the slice, or
                    # not in the project, or the slice does not exist
                    msg = ""
                    if urn:
                        msg = "No slice found or authorization failed (URN %s)" % str(
                            urn)
                    else:
                        msg = "No slice found or authorization failed (UID %s)" % str(
                            uuid)
                    chapi_info(PGCH_LOG_PREFIX, msg, {'user': user_email})
                    return {
                        'code': 12,
                        'value': {},
                        'output': msg
                    }  # 12 is what Flack expects for a nonexistent slice
                return lookup_slices_return
            slice_info_dict = lookup_slices_return['value']

            if len(slice_info_dict.keys()) == 0:
                msg = ""
                if urn:
                    msg = "No slice found URN %s" % str(urn)
                else:
                    msg = "No slice found UID %s" % str(uuid)
                chapi_info(PGCH_LOG_PREFIX, msg, {'user': user_email})
                return {'code': ARGUMENT_ERROR, 'value': {}, 'output': msg}

            slice_key = slice_info_dict.keys()[0]
            slice_info = slice_info_dict[slice_key]
            slice_name = slice_info['SLICE_NAME']
            slice_urn = slice_info['SLICE_URN']
            slice_uuid = slice_info['SLICE_UID']
            creator_uuid = slice_info['_GENI_SLICE_OWNER']

            match_clause = {'MEMBER_UID': creator_uuid}
            filter_clause = ['MEMBER_URN']
            options = {'match': match_clause, 'filter': filter_clause}
            lookup_member_return = \
                self._ma_handler.lookup_public_member_info(creds, options)

            if lookup_member_return['code'] != NO_ERROR:
                return lookup_member_return
            # If the slice owner listed is not in the DB this will
            # give an error, but that is also a DB error
            creator_urn = lookup_member_return['value'].keys()[0]

            options = {}
            get_credentials_return = \
                self._sa_handler.get_credentials(slice_urn, \
                                                     [], options)
            if get_credentials_return['code'] == AUTHORIZATION_ERROR:
                msg = "No slice found for urn %s" % slice_urn
                chapi_info(PGCH_LOG_PREFIX, msg, {'user': user_email})
                # Return an error with this message
                return {'code': ARGUMENT_ERROR, 'value': "", 'output': msg}

            if get_credentials_return['code'] != NO_ERROR:
                return get_credentials_return

            if not get_credentials_return['value'] or \
                    len(get_credentials_return['value']) == 0:
                msg = "No slice found for urn %s" % slice_urn
                chapi_info(PGCH_LOG_PREFIX, msg, {'user': user_email})
                # Return an error with this message
                return {'code': ARGUMENT_ERROR, 'value': "", 'output': msg}

            slice_cred = get_credentials_return['value'][0]['geni_value']
            slice_gid = gid.GID(slice_cred)

            resolve = {'urn' : slice_urn, \
                           'uuid' : slice_uuid, \
                           'creator_uuid' : creator_uuid, \
                           'creator_urn' : creator_urn,  \
                           # PG Identifier (an x509 cert)

                           'gid' : slice_gid.save_to_string(),   \
                           'component_managers' : []
                       }

        return self._successReturn(resolve)
Esempio n. 4
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    (opts, args) = parse_args(argv)
    # Ignore args, appease eclipse.
    _ = args
    global config, CERT_AUTHORITY
    optspath = None
    if not opts.configfile is None:
        optspath = os.path.expanduser(opts.configfile)

    config = read_config(optspath)
    CERT_AUTHORITY = config['global']['base_name']
    username = "******"
    if opts.username:
        # We'll check this is legal once we have a full URN
        username = opts.username
    dir = "."
    if opts.directory:
        dir = opts.directory

    if not opts.authority is None:
        # FIXME: Check it's legal? Should be 'an internationalized
        # domain name'
        CERT_AUTHORITY = opts.authority

    global CH_CERT_FILE, CH_KEY_FILE, AM_CERT_FILE, AM_KEY_FILE, USER_CERT_FILE, USER_KEY_FILE
    CH_CERT_FILE = getAbsPath(config['clearinghouse']['certfile'])
    CH_KEY_FILE = getAbsPath(config['clearinghouse']['keyfile'])
    AM_CERT_FILE = getAbsPath(config['aggregate_manager']['certfile'])
    AM_KEY_FILE = getAbsPath(config['aggregate_manager']['keyfile'])
    USER_CERT_FILE = getAbsPath(config['gcf-test']['certfile'])
    USER_KEY_FILE = getAbsPath(config['gcf-test']['keyfile'])

    # If username != alice then substitute actual username
    # in user_cert_file and user_key_file as appropriate
    # like USER_CERT_FILE = s/alice/$username/
    # Of course if the user edits the file to have something
    # other than alice in the filename then this does something odd
    if username != 'alice':
        USER_CERT_FILE = string.replace(USER_CERT_FILE, 'alice', username)
        USER_KEY_FILE = string.replace(USER_KEY_FILE, 'alice', username)

    try:
        for p in [
                CH_CERT_FILE, CH_KEY_FILE, AM_CERT_FILE, AM_KEY_FILE,
                USER_CERT_FILE, USER_KEY_FILE
        ]:
            if '/' in p:
                os.mkdir(p[:p.rfind('/')])
    except:
        pass

    ch_keys = None
    ch_cert = None
    if not opts.notAll or opts.ch:
        (ch_keys, ch_cert) = make_ch_cert(dir)
    else:
        if not opts.notAll or opts.exp:
            try:
                ch_cert = gid.GID(filename=os.path.join(dir, CH_CERT_FILE))
                ch_keys = cert.Keypair(filename=os.path.join(dir, CH_KEY_FILE))
            except Exception, exc:
                sys.exit(
                    "Failed to read CH(SA) cert/key from %s/%s and %s: %s" %
                    (dir, CH_CERT_FILE, CH_KEY_FILE, exc))
Esempio n. 5
0
    def get_requested_allocation_state(self, aggregate_manager, method_name,
                                       arguments, options, credentials):
        resource_info = []
        amd = aggregate_manager._delegate

        if method_name in [
                AM_Methods.CREATE_SLIVER_V2, AM_Methods.ALLOCATE_V3
        ]:

            creds = [credential.Credential(string=c) for c in credentials]

            # Grab info about  current slivers
            slices = SliceURNtoSliceObject._slices
            for slice_urn in slices:
                slice_obj = slices[slice_urn]
                slivers = slice_obj.getSlivers()
                for sliver_urn, sliver_obj in slivers.items():
                    user_urn = sliver_obj.getUserURN()
                    start_time = str(datetime.datetime.utcnow())
                    end_time = str(sliver_obj.getExpiration())
                    if isinstance(sliver_obj, VirtualMachine):
                        sliver_info = {
                            'sliver_urn': sliver_urn,
                            'slice_urn': slice_urn,
                            'user_urn': user_urn,
                            'start_time': start_time,
                            'end_time': end_time,
                            'measurements': {
                                "NODE": 1
                            }
                        }
                        resource_info.append(sliver_info)
                    elif isinstance(sliver_obj, NetworkLink):
                        self.processCapacity(resource_info,
                                             slice_obj.getRequestRspec(),
                                             sliver_urn, slice_urn, user_urn,
                                             start_time, end_time)

            # Grab all nodes from request rspec
            if 'rspec' in arguments and 'slice_urn' in arguments:
                rspec_raw = arguments['rspec']
                slice_urn = arguments['slice_urn']
                user_urn = gid.GID(
                    string=options['geni_true_caller_cert']).get_urn()

                start_time = datetime.datetime.utcnow()
                if 'geni_start_time' in options:
                    raw_start_time = options['geni_start_time']
                    start_time = amd._nativeUTC(
                        dateutil.parse.parse(raw_start_time))

                if 'geni_end_time' in options:
                    raw_end_time = options['geni_end_time']
                    end_time = amd.min_expire(creds, requested=raw_end_time)
                else:
                    end_time = amd.min_expire(creds)

                rspec = xml.dom.minidom.parseString(rspec_raw)
                nodes = rspec.getElementsByTagName('node')
                for node in nodes:
                    entry = {
                        'sliver_urn': 'not_set_yet',
                        'slice_urn': slice_urn,
                        'user_urn': user_urn,
                        'start_time': str(start_time),
                        'end_time': str(end_time),
                        'measurements': {
                            "NODE": 1
                        }
                    }
                    resource_info.append(entry)

                self.processCapacity(resource_info, rspec, 'not_set_yet',
                                     slice_urn, user_urn, start_time, end_time)

        elif method_name in [AM_Methods.RENEW_SLIVER_V2, AM_Methods.RENEW_V3]:

            # Grab the current slivers (as if we were calling createsliver/allocate with no new rspec
            resource_info = self.get_requested_allocation_state(
                aggregate_manager, AM_Methods.ALLOCATE_V3, {}, {}, [])

            creds = [credential.Credential(string=c) for c in credentials]
            expiration = amd.min_expire(creds, max_duration=amd.max_lease)
            requested_str = arguments['expiration_time']
            requested = dateutil.parser.parse(requested_str, tzinfos=tzd)
            requested = amd._naiveUTC(requested)
            if 'geni_extend_alap' in options:
                requested = min(expiration, requested)
            requested = str(requested)

            if method_name == AM_Methods.RENEW_SLIVER_V2:
                the_slice_urn = arguments['slice_urn']
                the_slice = SliceURNtoSliceObject._slices[the_slice_urn]
                slivers = the_slice.getSlivers().values()
            else:
                urns = arguments['urns']
                the_slice, slivers = amd.decode_urns(urns)
            sliver_urns = [the_sliver.getSliverURN() for the_sliver in slivers]
            for entry in resource_info:
                if entry['sliver_urn'] in sliver_urns:
                    entry['end_time'] = requested

        else:
            pass

        return resource_info