remove stale records from sfa db
[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 def main():
47     process_options()
48     config = Config()
49     root_auth = config.SFA_REGISTRY_ROOT_AUTH
50     level1_auth = config.SFA_REGISTRY_LEVEL1_AUTH
51     sfaImporter = sfaImport()
52     shell = sfaImporter.shell
53     plc_auth = sfaImporter.plc_auth 
54     AuthHierarchy = sfaImporter.AuthHierarchy
55     TrustedRoots = sfaImporter.TrustedRoots
56     table = GeniTable()
57     if not table.exists():
58         table.create()
59
60     if not level1_auth or level1_auth in ['']:
61         level1_auth = None
62     
63     print "Import: creating top level authorities"
64     if not level1_auth:
65         sfaImporter.create_top_level_auth_records(root_auth)
66         import_auth = root_auth
67     else:
68         if not AuthHierarchy.auth_exists(level1_auth):
69             AuthHierarchy.create_auth(level1_auth)
70         sfaImporter.create_top_level_auth_records(level1_auth)
71         import_auth = level1_auth
72
73     print "Import: adding", import_auth, "to trusted list"
74     authority = AuthHierarchy.get_auth_info(import_auth)
75     TrustedRoots.add_gid(authority.get_gid_object())
76
77     if ".vini" in import_auth and import_auth.endswith('vini'):
78         # create a fake internet2 site first
79         i2site = {'name': 'Internet2', 'abbreviated_name': 'I2',
80                     'login_base': 'internet2', 'site_id': -1}
81         sfaImporter.import_site(import_auth, i2site)
82    
83     # create dict of all existing sfa records
84     existing_records = {}
85     existing_hrns = []
86     results = table.find()
87     for result in results:
88         existing_records[(result['hrn'], result['type'])] = result
89         existing_hrns.append(result['hrn']) 
90             
91     # Get all plc sites
92     sites = shell.GetSites(plc_auth)
93     
94     # Get all plc users
95     persons = shell.GetPersons(plc_auth, {}, ['person_id', 'email', 'key_ids'])
96     persons_dict = {}
97     for person in persons:
98         persons_dict[person['person_id']] = person
99
100     # Get all plc nodes  
101     nodes = shell.GetNodes(plc_auth, {}, ['node_id', 'hostname'])
102     nodes_dict = {}
103     for node in nodes:
104         nodes_dict[node['node_id']] = node
105
106     # Get all plc slices
107     slices = shell.GetSlices(plc_auth, {}, ['slice_id', 'name'])
108     slices_dict = {}
109     for slice in slices:
110         slices_dict[slice['slice_id']] = slice
111
112     # start importing 
113     for site in sites:
114         site_hrn = import_auth + "." + site['login_base']
115         # import if hrn is not in list of existing hrns or if the hrn exists
116         # but its not a site record
117         if site_hrn not in existing_hrns or \
118            (site_hrn, 'authority') not in existing_records:
119             sfaImporter.import_site(import_auth, site)
120              
121         # import node records
122         for node_id in site['node_ids']:
123             if node_id not in nodes_dict:
124                 continue 
125             node = nodes_dict[node_id]
126             hrn =  hostname_to_hrn(import_auth, site['login_base'], node['hostname'])
127             if hrn not in existing_hrns or \
128                (hrn, 'node') not in existing_records:
129                 sfaImporter.import_node(site_hrn, node)
130
131         # import slices
132         for slice_id in site['slice_ids']:
133             if slice_id not in slices_dict:
134                 continue 
135             slice = slices_dict[slice_id]
136             hrn = slicename_to_hrn(import_auth, slice['name'])
137             if hrn not in existing_hrns or \
138                (hrn, 'slice') not in existing_records:
139                 sfaImporter.import_slice(site_hrn, slice)      
140
141         # import persons
142         for person_id in site['person_ids']:
143             if person_id not in persons_dict:
144                 continue 
145             person = persons_dict[person_id]
146             hrn = email_to_hrn(site_hrn, person['email'])
147             if hrn not in existing_hrns or \
148                (hrn, 'user') not in existing_records:
149                 sfaImporter.import_person(site_hrn, person)
150
151         
152         # remove any record in existing_hrns that does not 
153         # have a plc record
154         site_existing_records_only = lambda (r_hrn, r_type): r_hrn.startswith(site_hrn)
155         site_existing_records = filter(site_existing_records_only, existing_records.keys())
156         for (record_hrn, type) in site_existing_records:
157             found = False
158             if type == 'user':
159                 for person in persons_dict.values():
160                     tmp_hrn = email_to_hrn(site_hrn, person['email'])
161                     if record_hrn == tmp_hrn:
162                         found = True
163
164             elif type == 'node':
165                 for node in nodes_dict.values():
166                     tmp_hrn = hostname_to_hrn(import_auth, site['login_base'], node['hostname'])
167                     if record_hrn == tmp_hrn:
168                         found = True
169             elif type == 'slice':
170                 for slice in slices_dict.values():
171                     tmp_hrn = slicename_to_hrn(import_auth, slice['name'])
172                     if record_hrn == tmp_hrn:
173                         found = True
174             else:
175                 continue
176  
177             if not found:
178                 trace("Import: Removing %s %s" % (type, record_hrn)) 
179                 record_object = existing_records[(record_hrn, type)]
180                 sfaImporter.delete_record(record_hrn, type)
181     
182     # remove stale site_records    
183     site_records_only = lambda(r_hrn, r_type): r_type == 'authority' and r_hrn != import_auth
184     site_records = filter(site_records_only, existing_records.keys())
185     for (record_hrn, type) in site_records:
186         found = False
187         for site in sites:
188             site_hrn = import_auth + "." + site['login_base']
189             if site_hrn == record_hrn:
190                 found = True
191         if not found:
192             trace("Import: Removing %s %s" % (type,  record_hrn))
193             record_object = existing_records[(record_hrn, type)]
194             sfaImporter.delete_record(record_hrn, type) 
195                                    
196                     
197         
198 if __name__ == "__main__":
199     main()