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