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