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