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