Gid creation code moved. NT.
[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 from sfa.senslab.OARrestapi import OARapi
10 from sfa.senslab.LDAPapi import LDAPapi
11 from sfa.senslab.slabdriver import SlabDriver
12 from sfa.util.config import Config
13 from sfa.util.xrn import hrn_to_urn, get_authority,Xrn,get_leaf
14 from sfa.util.table import SfaTable
15 from sfa.util.record import SfaRecord
16 from sfa.trust.hierarchy import Hierarchy
17 from sfa.trust.certificate import Keypair
18 from sfa.trust.gid import create_uuid
19
20
21 AuthHierarchy = Hierarchy()
22 table = SfaTable()
23 if not table.exists():
24     table.create()
25     
26 def create_top_level_auth_records(hrn):
27     """
28     Create top level records (includes root and sub authorities (local/remote)
29     """
30     print>>sys.stderr, "\r\n =========SenslabImport create_top_level_auth_records\r\n"
31     urn = hrn_to_urn(hrn, 'authority')
32     # make sure parent exists
33     parent_hrn = get_authority(hrn)
34     if not parent_hrn:
35         parent_hrn = hrn
36     if not parent_hrn == hrn:
37         create_top_level_auth_records(parent_hrn)
38         
39     
40     # create the authority if it doesnt already exist 
41     if not AuthHierarchy.auth_exists(urn):
42         AuthHierarchy.create_auth(urn)
43     
44     # create the db record if it doesnt already exist    
45     auth_info = AuthHierarchy.get_auth_info(hrn)
46    
47     auth_record = table.find({'type': 'authority', 'hrn': hrn})
48
49     if not auth_record:
50         auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
51         auth_record['authority'] = get_authority(auth_record['hrn'])
52         print sys.stderr, " \r\n \t slab-import : auth record %s inserted" %(auth_record['hrn'])
53         table.insert(auth_record)
54         print>>sys.stderr, "\r\n ========= \t\t SenslabImport NO AUTH RECORD \r\n" ,auth_record['authority']
55         
56     
57 def import_node(hrn, node):
58
59     # ASN.1 will have problems with hrn's longer than 64 characters
60     if len(hrn) > 64:
61         hrn = hrn[:64]
62
63     node_record = table.find({'type': 'node', 'hrn': hrn})
64     pkey = Keypair(create=True)
65     urn = hrn_to_urn(hrn, 'node')
66     node_gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
67     node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
68     node_record['authority'] = get_authority(node_record['hrn'])
69     existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
70     if not existing_records:
71         print>>sys.stderr, " \r\n \t slab-import : node record %s inserted" %(node_record['hrn'])
72         table.insert(node_record)
73     else:
74         existing_record = existing_records[0]
75         node_record['record_id'] = existing_record['record_id']
76         table.update(node_record)
77
78 # person is already a sfa record 
79 def import_person(person):       
80     existing_records = table.find({'hrn': person['hrn'], 'type': 'user'})
81     if not existing_records:
82         print>>sys.stderr, " \r\n \t slab-import : person record %s inserted" %(person['hrn'])
83         uuid=create_uuid() 
84         RSA_KEY_STRING=person['pkey']
85         pkey=convert_public_key(RSA_KEY_STRING)
86         person['gid']=self.senslabauth.create_gid("urn:publicid:IDN+"+self.authname+"+user+"+ldapentry[1]['uid'][0], uuid, pkey, CA=False)
87         table.insert(person)
88     else:
89         existing_record = existing_records[0]
90         person['record_id'] = existing_record['record_id']
91         # handle key change ??? 
92         table.update(person)
93         
94 def import_slice(person):
95
96     hrn = person['hrn']+'_slice'
97     pkey = Keypair(create=True)
98     urn = hrn_to_urn(hrn, 'slice')
99     gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
100     slice_record= SfaRecord(hrn=hrn, gid=gid, type="slice", pointer=-1)
101     slice_record['authority'] = get_authority(slice_record['hrn'])
102     print>>sys.stderr, " \r\n \t slab-import : slice record %s " %(slice_record['hrn']) 
103     existing_records = table.find({'hrn': slice_record['hrn'], 'type': 'slice'})
104     if not existing_records:
105         print>>sys.stderr, " \r\n \t slab-import : slice record %s inserted" %(slice_record['hrn'])
106         table.insert(slice_record)
107     else:
108         print>>sys.stderr, " \r\n \t slab-import : slice record %s updated" %(slice_record['hrn'])
109         existing_record = existing_records[0]
110         slice_record['record_id'] = existing_record['record_id']
111         table.update(slice_record)        
112         
113 def delete_record( hrn, type):
114     # delete the record
115     record_list = table.find({'type': type, 'hrn': hrn})
116     for record in record_list:
117         print>>sys.stderr, " \r\n \t slab-import : record %s deleted" %(record['hrn'])
118         table.remove(record)
119                 
120 def hostname_to_hrn(root_auth,hostname):
121     # keep only the first part of the DNS name
122     #hrn='.'.join( [auth,hostname.split(".")[0] ] )
123     # escape the '.' in the hostname
124     hrn='.'.join( [root_auth,Xrn.escape(hostname)] )
125     return hrn_to_urn(hrn,'node')
126     
127 def main():
128
129     config = Config()
130     if not config.SFA_REGISTRY_ENABLED:
131         sys.exit(0)
132     root_auth = config.SFA_REGISTRY_ROOT_AUTH
133     interface_hrn = config.SFA_INTERFACE_HRN
134     print interface_hrn, root_auth
135     
136      # initialize registry db table
137     #table = SfaTable()
138     #if not table.exists():
139         #table.create()
140
141     # create root authority 
142     create_top_level_auth_records(root_auth)
143     
144     # create s user record for the slice manager
145     #Do we need this?
146     #SenslabImporter.create_sm_client_record()
147     
148     # create interface records 
149     #Do we need this?
150     #SenslabImporter.logger.info("Import: creating interface records")
151     #SenslabImporter.create_interface_records()
152      # create dict of all existing sfa records
153      
154     existing_records = {}
155     existing_hrns = []
156     key_ids = []
157     person_keys = {} 
158     results = table.find()
159     for result in results:
160         existing_records[(result['hrn'], result['type'])] = result
161         existing_hrns.append(result['hrn'])   
162         
163     #Get Senslab nodes 
164    
165     Driver = SlabDriver(config)
166     nodes_dict  = Driver.GetNodes()
167     #print "\r\n NODES8DICT ",nodes_dict
168     
169     ldap_person_list = Driver.GetPersons()
170     
171
172     #slices_list = SenslabUsers.GetSlices()
173     #print "\r\n SLICES_LIST ",slices_list
174     
175         # Get all Senslab sites
176     #sites_dict  = OARImporter.GetSites()
177     #print "\r\n sSITES_DICT" , sites_dict
178     
179      # start importing 
180     #for site in sites_dict:
181         #site_hrn = interface_hrn + "." + site['login_base']
182         ##sfa_logger().info("Importing site: %s" % site_hrn)
183         #print "HRN %s %s site existing in hrn ? %s" %( site['login_base'],site_hrn, site_hrn in existing_hrns)
184         ## import if hrn is not in list of existing hrns or if the hrn exists
185         ## but its not a site record
186         #if site_hrn not in existing_hrns or \
187             #(site_hrn, 'authority') not in existing_records:
188              #print "SITE HRN UNKNOWN" , site, site_hrn
189              #site_hrn = SenslabImporter.import_site(interface_hrn, site)
190    
191         # import node records
192     for node in nodes_dict:
193         hrn =  hostname_to_hrn( root_auth, node['hostname'])
194         if hrn not in existing_hrns or \
195         (hrn, 'node') not in existing_records:
196             import_node(hrn, node)
197
198    # import persons
199     for person in ldap_person_list:
200         if person['hrn'] not in existing_hrns or \
201             (person['hrn'], 'user') not in existing_records :
202             import_person(person)
203             import_slice(person)
204
205 # import slices
206         #for slice_id in site['slice_ids']:
207                 #print >>sys.stderr, "\r\n\r\n \t ^^^^^^^\\\\\\\\\\\\\\\^^^^^^ slice_id  %s  " %(slice_id)              
208                 #for sl in slices_list:
209                         #if slice_id is sl['slice_id']:
210                                 ##hrn = slicename_to_hrn(interface_hrn, sl['name'])
211                                 #hrn = email_to_hrn(site_hrn, sl['name'])
212                                 #print >>sys.stderr, "\r\n\r\n^^^^^^^^^^^^^SLICE ID hrn %s  site_hrn %s" %(hrn,site_hrn)                                
213                                 #if hrn not in existing_hrns or \
214                                 #(hrn, 'slice') not in existing_records:
215                                         #SenslabImporter.import_slice(site_hrn, sl)     
216
217                                         
218     # remove stale records    
219     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
220
221     for (record_hrn, type) in existing_records.keys():
222         if record_hrn in system_records:
223             continue
224         
225         record = existing_records[(record_hrn, type)]
226         if record['peer_authority']:
227             continue                                    
228
229
230
231         found = False
232         
233         if type == 'authority':    
234             #for site in sites_dict:
235                 #print "\t type : authority : ", site
236                 #site_hrn = interface_hrn + "." + site['login_base']
237                 #if site_hrn == record_hrn and site['site_id'] == record['pointer']:
238             found = True
239             print "\t \t Found :", found
240             break
241                 
242         elif type == 'user':
243             for person in ldap_person_list:
244                 if person['hrn'] == record_hrn:
245                     found = True
246                     break
247             
248         elif type == 'node':
249             login_base = get_leaf(get_authority(record_hrn))
250             nodename = Xrn.unescape(get_leaf(record_hrn))
251             for node in nodes_dict:
252                 if node['hostname'] == nodename :
253                     found = True
254                     break 
255                 
256         elif type == 'slice':
257             for person in ldap_person_list:
258                 if person['hrn']+'_slice' == record_hrn:
259                     found = True
260                     break           
261         else:
262             continue 
263         
264         if not found:
265             record_object = existing_records[(record_hrn, type)]
266             print "\t\t  NOT FOUND ! ", record_hrn
267             delete_record(record_hrn, type) 
268     
269 if __name__ == "__main__":
270     main()