documentation updates
[sfa.git] / registry / registry.py
1 ##
2 # Geni Registry Wrapper
3 #
4 # This wrapper implements the Geni Registry.
5 #
6 # There are several items that need to be done before starting the registry.
7 #
8 # 1) Import the existing planetlab database, creating the
9 # appropriate geni records. This is done by running the "import.py" tool.
10 #
11 # 2) Create a "trusted_roots" directory and place the certificate of the root
12 # authority in that directory. Given the defaults in import.py, this certificate
13 # would be named "planetlab.gid". For example,
14 #
15 #    mkdir trusted_roots; cp authorities/planetlab.gid trusted_roots/
16 ##
17
18 import tempfile
19 import os
20 import time
21 import sys
22
23 from cert import *
24 from gid import *
25 from geniserver import *
26 from excep import *
27 from trustedroot import *
28 from hierarchy import *
29 from misc import *
30 from record import *
31 from genitable import *
32 from geniticket import *
33
34 ##
35 # Convert geni fields to PLC fields for use when registering up updating
36 # registry record in the PLC database
37 #
38 # @params type type of record (user, slice, ...)
39 # @params hrn human readable name
40 # @params geni_fields dictionary of geni fields
41 # @params pl_fields dictionary of PLC fields (output)
42
43 def geni_fields_to_pl_fields(type, hrn, geni_fields, pl_fields):
44     if type == "user":
45         if not "email" in pl_fields:
46             if not "email" in geni_fields:
47                 raise MissingGeniInfo("email")
48             pl_fields["email"] = geni_fields["email"]
49
50         if not "first_name" in pl_fields:
51             pl_fields["first_name"] = "geni"
52
53         if not "last_name" in pl_fields:
54             pl_fields["last_name"] = hrn
55
56     elif type == "slice":
57         if not "instantiation" in pl_fields:
58             pl_fields["instantiation"] = "plc-instantiated"
59         if not "name" in pl_fields:
60             pl_fields["name"] = hrn_to_pl_slicename(hrn)
61         if not "max_nodes" in pl_fields:
62             pl_fields["max_nodes"] = 10
63
64     elif type == "node":
65         if not "hostname" in pl_fields:
66             if not "dns" in geni_fields:
67                 raise MissingGeniInfo("dns")
68             pl_fields["hostname"] = geni_fields["dns"]
69
70         if not "model" in pl_fields:
71             pl_fields["model"] = "geni"
72
73     elif type == "sa":
74         pl_fields["login_base"] = hrn_to_pl_login_base(hrn)
75
76         if not "name" in pl_fields:
77             pl_fields["name"] = hrn
78
79         if not "abbreviated_name" in pl_fields:
80             pl_fields["abbreviated_name"] = hrn
81
82         if not "enabled" in pl_fields:
83             pl_fields["enabled"] = True
84
85         if not "is_public" in pl_fields:
86             pl_fields["is_public"] = True
87
88 ##
89 # Registry is a GeniServer that serves registry requests. It also serves
90 # component and slice operations that are implemented on the registry
91 # due to SFA engineering decisions
92 #
93
94 class Registry(GeniServer):
95     ##
96     # Create a new registry object.
97     #
98     # @param ip the ip address to listen on
99     # @param port the port to listen on
100     # @param key_file private key filename of registry
101     # @param cert_file certificate filename containing public key (could be a GID file)
102
103     def __init__(self, ip, port, key_file, cert_file):
104         GeniServer.__init__(self, ip, port, key_file, cert_file)
105
106         # get PL account settings from config module
107         self.pl_auth = get_pl_auth()
108
109         # connect to planetlab
110         if "Url" in self.pl_auth:
111             self.connect_remote_shell()
112         else:
113             self.connect_local_shell()
114
115     ##
116     # Connect to a remote shell via XMLRPC
117
118     def connect_remote_shell(self):
119         import remoteshell
120         self.shell = remoteshell.RemoteShell()
121
122     ##
123     # Connect to a local shell via local API functions
124
125     def connect_local_shell(self):
126         import PLC.Shell
127         self.shell = PLC.Shell.Shell(globals = globals())
128
129     ##
130     # Register the server RPCs for the registry
131
132     def register_functions(self):
133         GeniServer.register_functions(self)
134         # registry interface
135         self.server.register_function(self.create_gid)
136         self.server.register_function(self.get_self_credential)
137         self.server.register_function(self.get_credential)
138         self.server.register_function(self.get_gid)
139         self.server.register_function(self.register)
140         self.server.register_function(self.remove)
141         self.server.register_function(self.update)
142         self.server.register_function(self.list)
143         self.server.register_function(self.resolve)
144         # component interface
145         self.server.register_function(self.get_ticket)
146
147     ##
148     # Given an authority name, return the information for that authority. This
149     # is basically a stub that calls the hierarchy module.
150     #
151     # @param auth_hrn human readable name of authority
152
153     def get_auth_info(self, auth_hrn):
154         return AuthHierarchy.get_auth_info(auth_hrn)
155
156     ##
157     # Given an authority name, return the database table for that authority. If
158     # the database table does not exist, then one will be automatically
159     # created.
160     #
161     # @param auth_name human readable name of authority
162
163     def get_auth_table(self, auth_name):
164         auth_info = self.get_auth_info(auth_name)
165
166         table = GeniTable(hrn=auth_name,
167                           cninfo=auth_info.get_dbinfo())
168
169         # if the table doesn't exist, then it means we haven't put any records
170         # into this authority yet.
171
172         if not table.exists():
173             report.trace("Registry: creating table for authority " + auth_name)
174             table.create()
175
176         return table
177
178     ##
179     # Verify that an authority belongs to this registry. This is basically left
180     # up to the implementation of the hierarchy module. If the specified name
181     # does not belong to this registry, an exception is thrown indicating the
182     # caller should contact someone else.
183     #
184     # @param auth_name human readable name of authority
185
186     def verify_auth_belongs_to_me(self, name):
187         # get_auth_info will throw an exception if the authority does not
188         # exist
189         self.get_auth_info(name)
190
191     ##
192     # Verify that an object belongs to this registry. By extension, this implies
193     # that the authority that owns the object belongs to this registry. If the
194     # object does not belong to this registry, then an exception is thrown.
195     #
196     # @param name human readable name of object
197
198     def verify_object_belongs_to_me(self, name):
199         auth_name = get_authority(name)
200         if not auth_name:
201             # the root authority belongs to the registry by default?
202             # TODO: is this true?
203             return
204         self.verify_auth_belongs_to_me(auth_name)
205
206     ##
207     # Verify that the object_gid that was specified in the credential allows
208     # permission to the object 'name'. This is done by a simple prefix test.
209     # For example, an object_gid for planetlab.us.arizona would match the
210     # objects planetlab.us.arizona.slice1 and planetlab.us.arizona.
211     #
212     # @param name human readable name to test
213
214     def verify_object_permission(self, name):
215         object_hrn = self.object_gid.get_hrn()
216         if object_hrn == name:
217             return
218         if name.startswith(object_hrn + "."):
219             return
220         raise PermissionError(name)
221
222     ##
223     # Fill in the planetlab-specific fields of a Geni record. This involves
224     # calling the appropriate PLC methods to retrieve the database record for
225     # the object.
226     #
227     # PLC data is filled into the pl_info field of the record.
228     #
229     # @param record record to fill in fields (in/out param)
230
231     def fill_record_pl_info(self, record):
232         type = record.get_type()
233         pointer = record.get_pointer()
234
235         # records with pointer==-1 do not have plc info associated with them.
236         # for example, the top level authority records which are
237         # authorities, but not PL "sites"
238         if pointer == -1:
239             return
240
241         if (type == "sa") or (type == "ma"):
242             pl_res = self.shell.GetSites(self.pl_auth, [pointer])
243         elif (type == "slice"):
244             pl_res = self.shell.GetSlices(self.pl_auth, [pointer])
245         elif (type == "user"):
246             pl_res = self.shell.GetPersons(self.pl_auth, [pointer])
247         elif (type == "node"):
248             pl_res = self.shell.GetNodes(self.pl_auth, [pointer])
249         else:
250             raise UnknownGeniType(type)
251
252         if not pl_res:
253             # the planetlab record no longer exists
254             # TODO: delete the geni record ?
255             raise PlanetLabRecordDoesNotExist(record.get_name())
256
257         record.set_pl_info(pl_res[0])
258
259     ##
260     # Look up user records given PLC user-ids. This is used as part of the
261     # process for reverse-mapping PLC records into Geni records.
262     #
263     # @param auth_table database table for the authority that holds the user records
264     # @param user_id_list list of user ids
265     # @param role either "*" or a string describing the role to look for ("pi", "user", ...)
266     #
267     # TODO: This function currently only searches one authority because it would
268     # be inefficient to brute-force search all authorities for a user id. The
269     # solution would likely be to implement a reverse mapping of user-id to
270     # (type, hrn) pairs.
271
272     def lookup_users(self, auth_table, user_id_list, role="*"):
273         record_list = []
274         for person_id in user_id_list:
275             user_records = auth_table.find("user", person_id, "pointer")
276             for user_record in user_records:
277                 self.fill_record_info(user_record)
278
279                 user_roles = user_record.get_pl_info().get("roles")
280                 if (role=="*") or (role in user_roles):
281                     record_list.append(user_record.get_name())
282         return record_list
283
284     ##
285     # Fill in the geni-specific fields of the record.
286     #
287     # Note: It is assumed the fill_record_pl_info() has already been performed
288     # on the record.
289
290     def fill_record_geni_info(self, record):
291         geni_info = {}
292         type = record.get_type()
293
294         if (type == "slice"):
295             auth_table = self.get_auth_table(get_authority(record.get_name()))
296             person_ids = record.pl_info.get("person_ids", [])
297             researchers = self.lookup_users(auth_table, person_ids)
298             geni_info['researcher'] = researchers
299
300         elif (type == "sa"):
301             auth_table = self.get_auth_table(record.get_name())
302             person_ids = record.pl_info.get("person_ids", [])
303             pis = self.lookup_users(auth_table, person_ids, "pi")
304             geni_info['pi'] = pis
305             # TODO: OrganizationName
306
307         elif (type == "ma"):
308             auth_table = self.get_auth_table(record.get_name())
309             person_ids = record.pl_info.get("person_ids", [])
310             operators = self.lookup_users(auth_table, person_ids, "tech")
311             geni_info['operator'] = operators
312             # TODO: OrganizationName
313
314             auth_table = self.get_auth_table(record.get_name())
315             person_ids = record.pl_info.get("person_ids", [])
316             owners = self.lookup_users(auth_table, person_ids, "admin")
317             geni_info['owner'] = owners
318
319         elif (type == "node"):
320             geni_info['dns'] = record.pl_info.get("hostname", "")
321             # TODO: URI, LatLong, IP, DNS
322
323         elif (type == "user"):
324             geni_info['email'] = record.pl_info.get("email", "")
325             # TODO: PostalAddress, Phone
326
327         record.set_geni_info(geni_info)
328
329     ##
330     # Given a Geni record, fill in the PLC-specific and Geni-specific fields
331     # in the record.
332
333     def fill_record_info(self, record):
334         self.fill_record_pl_info(record)
335         self.fill_record_geni_info(record)
336
337     ##
338     # GENI API: register
339     #
340     # Register an object with the registry. In addition to being stored in the
341     # Geni database, the appropriate records will also be created in the
342     # PLC databases
343     #
344     # @param cred credential string
345     # @param record_dict dictionary containing record fields
346
347     def register(self, cred, record_dict):
348         self.decode_authentication(cred, "register")
349
350         record = GeniRecord(dict = record_dict)
351         type = record.get_type()
352         name = record.get_name()
353
354         auth_name = get_authority(name)
355         self.verify_object_permission(auth_name)
356         auth_info = self.get_auth_info(auth_name)
357         table = self.get_auth_table(auth_name)
358
359         pkey = None
360
361         # check if record already exists
362         existing_records = table.resolve(type, name)
363         if existing_records:
364             raise ExistingRecord(name)
365
366         if (type == "sa") or (type=="ma"):
367             # update the tree
368             if not AuthHierarchy.auth_exists(name):
369                 AuthHierarchy.create_auth(name)
370
371             # authorities are special since they are managed by the registry
372             # rather than by the caller. We create our own GID for the
373             # authority rather than relying on the caller to supply one.
374
375             # get the GID from the newly created authority
376             child_auth_info = self.get_auth_info(name)
377             gid = auth_info.get_gid_object()
378             record.set_gid(gid.save_to_string(save_parents=True))
379
380             geni_fields = record.get_geni_info()
381             site_fields = record.get_pl_info()
382
383             # if registering a sa, see if a ma already exists
384             # if registering a ma, see if a sa already exists
385             if (type == "sa"):
386                 other_rec = table.resolve("ma", record.get_name())
387             elif (type == "ma"):
388                 other_rec = table.resolve("sa", record.get_name())
389
390             if other_rec:
391                 print "linking ma and sa to the same plc site"
392                 pointer = other_rec[0].get_pointer()
393             else:
394                 geni_fields_to_pl_fields(type, name, geni_fields, site_fields)
395                 print "adding site with fields", site_fields
396                 pointer = self.shell.AddSite(self.pl_auth, site_fields)
397
398             record.set_pointer(pointer)
399
400         elif (type == "slice"):
401             geni_fields = record.get_geni_info()
402             slice_fields = record.get_pl_info()
403
404             geni_fields_to_pl_fields(type, name, geni_fields, slice_fields)
405
406             pointer = self.shell.AddSlice(self.pl_auth, slice_fields)
407             record.set_pointer(pointer)
408
409         elif (type == "user"):
410             geni_fields = record.get_geni_info()
411             user_fields = record.get_pl_info()
412
413             geni_fields_to_pl_fields(type, name, geni_fields, user_fields)
414
415             pointer = self.shell.AddPerson(self.pl_auth, user_fields)
416             record.set_pointer(pointer)
417
418         elif (type == "node"):
419             geni_fields = record.get_geni_info()
420             node_fields = record.get_pl_info()
421
422             geni_fields_to_pl_fields(type, name, geni_fields, node_fields)
423
424             login_base = hrn_to_pl_login_base(auth_name)
425
426             print "calling addnode with", login_base, node_fields
427             pointer = self.shell.AddNode(self.pl_auth, login_base, node_fields)
428             record.set_pointer(pointer)
429
430         else:
431             raise UnknownGeniType(type)
432
433         table.insert(record)
434
435         return record.get_gid_object().save_to_string(save_parents=True)
436
437     ##
438     # GENI API: remove
439     #
440     # Remove an object from the registry. If the object represents a PLC object,
441     # then the PLC records will also be removed.
442     #
443     # @param cred credential string
444     # @param record_dict dictionary containing record fields. The only relevant
445     #     fields of the record are 'name' and 'type', which are used to lookup
446     #     the current copy of the record in the Geni database, to make sure
447     #     that the appopriate record is removed.
448
449     def remove(self, cred, record_dict):
450         self.decode_authentication(cred, "remove")
451
452         record = GeniRecord(dict = record_dict)
453         type = record.get_type()
454
455         self.verify_object_permission(record.get_name())
456
457         auth_name = get_authority(record.get_name())
458         table = self.get_auth_table(auth_name)
459
460         # let's not trust that the caller has a well-formed record (a forged
461         # pointer field could be a disaster), so look it up ourselves
462         record_list = table.resolve(type, record.get_name())
463         if not record_list:
464             raise RecordNotFound(name)
465         record = record_list[0]
466
467         # TODO: sa, ma
468         if type == "user":
469             self.shell.DeletePerson(self.pl_auth, record.get_pointer())
470         elif type == "slice":
471             self.shell.DeleteSlice(self.pl_auth, record.get_pointer())
472         elif type == "node":
473             self.shell.DeleteNode(self.pl_auth, record.get_pointer())
474         elif (type == "sa") or (type == "ma"):
475             if (type == "sa"):
476                 other_rec = table.resolve("ma", record.get_name())
477             elif (type == "ma"):
478                 other_rec = table.resolve("sa", record.get_name())
479
480             if other_rec:
481                 # sa and ma both map to a site, so if we are deleting one
482                 # but the other still exists, then do not delete the site
483                 print "not removing site", record.get_name(), "because either sa or ma still exists"
484                 pass
485             else:
486                 print "removing site", record.get_name()
487                 self.shell.DeleteSite(self.pl_auth, record.get_pointer())
488         else:
489             raise UnknownGeniType(type)
490
491         table.remove(record)
492
493         return True
494
495     ##
496     # GENI API: Register
497     #
498     # Update an object in the registry. Currently, this only updates the
499     # PLC information associated with the record. The Geni fields (name, type,
500     # GID) are fixed.
501     #
502     # The record is expected to have the pl_info field filled in with the data
503     # that should be updated.
504     #
505     # TODO: The geni_info member of the record should be parsed and the pl_info
506     # adjusted as necessary (add/remove users from a slice, etc)
507     #
508     # @param cred credential string specifying rights of the caller
509     # @param record a record dictionary to be updated
510
511     def update(self, cred, record_dict):
512         self.decode_authentication(cred, "update")
513
514         record = GeniRecord(dict = record_dict)
515         type = record.get_type()
516
517         self.verify_object_permission(record.get_name())
518
519         auth_name = get_authority(record.get_name())
520         table = self.get_auth_table(auth_name)
521
522         # make sure the record exists
523         existing_record_list = table.resolve(type, record.get_name())
524         if not existing_record_list:
525             raise RecordNotFound(record.get_name())
526
527         existing_record = existing_record_list[0]
528         pointer = existing_record.get_pointer()
529
530         # update the PLC information that was specified with the record
531
532         if (type == "sa") or (type == "ma"):
533             self.shell.UpdateSite(self.pl_auth, pointer, record.get_pl_info())
534
535         elif type == "slice":
536             self.shell.UpdateSlice(self.pl_auth, pointer, record.get_pl_info())
537
538         elif type == "user":
539             self.shell.UpdatePerson(self.pl_auth, pointer, record.get_pl_info())
540
541         elif type == "node":
542             self.shell.UpdateNode(self.pl_auth, pointer, record.get_pl_info())
543
544         else:
545             raise UnknownGeniType(type)
546
547     ##
548     # List the records in an authority. The objectGID in the supplied credential
549     # should name the authority that will be listed.
550     #
551     # TODO: List doesn't take an hrn and uses the hrn contained in the
552     #    objectGid of the credential. Does this mean the only way to list an
553     #    authority is by having a credential for that authority?
554     #
555     # @param cred credential string specifying rights of the caller
556     #
557     # @return list of record dictionaries
558     def list(self, cred):
559         self.decode_authentication(cred, "list")
560
561         auth_name = self.object_gid.get_hrn()
562         table = self.get_auth_table(auth_name)
563
564         records = table.list()
565
566         good_records = []
567         for record in records:
568             try:
569                 self.fill_record_info(record)
570                 good_records.append(record)
571             except PlanetLabRecordDoesNotExist:
572                 # silently drop the ones that are missing in PL.
573                 # is this the right thing to do?
574                 report.error("ignoring geni record " + record.get_name() + " because pl record does not exist")
575                 table.remove(record)
576
577         dicts = []
578         for record in good_records:
579             dicts.append(record.as_dict())
580
581         return dicts
582
583         return dict_list
584
585     ##
586     # Resolve a record. This is an internal version of the Resolve API call
587     # and returns records in record object format rather than dictionaries
588     # that may be sent over XMLRPC.
589     #
590     # @param type type of record to resolve (user | sa | ma | slice | node)
591     # @param name human readable name of object
592     # @param must_exist if True, throw an exception if no records are found
593     #
594     # @return a list of record objects, or an empty list []
595
596     def resolve_raw(self, type, name, must_exist=True):
597         auth_name = get_authority(name)
598
599         table = self.get_auth_table(auth_name)
600
601         records = table.resolve(type, name)
602
603         if (not records) and must_exist:
604             raise RecordNotFound(name)
605
606         good_records = []
607         for record in records:
608             try:
609                 self.fill_record_info(record)
610                 good_records.append(record)
611             except PlanetLabRecordDoesNotExist:
612                 # silently drop the ones that are missing in PL.
613                 # is this the right thing to do?
614                 report.error("ignoring geni record " + record.get_name() + " because pl record does not exist")
615                 table.remove(record)
616
617         return good_records
618
619     ##
620     # GENI API: Resolve
621     #
622     # This is a wrapper around resolve_raw that converts records objects into
623     # dictionaries before returning them to the user.
624     #
625     # @param cred credential string authorizing the caller
626     # @param name human readable name to resolve
627     #
628     # @return a list of record dictionaries, or an empty list
629
630     def resolve(self, cred, name):
631         self.decode_authentication(cred, "resolve")
632
633         records = self.resolve_raw("*", name)
634         dicts = []
635         for record in records:
636             dicts.append(record.as_dict())
637
638         return dicts
639
640     ##
641     # GENI API: get_gid
642     #
643     # Retrieve the GID for an object. This function looks up a record in the
644     # registry and returns the GID of the record if it exists.
645     # TODO: Is this function needed? It's a shortcut for Resolve()
646     #
647     # @param name hrn to look up
648     #
649     # @return the string representation of a GID object
650
651     def get_gid(self, name):
652         self.verify_object_belongs_to_me(name)
653         records = self.resolve_raw("*", name)
654         gid_string_list = []
655         for record in records:
656             gid = record.get_gid()
657             gid_string_list.append(gid.save_to_string(save_parents=True))
658         return gid_string_list
659
660     ##
661     # Determine tje rights that an object should have. The rights are entirely
662     # dependent on the type of the object. For example, users automatically
663     # get "refresh", "resolve", and "info".
664     #
665     # @param type the type of the object (user | sa | ma | slice | node)
666     # @param name human readable name of the object (not used at this time)
667     #
668     # @return RightList object containing rights
669
670     def determine_rights(self, type, name):
671         rl = RightList()
672
673         # rights seem to be somewhat redundant with the type of the credential.
674         # For example, a "sa" credential implies the authority right, because
675         # a sa credential cannot be issued to a user who is not an owner of
676         # the authority
677
678         if type == "user":
679             rl.add("refresh")
680             rl.add("resolve")
681             rl.add("info")
682         elif type == "sa":
683             rl.add("authority")
684         elif type == "ma":
685             rl.add("authority")
686         elif type == "slice":
687             rl.add("embed")
688             rl.add("bind")
689             rl.add("control")
690             rl.add("info")
691         elif type == "component":
692             rl.add("operator")
693
694         return rl
695
696     ##
697     # GENI API: Get_self_credential
698     #
699     # Get_self_credential a degenerate version of get_credential used by a
700     # client to get his initial credential when he doesn't have one. This is
701     # the same as get_credential(..., cred=None,...).
702     #
703     # The registry ensures that the client is the principal that is named by
704     # (type, name) by comparing the public key in the record's GID to the
705     # private key used to encrypt the client-side of the HTTPS connection. Thus
706     # it is impossible for one principal to retrieve another principal's
707     # credential without having the appropriate private key.
708     #
709     # @param type type of object (user | slice | sa | ma | node
710     # @param name human readable name of object
711     #
712     # @return the string representation of a credential object
713
714     def get_self_credential(self, type, name):
715         self.verify_object_belongs_to_me(name)
716
717         auth_hrn = get_authority(name)
718         auth_info = self.get_auth_info(auth_hrn)
719
720         # find a record that matches
721         records = self.resolve_raw(type, name, must_exist=True)
722         record = records[0]
723
724         gid = record.get_gid_object()
725         peer_cert = self.server.peer_cert
726         if not peer_cert.is_pubkey(gid.get_pubkey()):
727            raise ConnectionKeyGIDMismatch(gid.get_subject())
728
729         # create the credential
730         gid = record.get_gid_object()
731         cred = Credential(subject = gid.get_subject())
732         cred.set_gid_caller(gid)
733         cred.set_gid_object(gid)
734         cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
735         cred.set_pubkey(gid.get_pubkey())
736
737         rl = self.determine_rights(type, name)
738         cred.set_privileges(rl)
739
740         cred.set_parent(AuthHierarchy.get_auth_cred(auth_hrn))
741
742         cred.encode()
743         cred.sign()
744
745         return cred.save_to_string(save_parents=True)
746
747     ##
748     # GENI API: Get_credential
749     #
750     # Retrieve a credential for an object.
751     #
752     # If cred==None, then the behavior reverts to get_self_credential()
753     #
754     # @param cred credential object specifying rights of the caller
755     # @param type type of object (user | slice | sa | ma | node)
756     # @param name human readable name of object
757     #
758     # @return the string representation of a credental object
759
760     def get_credential(self, cred, type, name):
761         if not cred:
762             return get_self_credential(self, type, name)
763
764         self.decode_authentication(cred, "getcredential")
765
766         self.verify_object_belongs_to_me(name)
767
768         auth_hrn = get_authority(name)
769         auth_info = self.get_auth_info(auth_hrn)
770
771         records = self.resolve_raw(type, name, must_exist=True)
772         record = records[0]
773
774         # TODO: Check permission that self.client_cred can access the object
775
776         object_gid = record.get_gid_object()
777         new_cred = Credential(subject = object_gid.get_subject())
778         new_cred.set_gid_caller(self.client_gid)
779         new_cred.set_gid_object(object_gid)
780         new_cred.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
781         new_cred.set_pubkey(object_gid.get_pubkey())
782
783         rl = self.determine_rights(type, name)
784         new_cred.set_privileges(rl)
785
786         new_cred.set_parent(AuthHierarchy.get_auth_cred(auth_hrn))
787
788         new_cred.encode()
789         new_cred.sign()
790
791         return new_cred.save_to_string(save_parents=True)
792
793     ##
794     # GENI_API: Create_gid
795     #
796     # Create a new GID. For MAs and SAs that are physically located on the
797     # registry, this allows a owner/operator/PI to create a new GID and have it
798     # signed by his respective authority.
799     #
800     # @param cred credential of caller
801     # @param name hrn for new GID
802     # @param uuid unique identifier for new GID
803     # @param pkey_string public-key string (TODO: why is this a string and not a keypair object?)
804     #
805     # @return the string representation of a GID object
806
807     def create_gid(self, cred, name, uuid, pubkey_str):
808         self.decode_authentication(cred, "getcredential")
809
810         self.verify_object_belongs_to_me(name)
811
812         self.verify_object_permission(name)
813
814         if uuid == None:
815             uuid = create_uuid()
816
817         pkey = Keypair()
818         pkey.load_pubkey_from_string(pubkey_str)
819         gid = AuthHierarchy.create_gid(name, uuid, pkey)
820
821         return gid.save_to_string(save_parents=True)
822
823     # ------------------------------------------------------------------------
824     # Component Interface
825
826     ##
827     # Convert a PLC record into the slice information that will be stored in
828     # a ticket. There are two parts to this information: attributes and
829     # rspec.
830     #
831     # Attributes are non-resource items, such as keys and the initscript
832     # Rspec is a set of resource specifications
833     #
834     # @param record a record object
835     #
836     # @return a tuple (attrs, rspec) of dictionaries
837
838     def record_to_slice_info(self, record):
839
840         # get the user keys from the slice
841         keys = []
842         persons = self.shell.GetPersons(self.pl_auth, record.pl_info['person_ids'])
843         for person in persons:
844             person_keys = self.shell.GetKeys(self.pl_auth, person["key_ids"])
845             for person_key in person_keys:
846                 keys = keys + [person_key['key']]
847
848         attributes={}
849         attributes['name'] = record.pl_info['name']
850         attributes['keys'] = keys
851         attributes['instantiation'] = record.pl_info['instantiation']
852         attributes['vref'] = 'default'
853         attributes['timestamp'] = time.time()
854
855         rspec = {}
856
857         # get the PLC attributes and separate them into slice attributes and
858         # rspec attributes
859         filter = {}
860         filter['slice_id'] = record.pl_info['slice_id']
861         plc_attrs = self.shell.GetSliceAttributes(self.pl_auth, filter)
862         for attr in plc_attrs:
863             name = attr['name']
864
865             # initscripts: lookup the contents of the initscript and store it
866             # in the ticket attributes
867             if (name == "initscript"):
868                 filter={'name': attr['value']}
869                 initscripts = self.shell.GetInitScripts(self.pl_auth, filter)
870                 if initscripts:
871                     attributes['initscript'] = initscripts[0]['script']
872             else:
873                 rspec[name] = attr['value']
874
875         return (attributes, rspec)
876
877     ##
878     # GENI API: get_ticket
879     #
880     # Retrieve a ticket. This operation is currently implemented on the
881     # registry (see SFA, engineering decisions), and is not implemented on
882     # components.
883     #
884     # The ticket is filled in with information from the PLC database. This
885     # information includes resources, and attributes such as user keys and
886     # initscripts.
887     #
888     # @param cred credential string
889     # @param name name of the slice to retrieve a ticket for
890     # @param rspec resource specification dictionary
891     #
892     # @return the string representation of a ticket object
893
894     def get_ticket(self, cred, name, rspec):
895         self.decode_authentication(cred, "getticket")
896
897         self.verify_object_belongs_to_me(name)
898
899         self.verify_object_permission(name)
900
901         # XXX much of this code looks like get_credential... are they so similar
902         # that they should be combined?
903
904         auth_hrn = get_authority(name)
905         auth_info = self.get_auth_info(auth_hrn)
906
907         records = self.resolve_raw("slice", name, must_exist=True)
908         record = records[0]
909
910         object_gid = record.get_gid_object()
911         new_ticket = Ticket(subject = object_gid.get_subject())
912         new_ticket.set_gid_caller(self.client_gid)
913         new_ticket.set_gid_object(object_gid)
914         new_ticket.set_issuer(key=auth_info.get_pkey_object(), subject=auth_hrn)
915         new_ticket.set_pubkey(object_gid.get_pubkey())
916
917         self.fill_record_info(record)
918
919         (attributes, rspec) = self.record_to_slice_info(record)
920
921         new_ticket.set_attributes(attributes)
922         new_ticket.set_rspec(rspec)
923
924         new_ticket.set_parent(AuthHierarchy.get_auth_ticket(auth_hrn))
925
926         new_ticket.encode()
927         new_ticket.sign()
928
929         return new_ticket.save_to_string(save_parents=True)
930
931
932 if __name__ == "__main__":
933     global AuthHierarchy
934     global TrustedRoots
935
936     key_file = "server.key"
937     cert_file = "server.cert"
938
939     # if no key is specified, then make one up
940     if (not os.path.exists(key_file)) or (not os.path.exists(cert_file)):
941         key = Keypair(create=True)
942         key.save_to_file(key_file)
943
944         cert = Certificate(subject="registry")
945         cert.set_issuer(key=key, subject="registry")
946         cert.set_pubkey(key)
947         cert.sign()
948         cert.save_to_file(cert_file)
949
950     AuthHierarchy = Hierarchy()
951
952     TrustedRoots = TrustedRootList()
953
954     s = Registry("", 12345, key_file, cert_file)
955     s.trusted_cert_list = TrustedRoots.get_list()
956     s.run()
957