Merge branch 'master' into senslab2
[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     def create_sm_client_record(self):
70         """
71         Create a user record for the Slicemanager service.
72         """
73         hrn = self.config.SFA_INTERFACE_HRN + '.slicemanager'
74         urn = hrn_to_urn(hrn, 'user')
75         if not self.AuthHierarchy.auth_exists(urn):
76             self.logger.info("Import: creating Slice Manager user")
77             self.AuthHierarchy.create_auth(urn)
78
79         auth_info = self.AuthHierarchy.get_auth_info(hrn)
80         table = SfaTable()
81         sm_user_record = table.find({'type': 'user', 'hrn': hrn})
82         if not sm_user_record:
83             record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="user", pointer=-1)
84             record['authority'] = get_authority(record['hrn'])
85             table.insert(record)    
86
87     def create_top_level_auth_records(self, hrn):
88         """
89         Create top level records (includes root and sub authorities (local/remote)
90         """
91         print>>sys.stderr, "\r\n =========SenslabImport create_top_level_auth_records\r\n"
92         urn = hrn_to_urn(hrn, 'authority')
93         # make sure parent exists
94         parent_hrn = get_authority(hrn)
95         if not parent_hrn:
96             parent_hrn = hrn
97         if not parent_hrn == hrn:
98             self.create_top_level_auth_records(parent_hrn)
99
100         # create the authority if it doesnt already exist 
101         if not self.AuthHierarchy.auth_exists(urn):
102             self.logger.info("Import: creating top level authorities")
103             self.AuthHierarchy.create_auth(urn)
104         
105         # create the db record if it doesnt already exist    
106         auth_info = self.AuthHierarchy.get_auth_info(hrn)
107         table = SfaTable()
108         auth_record = table.find({'type': 'authority', 'hrn': hrn})
109
110         if not auth_record:
111             auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
112             auth_record['authority'] = get_authority(auth_record['hrn'])
113             self.logger.info("Import: inserting authority record for %s"%hrn)
114             table.insert(auth_record)
115             print>>sys.stderr, "\r\n ========= \t\t SenslabImport NO AUTH RECORD \r\n" ,auth_record['authority']
116             
117             
118     def create_interface_records(self):
119         """
120         Create a record for each SFA interface
121         """
122         # just create certs for all sfa interfaces even if they
123         # arent enabled
124         interface_hrn = self.config.SFA_INTERFACE_HRN
125         interfaces = ['authority+sa', 'authority+am', 'authority+sm']
126         table = SfaTable()
127         auth_info = self.AuthHierarchy.get_auth_info(interface_hrn)
128         pkey = auth_info.get_pkey_object()
129         for interface in interfaces:
130             interface_record = table.find({'type': interface, 'hrn': interface_hrn})
131             if not interface_record:
132                 self.logger.info("Import: interface %s %s " % (interface_hrn, interface))
133                 urn = hrn_to_urn(interface_hrn, interface)
134                 gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
135                 record = SfaRecord(hrn=interface_hrn, gid=gid, type=interface, pointer=-1)  
136                 record['authority'] = get_authority(interface_hrn)
137                 print>>sys.stderr,"\r\n ==========create_interface_records", record['authority']
138                 table.insert(record) 
139
140     def import_person(self, parent_hrn, person, keys):
141         """
142         Register a user record 
143         """
144         hrn = email_to_hrn(parent_hrn, person['email'])
145
146         print >>sys.stderr , "\r\n_____00______SenslabImport : person", person  
147         # ASN.1 will have problems with hrn's longer than 64 characters
148         if len(hrn) > 64:
149             hrn = hrn[:64]
150         print >>sys.stderr , "\r\n_____0______SenslabImport : parent_hrn", parent_hrn
151         self.logger.info("Import: person %s"%hrn)
152         key_ids = []
153         # choper les cles ssh des users , sont ils dans OAR
154         if 'key_ids' in person and person['key_ids']:
155             key_ids = person["key_ids"]
156             # get the user's private key from the SSH keys they have uploaded
157             # to planetlab
158  
159             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])
160             key = keys[0]['key']
161             pkey = convert_public_key(key)
162             print >>sys.stderr , "\r\n_____2______SenslabImport : key %s pkey %s"% (key,pkey.as_pem())      
163             if not pkey:
164                 pkey = Keypair(create=True)
165         else:
166             # the user has no keys
167             self.logger.warning("Import: person %s does not have a PL public key"%hrn)
168             # if a key is unavailable, then we still need to put something in the
169             # user's GID. So make one up.
170             pkey = Keypair(create=True)
171             print >>sys.stderr , "\r\n___ELSE________SenslabImport pkey : %s"%(pkey.key)
172         # create the gid
173         urn = hrn_to_urn(hrn, 'user')
174         print >>sys.stderr , "\r\n \t\t : urn ", urn
175         person_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
176         table = SfaTable()
177         person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
178         person_record['authority'] = get_authority(person_record['hrn'])
179         existing_records = table.find({'hrn': hrn, 'type': 'user', 'pointer': person['person_id']})
180         if not existing_records:
181             table.insert(person_record)
182         else:
183             self.logger.info("Import: %s exists, updating " % hrn)
184             existing_record = existing_records[0]
185             person_record['record_id'] = existing_record['record_id']
186             table.update(person_record)
187
188     def import_slice(self, parent_hrn, slice):
189         #slicename = slice['name'].split("_",1)[-1]
190         
191         slicename = _cleanup_string(slice['name'])
192
193         if not slicename:
194             self.logger.error("Import: failed to parse slice name %s" %slice['name'])
195             return
196
197         hrn = parent_hrn + "." + slicename
198         self.logger.info("Import: slice %s"%hrn)
199
200         pkey = Keypair(create=True)
201         urn = hrn_to_urn(hrn, 'slice')
202         slice_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
203         slice_record = SfaRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
204         slice_record['authority'] = get_authority(slice_record['hrn'])
205         table = SfaTable()
206         existing_records = table.find({'hrn': hrn, 'type': 'slice', 'pointer': slice['slice_id']})
207         if not existing_records:
208             table.insert(slice_record)
209         else:
210             self.logger.info("Import: %s exists, updating " % hrn)
211             existing_record = existing_records[0]
212             slice_record['record_id'] = existing_record['record_id']
213             table.update(slice_record)
214
215     def import_node(self, hrn, node):
216         self.logger.info("Import: node %s" % hrn)
217         # ASN.1 will have problems with hrn's longer than 64 characters
218         if len(hrn) > 64:
219             hrn = hrn[:64]
220
221         table = SfaTable()
222         node_record = table.find({'type': 'node', 'hrn': hrn})
223         pkey = Keypair(create=True)
224         urn = hrn_to_urn(hrn, 'node')
225         node_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
226         node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
227         node_record['authority'] = get_authority(node_record['hrn'])
228         existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
229         if not existing_records:
230             table.insert(node_record)
231         else:
232             self.logger.info("Import: %s exists, updating " % hrn)
233             existing_record = existing_records[0]
234             node_record['record_id'] = existing_record['record_id']
235             table.update(node_record)
236
237     
238     def import_site(self, parent_hrn, site):
239         plc_auth = self.plc_auth
240         sitename = site['login_base']
241         sitename = _cleanup_string(sitename)
242         hrn = parent_hrn + "." + sitename 
243
244         urn = hrn_to_urn(hrn, 'authority')
245         self.logger.info("Import: site %s"%hrn)
246
247         # create the authority
248         if not self.AuthHierarchy.auth_exists(urn):
249             self.AuthHierarchy.create_auth(urn)
250
251         auth_info = self.AuthHierarchy.get_auth_info(urn)
252
253         table = SfaTable()
254         auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
255         auth_record['authority'] = get_authority(auth_record['hrn'])
256         existing_records = table.find({'hrn': hrn, 'type': 'authority', 'pointer': site['site_id']})
257         if not existing_records:
258             table.insert(auth_record)
259         else:
260             self.logger.info("Import: %s exists, updating " % hrn)
261             existing_record = existing_records[0]
262             auth_record['record_id'] = existing_record['record_id']
263             table.update(auth_record)
264
265         return hrn
266
267
268     def delete_record(self, hrn, type):
269         # delete the record
270         table = SfaTable()
271         record_list = table.find({'type': type, 'hrn': hrn})
272         for record in record_list:
273             self.logger.info("Import: removing record %s %s" % (type, hrn))
274             table.remove(record)