490b0b7a53a83702e98face2aea3b24c3629e403
[sfa.git] / geni / gimport.py
1 #!/usr/bin/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
56 def un_unicode(str):
57    if isinstance(str, unicode):
58        return str.encode("ascii", "ignore")
59    else:
60        return str
61
62 def cleanup_string(str):
63     # pgsql has a fit with strings that have high ascii in them, so filter it
64     # out when generating the hrns.
65     tmp = ""
66     for c in str:
67         if ord(c) < 128:
68             tmp = tmp + c
69     str = tmp
70
71     str = un_unicode(str)
72     str = str.replace(" ", "_")
73     str = str.replace(".", "_")
74     str = str.replace("(", "_")
75     str = str.replace("'", "_")
76     str = str.replace(")", "_")
77     str = str.replace('"', "_")
78     return str
79
80 def process_options():
81    global hrn
82
83    (options, args) = getopt.getopt(sys.argv[1:], '', [])
84    for opt in options:
85        name = opt[0]
86        val = opt[1]
87
88 def connect_shell():
89     global pl_auth, shell
90
91     # get PL account settings from config module
92     pl_auth = get_pl_auth()
93
94     # connect to planetlab
95     if "Url" in pl_auth:
96         from geni.util import remoteshell
97         shell = remoteshell.RemoteShell()
98     else:
99         import PLC.Shell
100         shell = PLC.Shell.Shell(globals = globals())
101
102     return shell
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         report.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     report.trace("Import: importing person " + hrn)
141
142     table = get_auth_table(parent_hrn)
143
144     person_record = table.resolve("user", hrn)
145     if not person_record:
146         key_ids = []
147         if 'key_ids' in person:    
148             key_ids = person["key_ids"]
149
150         if key_ids:
151             # get the user's private key from the SSH keys they have uploaded
152             # to planetlab
153             keys = shell.GetKeys(pl_auth, key_ids)
154             key = keys[0]
155             pkey =convert_public_key(key)
156         else:
157             # the user has no keys
158             report.trace("   person " + hrn + " does not have a PL public key")
159             pkey = None
160
161         # if a key is unavailable, then we still need to put something in the
162         # user's GID. So make one up.
163         if not pkey:
164             pkey = Keypair(create=True)
165
166         person_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
167         person_record = GeniRecord(name=hrn, gid=person_gid, type="user", pointer=person['person_id'])
168         report.trace("  inserting user record for " + hrn)
169         table.insert(person_record)
170     else:
171         key_ids = person["key_ids"]
172
173     if key_ids:
174         pkey = get_pl_pubkey(key_ids[0])
175         person_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
176         person_record = GeniRecord(name=hrn, gid=person_gid, type="user", pointer=person['person_id'])
177         report.trace("  updating user record for " + hrn)
178         table.update(person_record)
179         
180 def import_slice(parent_hrn, slice):
181     AuthHierarchy = Hierarchy()
182     slicename = slice['name'].split("_",1)[-1]
183     slicename = cleanup_string(slicename)
184
185     if not slicename:
186         report.error("Import_Slice: failed to parse slice name " + slice['name'])
187         return
188
189     hrn = parent_hrn + "." + slicename
190     report.trace("Import: importing slice " + hrn)
191
192     table = get_auth_table(parent_hrn)
193
194     slice_record = table.resolve("slice", hrn)
195     if not slice_record:
196         pkey = Keypair(create=True)
197         slice_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
198         slice_record = GeniRecord(name=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
199         report.trace("  inserting slice record for " + hrn)
200         table.insert(slice_record)
201
202 def import_node(parent_hrn, node):
203     AuthHierarchy = Hierarchy()
204     nodename = node['hostname'].split(".")[0]
205     nodename = cleanup_string(nodename)
206
207     if not nodename:
208         report.error("Import_node: failed to parse node name " + node['hostname'])
209         return
210
211     hrn = parent_hrn + "." + nodename
212
213     # ASN.1 will have problems with hrn's longer than 64 characters
214     if len(hrn) > 64:
215         hrn = hrn[:64]
216
217     report.trace("Import: importing node " + hrn)
218
219     table = get_auth_table(parent_hrn)
220
221     node_record = table.resolve("node", hrn)
222     if not node_record:
223         pkey = Keypair(create=True)
224         node_gid = AuthHierarchy.create_gid(hrn, create_uuid(), pkey)
225         node_record = GeniRecord(name=hrn, gid=node_gid, type="node", pointer=node['node_id'])
226         report.trace("  inserting node record for " + hrn)
227         table.insert(node_record)
228
229 def import_site(parent_hrn, site):
230     AuthHierarchy = Hierarchy()
231     sitename = site['login_base']
232     sitename = cleanup_string(sitename)
233     
234     hrn = parent_hrn + "." + sitename
235     
236     # Hardcode 'internet2' into the hrn for sites hosting 
237     # internet2 nodes. This is a special operation for some vini
238     # sites only
239     if ".vini" in parent_hrn and parent_hrn.endswith('vini'):
240         if sitename.startswith("ii"): 
241             sitename = sitename.replace("ii", "")
242             hrn = ".".join([parent_hrn, "internet2", sitename]) 
243         elif sitename.startswith("nlr"): 
244             hrn = ".".join([parent_hrn, "internet2", sitename]) 
245             sitename = sitename.replace("nlr", "")
246          
247     report.trace("Import_Site: importing site " + hrn)
248
249     # create the authority
250     if not AuthHierarchy.auth_exists(hrn):
251         AuthHierarchy.create_auth(hrn)
252
253     auth_info = AuthHierarchy.get_auth_info(hrn)
254
255     table = get_auth_table(parent_hrn)
256
257     auth_record = table.resolve("authority", hrn)
258     if not auth_record:
259         auth_record = GeniRecord(name=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
260         report.trace("  inserting authority record for " + hrn)
261         table.insert(auth_record)
262
263     if 'person_ids' in site: 
264         for person_id in site['person_ids']:
265             persons = shell.GetPersons(pl_auth, [person_id])
266             if persons:
267                 try: 
268                     import_person(hrn, persons[0])
269                 except:
270                     report.trace("Failed to import: %s" % persons[0])
271     if 'slice_ids' in site:
272         for slice_id in site['slice_ids']:
273             slices = shell.GetSlices(pl_auth, [slice_id])
274             if slices:
275                 try:
276                     import_slice(hrn, slices[0])
277                 except:
278                     report.trace("Failed to import: %s" % slices[0])
279     if 'node_ids' in site:
280         for node_id in site['node_ids']:
281             nodes = shell.GetNodes(pl_auth, [node_id])
282             if nodes:
283                 try:
284                     import_node(hrn, nodes[0])
285                 except:
286                     report.trace("Failed to import: %s" % nodes[0])
287
288 def create_top_level_auth_records(hrn):
289     parent_hrn = get_authority(hrn)
290     print hrn, ":", parent_hrn
291     if not parent_hrn:
292         parent_hrn = hrn    
293     auth_info = AuthHierarchy.get_auth_info(parent_hrn)
294     table = get_auth_table(parent_hrn)
295
296     auth_record = table.resolve("authority", hrn)
297     if not auth_record:
298         auth_record = GeniRecord(name=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
299         report.trace("  inserting authority record for " + hrn)
300         table.insert(auth_record)
301
302 def main():
303     global AuthHierarchy
304     global TrustedRoots
305
306     process_options()
307
308     AuthHierarchy = Hierarchy()
309     TrustedRoots = TrustedRootList()
310
311     print "Import: creating top level authorities"
312
313     if not AuthHierarchy.auth_exists(root_auth):
314         AuthHierarchy.create_auth(root_auth)
315
316     create_top_level_auth_records(root_auth)
317     if level1_auth:
318         if not AuthHierarchy.auth_exists(level1_auth):
319             AuthHierarchy.create_auth(level1_auth)
320         create_top_level_auth_records(level1_auth)
321         import_auth = level1_auth
322     else:
323         import_auth = root_auth
324
325     print "Import: adding", root_auth, "to trusted list"
326     root = AuthHierarchy.get_auth_info(root_auth)
327     TrustedRoots.add_gid(root.get_gid_object())
328
329     connect_shell()
330
331     sites = shell.GetSites(pl_auth, {'peer_id': None})
332     # create a fake internet2 site first
333     i2site = {'name': 'Internet2', 'abbreviated_name': 'I2',
334                     'login_base': 'internet2', 'site_id': -1}
335     import_site(import_auth, i2site)
336     
337     for site in sites:
338         import_site(import_auth, site)
339
340 if __name__ == "__main__":
341     main()