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