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