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