move generic code from sfa.importer.sfa-import-plc sfa.importer.sfaImport
[sfa.git] / sfa / importer / 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 from sfa.util.sfalogging import _SfaLogger
12 from sfa.util.xrn import get_authority, hrn_to_urn
13 from sfa.util.plxrn import email_to_hrn
14 from sfa.util.config import Config
15 from sfa.trust.certificate import convert_public_key, Keypair
16 from sfa.trust.trustedroots import TrustedRoots
17 from sfa.trust.hierarchy import Hierarchy
18 from sfa.trust.gid import create_uuid
19 from sfa.storage.table import SfaTable
20 from sfa.storage.record import SfaRecord
21 from sfa.storage.table import SfaTable
22
23
24 def _un_unicode(str):
25    if isinstance(str, unicode):
26        return str.encode("ascii", "ignore")
27    else:
28        return str
29
30 def _cleanup_string(str):
31     # pgsql has a fit with strings that have high ascii in them, so filter it
32     # out when generating the hrns.
33     tmp = ""
34     for c in str:
35         if ord(c) < 128:
36             tmp = tmp + c
37     str = tmp
38
39     str = _un_unicode(str)
40     str = str.replace(" ", "_")
41     str = str.replace(".", "_")
42     str = str.replace("(", "_")
43     str = str.replace("'", "_")
44     str = str.replace(")", "_")
45     str = str.replace('"', "_")
46     return str
47
48 class sfaImport:
49
50     def __init__(self):
51        self.logger = _SfaLogger(logfile='/var/log/sfa_import.log', loggername='importlog')
52        self.AuthHierarchy = Hierarchy()
53        self.table = SfaTable()     
54        self.config = Config()
55        self.TrustedRoots = TrustedRoots(Config.get_trustedroots_dir(self.config))
56        self.root_auth = self.config.SFA_REGISTRY_ROOT_AUTH
57        # should use a driver instead...
58        from sfa.plc.plshell import PlShell
59        # how to connect to planetlab 
60        self.shell = PlShell (self.config)
61
62     def create_top_level_records(self):
63         """
64         Create top level and interface records
65         """
66         # create root authority
67         self.create_top_level_auth_records(interface_hrn)
68
69         # create s user record for the slice manager
70         self.create_sm_client_record()
71
72         # create interface records
73         self.logger.info("Import: creating interface records")
74         self.create_interface_records()
75
76         # add local root authority's cert  to trusted list
77         self.logger.info("Import: adding " + interface_hrn + " to trusted list")
78         authority = sfaImporter.AuthHierarchy.get_auth_info(interface_hrn)
79         self.TrustedRoots.add_gid(authority.get_gid_object())
80
81     def create_top_level_auth_records(self, hrn):
82         """
83         Create top level db records (includes root and sub authorities (local/remote)
84         """
85         # make sure parent exists
86         parent_hrn = get_authority(hrn)
87         if not parent_hrn:
88             parent_hrn = hrn
89         if not parent_hrn == hrn:
90             self.create_top_level_auth_records(parent_hrn)
91
92         # enxure key and cert exists:
93         self.AuthHierarchy.create_top_level_auth(hrn)    
94         # create the db record if it doesnt already exist    
95         auth_info = self.AuthHierarchy.get_auth_info(hrn)
96         table = SfaTable()
97         auth_record = table.find({'type': 'authority', 'hrn': hrn})
98
99         if not auth_record:
100             auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
101             auth_record['authority'] = get_authority(auth_record['hrn'])
102             self.logger.info("Import: inserting authority record for %s"%hrn)
103             table.insert(auth_record)
104
105     def create_sm_client_record(self):
106         """
107         Create a user record for the Slicemanager service.
108         """
109         hrn = self.config.SFA_INTERFACE_HRN + '.slicemanager'
110         urn = hrn_to_urn(hrn, 'user')
111         if not self.AuthHierarchy.auth_exists(urn):
112             self.logger.info("Import: creating Slice Manager user")
113             self.AuthHierarchy.create_auth(urn)
114
115         auth_info = self.AuthHierarchy.get_auth_info(hrn)
116         table = SfaTable()
117         sm_user_record = table.find({'type': 'user', 'hrn': hrn})
118         if not sm_user_record:
119             record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="user", pointer=-1)
120             record['authority'] = get_authority(record['hrn'])
121             table.insert(record)    
122
123     def create_interface_records(self):
124         """
125         Create a record for each SFA interface
126         """
127         # just create certs for all sfa interfaces even if they
128         # arent enabled
129         interface_hrn = self.config.SFA_INTERFACE_HRN
130         interfaces = ['authority+sa', 'authority+am', 'authority+sm']
131         table = SfaTable()
132         auth_info = self.AuthHierarchy.get_auth_info(interface_hrn)
133         pkey = auth_info.get_pkey_object()
134         for interface in interfaces:
135             interface_record = table.find({'type': interface, 'hrn': interface_hrn})
136             if not interface_record:
137                 self.logger.info("Import: interface %s %s " % (interface_hrn, interface))
138                 urn = hrn_to_urn(interface_hrn, interface)
139                 gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
140                 record = SfaRecord(hrn=interface_hrn, gid=gid, type=interface, pointer=-1)  
141                 record['authority'] = get_authority(interface_hrn)
142                 table.insert(record) 
143                                 
144     def import_person(self, parent_hrn, person):
145         """
146         Register a user record 
147         """
148         hrn = email_to_hrn(parent_hrn, person['email'])
149
150         # ASN.1 will have problems with hrn's longer than 64 characters
151         if len(hrn) > 64:
152             hrn = hrn[:64]
153
154         self.logger.info("Import: person %s"%hrn)
155         key_ids = []
156         if 'key_ids' in person and person['key_ids']:
157             key_ids = person["key_ids"]
158             # get the user's private key from the SSH keys they have uploaded
159             # to planetlab
160             keys = self.shell.GetKeys(key_ids)
161             key = keys[0]['key']
162             pkey = None
163             try:
164                 pkey = convert_public_key(key)
165             except:
166                 self.logger.warn('unable to convert public key for %s' % hrn) 
167             if not pkey:
168                 pkey = Keypair(create=True)
169         else:
170             # the user has no keys
171             self.logger.warn("Import: person %s does not have a PL public key"%hrn)
172             # if a key is unavailable, then we still need to put something in the
173             # user's GID. So make one up.
174             pkey = Keypair(create=True)
175
176         # create the gid
177         urn = hrn_to_urn(hrn, 'user')
178         person_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
179         table = SfaTable()
180         person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
181         person_record['authority'] = get_authority(person_record['hrn'])
182         existing_records = table.find({'hrn': hrn, 'type': 'user', 'pointer': person['person_id']})
183         if not existing_records:
184             table.insert(person_record)
185         else:
186             self.logger.info("Import: %s exists, updating " % hrn)
187             existing_record = existing_records[0]
188             person_record['record_id'] = existing_record['record_id']
189             table.update(person_record)
190
191     def import_slice(self, parent_hrn, slice):
192         slicename = slice['name'].split("_",1)[-1]
193         slicename = _cleanup_string(slicename)
194
195         if not slicename:
196             self.logger.error("Import: failed to parse slice name %s" %slice['name'])
197             return
198
199         hrn = parent_hrn + "." + slicename
200         self.logger.info("Import: slice %s"%hrn)
201
202         pkey = Keypair(create=True)
203         urn = hrn_to_urn(hrn, 'slice')
204         slice_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
205         slice_record = SfaRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
206         slice_record['authority'] = get_authority(slice_record['hrn'])
207         table = SfaTable()
208         existing_records = table.find({'hrn': hrn, 'type': 'slice', 'pointer': slice['slice_id']})
209         if not existing_records:
210             table.insert(slice_record)
211         else:
212             self.logger.info("Import: %s exists, updating " % hrn)
213             existing_record = existing_records[0]
214             slice_record['record_id'] = existing_record['record_id']
215             table.update(slice_record)
216
217     def import_node(self, hrn, node):
218         self.logger.info("Import: node %s" % hrn)
219         # ASN.1 will have problems with hrn's longer than 64 characters
220         if len(hrn) > 64:
221             hrn = hrn[:64]
222
223         table = SfaTable()
224         node_record = table.find({'type': 'node', 'hrn': hrn})
225         pkey = Keypair(create=True)
226         urn = hrn_to_urn(hrn, 'node')
227         node_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
228         node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
229         node_record['authority'] = get_authority(node_record['hrn'])
230         existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
231         if not existing_records:
232             table.insert(node_record)
233         else:
234             self.logger.info("Import: %s exists, updating " % hrn)
235             existing_record = existing_records[0]
236             node_record['record_id'] = existing_record['record_id']
237             table.update(node_record)
238
239     
240     def import_site(self, hrn, site):
241         urn = hrn_to_urn(hrn, 'authority')
242         self.logger.info("Import: site %s"%hrn)
243
244         # create the authority
245         if not self.AuthHierarchy.auth_exists(urn):
246             self.AuthHierarchy.create_auth(urn)
247
248         auth_info = self.AuthHierarchy.get_auth_info(urn)
249
250         table = SfaTable()
251         auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
252         auth_record['authority'] = get_authority(auth_record['hrn'])
253         existing_records = table.find({'hrn': hrn, 'type': 'authority', 'pointer': site['site_id']})
254         if not existing_records:
255             table.insert(auth_record)
256         else:
257             self.logger.info("Import: %s exists, updating " % hrn)
258             existing_record = existing_records[0]
259             auth_record['record_id'] = existing_record['record_id']
260             table.update(auth_record)
261
262         return hrn
263
264
265     def delete_record(self, hrn, type):
266         # delete the record
267         table = SfaTable()
268         record_list = table.find({'type': type, 'hrn': hrn})
269         for record in record_list:
270             self.logger.info("Import: removing record %s %s" % (type, hrn))
271             table.remove(record)