44a2e8c2a9526b27f33e0365113e23fbae6ac8be
[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
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         table.insert(auth_record)
53         print>>sys.stderr, "\r\n ========= \t\t SenslabImport NO AUTH RECORD \r\n" ,auth_record['authority']
54         
55     
56 def import_node(hrn, node):
57
58     # ASN.1 will have problems with hrn's longer than 64 characters
59     if len(hrn) > 64:
60         hrn = hrn[:64]
61
62     node_record = table.find({'type': 'node', 'hrn': hrn})
63     pkey = Keypair(create=True)
64     urn = hrn_to_urn(hrn, 'node')
65     node_gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
66     node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
67     node_record['authority'] = get_authority(node_record['hrn'])
68     existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
69     if not existing_records:
70         table.insert(node_record)
71     else:
72         existing_record = existing_records[0]
73         node_record['record_id'] = existing_record['record_id']
74         table.update(node_record)
75
76 # person is already a sfa record 
77 def import_person(person):       
78     existing_records = table.find({'hrn': person['hrn'], 'type': 'user'})
79     if not existing_records:
80         table.insert(person)
81     else:
82         existing_record = existing_records[0]
83         person['record_id'] = existing_record['record_id']
84         table.update(person)      
85         
86         
87         
88 def delete_record( hrn, type):
89     # delete the record
90     record_list = table.find({'type': type, 'hrn': hrn})
91     for record in record_list:
92         table.remove(record)
93                 
94 def hostname_to_hrn(root_auth,hostname):
95     # keep only the first part of the DNS name
96     #hrn='.'.join( [auth,hostname.split(".")[0] ] )
97     # escape the '.' in the hostname
98     hrn='.'.join( [root_auth,Xrn.escape(hostname)] )
99     return hrn_to_urn(hrn,'node')
100     
101 def main():
102
103     config = Config()
104     if not config.SFA_REGISTRY_ENABLED:
105         sys.exit(0)
106     root_auth = config.SFA_REGISTRY_ROOT_AUTH
107     interface_hrn = config.SFA_INTERFACE_HRN
108     print interface_hrn, root_auth
109     
110      # initialize registry db table
111     #table = SfaTable()
112     #if not table.exists():
113         #table.create()
114
115     # create root authority 
116     create_top_level_auth_records(root_auth)
117     
118     # create s user record for the slice manager
119     #Do we need this?
120     #SenslabImporter.create_sm_client_record()
121     
122     # create interface records 
123     #Do we need this?
124     #SenslabImporter.logger.info("Import: creating interface records")
125     #SenslabImporter.create_interface_records()
126      # create dict of all existing sfa records
127      
128     existing_records = {}
129     existing_hrns = []
130     key_ids = []
131     person_keys = {} 
132     results = table.find()
133     for result in results:
134         existing_records[(result['hrn'], result['type'])] = result
135         existing_hrns.append(result['hrn'])   
136         
137     #Get Senslab nodes 
138    
139     Driver = SlabDriver(config)
140     nodes_dict  = Driver.GetNodes()
141     #print "\r\n NODES8DICT ",nodes_dict
142     
143     ldap_person_list = Driver.GetPersons()
144     print "\r\n PERSONS_LIST ",ldap_person_list
145
146    
147     
148     #slices_list = SenslabUsers.GetSlices()
149     #print "\r\n SLICES_LIST ",slices_list
150     
151         # Get all Senslab sites
152     #sites_dict  = OARImporter.GetSites()
153     #print "\r\n sSITES_DICT" , sites_dict
154     
155      # start importing 
156     #for site in sites_dict:
157         #site_hrn = interface_hrn + "." + site['login_base']
158         ##sfa_logger().info("Importing site: %s" % site_hrn)
159         #print "HRN %s %s site existing in hrn ? %s" %( site['login_base'],site_hrn, site_hrn in existing_hrns)
160         ## import if hrn is not in list of existing hrns or if the hrn exists
161         ## but its not a site record
162         #if site_hrn not in existing_hrns or \
163             #(site_hrn, 'authority') not in existing_records:
164              #print "SITE HRN UNKNOWN" , site, site_hrn
165              #site_hrn = SenslabImporter.import_site(interface_hrn, site)
166    
167         # import node records
168         #for node_id in site['node_ids']:
169                 #for[node['node_id'] for node in nodes_dict]:
170                         #print '\r\n \t **NODE_ID %s node %s '%( node_id, node)         
171                         #continue 
172     for node in nodes_dict:
173         hrn =  hostname_to_hrn( root_auth, node['hostname'])
174         if hrn not in existing_hrns or \
175         (hrn, 'node') not in existing_records:
176             print "\t\t NODE HRN NOT in existing record, importing it" ,hrn
177             import_node(hrn, node)
178
179    # import persons
180     for person in ldap_person_list:
181         if person['hrn'] not in existing_hrns or \
182             (person['hrn'], 'user') not in existing_records :
183             import_person( person)      
184 # import slices
185         #for slice_id in site['slice_ids']:
186                 #print >>sys.stderr, "\r\n\r\n \t ^^^^^^^\\\\\\\\\\\\\\\^^^^^^ slice_id  %s  " %(slice_id)              
187                 #for sl in slices_list:
188                         #if slice_id is sl['slice_id']:
189                                 ##hrn = slicename_to_hrn(interface_hrn, sl['name'])
190                                 #hrn = email_to_hrn(site_hrn, sl['name'])
191                                 #print >>sys.stderr, "\r\n\r\n^^^^^^^^^^^^^SLICE ID hrn %s  site_hrn %s" %(hrn,site_hrn)                                
192                                 #if hrn not in existing_hrns or \
193                                 #(hrn, 'slice') not in existing_records:
194                                         #SenslabImporter.import_slice(site_hrn, sl)     
195
196                                         
197     # remove stale records    
198     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
199     for (record_hrn, type) in existing_records.keys():
200         if record_hrn in system_records:
201             continue
202         
203         record = existing_records[(record_hrn, type)]
204         if record['peer_authority']:
205             continue                                    
206
207
208
209         found = False
210         
211         if type == 'authority':    
212             #for site in sites_dict:
213                 #print "\t type : authority : ", site
214                 #site_hrn = interface_hrn + "." + site['login_base']
215                 #if site_hrn == record_hrn and site['site_id'] == record['pointer']:
216             found = True
217             print "\t \t Found :", found
218             break
219                 
220         elif type == 'user':
221             for person in persons:
222                 if person['hrn'] == record_hrn:
223                     found = True
224                 break
225             
226         elif type == 'node':
227             login_base = get_leaf(get_authority(record_hrn))
228             nodename = Xrn.unescape(get_leaf(record_hrn))
229             print "type: node :  nodename %s" %(nodename)
230             for node in nodes_dict.values():
231                 if node['hostname'] == nodename :
232                     found = True
233                     break 
234                     
235         else:
236             continue 
237         
238         if not found:
239             record_object = existing_records[(record_hrn, type)]
240             print "\t\t NOT FOUND ! "
241             delete_record(record_hrn, type) 
242     
243 if __name__ == "__main__":
244     main()