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