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