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