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