make sure to check plc object id against sfa record pointer when deleting stale records
[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 Geni database. It is indended that this tool be
8 # run once to create Geni 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.genitable import GeniTable
26 from sfa.util.misc import *
27 from sfa.util.config import Config
28 from sfa.util.report import trace, error
29
30 from sfa.trust.certificate import convert_public_key, Keypair
31 from sfa.trust.trustedroot import *
32 from sfa.trust.hierarchy import *
33 from sfa.trust.gid import create_uuid
34 from sfa.plc.sfaImport import *
35
36
37
38 def process_options():
39    global hrn
40
41    (options, args) = getopt.getopt(sys.argv[1:], '', [])
42    for opt in options:
43        name = opt[0]
44        val = opt[1]
45
46
47 def load_keys(filename):
48     keys = {}
49     tmp_dict = {}
50     try:
51         execfile(filename, tmp_dict)
52         if 'keys' in tmp_dict:
53             keys = tmp_dict['keys']
54         return keys
55     except:
56         return keys
57
58 def save_keys(filename, keys):
59     f = open(filename, 'w')
60     f.write("keys = %s" % str(keys))
61     f.close()
62
63 def main():
64     process_options()
65     config = Config()
66     root_auth = config.SFA_REGISTRY_ROOT_AUTH
67     level1_auth = config.SFA_REGISTRY_LEVEL1_AUTH
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 = GeniTable()
75     if not table.exists():
76         table.create()
77
78     if not level1_auth or level1_auth in ['']:
79         level1_auth = None
80     
81     print "Import: creating top level authorities"
82     if not level1_auth:
83         sfaImporter.create_top_level_auth_records(root_auth)
84         import_auth = root_auth
85     else:
86         if not AuthHierarchy.auth_exists(level1_auth):
87             AuthHierarchy.create_auth(level1_auth)
88         sfaImporter.create_top_level_auth_records(level1_auth)
89         import_auth = level1_auth
90
91     print "Import: adding", import_auth, "to trusted list"
92     authority = AuthHierarchy.get_auth_info(import_auth)
93     TrustedRoots.add_gid(authority.get_gid_object())
94
95     if ".vini" in import_auth and import_auth.endswith('vini'):
96         # create a fake internet2 site first
97         i2site = {'name': 'Internet2', 'abbreviated_name': 'I2',
98                     'login_base': 'internet2', 'site_id': -1}
99         sfaImporter.import_site(import_auth, i2site)
100    
101     # create dict of all existing sfa records
102     existing_records = {}
103     existing_hrns = []
104     key_ids = []
105     person_keys = {} 
106     results = table.find()
107     for result in results:
108         existing_records[(result['hrn'], result['type'])] = result
109         existing_hrns.append(result['hrn']) 
110             
111     # Get all plc sites
112     sites = shell.GetSites(plc_auth, {'peer_id': None})
113     sites_dict = {}
114     for site in sites:
115         sites_dict[site['login_base']] = site 
116     
117     # Get all plc users
118     persons = shell.GetPersons(plc_auth, {'peer_id': None}, ['person_id', 'email', 'key_ids', 'site_ids'])
119     persons_dict = {}
120     for person in persons:
121         persons_dict[person['person_id']] = person
122         key_ids.extend(person['key_ids'])
123
124     # Get all public keys
125     keys = shell.GetKeys(plc_auth, {'peer_id': None, 'key_id': key_ids})
126     keys_dict = {}
127     for key in keys:
128         keys_dict[key['key_id']] = key['key']
129
130     # create a dict of person keys keyed on key_id 
131     old_person_keys = load_keys(keys_filename)
132     for person in persons:
133         pubkeys = []
134         for key_id in person['key_ids']:
135             pubkeys.append(keys_dict[key_id])
136         person_keys[person['person_id']] = pubkeys
137
138     # Get all plc nodes  
139     nodes = shell.GetNodes(plc_auth, {'peer_id': None}, ['node_id', 'hostname', 'site_id'])
140     nodes_dict = {}
141     for node in nodes:
142         nodes_dict[node['node_id']] = node
143
144     # Get all plc slices
145     slices = shell.GetSlices(plc_auth, {'peer_id': None}, ['slice_id', 'name'])
146     slices_dict = {}
147     for slice in slices:
148         slices_dict[slice['slice_id']] = slice
149
150     # start importing 
151     for site in sites:
152         site_hrn = import_auth + "." + site['login_base']
153         # import if hrn is not in list of existing hrns or if the hrn exists
154         # but its not a site record
155         if site_hrn not in existing_hrns or \
156            (site_hrn, 'authority') not in existing_records:
157             sfaImporter.import_site(import_auth, site)
158              
159         # import node records
160         for node_id in site['node_ids']:
161             if node_id not in nodes_dict:
162                 continue 
163             node = nodes_dict[node_id]
164             hrn =  hostname_to_hrn(import_auth, site['login_base'], node['hostname'])
165             if hrn not in existing_hrns or \
166                (hrn, 'node') not in existing_records:
167                 sfaImporter.import_node(site_hrn, node)
168
169         # import slices
170         for slice_id in site['slice_ids']:
171             if slice_id not in slices_dict:
172                 continue 
173             slice = slices_dict[slice_id]
174             hrn = slicename_to_hrn(import_auth, slice['name'])
175             if hrn not in existing_hrns or \
176                (hrn, 'slice') not in existing_records:
177                 sfaImporter.import_slice(site_hrn, slice)      
178
179         # import persons
180         for person_id in site['person_ids']:
181             if person_id not in persons_dict:
182                 continue 
183             person = persons_dict[person_id]
184             hrn = email_to_hrn(site_hrn, person['email'])
185             old_keys = []
186             new_keys = []
187             if person_id in old_person_keys:
188                 old_keys = old_person_keys[person_id]
189             if person_id in person_keys:
190                 new_keys = person_keys[person_id]
191             update_record = False
192             for key in new_keys:
193                 if key not in old_keys:
194                     update_record = True 
195
196             if hrn not in existing_hrns or \
197                (hrn, 'user') not in existing_records or update_record:
198                 sfaImporter.import_person(site_hrn, person)
199
200     
201     # remove stale records    
202     for (record_hrn, type) in existing_records.keys():
203         # if this is the interface name dont do anything
204         if record_hrn == import_auth:
205             continue    
206         
207         found = False
208         record = existing_records[(record_hrn, type)]
209         
210         if type == 'authority':    
211             for site in sites:
212                 site_hrn = import_auth + "." + 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             trace("Import: Removing %s %s" % (type,  record_hrn))
256             record_object = existing_records[(record_hrn, type)]
257             sfaImporter.delete_record(record_hrn, type) 
258                                    
259     # save pub keys
260     trace('saving current pub keys') 
261     save_keys(keys_filename, person_keys)                
262         
263 if __name__ == "__main__":
264     main()