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