import_site() returns the site hrn
[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 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.util.geniclient import *
34 from sfa.trust.gid import create_uuid
35 from sfa.plc.sfaImport import *
36
37
38
39 def process_options():
40    global hrn
41
42    (options, args) = getopt.getopt(sys.argv[1:], '', [])
43    for opt in options:
44        name = opt[0]
45        val = opt[1]
46
47
48 def load_keys(filename):
49     keys = {}
50     tmp_dict = {}
51     try:
52         execfile(filename, tmp_dict)
53         if 'keys' in tmp_dict:
54             keys = tmp_dict['keys']
55         return keys
56     except:
57         return keys
58
59 def save_keys(filename, keys):
60     f = open(filename, 'w')
61     f.write("keys = %s" % str(keys))
62     f.close()
63
64 def main():
65     process_options()
66     config = Config()
67     if not config.SFA_REGISTRY_ENABLED:
68         sys.exit(0)
69     root_auth = config.SFA_REGISTRY_ROOT_AUTH
70     level1_auth = config.SFA_REGISTRY_LEVEL1_AUTH
71     keys_filename = config.config_path + os.sep + 'person_keys.py' 
72     sfaImporter = sfaImport()
73     shell = sfaImporter.shell
74     plc_auth = sfaImporter.plc_auth 
75     AuthHierarchy = sfaImporter.AuthHierarchy
76     TrustedRoots = sfaImporter.TrustedRoots
77     table = GeniTable()
78     if not table.exists():
79         table.create()
80
81     if not level1_auth or level1_auth in ['']:
82         level1_auth = None
83     
84     print "Import: creating top level authorities"
85     if not level1_auth:
86         sfaImporter.create_top_level_auth_records(root_auth)
87         import_auth = root_auth
88     else:
89         if not AuthHierarchy.auth_exists(level1_auth):
90             AuthHierarchy.create_auth(level1_auth)
91         sfaImporter.create_top_level_auth_records(level1_auth)
92         import_auth = level1_auth
93
94     print "Import: adding", import_auth, "to trusted list"
95     authority = AuthHierarchy.get_auth_info(import_auth)
96     TrustedRoots.add_gid(authority.get_gid_object())
97
98     if ".vini" in import_auth and import_auth.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(import_auth, 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}, ['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
153     # start importing 
154     for site in sites:
155         site_hrn = import_auth + "." + site['login_base']
156         # import if hrn is not in list of existing hrns or if the hrn exists
157         # but its not a site record
158         if site_hrn not in existing_hrns or \
159            (site_hrn, 'authority') not in existing_records:
160             site_hrn = sfaImporter.import_site(import_auth, site)
161              
162         # import node records
163         for node_id in site['node_ids']:
164             if node_id not in nodes_dict:
165                 continue 
166             node = nodes_dict[node_id]
167             hrn =  hostname_to_hrn(import_auth, site['login_base'], node['hostname'])
168             if hrn not in existing_hrns or \
169                (hrn, 'node') not in existing_records:
170                 sfaImporter.import_node(site_hrn, node)
171
172         # import slices
173         for slice_id in site['slice_ids']:
174             if slice_id not in slices_dict:
175                 continue 
176             slice = slices_dict[slice_id]
177             hrn = slicename_to_hrn(import_auth, slice['name'])
178             if hrn not in existing_hrns or \
179                (hrn, 'slice') not in existing_records:
180                 sfaImporter.import_slice(site_hrn, slice)      
181
182         # import persons
183         for person_id in site['person_ids']:
184             if person_id not in persons_dict:
185                 continue 
186             person = persons_dict[person_id]
187             hrn = email_to_hrn(site_hrn, person['email'])
188             old_keys = []
189             new_keys = []
190             if person_id in old_person_keys:
191                 old_keys = old_person_keys[person_id]
192             if person_id in person_keys:
193                 new_keys = person_keys[person_id]
194             update_record = False
195             for key in new_keys:
196                 if key not in old_keys:
197                     update_record = True 
198
199             if hrn not in existing_hrns or \
200                (hrn, 'user') not in existing_records or update_record:
201                 sfaImporter.import_person(site_hrn, person)
202
203     # remove stale records    
204     for (record_hrn, type) in existing_records.keys():
205         record = existing_records[(record_hrn, type)]
206         # if this is the interface name dont do anything
207         if record_hrn == import_auth or record['peer_authority']:
208             continue    
209         
210         found = False
211         
212         if type == 'authority':    
213             for site in sites:
214                 site_hrn = import_auth + "." + site['login_base']
215                 if site_hrn == record_hrn and site['site_id'] == record['pointer']:
216                     found = True
217                     break
218
219         elif type == 'user':
220             login_base = get_leaf(get_authority(record_hrn))
221             username = get_leaf(record_hrn)
222             if login_base in sites_dict:
223                 site = sites_dict[login_base]
224                 for person in persons:
225                     tmp_username = person['email'].split("@")[0]
226                     alt_username = person['email'].split("@")[0].replace(".", "_")
227                     if username in [tmp_username, alt_username] and \
228                        site['site_id'] in person['site_ids'] and \
229                        person['person_id'] == record['pointer']:
230                         found = True
231                         break
232         
233         elif type == 'slice':
234             slicename = hrn_to_pl_slicename(record_hrn)
235             for slice in slices:
236                 if slicename == slice['name'] and \
237                    slice['slice_id'] == record['pointer']:
238                     found = True
239                     break    
240  
241         elif type == 'node':
242             login_base = get_leaf(get_authority(record_hrn))
243             nodename = get_leaf(record_hrn)
244             if login_base in sites_dict:
245                 site = sites_dict[login_base]
246                 for node in nodes:
247                     tmp_nodename = node['hostname'].split(".")[0]
248                     if tmp_nodename == nodename and \
249                        node['site_id'] == site['site_id'] and \
250                        node['node_id'] == record['pointer']:
251                         found = True
252                         break  
253         else:
254             continue 
255         
256         if not found:
257             trace("Import: Removing %s %s" % (type,  record_hrn))
258             record_object = existing_records[(record_hrn, type)]
259             sfaImporter.delete_record(record_hrn, type) 
260                                    
261     # save pub keys
262     trace('saving current pub keys')
263     save_keys(keys_filename, person_keys)                
264         
265 if __name__ == "__main__":
266     main()