fix some bugs regarding sub authority implementaiton
[sfa.git] / sfa / plc / sfaImport.py
1 #
2 # The import tool assumes that the existing PLC hierarchy should all be part
3 # of "planetlab.us" (see the root_auth and level1_auth variables below).
4 #
5 # Public keys are extracted from the users' SSH keys automatically and used to
6 # create GIDs. This is relatively experimental as a custom tool had to be
7 # written to perform conversion from SSH to OpenSSL format. It only supports
8 # RSA keys at this time, not DSA keys.
9 ##
10
11 import getopt
12 import sys
13 import tempfile
14
15 from sfa.util.record import *
16 from sfa.util.genitable import GeniTable
17 from sfa.util.misc import *
18 from sfa.util.config import Config
19 from sfa.util.report import trace, error
20
21 from sfa.trust.certificate import convert_public_key, Keypair
22 from sfa.trust.trustedroot import *
23 from sfa.trust.hierarchy import *
24 from sfa.trust.gid import create_uuid
25
26
27 def un_unicode(str):
28    if isinstance(str, unicode):
29        return str.encode("ascii", "ignore")
30    else:
31        return str
32
33 def cleanup_string(str):
34     # pgsql has a fit with strings that have high ascii in them, so filter it
35     # out when generating the hrns.
36     tmp = ""
37     for c in str:
38         if ord(c) < 128:
39             tmp = tmp + c
40     str = tmp
41
42     str = un_unicode(str)
43     str = str.replace(" ", "_")
44     str = str.replace(".", "_")
45     str = str.replace("(", "_")
46     str = str.replace("'", "_")
47     str = str.replace(")", "_")
48     str = str.replace('"', "_")
49     return str
50
51 def person_to_hrn(parent_hrn, person):
52     # the old way - Lastname_Firstname
53     #personname = person['last_name'] + "_" + person['first_name']
54
55     # the new way - use email address up to the "@"
56     personname = person['email'].split("@")[0]
57
58     personname = cleanup_string(personname)
59
60     hrn = parent_hrn + "." + personname
61     return hrn
62
63
64 class sfaImport:
65
66     def __init__(self):
67         self.AuthHierarchy = Hierarchy()
68         self.TrustedRoots = TrustedRootList()
69
70         self.config = Config()
71         self.plc_auth = self.config.get_plc_auth()
72         self.root_auth = self.config.SFA_REGISTRY_ROOT_AUTH
73         self.level1_auth = self.config.SFA_REGISTRY_LEVEL1_AUTH
74         if not self.level1_auth or self.level1_auth in ['']:
75             self.level1_auth = None
76         
77         # connect to planetlab
78         self.shell = None
79         if "Url" in self.plc_auth:
80             from sfa.plc.remoteshell import RemoteShell
81             self.shell = RemoteShell()
82         else:
83             import PLC.Shell
84             self.shell = PLC.Shell.Shell(globals = globals())        
85
86     def get_auth_table(self, auth_name):
87         AuthHierarchy = self.AuthHierarchy
88         auth_info = AuthHierarchy.get_auth_info(auth_name)
89
90         table = GeniTable(hrn=auth_name, cninfo=auth_info.get_dbinfo())
91
92         # if the table doesn't exist, then it means we haven't put any records
93         # into this authority yet.
94
95         if not table.exists():
96             trace("Import: creating table for authority " + auth_name)
97             table.create()
98
99         return table
100
101
102     def create_top_level_auth_records(self, hrn):
103         AuthHierarchy = self.AuthHierarchy
104         
105         # if auth records for this hrn dont exist, create it
106         if not AuthHierarchy.auth_exists(hrn):
107             AuthHierarchy.create_auth(hrn)
108         
109
110         # get the auth info of the newly created root auth (parent)
111         # or level1_auth if it exists
112         if self.level1_auth:
113             auth_info = AuthHierarchy.get_auth_info(hrn)
114             parent_hrn = hrn
115         else:
116             parent_hrn = get_authority(hrn)
117             if not parent_hrn:
118                 parent_hrn = hrn
119             auth_info = AuthHierarchy.get_auth_info(parent_hrn)
120             
121         table = self.get_auth_table(parent_hrn)
122
123         auth_record = table.resolve("authority", hrn)
124         if not auth_record:
125             auth_record = GeniRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
126             trace("  inserting authority record for " + hrn)
127             table.insert(auth_record)
128
129
130     def import_person(self, parent_hrn, person):
131         AuthHierarchy = self.AuthHierarchy
132         hrn = person_to_hrn(parent_hrn, person)
133
134         # ASN.1 will have problems with hrn's longer than 64 characters
135         if len(hrn) > 64:
136             hrn = hrn[:64]
137
138         trace("Import: importing person " + hrn)
139
140         table = self.get_auth_table(parent_hrn)
141
142         key_ids = []
143         if 'key_ids' in person and person['key_ids']:
144             key_ids = person["key_ids"]
145
146             # get the user's private key from the SSH keys they have uploaded
147             # to planetlab
148             keys = self.shell.GetKeys(self.plc_auth, key_ids)
149             key = keys[0]['key']
150             pkey = convert_public_key(key)
151         else:
152             # the user has no keys
153             trace("   person " + hrn + " does not have a PL public key")
154
155             # if a key is unavailable, then we still need to put something in the
156             # user's GID. So make one up.
157             pkey = Keypair(create=True)
158
159         # create the gid
160         person_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
161         person_record = table.resolve("user", hrn)
162         if not person_record:
163             trace("  inserting user record for " + hrn)
164             person_record = GeniRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
165             table.insert(person_record)
166         else:
167             trace("  updating user record for " + hrn)
168             person_record = GeniRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
169             table.update(person_record)
170
171     def import_slice(self, parent_hrn, slice):
172         AuthHierarchy = self.AuthHierarchy
173         slicename = slice['name'].split("_",1)[-1]
174         slicename = cleanup_string(slicename)
175
176         if not slicename:
177             error("Import_Slice: failed to parse slice name " + slice['name'])
178             return
179
180         hrn = parent_hrn + "." + slicename
181         trace("Import: importing slice " + hrn)
182
183         table = self.get_auth_table(parent_hrn)
184
185         slice_record = table.resolve("slice", hrn)
186         if not slice_record:
187             pkey = Keypair(create=True)
188             slice_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
189             slice_record = GeniRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
190             trace("  inserting slice record for " + hrn)
191             table.insert(slice_record)
192
193     def import_node(self, parent_hrn, node):
194         AuthHierarchy = self.AuthHierarchy
195         nodename = node['hostname'].replace(".", "_")
196         nodename = cleanup_string(nodename)
197
198         if not nodename:
199             error("Import_node: failed to parse node name " + node['hostname'])
200             return
201
202         hrn = parent_hrn + "." + nodename
203
204         # ASN.1 will have problems with hrn's longer than 64 characters
205         if len(hrn) > 64:
206             hrn = hrn[:64]
207
208         trace("Import: importing node " + hrn)
209
210         table = self.get_auth_table(parent_hrn)
211
212         node_record = table.resolve("node", hrn)
213         if not node_record:
214             pkey = Keypair(create=True)
215             node_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
216             node_record = GeniRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
217             trace("  inserting node record for " + hrn)
218             table.insert(node_record)
219
220
221     
222     def import_site(self, parent_hrn, site):
223         AuthHierarchy = self.AuthHierarchy
224         shell = self.shell
225         plc_auth = self.plc_auth
226         sitename = site['login_base']
227         sitename = cleanup_string(sitename)
228
229         hrn = parent_hrn + "." + sitename
230
231         # Hardcode 'internet2' into the hrn for sites hosting
232         # internet2 nodes. This is a special operation for some vini
233         # sites only
234         if ".vini" in parent_hrn and parent_hrn.endswith('vini'):
235             if sitename.startswith("ii"):
236                 sitename = sitename.replace("ii", "")
237                 hrn = ".".join([parent_hrn, "internet2", sitename])
238             elif sitename.startswith("nlr"):
239                 hrn = ".".join([parent_hrn, "internet2", sitename])
240                 sitename = sitename.replace("nlr", "")
241
242         trace("Import_Site: importing site " + hrn)
243
244         # create the authority
245         if not AuthHierarchy.auth_exists(hrn):
246             AuthHierarchy.create_auth(hrn)
247
248         auth_info = AuthHierarchy.get_auth_info(hrn)
249
250         table = self.get_auth_table(parent_hrn)
251
252         auth_record = table.resolve("authority", hrn)
253         if not auth_record:
254             auth_record = GeniRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
255             trace("  inserting authority record for " + hrn)
256             table.insert(auth_record)
257
258         if 'person_ids' in site:
259             for person_id in site['person_ids']:
260                 persons = shell.GetPersons(plc_auth, [person_id])
261                 if persons:
262                     try:
263                         self.import_person(hrn, persons[0])
264                     except Exception, e:
265                         trace("Failed to import: %s (%s)" % (persons[0], e))
266         if 'slice_ids' in site:
267             for slice_id in site['slice_ids']:
268                 slices = shell.GetSlices(plc_auth, [slice_id])
269                 if slices:
270                     try:
271                         self.import_slice(hrn, slices[0])
272                     except Exception, e:
273                         trace("Failed to import: %s (%s)" % (slices[0], e))
274         if 'node_ids' in site:
275             for node_id in site['node_ids']:
276                 nodes = shell.GetNodes(plc_auth, [node_id])
277                 if nodes:
278                     try:
279                         self.import_node(hrn, nodes[0])
280                     except Exception, e:
281                         trace("Failed to import: %s (%s)" % (nodes[0], e))     
282
283     def delete_record(self, parent_hrn, object, type):
284         # get the hrn
285         hrn = None
286         if type in ['slice'] and 'name' in object and object['name']:
287             slice_name = object['name'].split("_")[0]
288             hrn = parent_hrn + "." + slice_name
289         elif type in ['user'] and 'email' in object and object['email']:
290             person_name = object['email'].split('@')[0]
291             hrn = parent_hrn + "." + person_name
292         elif type in ['node'] and 'hostname' in object and object['hostname']:
293             node_name =  object['hostname'].replace('.','_')  
294             hrn = parent_hrn + "." + node_name
295         elif type in ['site'] and 'login_base' in object and object['login_base']:
296             site_name = object['login_base']
297             hrn = parent_hrn
298             parent_hrn = get_authority(hrn)
299             type = "authority"
300             # delete the site table
301             site_table = self.get_auth_table(hrn)
302             site_table.drop()
303         else:
304             return
305         
306         # delete the record
307         table = self.get_auth_table(parent_hrn)
308         record_list = table.resolve(type, hrn)
309         if not record_list:
310             return
311         record = record_list[0]
312         table.remove(record)