Removed SA special ssh key in slab import script (ssh key copied from senslab VM...
[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      # initialize registry db table
190     #table = SfaTable()
191     #if not table.exists():
192         #table.create()
193
194     # create root authority 
195     create_top_level_auth_records(root_auth)
196     if not root_auth == interface_hrn:
197        create_top_level_auth_records(interface_hrn)
198     
199     # create s user record for the slice manager Do we need this?
200     #create_sm_client_record()
201        
202     # create interface records ADDED 18 nov 11 Do we need this?
203
204     create_interface_records()
205
206     # add local root authority's cert  to trusted list ADDED 18 nov 11 Do we need this?
207     
208     authority = AuthHierarchy.get_auth_info(interface_hrn)
209     TrustedR.add_gid(authority.get_gid_object())
210
211
212
213      # create dict of all existing sfa records
214      
215     existing_records = {}
216     existing_hrns = []
217     key_ids = []
218     person_keys = {} 
219     results = table.find()
220     for result in results:
221         existing_records[(result['hrn'], result['type'])] = result
222         existing_hrns.append(result['hrn'])   
223         
224     #Get Senslab nodes 
225    
226     Driver = SlabDriver(config)
227     nodes_dict  = Driver.GetNodes()
228     #print "\r\n NODES8DICT ",nodes_dict
229     
230     ldap_person_list = Driver.GetPersons()
231     
232
233    
234         # import node records
235     for node in nodes_dict:
236         hrn =  hostname_to_hrn( root_auth, node['hostname'])
237         if hrn not in existing_hrns or \
238         (hrn, 'node') not in existing_records:
239             import_node(hrn, node)
240
241    # import persons and slices
242     for person in ldap_person_list:
243         if person['hrn'] not in existing_hrns or \
244             (person['hrn'], 'user') not in existing_records :
245             import_person(root_auth,person)
246             import_slice(person)
247
248
249
250                                         
251     # remove stale records    
252     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
253
254     for (record_hrn, type) in existing_records.keys():
255         if record_hrn in system_records:
256             continue
257         
258         record = existing_records[(record_hrn, type)]
259         if record['peer_authority']:
260             continue                                    
261
262
263
264         found = False
265         
266         if type == 'authority':    
267             #for site in sites_dict:
268                 #print "\t type : authority : ", site
269                 #site_hrn = interface_hrn + "." + site['login_base']
270                 #if site_hrn == record_hrn and site['site_id'] == record['pointer']:
271             found = True
272             print "\t \t Found :", found
273             break
274                 
275         elif type == 'user':
276             for person in ldap_person_list:
277                 if person['hrn'] == record_hrn:
278                     found = True
279                     break
280             
281         elif type == 'node':
282             login_base = get_leaf(get_authority(record_hrn))
283             nodename = Xrn.unescape(get_leaf(record_hrn))
284             for node in nodes_dict:
285                 if node['hostname'] == nodename :
286                     found = True
287                     break 
288                 
289         elif type == 'slice':
290             for person in ldap_person_list:
291                 if person['hrn']+'_slice' == record_hrn:
292                     found = True
293                     break           
294         else:
295             continue 
296         
297         if not found:
298             record_object = existing_records[(record_hrn, type)]
299             print "\t\t  NOT FOUND ! ", record_hrn
300             delete_record(record_hrn, type) 
301     
302 if __name__ == "__main__":
303     main()