1effe7184faa3d6b5fc7e4191b542bebd3affb34
[sfa.git] / sfa / plc / 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 _SfaLogger
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.trustedroots import TrustedRoots
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        self.logger = _SfaLogger(logfile='/var/log/sfa_import.log', loggername='importlog')
56        self.AuthHierarchy = Hierarchy()
57        self.config = Config()
58        self.TrustedRoots = TrustedRoots(Config.get_trustedroots_dir(self.config))
59        self.plc_auth = self.config.get_plc_auth()
60        self.root_auth = self.config.SFA_REGISTRY_ROOT_AUTH
61         
62        # connect to planetlab
63        self.shell = None
64        if "Url" in self.plc_auth:
65           from sfa.plc.remoteshell import RemoteShell
66           self.shell = RemoteShell(self.logger)
67        else:
68           import PLC.Shell
69           self.shell = PLC.Shell.Shell(globals = globals())        
70
71     def create_top_level_auth_records(self, hrn):
72         """
73         Create top level records (includes root and sub authorities (local/remote)
74         """
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
99     def create_sm_client_record(self):
100         """
101         Create a user record for the Slicemanager service.
102         """
103         hrn = self.config.SFA_INTERFACE_HRN + '.slicemanager'
104         urn = hrn_to_urn(hrn, 'user')
105         if not self.AuthHierarchy.auth_exists(urn):
106             self.logger.info("Import: creating Slice Manager user")
107             self.AuthHierarchy.create_auth(urn)
108
109         auth_info = self.AuthHierarchy.get_auth_info(hrn)
110         table = SfaTable()
111         sm_user_record = table.find({'type': 'user', 'hrn': hrn})
112         if not sm_user_record:
113             record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="user", pointer=-1)
114             record['authority'] = get_authority(record['hrn'])
115             table.insert(record)    
116
117     def create_interface_records(self):
118         """
119         Create a record for each SFA interface
120         """
121         # just create certs for all sfa interfaces even if they
122         # arent enabled
123         interface_hrn = self.config.SFA_INTERFACE_HRN
124         interfaces = ['authority+sa', 'authority+am', 'authority+sm']
125         table = SfaTable()
126         auth_info = self.AuthHierarchy.get_auth_info(interface_hrn)
127         pkey = auth_info.get_pkey_object()
128         for interface in interfaces:
129             interface_record = table.find({'type': interface, 'hrn': interface_hrn})
130             if not interface_record:
131                 self.logger.info("Import: interface %s %s " % (interface_hrn, interface))
132                 urn = hrn_to_urn(interface_hrn, interface)
133                 gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
134                 record = SfaRecord(hrn=interface_hrn, gid=gid, type=interface, pointer=-1)  
135                 record['authority'] = get_authority(interface_hrn)
136                 table.insert(record) 
137                                 
138
139     
140     def import_person(self, parent_hrn, person):
141         """
142         Register a user record 
143         """
144         hrn = email_to_hrn(parent_hrn, person['email'])
145
146         # ASN.1 will have problems with hrn's longer than 64 characters
147         if len(hrn) > 64:
148             hrn = hrn[:64]
149
150         self.logger.info("Import: person %s"%hrn)
151         key_ids = []
152         if 'key_ids' in person and person['key_ids']:
153             key_ids = person["key_ids"]
154             # get the user's private key from the SSH keys they have uploaded
155             # to planetlab
156             keys = self.shell.GetKeys(self.plc_auth, key_ids)
157             key = keys[0]['key']
158             pkey = None
159             try:
160                 pkey = convert_public_key(key)
161             except:
162                 self.logger.warn('unable to convert public key for %s' % hrn) 
163             if not pkey:
164                 pkey = Keypair(create=True)
165         else:
166             # the user has no keys
167             self.logger.warn("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
172         # create the gid
173         urn = hrn_to_urn(hrn, 'user')
174         person_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
175         table = SfaTable()
176         person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
177         person_record['authority'] = get_authority(person_record['hrn'])
178         existing_records = table.find({'hrn': hrn, 'type': 'user', 'pointer': person['person_id']})
179         if not existing_records:
180             table.insert(person_record)
181         else:
182             self.logger.info("Import: %s exists, updating " % hrn)
183             existing_record = existing_records[0]
184             person_record['record_id'] = existing_record['record_id']
185             table.update(person_record)
186
187     def import_slice(self, parent_hrn, slice):
188         slicename = slice['name'].split("_",1)[-1]
189         slicename = _cleanup_string(slicename)
190
191         if not slicename:
192             self.logger.error("Import: failed to parse slice name %s" %slice['name'])
193             return
194
195         hrn = parent_hrn + "." + slicename
196         self.logger.info("Import: slice %s"%hrn)
197
198         pkey = Keypair(create=True)
199         urn = hrn_to_urn(hrn, 'slice')
200         slice_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
201         slice_record = SfaRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
202         slice_record['authority'] = get_authority(slice_record['hrn'])
203         table = SfaTable()
204         existing_records = table.find({'hrn': hrn, 'type': 'slice', 'pointer': slice['slice_id']})
205         if not existing_records:
206             table.insert(slice_record)
207         else:
208             self.logger.info("Import: %s exists, updating " % hrn)
209             existing_record = existing_records[0]
210             slice_record['record_id'] = existing_record['record_id']
211             table.update(slice_record)
212
213     def import_node(self, hrn, node):
214         self.logger.info("Import: node %s" % hrn)
215         # ASN.1 will have problems with hrn's longer than 64 characters
216         if len(hrn) > 64:
217             hrn = hrn[:64]
218
219         table = SfaTable()
220         node_record = table.find({'type': 'node', 'hrn': hrn})
221         pkey = Keypair(create=True)
222         urn = hrn_to_urn(hrn, 'node')
223         node_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
224         node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
225         node_record['authority'] = get_authority(node_record['hrn'])
226         existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
227         if not existing_records:
228             table.insert(node_record)
229         else:
230             self.logger.info("Import: %s exists, updating " % hrn)
231             existing_record = existing_records[0]
232             node_record['record_id'] = existing_record['record_id']
233             table.update(node_record)
234
235     
236     def import_site(self, hrn, site):
237         shell = self.shell
238         plc_auth = self.plc_auth
239         urn = hrn_to_urn(hrn, 'authority')
240         self.logger.info("Import: site %s"%hrn)
241
242         # create the authority
243         if not self.AuthHierarchy.auth_exists(urn):
244             self.AuthHierarchy.create_auth(urn)
245
246         auth_info = self.AuthHierarchy.get_auth_info(urn)
247
248         table = SfaTable()
249         auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
250         auth_record['authority'] = get_authority(auth_record['hrn'])
251         existing_records = table.find({'hrn': hrn, 'type': 'authority', 'pointer': site['site_id']})
252         if not existing_records:
253             table.insert(auth_record)
254         else:
255             self.logger.info("Import: %s exists, updating " % hrn)
256             existing_record = existing_records[0]
257             auth_record['record_id'] = existing_record['record_id']
258             table.update(auth_record)
259
260         return hrn
261
262
263     def delete_record(self, hrn, type):
264         # delete the record
265         table = SfaTable()
266         record_list = table.find({'type': type, 'hrn': hrn})
267         for record in record_list:
268             self.logger.info("Import: removing record %s %s" % (type, hrn))
269             table.remove(record)