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