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