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