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