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