0fb427339ee537b345cc7472fd7c0189badb3731
[sfa.git] / geni / gimport.py
1 #!/usr/bin/python
2 #
3 #
4 ##
5 # Import PLC records into the Geni database. It is indended that this tool be
6 # run once to create Geni records that reflect the current state of the
7 # planetlab database.
8 #
9 # The import tool assumes that the existing PLC hierarchy should all be part
10 # of "planetlab.us" (see the root_auth and level1_auth variables below).
11 #
12 # Public keys are extracted from the users' SSH keys automatically and used to
13 # create GIDs. This is relatively experimental as a custom tool had to be
14 # written to perform conversion from SSH to OpenSSL format. It only supports
15 # RSA keys at this time, not DSA keys.
16 ##
17
18 import getopt
19 import sys
20 import tempfile
21
22 from geni.util.cert import *
23 from geni.util.trustedroot import *
24 from geni.util.hierarchy import *
25 from geni.util.record import *
26 from geni.util.genitable import *
27 from geni.util.misc import *
28 from geni.util.config import *
29
30 # get PL account settings from config module
31 pl_auth = get_pl_auth()
32
33 # connect to planetlab
34 if "Url" in pl_auth:
35     from geni.util import remoteshell
36     shell = remoteshell.RemoteShell()
37 else:
38     import PLC.Shell
39     shell = PLC.Shell.Shell(globals = globals())
40
41 ##
42 # Two authorities are specified: the root authority and the level1 authority.
43
44 #root_auth = "plc"
45 #level1_auth = None
46
47 #root_auth = "planetlab"
48 #level1_auth = "planetlab.us"
49 config = Config()
50
51 root_auth = config.GENI_REGISTRY_ROOT_AUTH
52 level1_auth = config.GENI_REGISTRY_LEVEL1_AUTH
53 if not level1_auth or level1_auth in ['']:
54     level1_auth = None
55
56 keyconvert = 'keyconvert'
57 loaded = False
58 default_path = "/usr/share/keyconvert/" + keyconvert
59 cwd = os.path.dirname(os.path.abspath(__file__))
60 alt_path = os.sep.join(cwd.split(os.sep)[:-1] + ['keyconvert', 'keyconvert'])
61 geni_path = config.GENI_BASE_DIR + os.sep + "keyconvert/keyconvert"
62 files = [default_path, alt_path, geni_path]
63 for path in files:
64     print os.path.isfile(path), path
65     if os.path.isfile(path):
66         keyconvert_fn = path
67         loaded = True
68         break
69
70 if not loaded:
71     raise Exception, "Could not find config in " + ", ".join(files)        
72
73 keyconvert_fn = config.GENI_BASE_DIR + os.sep + "keyconvert/keyconvert"
74
75 def un_unicode(str):
76    if isinstance(str, unicode):
77        return str.encode("ascii", "ignore")
78    else:
79        return str
80
81 def cleanup_string(str):
82     # pgsql has a fit with strings that have high ascii in them, so filter it
83     # out when generating the hrns.
84     tmp = ""
85     for c in str:
86         if ord(c) < 128:
87             tmp = tmp + c
88     str = tmp
89
90     str = un_unicode(str)
91     str = str.replace(" ", "_")
92     str = str.replace(".", "_")
93     str = str.replace("(", "_")
94     str = str.replace("'", "_")
95     str = str.replace(")", "_")
96     str = str.replace('"', "_")
97     return str
98
99 def process_options():
100    global hrn
101
102    (options, args) = getopt.getopt(sys.argv[1:], '', [])
103    for opt in options:
104        name = opt[0]
105        val = opt[1]
106
107 def connect_shell():
108     global pl_auth, shell
109
110     # get PL account settings from config module
111     pl_auth = get_pl_auth()
112
113     # connect to planetlab
114     if "Url" in pl_auth:
115         from geni.util import remoteshell
116         shell = remoteshell.RemoteShell()
117     else:
118         import PLC.Shell
119         shell = PLC.Shell.Shell(globals = globals())
120
121     return shell
122
123 def get_auth_table(auth_name):
124     AuthHierarchy = Hierarchy()
125     auth_info = AuthHierarchy.get_auth_info(auth_name)
126
127     table = GeniTable(hrn=auth_name,
128                       cninfo=auth_info.get_dbinfo())
129
130     # if the table doesn't exist, then it means we haven't put any records
131     # into this authority yet.
132
133     if not table.exists():
134         report.trace("Import: creating table for authority " + auth_name)
135         table.create()
136
137     return table
138
139 def get_pl_pubkey(key_id):
140     keys = shell.GetKeys(pl_auth, [key_id])
141     if keys:
142         key_str = keys[0]['key']
143
144         if "ssh-dss" in key_str:
145             print "XXX: DSA key encountered, ignoring"
146             return None
147
148         # generate temporary files to hold the keys
149         (ssh_f, ssh_fn) = tempfile.mkstemp()
150         ssl_fn = tempfile.mktemp()
151
152         os.write(ssh_f, key_str)
153         os.close(ssh_f)
154
155         if not os.path.exists(keyconvert_fn):
156             report.trace("  keyconvert utility " + str(keyconvert_fn) + " does not exist");
157             sys.exit(-1)
158
159         cmd = keyconvert_fn + " " + ssh_fn + " " + ssl_fn
160         print cmd
161         os.system(cmd)
162
163         # this check leaves the temporary file containing the public key so
164         # that it can be expected to see why it failed.
165         # TODO: for production, cleanup the temporary files
166         if not os.path.exists(ssl_fn):
167             report.trace("  failed to convert key from " + ssh_fn + " to " + ssl_fn)
168             return None
169
170         k = Keypair()
171         try:
172             k.load_pubkey_from_file(ssl_fn)
173         except:
174             print "XXX: Error while converting key: ", key_str
175             k = None
176
177         # remove the temporary files
178         os.remove(ssh_fn)
179         os.remove(ssl_fn)
180
181         return k
182     else:
183         return None
184
185 def person_to_hrn(parent_hrn, person):
186     # the old way - Lastname_Firstname
187     #personname = person['last_name'] + "_" + person['first_name']
188
189     # the new way - use email address up to the "@" 
190     personname = person['email'].split("@")[0]
191
192     personname = cleanup_string(personname)
193
194     hrn = parent_hrn + "." + personname
195     return hrn
196
197 def import_person(parent_hrn, person):
198     AuthHierarchy = Hierarchy()
199     hrn = person_to_hrn(parent_hrn, person)
200
201     # ASN.1 will have problems with hrn's longer than 64 characters
202     if len(hrn) > 64:
203         hrn = hrn[:64]
204
205     report.trace("Import: importing person " + hrn)
206
207     table = get_auth_table(parent_hrn)
208
209     person_record = table.resolve("user", hrn)
210     if not person_record:
211         key_ids = []
212         if 'key_ids' in person:    
213             key_ids = person["key_ids"]
214
215         if key_ids:
216             # get the user's private key from the SSH keys they have uploaded
217             # to planetlab
218             pkey = get_pl_pubkey(key_ids[0])
219         else:
220             # the user has no keys
221             report.trace("   person " + hrn + " does not have a PL public key")
222             pkey = None
223
224         # if a key is unavailable, then we still need to put something in the
225         # user's GID. So make one up.
226         if not pkey:
227             pkey = Keypair(create=True)
228
229         person_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
230         person_record = GeniRecord(name=hrn, gid=person_gid, type="user", pointer=person['person_id'])
231         report.trace("  inserting user record for " + hrn)
232         table.insert(person_record)
233     else:
234         key_ids = person["key_ids"]
235
236     if key_ids:
237         pkey = get_pl_pubkey(key_ids[0])
238         person_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
239         person_record = GeniRecord(name=hrn, gid=person_gid, type="user", pointer=person['person_id'])
240         report.trace("  updating user record for " + hrn)
241         table.update(person_record)
242         
243 def import_slice(parent_hrn, slice):
244     AuthHierarchy = Hierarchy()
245     slicename = slice['name'].split("_",1)[-1]
246     slicename = cleanup_string(slicename)
247
248     if not slicename:
249         report.error("Import_Slice: failed to parse slice name " + slice['name'])
250         return
251
252     hrn = parent_hrn + "." + slicename
253     report.trace("Import: importing slice " + hrn)
254
255     table = get_auth_table(parent_hrn)
256
257     slice_record = table.resolve("slice", hrn)
258     if not slice_record:
259         pkey = Keypair(create=True)
260         slice_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
261         slice_record = GeniRecord(name=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
262         report.trace("  inserting slice record for " + hrn)
263         table.insert(slice_record)
264
265 def import_node(parent_hrn, node):
266     AuthHierarchy = Hierarchy()
267     nodename = node['hostname'].split(".")[0]
268     nodename = cleanup_string(nodename)
269
270     if not nodename:
271         report.error("Import_node: failed to parse node name " + node['hostname'])
272         return
273
274     hrn = parent_hrn + "." + nodename
275
276     # ASN.1 will have problems with hrn's longer than 64 characters
277     if len(hrn) > 64:
278         hrn = hrn[:64]
279
280     report.trace("Import: importing node " + hrn)
281
282     table = get_auth_table(parent_hrn)
283
284     node_record = table.resolve("node", hrn)
285     if not node_record:
286         pkey = Keypair(create=True)
287         node_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
288         node_record = GeniRecord(name=hrn, gid=node_gid, type="node", pointer=node['node_id'])
289         report.trace("  inserting node record for " + hrn)
290         table.insert(node_record)
291
292 def import_site(parent_hrn, site):
293     AuthHierarchy = Hierarchy()
294     sitename = site['login_base']
295     sitename = cleanup_string(sitename)
296
297     hrn = parent_hrn + "." + sitename
298
299     report.trace("Import_Site: importing site " + hrn)
300
301     # create the authority
302     if not AuthHierarchy.auth_exists(hrn):
303         AuthHierarchy.create_auth(hrn)
304
305     auth_info = AuthHierarchy.get_auth_info(hrn)
306
307     table = get_auth_table(parent_hrn)
308
309     auth_record = table.resolve("authority", hrn)
310     if not auth_record:
311         auth_record = GeniRecord(name=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
312         report.trace("  inserting authority record for " + hrn)
313         table.insert(auth_record)
314
315     if 'person_ids' in site: 
316         for person_id in site['person_ids']:
317             persons = shell.GetPersons(pl_auth, [person_id])
318             if persons:
319                 try: 
320                     import_person(hrn, persons[0])
321                 except:
322                     report.trace("Failed to import: %s" % persons[0])
323     if 'slice_ids' in site:
324         for slice_id in site['slice_ids']:
325             slices = shell.GetSlices(pl_auth, [slice_id])
326             if slices:
327                 try:
328                     import_slice(hrn, slices[0])
329                 except:
330                     report.trace("Failed to import: %s" % slices[0])
331     if 'node_ids' in site:
332         for node_id in site['node_ids']:
333             nodes = shell.GetNodes(pl_auth, [node_id])
334             if nodes:
335                 try:
336                     import_node(hrn, nodes[0])
337                 except:
338                     report.trace("Failed to import: %s" % nodes[0])
339
340 def create_top_level_auth_records(hrn):
341     parent_hrn = get_authority(hrn)
342     print hrn, ":", parent_hrn
343     if not parent_hrn:
344         parent_hrn = hrn    
345     auth_info = AuthHierarchy.get_auth_info(parent_hrn)
346     table = get_auth_table(parent_hrn)
347
348     auth_record = table.resolve("authority", hrn)
349     if not auth_record:
350         auth_record = GeniRecord(name=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
351         report.trace("  inserting authority record for " + hrn)
352         table.insert(auth_record)
353
354 def main():
355     global AuthHierarchy
356     global TrustedRoots
357
358     process_options()
359
360     print "Base Directory: ", config.GENI_BASE_DIR
361
362     AuthHierarchy = Hierarchy()
363     TrustedRoots = TrustedRootList()
364
365     print "Import: creating top level authorities"
366
367     if not AuthHierarchy.auth_exists(root_auth):
368         AuthHierarchy.create_auth(root_auth)
369
370     create_top_level_auth_records(root_auth)
371     if level1_auth:
372         if not AuthHierarchy.auth_exists(level1_auth):
373             AuthHierarchy.create_auth(level1_auth)
374         create_top_level_auth_records(level1_auth)
375         import_auth = level1_auth
376     else:
377         import_auth = root_auth
378
379     print "Import: adding", root_auth, "to trusted list"
380     root = AuthHierarchy.get_auth_info(root_auth)
381     TrustedRoots.add_gid(root.get_gid_object())
382
383     connect_shell()
384
385     sites = shell.GetSites(pl_auth)
386     for site in sites:
387         import_site(import_auth, site)
388
389 if __name__ == "__main__":
390     main()