delete stale records after all records have been added
[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     sites_dict = {}
94     for site in sites:
95         sites_dict[site['login_base']] = site 
96     
97     # Get all plc users
98     persons = shell.GetPersons(plc_auth, {}, ['person_id', 'email', 'key_ids', 'site_ids'])
99     persons_dict = {}
100     for person in persons:
101         persons_dict[person['person_id']] = person
102
103     # Get all plc nodes  
104     nodes = shell.GetNodes(plc_auth, {}, ['node_id', 'hostname', 'site_id'])
105     nodes_dict = {}
106     for node in nodes:
107         nodes_dict[node['node_id']] = node
108
109     # Get all plc slices
110     slices = shell.GetSlices(plc_auth, {}, ['slice_id', 'name'])
111     slices_dict = {}
112     for slice in slices:
113         slices_dict[slice['slice_id']] = slice
114
115     # start importing 
116     for site in sites:
117         site_hrn = import_auth + "." + site['login_base']
118         # import if hrn is not in list of existing hrns or if the hrn exists
119         # but its not a site record
120         if site_hrn not in existing_hrns or \
121            (site_hrn, 'authority') not in existing_records:
122             sfaImporter.import_site(import_auth, site)
123              
124         # import node records
125         for node_id in site['node_ids']:
126             if node_id not in nodes_dict:
127                 continue 
128             node = nodes_dict[node_id]
129             hrn =  hostname_to_hrn(import_auth, site['login_base'], node['hostname'])
130             if hrn not in existing_hrns or \
131                (hrn, 'node') not in existing_records:
132                 sfaImporter.import_node(site_hrn, node)
133
134         # import slices
135         for slice_id in site['slice_ids']:
136             if slice_id not in slices_dict:
137                 continue 
138             slice = slices_dict[slice_id]
139             hrn = slicename_to_hrn(import_auth, slice['name'])
140             if hrn not in existing_hrns or \
141                (hrn, 'slice') not in existing_records:
142                 sfaImporter.import_slice(site_hrn, slice)      
143
144         # import persons
145         for person_id in site['person_ids']:
146             if person_id not in persons_dict:
147                 continue 
148             person = persons_dict[person_id]
149             hrn = email_to_hrn(site_hrn, person['email'])
150             if hrn not in existing_hrns or \
151                (hrn, 'user') not in existing_records:
152                 sfaImporter.import_person(site_hrn, person)
153
154         
155     # remove stale records    
156     for (record_hrn, type) in existing_records.keys():
157         found = False
158         if record_hrn == import_auth:
159             continue    
160         if type == 'authority':    
161             for site in sites:
162                 site_hrn = import_auth + "." + site['login_base']
163                 if site_hrn == record_hrn:
164                     found = True
165                     break
166
167         elif type == 'user':
168             login_base = get_leaf(get_authority(record_hrn))
169             username = get_leaf(record_hrn)
170             site = sites_dict[login_base]
171             for person in persons:
172                 tmp_username = person['email'].split("@")[0]
173                 alt_username = person['email'].split("@")[0].replace(".", "_")
174                 if username in [tmp_username, alt_username] and site['site_id'] in person['site_ids']:
175                     found = True
176                     break
177         
178         elif type == 'slice':
179             slicename = hrn_to_pl_slicename(record_hrn)
180             site = sites_dict[login_base]
181             for slice in slices:
182                 if slicename == slice['name']:
183                     found = True
184                     break    
185  
186         elif type == 'node':
187             login_base = get_leaf(get_authority(record_hrn))
188             nodename = get_leaf(record_hrn)
189             site = sites_dict[login_base]
190             for node in nodes:
191                 tmp_nodename = node['hostname'].split(".")[0]
192                 if tmp_nodename == nodename and node['site_id'] == site['site_id']:
193                     found = True
194                     break  
195         else:
196             continue 
197         
198         if not found:
199             trace("Import: Removing %s %s" % (type,  record_hrn))
200             record_object = existing_records[(record_hrn, type)]
201             sfaImporter.delete_record(record_hrn, type) 
202                                    
203                     
204         
205 if __name__ == "__main__":
206     main()