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