console_logger defined for the client side
[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 import logging
21
22 from sfa.util.record import *
23 from sfa.util.table import SfaTable
24 from sfa.util.namespace import *
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    global hrn
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.setLevel(logging.DEBUG)
69     shell = sfaImporter.shell
70     plc_auth = sfaImporter.plc_auth 
71     AuthHierarchy = sfaImporter.AuthHierarchy
72     TrustedRoots = sfaImporter.TrustedRoots
73     table = SfaTable()
74
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     sfaImporter.logger.info("Import: adding " + interface_hrn + " to trusted list")
84     authority = AuthHierarchy.get_auth_info(interface_hrn)
85     TrustedRoots.add_gid(authority.get_gid_object())
86
87     if ".vini" in interface_hrn and interface_hrn.endswith('vini'):
88         # create a fake internet2 site first
89         i2site = {'name': 'Internet2', 'abbreviated_name': 'I2',
90                     'login_base': 'internet2', 'site_id': -1}
91         sfaImporter.import_site(interface_hrn, i2site)
92    
93     # create dict of all existing sfa records
94     existing_records = {}
95     existing_hrns = []
96     key_ids = []
97     person_keys = {} 
98     results = table.find()
99     for result in results:
100         existing_records[(result['hrn'], result['type'])] = result
101         existing_hrns.append(result['hrn']) 
102             
103     # Get all plc sites
104     sites = shell.GetSites(plc_auth, {'peer_id': None})
105     sites_dict = {}
106     for site in sites:
107         sites_dict[site['login_base']] = site 
108     
109     # Get all plc users
110     persons = shell.GetPersons(plc_auth, {'peer_id': None, 'enabled': True}, ['person_id', 'email', 'key_ids', 'site_ids'])
111     persons_dict = {}
112     for person in persons:
113         persons_dict[person['person_id']] = person
114         key_ids.extend(person['key_ids'])
115
116     # Get all public keys
117     keys = shell.GetKeys(plc_auth, {'peer_id': None, 'key_id': key_ids})
118     keys_dict = {}
119     for key in keys:
120         keys_dict[key['key_id']] = key['key']
121
122     # create a dict of person keys keyed on key_id 
123     old_person_keys = load_keys(keys_filename)
124     for person in persons:
125         pubkeys = []
126         for key_id in person['key_ids']:
127             pubkeys.append(keys_dict[key_id])
128         person_keys[person['person_id']] = pubkeys
129
130     # Get all plc nodes  
131     nodes = shell.GetNodes(plc_auth, {'peer_id': None}, ['node_id', 'hostname', 'site_id'])
132     nodes_dict = {}
133     for node in nodes:
134         nodes_dict[node['node_id']] = node
135
136     # Get all plc slices
137     slices = shell.GetSlices(plc_auth, {'peer_id': None}, ['slice_id', 'name'])
138     slices_dict = {}
139     for slice in slices:
140         slices_dict[slice['slice_id']] = slice
141     # start importing 
142     for site in sites:
143         site_hrn = interface_hrn + "." + site['login_base']
144         print "Importing site: %s" % site_hrn
145
146         # import if hrn is not in list of existing hrns or if the hrn exists
147         # but its not a site record
148         if site_hrn not in existing_hrns or \
149            (site_hrn, 'authority') not in existing_records:
150             site_hrn = sfaImporter.import_site(interface_hrn, site)
151              
152         # import node records
153         for node_id in site['node_ids']:
154             if node_id not in nodes_dict:
155                 continue 
156             node = nodes_dict[node_id]
157             hrn =  hostname_to_hrn(interface_hrn, site['login_base'], node['hostname'])
158             if hrn not in existing_hrns or \
159                (hrn, 'node') not in existing_records:
160                 sfaImporter.import_node(site_hrn, node)
161
162         # import slices
163         for slice_id in site['slice_ids']:
164             if slice_id not in slices_dict:
165                 continue 
166             slice = slices_dict[slice_id]
167             hrn = slicename_to_hrn(interface_hrn, slice['name'])
168             if hrn not in existing_hrns or \
169                (hrn, 'slice') not in existing_records:
170                 sfaImporter.import_slice(site_hrn, slice)      
171
172         # import persons
173         for person_id in site['person_ids']:
174             if person_id not in persons_dict:
175                 continue 
176             person = persons_dict[person_id]
177             hrn = email_to_hrn(site_hrn, person['email'])
178             old_keys = []
179             new_keys = []
180             if person_id in old_person_keys:
181                 old_keys = old_person_keys[person_id]
182             if person_id in person_keys:
183                 new_keys = person_keys[person_id]
184             update_record = False
185             for key in new_keys:
186                 if key not in old_keys:
187                     update_record = True 
188
189             if hrn not in existing_hrns or \
190                (hrn, 'user') not in existing_records or update_record:
191                 sfaImporter.import_person(site_hrn, person)
192
193     # remove stale records    
194     for (record_hrn, type) in existing_records.keys():
195         record = existing_records[(record_hrn, type)]
196         # if this is the interface name dont do anything
197         if record_hrn == interface_hrn or \
198            record_hrn == root_auth or \
199            record['peer_authority']:
200             continue
201         # dont delete vini's internet2 placeholdder record
202         # normally this would be deleted becuase it does not have a plc record 
203         if ".vini" in interface_hrn and interface_hrn.endswith('vini') and \
204            record_hrn.endswith("internet2"):     
205             continue
206
207         found = False
208         
209         if type == 'authority':    
210             for site in sites:
211                 site_hrn = interface_hrn + "." + site['login_base']
212                 if site_hrn == record_hrn and site['site_id'] == record['pointer']:
213                     found = True
214                     break
215
216         elif type == 'user':
217             login_base = get_leaf(get_authority(record_hrn))
218             username = get_leaf(record_hrn)
219             if login_base in sites_dict:
220                 site = sites_dict[login_base]
221                 for person in persons:
222                     tmp_username = person['email'].split("@")[0]
223                     alt_username = person['email'].split("@")[0].replace(".", "_")
224                     if username in [tmp_username, alt_username] and \
225                        site['site_id'] in person['site_ids'] and \
226                        person['person_id'] == record['pointer']:
227                         found = True
228                         break
229         
230         elif type == 'slice':
231             slicename = hrn_to_pl_slicename(record_hrn)
232             for slice in slices:
233                 if slicename == slice['name'] and \
234                    slice['slice_id'] == record['pointer']:
235                     found = True
236                     break    
237  
238         elif type == 'node':
239             login_base = get_leaf(get_authority(record_hrn))
240             nodename = get_leaf(record_hrn)
241             if login_base in sites_dict:
242                 site = sites_dict[login_base]
243                 for node in nodes:
244                     tmp_nodename = node['hostname'].split(".")[0]
245                     if tmp_nodename == nodename and \
246                        node['site_id'] == site['site_id'] and \
247                        node['node_id'] == record['pointer']:
248                         found = True
249                         break  
250         else:
251             continue 
252         
253         if not found:
254             record_object = existing_records[(record_hrn, type)]
255             sfaImporter.delete_record(record_hrn, type) 
256                                    
257     # save pub keys
258     sfaImporter.logger.info('Import: saving current pub keys')
259     save_keys(keys_filename, person_keys)                
260         
261 if __name__ == "__main__":
262     main()