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