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