dont inculde full dns name in the node hrn
[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
87     def create_top_level_auth_records(self, hrn):
88         AuthHierarchy = self.AuthHierarchy
89         
90         # if auth records for this hrn dont exist, create it
91         if not AuthHierarchy.auth_exists(hrn):
92             AuthHierarchy.create_auth(hrn)
93         
94
95         # get the auth info of the newly created root auth (parent)
96         # or level1_auth if it exists
97         if self.level1_auth:
98             auth_info = AuthHierarchy.get_auth_info(hrn)
99             parent_hrn = hrn
100         else:
101             parent_hrn = get_authority(hrn)
102             if not parent_hrn:
103                 parent_hrn = hrn
104             auth_info = AuthHierarchy.get_auth_info(parent_hrn)
105             
106         table = GeniTable()
107         auth_record = table.find({'type': 'authority', 'hrn': hrn})
108
109         if not auth_record:
110             auth_record = GeniRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
111             trace("  inserting authority record for " + hrn)
112             table.insert(auth_record)
113
114
115     def import_person(self, parent_hrn, person):
116         AuthHierarchy = self.AuthHierarchy
117         hrn = person_to_hrn(parent_hrn, person)
118
119         # ASN.1 will have problems with hrn's longer than 64 characters
120         if len(hrn) > 64:
121             hrn = hrn[:64]
122
123         trace("Import: importing person " + hrn)
124
125         table = GeniTable()
126
127         key_ids = []
128         if 'key_ids' in person and person['key_ids']:
129             key_ids = person["key_ids"]
130
131             # get the user's private key from the SSH keys they have uploaded
132             # to planetlab
133             keys = self.shell.GetKeys(self.plc_auth, key_ids)
134             key = keys[0]['key']
135             pkey = convert_public_key(key)
136         else:
137             # the user has no keys
138             trace("   person " + hrn + " does not have a PL public key")
139
140             # if a key is unavailable, then we still need to put something in the
141             # user's GID. So make one up.
142             pkey = Keypair(create=True)
143
144         # create the gid
145         person_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
146         person_record = table.find({'type': 'user', 'hrn': hrn})
147         if not person_record:
148             trace("  inserting user record for " + hrn)
149             person_record = GeniRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
150             table.insert(person_record)
151         else:
152             trace("  updating user record for " + hrn)
153             person_record = GeniRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
154             table.update(person_record)
155
156     def import_slice(self, parent_hrn, slice):
157         AuthHierarchy = self.AuthHierarchy
158         slicename = slice['name'].split("_",1)[-1]
159         slicename = cleanup_string(slicename)
160
161         if not slicename:
162             error("Import_Slice: failed to parse slice name " + slice['name'])
163             return
164
165         hrn = parent_hrn + "." + slicename
166         trace("Import: importing slice " + hrn)
167
168         table = GeniTable()
169
170         slice_record = table.find({'type': 'sslice', 'hrn': hrn})
171         if not slice_record:
172             pkey = Keypair(create=True)
173             slice_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
174             slice_record = GeniRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
175             trace("  inserting slice record for " + hrn)
176             table.insert(slice_record)
177
178     def import_node(self, parent_hrn, node):
179         AuthHierarchy = self.AuthHierarchy
180         nodename = node['hostname'].split(".")[0]
181         nodename = cleanup_string(nodename)
182
183         if not nodename:
184             error("Import_node: failed to parse node name " + node['hostname'])
185             return
186
187         hrn = parent_hrn + "." + nodename
188
189         # ASN.1 will have problems with hrn's longer than 64 characters
190         if len(hrn) > 64:
191             hrn = hrn[:64]
192
193         trace("Import: importing node " + hrn)
194
195         table = GeniTable()
196
197         node_record = table.find({'type': 'node', 'hrn': hrn})
198         if not node_record:
199             pkey = Keypair(create=True)
200             node_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
201             node_record = GeniRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
202             trace("  inserting node record for " + hrn)
203             table.insert(node_record)
204
205
206     
207     def import_site(self, parent_hrn, site):
208         AuthHierarchy = self.AuthHierarchy
209         shell = self.shell
210         plc_auth = self.plc_auth
211         sitename = site['login_base']
212         sitename = cleanup_string(sitename)
213
214         hrn = parent_hrn + "." + sitename
215
216         # Hardcode 'internet2' into the hrn for sites hosting
217         # internet2 nodes. This is a special operation for some vini
218         # sites only
219         if ".vini" in parent_hrn and parent_hrn.endswith('vini'):
220             if sitename.startswith("ii"):
221                 sitename = sitename.replace("ii", "")
222                 hrn = ".".join([parent_hrn, "internet2", sitename])
223             elif sitename.startswith("nlr"):
224                 hrn = ".".join([parent_hrn, "internet2", sitename])
225                 sitename = sitename.replace("nlr", "")
226
227         trace("Import_Site: importing site " + hrn)
228
229         # create the authority
230         if not AuthHierarchy.auth_exists(hrn):
231             AuthHierarchy.create_auth(hrn)
232
233         auth_info = AuthHierarchy.get_auth_info(hrn)
234
235         table = GeniTable()
236
237         auth_record = table.find({'type': 'authority', 'hrn': 'hrn'})
238         if not auth_record:
239             auth_record = GeniRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
240             trace("  inserting authority record for " + hrn)
241             table.insert(auth_record)
242
243         if 'person_ids' in site:
244             for person_id in site['person_ids']:
245                 persons = shell.GetPersons(plc_auth, [person_id])
246                 if persons:
247                     try:
248                         self.import_person(hrn, persons[0])
249                     except Exception, e:
250                         trace("Failed to import: %s (%s)" % (persons[0], e))
251         if 'slice_ids' in site:
252             for slice_id in site['slice_ids']:
253                 slices = shell.GetSlices(plc_auth, [slice_id])
254                 if slices:
255                     try:
256                         self.import_slice(hrn, slices[0])
257                     except Exception, e:
258                         trace("Failed to import: %s (%s)" % (slices[0], e))
259         if 'node_ids' in site:
260             for node_id in site['node_ids']:
261                 nodes = shell.GetNodes(plc_auth, [node_id])
262                 if nodes:
263                     try:
264                         self.import_node(hrn, nodes[0])
265                     except Exception, e:
266                         trace("Failed to import: %s (%s)" % (nodes[0], e))     
267
268     def delete_record(self, parent_hrn, object, type):
269         # get the hrn
270         table = GeniTable()
271         hrn = None
272         if type in ['slice'] and 'name' in object and object['name']:
273             slice_name = object['name'].split("_")[0]
274             hrn = parent_hrn + "." + slice_name
275         elif type in ['user'] and 'email' in object and object['email']:
276             person_name = object['email'].split('@')[0]
277             hrn = parent_hrn + "." + person_name
278         elif type in ['node'] and 'hostname' in object and object['hostname']:
279             node_name =  object['hostname'].replace('.','_')  
280             hrn = parent_hrn + "." + node_name
281         elif type in ['site'] and 'login_base' in object and object['login_base']:
282             site_name = object['login_base']
283             hrn = parent_hrn
284             parent_hrn = get_authority(hrn)
285             type = "authority"
286             # delete all records whos authority is this site
287             records = table.find({'authority': hrn})
288             for record in records:
289                 table.remove(record)
290         else:
291             return
292         
293         # delete the record
294         record_list = table.find({'type': type, 'hrn': hrn})
295         for record in record_list:
296             table.remove(record)