ced998084adb1cc6e5d7aba218af903c4280913f
[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         table.insert(person)
84     else:
85         existing_record = existing_records[0]
86         person['record_id'] = existing_record['record_id']
87         table.update(person)
88               
89 def init_slice_record(person):
90     slices_list = []
91     dflt_slice = { 'authority': None, 'gid': None,  'record_id':None ,'peer_authority': None, 'type':'slice','pointer':-1, 'date_created':None, 'last_updated': None}
92   
93     def_slice = {}
94     def_slice['hrn'] = person['hrn']+'_slice'
95     def_slice.update(dflt_slice)
96     return  def_slice
97         
98 def import_slice(slice_record):
99
100     pkey = Keypair(create=True)
101     urn = hrn_to_urn(slice['hrn'], 'slice')
102     slice_record['gid'] = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
103     
104     slice_record['authority'] = get_authority(slice['hrn'])
105     
106     existing_records = table.find({'hrn': hrn, 'type': 'slice'})
107     if not existing_records:
108          print>>sys.stderr, " \r\n \t slab-import : slice record %s inserted" %(slice_record['hrn'])
109         table.insert(slice_record)
110     else:
111         print>>sys.stderr, " \r\n \t slab-import : slice record %s updated" %(slice_record['hrn'])
112         existing_record = existing_records[0]
113         slice_record['record_id'] = existing_record['record_id']
114         table.update(slice_record)        
115         
116 def delete_record( hrn, type):
117     # delete the record
118     record_list = table.find({'type': type, 'hrn': hrn})
119     for record in record_list:
120         print>>sys.stderr, " \r\n \t slab-import : record %s deleted" %(record['hrn'])
121         table.remove(record)
122                 
123 def hostname_to_hrn(root_auth,hostname):
124     # keep only the first part of the DNS name
125     #hrn='.'.join( [auth,hostname.split(".")[0] ] )
126     # escape the '.' in the hostname
127     hrn='.'.join( [root_auth,Xrn.escape(hostname)] )
128     return hrn_to_urn(hrn,'node')
129     
130 def main():
131
132     config = Config()
133     if not config.SFA_REGISTRY_ENABLED:
134         sys.exit(0)
135     root_auth = config.SFA_REGISTRY_ROOT_AUTH
136     interface_hrn = config.SFA_INTERFACE_HRN
137     print interface_hrn, root_auth
138     
139      # initialize registry db table
140     #table = SfaTable()
141     #if not table.exists():
142         #table.create()
143
144     # create root authority 
145     create_top_level_auth_records(root_auth)
146     
147     # create s user record for the slice manager
148     #Do we need this?
149     #SenslabImporter.create_sm_client_record()
150     
151     # create interface records 
152     #Do we need this?
153     #SenslabImporter.logger.info("Import: creating interface records")
154     #SenslabImporter.create_interface_records()
155      # create dict of all existing sfa records
156      
157     existing_records = {}
158     existing_hrns = []
159     key_ids = []
160     person_keys = {} 
161     results = table.find()
162     for result in results:
163         existing_records[(result['hrn'], result['type'])] = result
164         existing_hrns.append(result['hrn'])   
165         
166     #Get Senslab nodes 
167    
168     Driver = SlabDriver(config)
169     nodes_dict  = Driver.GetNodes()
170     #print "\r\n NODES8DICT ",nodes_dict
171     
172     ldap_person_list = Driver.GetPersons()
173     
174
175     #slices_list = SenslabUsers.GetSlices()
176     #print "\r\n SLICES_LIST ",slices_list
177     
178         # Get all Senslab sites
179     #sites_dict  = OARImporter.GetSites()
180     #print "\r\n sSITES_DICT" , sites_dict
181     
182      # start importing 
183     #for site in sites_dict:
184         #site_hrn = interface_hrn + "." + site['login_base']
185         ##sfa_logger().info("Importing site: %s" % site_hrn)
186         #print "HRN %s %s site existing in hrn ? %s" %( site['login_base'],site_hrn, site_hrn in existing_hrns)
187         ## import if hrn is not in list of existing hrns or if the hrn exists
188         ## but its not a site record
189         #if site_hrn not in existing_hrns or \
190             #(site_hrn, 'authority') not in existing_records:
191              #print "SITE HRN UNKNOWN" , site, site_hrn
192              #site_hrn = SenslabImporter.import_site(interface_hrn, site)
193    
194         # import node records
195     for node in nodes_dict:
196         hrn =  hostname_to_hrn( root_auth, node['hostname'])
197         if hrn not in existing_hrns or \
198         (hrn, 'node') not in existing_records:
199             import_node(hrn, node)
200
201    # import persons
202     for person in ldap_person_list:
203         if person['hrn'] not in existing_hrns or \
204             (person['hrn'], 'user') not in existing_records :
205             import_person( person)
206             init_slice_record(person)
207         
208     
209     
210 # import slices
211         #for slice_id in site['slice_ids']:
212                 #print >>sys.stderr, "\r\n\r\n \t ^^^^^^^\\\\\\\\\\\\\\\^^^^^^ slice_id  %s  " %(slice_id)              
213                 #for sl in slices_list:
214                         #if slice_id is sl['slice_id']:
215                                 ##hrn = slicename_to_hrn(interface_hrn, sl['name'])
216                                 #hrn = email_to_hrn(site_hrn, sl['name'])
217                                 #print >>sys.stderr, "\r\n\r\n^^^^^^^^^^^^^SLICE ID hrn %s  site_hrn %s" %(hrn,site_hrn)                                
218                                 #if hrn not in existing_hrns or \
219                                 #(hrn, 'slice') not in existing_records:
220                                         #SenslabImporter.import_slice(site_hrn, sl)     
221
222                                         
223     # remove stale records    
224     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
225
226     for (record_hrn, type) in existing_records.keys():
227         if record_hrn in system_records:
228             continue
229         
230         record = existing_records[(record_hrn, type)]
231         if record['peer_authority']:
232             continue                                    
233
234
235
236         found = False
237         
238         if type == 'authority':    
239             #for site in sites_dict:
240                 #print "\t type : authority : ", site
241                 #site_hrn = interface_hrn + "." + site['login_base']
242                 #if site_hrn == record_hrn and site['site_id'] == record['pointer']:
243             found = True
244             print "\t \t Found :", found
245             break
246                 
247         elif type == 'user':
248             for person in ldap_person_list:
249                 if person['hrn'] == record_hrn:
250                     found = True
251                     break
252             
253         elif type == 'node':
254             login_base = get_leaf(get_authority(record_hrn))
255             nodename = Xrn.unescape(get_leaf(record_hrn))
256             for node in nodes_dict:
257                 if node['hostname'] == nodename :
258                     found = True
259                     break 
260                 
261         elif type == 'slice':
262             for person in ldap_person_list:
263                 if person['hrn']+'_slice' == record_hrn:
264                     found = True
265                     break           
266         else:
267             continue 
268         
269         if not found:
270             record_object = existing_records[(record_hrn, type)]
271             print "\t\t  NOT FOUND ! ", record_hrn
272             delete_record(record_hrn, type) 
273     
274 if __name__ == "__main__":
275     main()