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