Merge branch 'master' into senslab2
[sfa.git] / sfa / senslab / slab-import.py
1
2 import sys
3 import datetime
4 import time
5 from sfa.senslab.OARrestapi import OARapi
6 from sfa.senslab.LDAPapi import LDAPapi
7 from sfa.senslab.slabdriver import SlabDriver
8 from sfa.senslab.slabpostgres import SlabDB
9 from sfa.util.config import Config
10 from sfa.util.plxrn import PlXrn
11 from sfa.util.xrn import hrn_to_urn, get_authority,Xrn,get_leaf
12 from sfa.util.table import SfaTable
13 from sfa.util.record import SfaRecord
14 from sfa.trust.hierarchy import Hierarchy
15 from sfa.trust.certificate import Keypair,convert_public_key
16 from sfa.trust.gid import create_uuid
17 from sfa.trust.trustedroots import TrustedRoots
18
19 config = Config()
20 interface_hrn = config.SFA_INTERFACE_HRN
21 TrustedR = TrustedRoots(Config.get_trustedroots_dir(config))
22 AuthHierarchy = Hierarchy()
23 table = SfaTable()
24 db = SlabDB()
25 if not table.exists():
26     table.create()
27     
28     
29 def create_sm_client_record():
30     """
31     Create a user record for the Slicemanager service.
32     """
33     hrn = config.SFA_INTERFACE_HRN + '.slicemanager'
34     urn = hrn_to_urn(hrn, 'user')
35     if not AuthHierarchy.auth_exists(urn):
36         AuthHierarchy.create_auth(urn)
37
38     auth_info = AuthHierarchy.get_auth_info(hrn)
39     table = SfaTable()
40     sm_user_record = table.find({'type': 'user', 'hrn': hrn})
41     if not sm_user_record:
42         record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="user", pointer=-1)
43         record['authority'] = get_authority(record['hrn'])
44         table.insert(record)
45                 
46 def create_interface_records():
47     """
48     Create a record for each SFA interface
49     """
50     # just create certs for all sfa interfaces even if they
51     # arent enabled
52     interface_hrn = config.SFA_INTERFACE_HRN
53     interfaces = ['authority+sa', 'authority+am', 'authority+sm']
54     
55     auth_info = AuthHierarchy.get_auth_info(interface_hrn)
56     pkey = auth_info.get_pkey_object()
57     for interface in interfaces:
58         interface_record = table.find({'type': interface, 'hrn': interface_hrn})
59         if not interface_record:
60             urn = hrn_to_urn(interface_hrn, interface)
61             gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
62             record = SfaRecord(hrn=interface_hrn, gid=gid, type=interface, pointer=-1)  
63             record['authority'] = get_authority(interface_hrn)
64             print>>sys.stderr,"\r\n ==========create_interface_records", record['authority']
65             table.insert(record)                
66                 
67 def create_top_level_auth_records(hrn):
68     """
69     Create top level records (includes root and sub authorities (local/remote)
70     """
71
72     urn = hrn_to_urn(hrn, 'authority')
73     # make sure parent exists
74     parent_hrn = get_authority(hrn)
75     print>>sys.stderr, "\r\n =========slab-import create_top_level_auth_records hrn %s  urn %s parent_hrn %s \r\n" %(hrn, urn, parent_hrn)
76     if not parent_hrn:
77         parent_hrn = hrn
78     if not parent_hrn == hrn:
79         create_top_level_auth_records(parent_hrn)
80
81     # create the authority if it doesnt already exist 
82     if not AuthHierarchy.auth_exists(urn):
83         AuthHierarchy.create_auth(urn)
84     
85     # create the db record if it doesnt already exist    
86     auth_info = AuthHierarchy.get_auth_info(hrn)
87    
88     auth_record = table.find({'type': 'authority', 'hrn': hrn})
89
90     if not auth_record:
91         auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
92         auth_record['authority'] = get_authority(auth_record['hrn'])
93         print sys.stderr, " \r\n \t slab-import : auth record %s inserted record %s " %(auth_record['hrn'], auth_record)
94         table.insert(auth_record)
95
96         
97     
98 def import_node(hrn, node):
99
100     # ASN.1 will have problems with hrn's longer than 64 characters
101     if len(hrn) > 64:
102         hrn = hrn[:64]
103
104     node_record = table.find({'type': 'node', 'hrn': hrn})
105     pkey = Keypair(create=True)        
106     
107     urn = hrn_to_urn(hrn, 'node')
108     node_gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
109     node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
110     node_record['authority'] = get_authority(node_record['hrn'])
111     extime = datetime.datetime.utcnow()
112     node_record['date_created'] = int(time.mktime(extime.timetuple()))
113     existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
114     if not existing_records:
115         print>>sys.stderr, " \r\n \t slab-import : node record %s inserted" %(node['node_id'])
116         table.insert(node_record)
117     else:
118         existing_record = existing_records[0]
119         node_record['record_id'] = existing_record['record_id']
120         table.update(node_record)
121
122 # person is already a sfa record 
123 def import_person(authname,person):       
124     existing_records = table.find({'hrn': person['hrn'], 'type': 'user'})
125     extime = datetime.datetime.utcnow()
126     person['date_created'] = int(time.mktime(extime.timetuple()))
127
128   
129     if not existing_records:
130         print>>sys.stderr, " \r\n \t slab-import : person record %s inserted" %(person['hrn'])
131         uuid=create_uuid() 
132         RSA_KEY_STRING=person['pkey']
133         pkey=convert_public_key(RSA_KEY_STRING)
134         person['gid']=AuthHierarchy.create_gid("urn:publicid:IDN+"+authname+"+user+"+person['uid'], uuid, pkey, CA=False).save_to_string()
135         table.insert(person)
136     else:
137         existing_record = existing_records[0]
138         person['record_id'] = existing_record['record_id']
139         # handle key change ??? 
140         table.update(person)
141         
142 def import_slice(person):
143
144     hrn = person['hrn']+'_slice'
145     pkey = Keypair(create=True)
146     urn = hrn_to_urn(hrn, 'slice')
147     gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
148     slice_record= SfaRecord(hrn=hrn, gid=gid, type="slice", pointer=-1)
149     slice_record['authority'] = get_authority(slice_record['hrn'])
150    
151     extime = datetime.datetime.utcnow()
152     slice_record['date_created'] = int(time.mktime(extime.timetuple()))
153     #special slice table for Senslab, to store nodes info (OAR)                         
154
155     existing_records = table.find({'hrn': slice_record['hrn'], 'type': 'slice'})
156     if not existing_records:
157         print>>sys.stderr, " \r\n \t slab-import : slice record %s inserted" %(slice_record['hrn'])
158         table.insert(slice_record)
159         db.insert_slab_slice(person)
160
161     else:
162         print>>sys.stderr, " \r\n \t slab-import : slice record %s updated" %(slice_record['hrn'])
163         existing_record = existing_records[0]
164         slice_record['record_id'] = existing_record['record_id']
165         table.update(slice_record)
166         db.update_senslab_slice(slice_record)   
167         
168 def delete_record( hrn, type):
169     # delete the record
170     record_list = table.find({'type': type, 'hrn': hrn})
171     for record in record_list:
172         print>>sys.stderr, " \r\n \t slab-import : record %s deleted" %(record['hrn'])
173         table.remove(record)
174                 
175 def hostname_to_hrn(root_auth,login_base,hostname):
176     return PlXrn(auth=root_auth,hostname=login_base+'_'+hostname).get_hrn()
177
178     
179 def main():
180
181     if not db.exists('slice'):
182         db.createtable('slice')
183         
184     if not config.SFA_REGISTRY_ENABLED:
185         sys.exit(0)
186     root_auth = config.SFA_REGISTRY_ROOT_AUTH
187     interface_hrn = config.SFA_INTERFACE_HRN
188
189     
190     #Get all records in the sfa table   
191     # create dict of all existing sfa records
192     existing_records = {}
193     existing_hrns = []
194     key_ids = []
195     results = table.find()
196    
197     for result in results:
198         existing_records[(result['hrn'], result['type'])] = result
199         existing_hrns.append(result['hrn'])   
200         
201     # create root authority if it doesn't exist
202     if root_auth not in  existing_hrns or \
203     (root_auth, 'authority') not in existing_records:
204         create_top_level_auth_records(root_auth)
205         if not root_auth == interface_hrn:
206             create_top_level_auth_records(interface_hrn)
207     
208         # create s user record for the slice manager Do we need this?
209         create_sm_client_record()
210         
211         # create interface records ADDED 18 nov 11 Do we need this?
212     
213         create_interface_records()
214     
215         # add local root authority's cert  to trusted list ADDED 18 nov 11 Do we need this?
216         
217         authority = AuthHierarchy.get_auth_info(interface_hrn)
218         TrustedR.add_gid(authority.get_gid_object())
219
220
221     #Get Senslab nodes 
222    
223     Driver = SlabDriver(config)
224     nodes_dict  = Driver.GetNodes()
225     #print "\r\n NODES8DICT ",nodes_dict
226     
227     ldap_person_list = Driver.GetPersons()
228
229         # import node records
230     for node in nodes_dict:
231         # Sandrine
232         # A changer pour l utilisation du nouveau OAR de prod, le site etant contenu dans le hostname
233         hrn =  hostname_to_hrn( root_auth,node['site_login_base'], node['hostname'])
234         if hrn not in existing_hrns or \
235         (hrn, 'node') not in existing_records:
236             import_node(hrn, node)
237
238    # import persons and slices
239     for person in ldap_person_list:
240         if person['hrn'] not in existing_hrns or \
241             (person['hrn'], 'user') not in existing_records :
242             import_person(root_auth,person)
243             import_slice(person)
244                                 
245                                 
246     # remove stale records    
247     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
248
249     for (record_hrn, type) in existing_records.keys():
250         if record_hrn in system_records:
251             continue
252         
253         record = existing_records[(record_hrn, type)]
254         if record['peer_authority']:
255             continue                                    
256
257
258
259         found = False
260         
261         if type == 'authority':    
262             found = True
263             print "\t \t Found :", found
264             break
265                 
266         elif type == 'user':
267             for person in ldap_person_list:
268                 if person['hrn'] == record_hrn:
269                     found = True
270                     break
271             
272         elif type == 'node':
273             login_base = get_leaf(get_authority(record_hrn))
274             nodename = Xrn.unescape(get_leaf(record_hrn))
275             for node in nodes_dict:
276                 if node['hostname'] == nodename :
277                     found = True
278                     break 
279                 
280         elif type == 'slice':
281             for person in ldap_person_list:
282                 if person['hrn']+'_slice' == record_hrn:
283                     found = True
284                     break           
285         else:
286             continue 
287         
288         if not found:
289             record_object = existing_records[(record_hrn, type)]
290             print "\t\t  NOT FOUND ! ", record_hrn
291             delete_record(record_hrn, type) 
292     
293 if __name__ == "__main__":
294     main()