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