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