Merge branch 'upstreammaster'
[sfa.git] / sfa / plc / 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.table import SfaTable
22 from sfa.util.xrn import get_leaf, get_authority
23 from sfa.util.plxrn import hostname_to_hrn, slicename_to_hrn, email_to_hrn, hrn_to_pl_slicename
24 from sfa.util.config import Config
25 from sfa.util.xrn import Xrn
26
27 from sfa.plc.sfaImport import sfaImport
28
29 def process_options():
30
31    (options, args) = getopt.getopt(sys.argv[1:], '', [])
32    for opt in options:
33        name = opt[0]
34        val = opt[1]
35
36
37 def load_keys(filename):
38     keys = {}
39     tmp_dict = {}
40     try:
41         execfile(filename, tmp_dict)
42         if 'keys' in tmp_dict:
43             keys = tmp_dict['keys']
44         return keys
45     except:
46         return keys
47
48 def save_keys(filename, keys):
49     f = open(filename, 'w')
50     f.write("keys = %s" % str(keys))
51     f.close()
52
53 def _get_site_hrn(interface_hrn, site):
54     # Hardcode 'internet2' into the hrn for sites hosting
55     # internet2 nodes. This is a special operation for some vini
56     # sites only
57     hrn = ".".join([interface_hrn, site['login_base']]) 
58     if ".vini" in interface_hrn and interface_hrn.endswith('vini'):
59         if site['login_base'].startswith("i2") or site['login_base'].startswith("nlr"):
60             hrn = ".".join([interface_hrn, "internet2", site['login_base']])
61     return hrn
62
63 def main():
64
65     process_options()
66     config = Config()
67     if not config.SFA_REGISTRY_ENABLED:
68         sys.exit(0)
69     root_auth = config.SFA_REGISTRY_ROOT_AUTH
70     interface_hrn = config.SFA_INTERFACE_HRN
71     keys_filename = config.config_path + os.sep + 'person_keys.py' 
72     sfaImporter = sfaImport()
73     if config.SFA_API_DEBUG: sfaImporter.logger.setLevelDebug()
74     shell = sfaImporter.shell
75     plc_auth = sfaImporter.plc_auth 
76     
77     # initialize registry db table
78     table = SfaTable()
79     if not table.exists():
80        table.create()
81
82     # create root authority 
83     sfaImporter.create_top_level_auth_records(root_auth)
84     if not root_auth == interface_hrn:
85         sfaImporter.create_top_level_auth_records(interface_hrn)
86
87     # create s user record for the slice manager
88     sfaImporter.create_sm_client_record()
89
90     # create interface records
91     sfaImporter.logger.info("Import: creating interface records")
92     sfaImporter.create_interface_records()
93
94     # add local root authority's cert  to trusted list
95     sfaImporter.logger.info("Import: adding " + interface_hrn + " to trusted list")
96     authority = sfaImporter.AuthHierarchy.get_auth_info(interface_hrn)
97     sfaImporter.TrustedRoots.add_gid(authority.get_gid_object())
98
99     # special case for vini
100     if ".vini" in interface_hrn and interface_hrn.endswith('vini'):
101         # create a fake internet2 site first
102         i2site = {'name': 'Internet2', 'abbreviated_name': 'I2',
103                     'login_base': 'internet2', 'site_id': -1}
104         sfaImporter.import_site(interface_hrn, i2site)
105    
106     # create dict of all existing sfa records
107     existing_records = {}
108     existing_hrns = []
109     key_ids = []
110     person_keys = {} 
111     results = table.find()
112     for result in results:
113         existing_records[(result['hrn'], result['type'])] = result
114         existing_hrns.append(result['hrn']) 
115             
116     # Get all plc sites
117     sites = shell.GetSites(plc_auth, {'peer_id': None})
118     sites_dict = {}
119     for site in sites:
120         sites_dict[site['login_base']] = site 
121     
122     # Get all plc users
123     persons = shell.GetPersons(plc_auth, {'peer_id': None, 'enabled': True}, 
124                                ['person_id', 'email', 'key_ids', 'site_ids'])
125     persons_dict = {}
126     for person in persons:
127         persons_dict[person['person_id']] = person
128         key_ids.extend(person['key_ids'])
129
130     # Get all public keys
131     keys = shell.GetKeys(plc_auth, {'peer_id': None, 'key_id': key_ids})
132     keys_dict = {}
133     for key in keys:
134         keys_dict[key['key_id']] = key['key']
135
136     # create a dict of person keys keyed on key_id 
137     old_person_keys = load_keys(keys_filename)
138     for person in persons:
139         pubkeys = []
140         for key_id in person['key_ids']:
141             pubkeys.append(keys_dict[key_id])
142         person_keys[person['person_id']] = pubkeys
143
144     # Get all plc nodes  
145     nodes = shell.GetNodes(plc_auth, {'peer_id': None}, ['node_id', 'hostname', 'site_id'])
146     nodes_dict = {}
147     for node in nodes:
148         nodes_dict[node['node_id']] = node
149
150     # Get all plc slices
151     slices = shell.GetSlices(plc_auth, {'peer_id': None}, ['slice_id', 'name'])
152     slices_dict = {}
153     for slice in slices:
154         slices_dict[slice['slice_id']] = slice
155     # start importing 
156     for site in sites:
157         site_hrn = _get_site_hrn(interface_hrn, site)
158         sfaImporter.logger.info("Importing site: %s" % site_hrn)
159
160         # import if hrn is not in list of existing hrns or if the hrn exists
161         # but its not a site record
162         if site_hrn not in existing_hrns or \
163            (site_hrn, 'authority') not in existing_records:
164             sfaImporter.import_site(site_hrn, site)
165              
166         # import node records
167         for node_id in site['node_ids']:
168             if node_id not in nodes_dict:
169                 continue 
170             node = nodes_dict[node_id]
171             site_auth = get_authority(site_hrn)
172             site_name = get_leaf(site_hrn)
173             hrn =  hostname_to_hrn(site_auth, site_name, node['hostname'])
174             if hrn not in existing_hrns or \
175                (hrn, 'node') not in existing_records:
176                 sfaImporter.import_node(hrn, node)
177
178         # import slices
179         for slice_id in site['slice_ids']:
180             if slice_id not in slices_dict:
181                 continue 
182             slice = slices_dict[slice_id]
183             hrn = slicename_to_hrn(interface_hrn, slice['name'])
184             if hrn not in existing_hrns or \
185                (hrn, 'slice') not in existing_records:
186                 sfaImporter.import_slice(site_hrn, slice)      
187
188         # import persons
189         for person_id in site['person_ids']:
190             if person_id not in persons_dict:
191                 continue 
192             person = persons_dict[person_id]
193             hrn = email_to_hrn(site_hrn, person['email'])
194             old_keys = []
195             new_keys = []
196             if person_id in old_person_keys:
197                 old_keys = old_person_keys[person_id]
198             if person_id in person_keys:
199                 new_keys = person_keys[person_id]
200             update_record = False
201             for key in new_keys:
202                 if key not in old_keys:
203                     update_record = True 
204
205             if hrn not in existing_hrns or \
206                (hrn, 'user') not in existing_records or update_record:
207                 sfaImporter.import_person(site_hrn, person)
208
209     
210     # remove stale records    
211     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
212     for (record_hrn, type) in existing_records.keys():
213         if record_hrn in system_records:
214             continue
215         
216         record = existing_records[(record_hrn, type)]
217         if record['peer_authority']:
218             continue
219
220         # dont delete vini's internet2 placeholdder record
221         # normally this would be deleted becuase it does not have a plc record 
222         if ".vini" in interface_hrn and interface_hrn.endswith('vini') and \
223            record_hrn.endswith("internet2"):     
224             continue
225
226         found = False
227         
228         if type == 'authority':    
229             for site in sites:
230                 site_hrn = interface_hrn + "." + site['login_base']
231                 if site_hrn == record_hrn and site['site_id'] == record['pointer']:
232                     found = True
233                     break
234
235         elif type == 'user':
236             login_base = get_leaf(get_authority(record_hrn))
237             username = get_leaf(record_hrn)
238             if login_base in sites_dict:
239                 site = sites_dict[login_base]
240                 for person in persons:
241                     tmp_username = person['email'].split("@")[0]
242                     alt_username = person['email'].split("@")[0].replace(".", "_").replace("+", "_")
243                     if username in [tmp_username, alt_username] and \
244                        site['site_id'] in person['site_ids'] and \
245                        person['person_id'] == record['pointer']:
246                         found = True
247                         break
248         
249         elif type == 'slice':
250             slicename = hrn_to_pl_slicename(record_hrn)
251             for slice in slices:
252                 if slicename == slice['name'] and \
253                    slice['slice_id'] == record['pointer']:
254                     found = True
255                     break    
256  
257         elif type == 'node':
258             login_base = get_leaf(get_authority(record_hrn))
259             nodename = Xrn.unescape(get_leaf(record_hrn))
260             if login_base in sites_dict:
261                 site = sites_dict[login_base]
262                 for node in nodes:
263                     tmp_nodename = node['hostname']
264                     if tmp_nodename == nodename and \
265                        node['site_id'] == site['site_id'] and \
266                        node['node_id'] == record['pointer']:
267                         found = True
268                         break  
269         else:
270             continue 
271         
272         if not found:
273             record_object = existing_records[(record_hrn, type)]
274             sfaImporter.delete_record(record_hrn, type) 
275                                    
276     # save pub keys
277     sfaImporter.logger.info('Import: saving current pub keys')
278     save_keys(keys_filename, person_keys)                
279         
280 if __name__ == "__main__":
281     main()