PlShell reference belongs in sfa-import-plc
[sfa.git] / sfa / importer / sfa-import-plc.py
1 #!/usr/bin/python
2 #
3 ##
4 # Import PLC records into the SFA database. It is indended that this tool be
5 # run once to create SFA records that reflect the current state of the
6 # planetlab database.
7 #
8 # The import tool assumes that the existing PLC hierarchy should all be part
9 # of "planetlab.us" (see the root_auth and level1_auth variables below).
10 #
11 # Public keys are extracted from the users' SSH keys automatically and used to
12 # create GIDs. This is relatively experimental as a custom tool had to be
13 # written to perform conversion from SSH to OpenSSL format. It only supports
14 # RSA keys at this time, not DSA keys.
15 ##
16
17 import os
18 import getopt
19 import sys
20
21 from sfa.util.config import Config
22 from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn
23 from sfa.util.plxrn import hostname_to_hrn, slicename_to_hrn, email_to_hrn, hrn_to_pl_slicename
24 from sfa.storage.table import SfaTable
25 from sfa.storage.record import SfaRecord
26 from sfa.trust.gid import create_uuid    
27 from sfa.trust.certificate import convert_public_key, Keypair
28 from sfa.importer.sfaImport import sfaImport, _cleanup_string
29 from sfa.util.sfalogging import logger
30 from sfa.plc.plshell import PlShell    
31
32 def process_options():
33
34    (options, args) = getopt.getopt(sys.argv[1:], '', [])
35    for opt in options:
36        name = opt[0]
37        val = opt[1]
38
39
40 def load_keys(filename):
41     keys = {}
42     tmp_dict = {}
43     try:
44         execfile(filename, tmp_dict)
45         if 'keys' in tmp_dict:
46             keys = tmp_dict['keys']
47         return keys
48     except:
49         return keys
50
51 def save_keys(filename, keys):
52     f = open(filename, 'w')
53     f.write("keys = %s" % str(keys))
54     f.close()
55
56 def _get_site_hrn(interface_hrn, site):
57     # Hardcode 'internet2' into the hrn for sites hosting
58     # internet2 nodes. This is a special operation for some vini
59     # sites only
60     hrn = ".".join([interface_hrn, site['login_base']]) 
61     if ".vini" in interface_hrn and interface_hrn.endswith('vini'):
62         if site['login_base'].startswith("i2") or site['login_base'].startswith("nlr"):
63             hrn = ".".join([interface_hrn, "internet2", site['login_base']])
64     return hrn
65
66 def main():
67
68     process_options()
69     config = Config()
70     if not config.SFA_REGISTRY_ENABLED:
71         sys.exit(0)
72     root_auth = config.SFA_REGISTRY_ROOT_AUTH
73     interface_hrn = config.SFA_INTERFACE_HRN
74     keys_filename = config.config_path + os.sep + 'person_keys.py' 
75     sfaImporter = sfaImport()
76     sfaImporter.create_top_level_records()
77     logger=sfaImporter.logger
78     logger.setLevelFromOptVerbose(config.SFA_API_LOGLEVEL)
79     shell = PlShell (config)
80     
81     # special case for vini
82     if ".vini" in interface_hrn and interface_hrn.endswith('vini'):
83         # create a fake internet2 site first
84         i2site = {'name': 'Internet2', 'abbreviated_name': 'I2',
85                     'login_base': 'internet2', 'site_id': -1}
86         sfaImporter.import_site(interface_hrn, i2site)
87    
88     # create dict of all existing sfa records
89     existing_records = {}
90     existing_hrns = []
91     key_ids = []
92     person_keys = {} 
93     table = SfaTable()
94     results = table.find()
95     for result in results:
96         existing_records[(result['hrn'], result['type'])] = result
97         existing_hrns.append(result['hrn']) 
98             
99     # Get all plc sites
100     sites = shell.GetSites({'peer_id': None})
101     sites_dict = {}
102     for site in sites:
103         sites_dict[site['login_base']] = site 
104     
105     # Get all plc users
106     persons = shell.GetPersons({'peer_id': None, 'enabled': True}, 
107                                ['person_id', 'email', 'key_ids', 'site_ids'])
108     persons_dict = {}
109     for person in persons:
110         persons_dict[person['person_id']] = person
111         key_ids.extend(person['key_ids'])
112
113     # Get all public keys
114     keys = shell.GetKeys( {'peer_id': None, 'key_id': key_ids})
115     keys_dict = {}
116     for key in keys:
117         keys_dict[key['key_id']] = key['key']
118
119     # create a dict of person keys keyed on key_id 
120     old_person_keys = load_keys(keys_filename)
121     for person in persons:
122         pubkeys = []
123         for key_id in person['key_ids']:
124             pubkeys.append(keys_dict[key_id])
125         person_keys[person['person_id']] = pubkeys
126
127     # Get all plc nodes  
128     nodes = shell.GetNodes( {'peer_id': None}, ['node_id', 'hostname', 'site_id'])
129     nodes_dict = {}
130     for node in nodes:
131         nodes_dict[node['node_id']] = node
132
133     # Get all plc slices
134     slices = shell.GetSlices( {'peer_id': None}, ['slice_id', 'name'])
135     slices_dict = {}
136     for slice in slices:
137         slices_dict[slice['slice_id']] = slice
138     # start importing 
139     for site in sites:
140         site_hrn = _get_site_hrn(interface_hrn, site)
141         logger.info("Importing site: %s" % site_hrn)
142
143         # import if hrn is not in list of existing hrns or if the hrn exists
144         # but its not a site record
145         if site_hrn not in existing_hrns or \
146            (site_hrn, 'authority') not in existing_records:
147             logger.info("Import: site %s " % site_hrn)
148             urn = hrn_to_urn(site_hrn, 'authority')
149             if not sfaImporter.AuthHierarchy.auth_exists(urn):
150                 sfaImporter.AuthHierarchy.create_auth(urn)
151             auth_info = sfaImporter.AuthHierarchy.get_auth_info(urn)
152             auth_record = SfaRecord(hrn=site_hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
153             auth_record.sync(verbose=True) 
154              
155         # import node records
156         for node_id in site['node_ids']:
157             if node_id not in nodes_dict:
158                 continue 
159             node = nodes_dict[node_id]
160             site_auth = get_authority(site_hrn)
161             site_name = get_leaf(site_hrn)
162             hrn =  hostname_to_hrn(site_auth, site_name, node['hostname'])
163             if len(hrn) > 64:
164                 hrn = hrn[:64]
165             if hrn not in existing_hrns or \
166                (hrn, 'node') not in existing_records:
167                 pkey = Keypair(create=True)
168                 urn = hrn_to_urn(hrn, 'node')
169                 node_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
170                 node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'], authority=get_authority(hrn))    
171                 node_record.sync(verbose=True)
172
173         # import slices
174         for slice_id in site['slice_ids']:
175             if slice_id not in slices_dict:
176                 continue 
177             slice = slices_dict[slice_id]
178             hrn = slicename_to_hrn(interface_hrn, slice['name'])
179             #slicename = slice['name'].split("_",1)[-1]
180             #slicename = _cleanup_string(slicename)
181             if hrn not in existing_hrns or \
182                (hrn, 'slice') not in existing_records:
183                 pkey = Keypair(create=True)
184                 urn = hrn_to_urn(hrn, 'slice')
185                 slice_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
186                 slice_record = SfaRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'],
187                                          authority=get_authority(hrn))
188                 slice_record.sync(verbose=True)
189
190         # import persons
191         for person_id in site['person_ids']:
192             if person_id not in persons_dict:
193                 continue 
194             person = persons_dict[person_id]
195             hrn = email_to_hrn(site_hrn, person['email'])
196             if len(hrn) > 64:
197                 hrn = hrn[:64]
198
199             # if user's primary key has chnaged then we need to update the 
200             # users gid by forcing a update here
201             old_keys = []
202             new_keys = []
203             if person_id in old_person_keys:
204                 old_keys = old_person_keys[person_id]
205             if person_id in person_keys:
206                 new_keys = person_keys[person_id]
207             update_record = False
208             for key in new_keys:
209                 if key not in old_keys:
210                     update_record = True 
211
212             if hrn not in existing_hrns or \
213                (hrn, 'user') not in existing_records or update_record:
214                 if 'key_ids' in person and person['key_ids']:
215                     key = new_keys[0]
216                     try:
217                         pkey = convert_public_key(key)
218                     except:
219                         logger.warn('unable to convert public key for %s' % hrn)
220                         pkey = Keypair(create=True)
221                 else:
222                     # the user has no keys. Creating a random keypair for the user's gid
223                     logger.warn("Import: person %s does not have a PL public key"%hrn)
224                     pkey = Keypair(create=True) 
225                 urn = hrn_to_urn(hrn, 'user')
226                 person_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
227                 person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", \
228                                           pointer=person['person_id'], authority=get_authority(hrn))
229                 person_record.sync(verbose=True)
230     
231     # remove stale records    
232     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
233     for (record_hrn, type) in existing_records.keys():
234         if record_hrn in system_records:
235             continue
236         
237         record = existing_records[(record_hrn, type)]
238         if record['peer_authority']:
239             continue
240
241         # dont delete vini's internet2 placeholdder record
242         # normally this would be deleted becuase it does not have a plc record 
243         if ".vini" in interface_hrn and interface_hrn.endswith('vini') and \
244            record_hrn.endswith("internet2"):     
245             continue
246
247         found = False
248         
249         if type == 'authority':    
250             for site in sites:
251                 site_hrn = interface_hrn + "." + site['login_base']
252                 if site_hrn == record_hrn and site['site_id'] == record['pointer']:
253                     found = True
254                     break
255
256         elif type == 'user':
257             login_base = get_leaf(get_authority(record_hrn))
258             username = get_leaf(record_hrn)
259             if login_base in sites_dict:
260                 site = sites_dict[login_base]
261                 for person in persons:
262                     tmp_username = person['email'].split("@")[0]
263                     alt_username = person['email'].split("@")[0].replace(".", "_").replace("+", "_")
264                     if username in [tmp_username, alt_username] and \
265                        site['site_id'] in person['site_ids'] and \
266                        person['person_id'] == record['pointer']:
267                         found = True
268                         break
269         
270         elif type == 'slice':
271             slicename = hrn_to_pl_slicename(record_hrn)
272             for slice in slices:
273                 if slicename == slice['name'] and \
274                    slice['slice_id'] == record['pointer']:
275                     found = True
276                     break    
277  
278         elif type == 'node':
279             login_base = get_leaf(get_authority(record_hrn))
280             nodename = Xrn.unescape(get_leaf(record_hrn))
281             if login_base in sites_dict:
282                 site = sites_dict[login_base]
283                 for node in nodes:
284                     tmp_nodename = node['hostname']
285                     if tmp_nodename == nodename and \
286                        node['site_id'] == site['site_id'] and \
287                        node['node_id'] == record['pointer']:
288                         found = True
289                         break  
290         else:
291             continue 
292         
293         if not found:
294             record_object = existing_records[(record_hrn, type)]
295             record = SfaRecord(dict=record_object)
296             record.delete()
297                                    
298     # save pub keys
299     logger.info('Import: saving current pub keys')
300     save_keys(keys_filename, person_keys)                
301         
302 if __name__ == "__main__":
303     main()