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