Added file slab-import : script to import LDAP users and OAR ressources to sfa table.
[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     SenslabImporter.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     nodes_dict  = OARImporter.GetNodes()
126     print "\r\n NODES8DICT ",nodes_dict
127     
128     persons_list = SenslabUsers.GetPersons()
129     print "\r\n PERSONS_LIST ",persons_list
130
131     keys_list = SenslabUsers.GetKeys()
132     print "\r\n KEYSS_LIST ",keys_list
133     
134     #slices_list = SenslabUsers.GetSlices()
135     #print "\r\n SLICES_LIST ",slices_list
136     
137         # Get all Senslab sites
138     #sites_dict  = OARImporter.GetSites()
139     #print "\r\n sSITES_DICT" , sites_dict
140     
141      # start importing 
142     #for site in sites_dict:
143         #site_hrn = interface_hrn + "." + site['login_base']
144         ##sfa_logger().info("Importing site: %s" % site_hrn)
145         #print "HRN %s %s site existing in hrn ? %s" %( site['login_base'],site_hrn, site_hrn in existing_hrns)
146         ## import if hrn is not in list of existing hrns or if the hrn exists
147         ## but its not a site record
148         #if site_hrn not in existing_hrns or \
149             #(site_hrn, 'authority') not in existing_records:
150              #print "SITE HRN UNKNOWN" , site, site_hrn
151              #site_hrn = SenslabImporter.import_site(interface_hrn, site)
152              
153     print "\r\n \r\n ===========IMPORT NODE_RECORDS ==========\r\n site %s \r\n \t nodes_dict %s" %(site,nodes_dict)             
154         # import node records
155         #for node_id in site['node_ids']:
156                 #for[node['node_id'] for node in nodes_dict]:
157                         #print '\r\n \t **NODE_ID %s node %s '%( node_id, node)         
158                         #continue 
159     for node in nodes_dict:
160         #if node_id is node['node_id']: 
161                 #node = nodes_dict[node_id]
162         print '\r\n \t NODE_ID %s node %s '%( node_id, node)
163         hrn =  hostname_to_hrn(interface_hrn, root_auth, node['hostname'])
164         break   
165
166     if hrn not in existing_hrns or \
167     (hrn, 'node') not in existing_records:
168         print "\t\t NODE HRN NOT in existing records!" ,hrn
169         import_node(hrn, node)
170
171    # import persons
172     for person in persons_list:
173         print >>sys.stderr, "\r\n\r\n^^^^^^^^^^^^^PERSON hrn %s person %s site hrn %s" %(hrn,person)    
174         SenslabImporter.import_person( site_hrn, person,keys_list)
175         if hrn not in existing_hrns or \
176             (hrn, 'user') not in existing_records or update_record:
177             import_person(site_hrn, person)     
178 # import slices
179         #for slice_id in site['slice_ids']:
180                 #print >>sys.stderr, "\r\n\r\n \t ^^^^^^^\\\\\\\\\\\\\\\^^^^^^ slice_id  %s  " %(slice_id)              
181                 #for sl in slices_list:
182                         #if slice_id is sl['slice_id']:
183                                 ##hrn = slicename_to_hrn(interface_hrn, sl['name'])
184                                 #hrn = email_to_hrn(site_hrn, sl['name'])
185                                 #print >>sys.stderr, "\r\n\r\n^^^^^^^^^^^^^SLICE ID hrn %s  site_hrn %s" %(hrn,site_hrn)                                
186                                 #if hrn not in existing_hrns or \
187                                 #(hrn, 'slice') not in existing_records:
188                                         #SenslabImporter.import_slice(site_hrn, sl)     
189
190                                         
191     # remove stale records    
192     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
193     for (record_hrn, type) in existing_records.keys():
194         if record_hrn in system_records:
195             continue
196         
197         record = existing_records[(record_hrn, type)]
198         if record['peer_authority']:
199             continue                                    
200
201
202
203         found = False
204         
205         if type == 'authority':    
206             #for site in sites_dict:
207                 #print "\t type : authority : ", site
208                 #site_hrn = interface_hrn + "." + site['login_base']
209                 #if site_hrn == record_hrn and site['site_id'] == record['pointer']:
210             found = True
211             print "\t \t Found :", found
212             break
213                 
214         elif type == 'user':
215             for person in persons:
216                 if person['hrn'] == record_hrn:
217                     found = True
218                 break
219             
220         elif type == 'node':
221             login_base = get_leaf(get_authority(record_hrn))
222             nodename = Xrn.unescape(get_leaf(record_hrn))
223             print "type: node :  nodename %s" %(nodename)
224             for node in nodes_dict.values():
225                 if node['hostname'] == nodename :
226                     found = True
227                     break 
228                     
229         else:
230             continue 
231         
232         if not found:
233             record_object = existing_records[(record_hrn, type)]
234             print "\t\t NOT FOUND ! "
235             delete_record(record_hrn, type) 
236     
237 if __name__ == "__main__":
238     main()