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