25c19d112f1ea949e50bd5721455142e1cb463c7
[sfa.git] / sfa / senslab / SenslabImport.py
1
2 #
3 # The import tool assumes that the existing PLC hierarchy should all be part
4 # of "planetlab.us" (see the root_auth and level1_auth variables below).
5 #
6 # Public keys are extracted from the users' SSH keys automatically and used to
7 # create GIDs. This is relatively experimental as a custom tool had to be
8 # written to perform conversion from SSH to OpenSSL format. It only supports
9 # RSA keys at this time, not DSA keys.
10 ##
11
12 import getopt
13 import sys
14 import tempfile
15 from sfa.util.sfalogging import _SfaLogger
16 #from sfa.util.sfalogging import sfa_logger_goes_to_import,sfa_logger
17
18 from sfa.util.record import *
19 from sfa.util.table import SfaTable
20 from sfa.util.xrn import get_authority, hrn_to_urn
21 from sfa.util.plxrn import email_to_hrn
22 from sfa.util.config import Config
23 from sfa.trust.certificate import convert_public_key, Keypair
24 from sfa.trust.trustedroots import *
25 from sfa.trust.hierarchy import *
26 from sfa.trust.gid import create_uuid
27
28
29
30 def _un_unicode(str):
31    if isinstance(str, unicode):
32        return str.encode("ascii", "ignore")
33    else:
34        return str
35
36 def _cleanup_string(str):
37     # pgsql has a fit with strings that have high ascii in them, so filter it
38     # out when generating the hrns.
39     tmp = ""
40     for c in str:
41         if ord(c) < 128:
42             tmp = tmp + c
43     str = tmp
44
45     str = _un_unicode(str)
46     str = str.replace(" ", "_")
47     str = str.replace(".", "_")
48     str = str.replace("(", "_")
49     str = str.replace("'", "_")
50     str = str.replace(")", "_")
51     str = str.replace('"', "_")
52     return str
53
54 class SenslabImport:
55
56     def __init__(self):
57        self.logger = _SfaLogger(logfile='/var/log/sfa_import.log', loggername='importlog')
58     
59        #sfa_logger_goes_to_import()
60        #self.logger = sfa_logger()
61        self.AuthHierarchy = Hierarchy()
62        self.config = Config()
63        self.TrustedRoots = TrustedRoots(Config.get_trustedroots_dir(self.config))
64        print>>sys.stderr, "\r\n ========= \t\t SenslabImport TrustedRoots\r\n" ,  self.TrustedRoots
65        self.plc_auth = self.config.get_plc_auth()
66        print>>sys.stderr, "\r\n ========= \t\t SenslabImport  self.plc_auth %s \r\n" %(self.plc_auth ) 
67        self.root_auth = self.config.SFA_REGISTRY_ROOT_AUTH
68
69
70     def create_top_level_auth_records(self, hrn):
71         """
72         Create top level records (includes root and sub authorities (local/remote)
73         """
74         print>>sys.stderr, "\r\n =========SenslabImport create_top_level_auth_records\r\n"
75         urn = hrn_to_urn(hrn, 'authority')
76         # make sure parent exists
77         parent_hrn = get_authority(hrn)
78         if not parent_hrn:
79             parent_hrn = hrn
80         if not parent_hrn == hrn:
81             self.create_top_level_auth_records(parent_hrn)
82
83         # create the authority if it doesnt already exist 
84         if not self.AuthHierarchy.auth_exists(urn):
85             self.logger.info("Import: creating top level authorities")
86             self.AuthHierarchy.create_auth(urn)
87         
88         # create the db record if it doesnt already exist    
89         auth_info = self.AuthHierarchy.get_auth_info(hrn)
90         table = SfaTable()
91         auth_record = table.find({'type': 'authority', 'hrn': hrn})
92
93         if not auth_record:
94             auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
95             auth_record['authority'] = get_authority(auth_record['hrn'])
96             self.logger.info("Import: inserting authority record for %s"%hrn)
97             table.insert(auth_record)
98             print>>sys.stderr, "\r\n ========= \t\t SenslabImport NO AUTH RECORD \r\n" ,auth_record['authority']
99             
100             
101     def create_interface_records(self):
102         """
103         Create a record for each SFA interface
104         """
105         # just create certs for all sfa interfaces even if they
106         # arent enabled
107         interface_hrn = self.config.SFA_INTERFACE_HRN
108         interfaces = ['authority+sa', 'authority+am', 'authority+sm']
109         table = SfaTable()
110         auth_info = self.AuthHierarchy.get_auth_info(interface_hrn)
111         pkey = auth_info.get_pkey_object()
112         for interface in interfaces:
113             interface_record = table.find({'type': interface, 'hrn': interface_hrn})
114             if not interface_record:
115                 self.logger.info("Import: interface %s %s " % (interface_hrn, interface))
116                 urn = hrn_to_urn(interface_hrn, interface)
117                 gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
118                 record = SfaRecord(hrn=interface_hrn, gid=gid, type=interface, pointer=-1)  
119                 record['authority'] = get_authority(interface_hrn)
120                 print>>sys.stderr,"\r\n ==========create_interface_records", record['authority']
121                 table.insert(record) 
122
123     def import_person(self, parent_hrn, person, keys):
124         """
125         Register a user record 
126         """
127         hrn = email_to_hrn(parent_hrn, person['email'])
128
129         print >>sys.stderr , "\r\n_____00______SenslabImport : person", person  
130         # ASN.1 will have problems with hrn's longer than 64 characters
131         if len(hrn) > 64:
132             hrn = hrn[:64]
133         print >>sys.stderr , "\r\n_____0______SenslabImport : parent_hrn", parent_hrn
134         self.logger.info("Import: person %s"%hrn)
135         key_ids = []
136         # choper les cles ssh des users , sont ils dans OAR
137         if 'key_ids' in person and person['key_ids']:
138             key_ids = person["key_ids"]
139             # get the user's private key from the SSH keys they have uploaded
140             # to planetlab
141  
142             print >>sys.stderr , "\r\n_____1______SenslabImport : self.plc_auth %s \r\n \t keys %s key[0] %s" %(self.plc_auth,keys, keys[0])
143             key = keys[0]['key']
144             pkey = convert_public_key(key)
145             print >>sys.stderr , "\r\n_____2______SenslabImport : key %s pkey %s"% (key,pkey.as_pem())      
146             if not pkey:
147                 pkey = Keypair(create=True)
148         else:
149             # the user has no keys
150             self.logger.warning("Import: person %s does not have a PL public key"%hrn)
151             # if a key is unavailable, then we still need to put something in the
152             # user's GID. So make one up.
153             pkey = Keypair(create=True)
154             print >>sys.stderr , "\r\n___ELSE________SenslabImport pkey : %s"%(pkey.key)
155         # create the gid
156         urn = hrn_to_urn(hrn, 'user')
157         print >>sys.stderr , "\r\n \t\t : urn ", urn
158         person_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
159         table = SfaTable()
160         person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
161         person_record['authority'] = get_authority(person_record['hrn'])
162         existing_records = table.find({'hrn': hrn, 'type': 'user', 'pointer': person['person_id']})
163         if not existing_records:
164             table.insert(person_record)
165         else:
166             self.logger.info("Import: %s exists, updating " % hrn)
167             existing_record = existing_records[0]
168             person_record['record_id'] = existing_record['record_id']
169             table.update(person_record)
170
171     def import_slice(self, parent_hrn, slice):
172         #slicename = slice['name'].split("_",1)[-1]
173         
174         slicename = _cleanup_string(slice['name'])
175
176         if not slicename:
177             self.logger.error("Import: failed to parse slice name %s" %slice['name'])
178             return
179
180         hrn = parent_hrn + "." + slicename
181         self.logger.info("Import: slice %s"%hrn)
182
183         pkey = Keypair(create=True)
184         urn = hrn_to_urn(hrn, 'slice')
185         slice_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
186         slice_record = SfaRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
187         slice_record['authority'] = get_authority(slice_record['hrn'])
188         table = SfaTable()
189         existing_records = table.find({'hrn': hrn, 'type': 'slice', 'pointer': slice['slice_id']})
190         if not existing_records:
191             table.insert(slice_record)
192         else:
193             self.logger.info("Import: %s exists, updating " % hrn)
194             existing_record = existing_records[0]
195             slice_record['record_id'] = existing_record['record_id']
196             table.update(slice_record)
197
198     def import_node(self, hrn, node):
199         self.logger.info("Import: node %s" % hrn)
200         # ASN.1 will have problems with hrn's longer than 64 characters
201         if len(hrn) > 64:
202             hrn = hrn[:64]
203
204         table = SfaTable()
205         node_record = table.find({'type': 'node', 'hrn': hrn})
206         pkey = Keypair(create=True)
207         urn = hrn_to_urn(hrn, 'node')
208         node_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
209         node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
210         node_record['authority'] = get_authority(node_record['hrn'])
211         existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
212         if not existing_records:
213             table.insert(node_record)
214         else:
215             self.logger.info("Import: %s exists, updating " % hrn)
216             existing_record = existing_records[0]
217             node_record['record_id'] = existing_record['record_id']
218             table.update(node_record)
219
220     
221     def import_site(self, parent_hrn, site):
222         plc_auth = self.plc_auth
223         sitename = site['login_base']
224         sitename = _cleanup_string(sitename)
225         hrn = parent_hrn + "." + sitename 
226
227         urn = hrn_to_urn(hrn, 'authority')
228         self.logger.info("Import: site %s"%hrn)
229
230         # create the authority
231         if not self.AuthHierarchy.auth_exists(urn):
232             self.AuthHierarchy.create_auth(urn)
233
234         auth_info = self.AuthHierarchy.get_auth_info(urn)
235
236         table = SfaTable()
237         auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
238         auth_record['authority'] = get_authority(auth_record['hrn'])
239         existing_records = table.find({'hrn': hrn, 'type': 'authority', 'pointer': site['site_id']})
240         if not existing_records:
241             table.insert(auth_record)
242         else:
243             self.logger.info("Import: %s exists, updating " % hrn)
244             existing_record = existing_records[0]
245             auth_record['record_id'] = existing_record['record_id']
246             table.update(auth_record)
247
248         return hrn
249
250
251     def delete_record(self, hrn, type):
252         # delete the record
253         table = SfaTable()
254         record_list = table.find({'type': type, 'hrn': hrn})
255         for record in record_list:
256             self.logger.info("Import: removing record %s %s" % (type, hrn))
257             table.remove(record)