fix name error
[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         interface_hrn = self.config.SFA_INTERFACE_HRN
68         self.create_top_level_auth_records(interface_hrn)
69
70         # create s user record for the slice manager
71         self.create_sm_client_record()
72
73         # create interface records
74         self.logger.info("Import: creating interface records")
75         self.create_interface_records()
76
77         # add local root authority's cert  to trusted list
78         self.logger.info("Import: adding " + interface_hrn + " to trusted list")
79         authority = self.AuthHierarchy.get_auth_info(interface_hrn)
80         self.TrustedRoots.add_gid(authority.get_gid_object())
81
82     def create_top_level_auth_records(self, hrn):
83         """
84         Create top level db records (includes root and sub authorities (local/remote)
85         """
86         # make sure parent exists
87         parent_hrn = get_authority(hrn)
88         if not parent_hrn:
89             parent_hrn = hrn
90         if not parent_hrn == hrn:
91             self.create_top_level_auth_records(parent_hrn)
92
93         # enxure key and cert exists:
94         self.AuthHierarchy.create_top_level_auth(hrn)    
95         # create the db record if it doesnt already exist    
96         auth_info = self.AuthHierarchy.get_auth_info(hrn)
97         table = SfaTable()
98         auth_record = table.find({'type': 'authority', 'hrn': hrn})
99
100         if not auth_record:
101             auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
102             auth_record['authority'] = get_authority(auth_record['hrn'])
103             self.logger.info("Import: inserting authority record for %s"%hrn)
104             table.insert(auth_record)
105
106     def create_sm_client_record(self):
107         """
108         Create a user record for the Slicemanager service.
109         """
110         hrn = self.config.SFA_INTERFACE_HRN + '.slicemanager'
111         urn = hrn_to_urn(hrn, 'user')
112         if not self.AuthHierarchy.auth_exists(urn):
113             self.logger.info("Import: creating Slice Manager user")
114             self.AuthHierarchy.create_auth(urn)
115
116         auth_info = self.AuthHierarchy.get_auth_info(hrn)
117         table = SfaTable()
118         sm_user_record = table.find({'type': 'user', 'hrn': hrn})
119         if not sm_user_record:
120             record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="user", pointer=-1)
121             record['authority'] = get_authority(record['hrn'])
122             table.insert(record)    
123
124     def create_interface_records(self):
125         """
126         Create a record for each SFA interface
127         """
128         # just create certs for all sfa interfaces even if they
129         # arent enabled
130         interface_hrn = self.config.SFA_INTERFACE_HRN
131         interfaces = ['authority+sa', 'authority+am', 'authority+sm']
132         table = SfaTable()
133         auth_info = self.AuthHierarchy.get_auth_info(interface_hrn)
134         pkey = auth_info.get_pkey_object()
135         for interface in interfaces:
136             interface_record = table.find({'type': interface, 'hrn': interface_hrn})
137             if not interface_record:
138                 self.logger.info("Import: interface %s %s " % (interface_hrn, interface))
139                 urn = hrn_to_urn(interface_hrn, interface)
140                 gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
141                 record = SfaRecord(hrn=interface_hrn, gid=gid, type=interface, pointer=-1)  
142                 record['authority'] = get_authority(interface_hrn)
143                 table.insert(record) 
144                                 
145     def import_person(self, parent_hrn, person):
146         """
147         Register a user record 
148         """
149         hrn = email_to_hrn(parent_hrn, person['email'])
150
151         # ASN.1 will have problems with hrn's longer than 64 characters
152         if len(hrn) > 64:
153             hrn = hrn[:64]
154
155         self.logger.info("Import: person %s"%hrn)
156         key_ids = []
157         if 'key_ids' in person and person['key_ids']:
158             key_ids = person["key_ids"]
159             # get the user's private key from the SSH keys they have uploaded
160             # to planetlab
161             keys = self.shell.GetKeys(key_ids)
162             key = keys[0]['key']
163             pkey = None
164             try:
165                 pkey = convert_public_key(key)
166             except:
167                 self.logger.warn('unable to convert public key for %s' % hrn) 
168             if not pkey:
169                 pkey = Keypair(create=True)
170         else:
171             # the user has no keys
172             self.logger.warn("Import: person %s does not have a PL public key"%hrn)
173             # if a key is unavailable, then we still need to put something in the
174             # user's GID. So make one up.
175             pkey = Keypair(create=True)
176
177         # create the gid
178         urn = hrn_to_urn(hrn, 'user')
179         person_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
180         table = SfaTable()
181         person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
182         person_record['authority'] = get_authority(person_record['hrn'])
183         existing_records = table.find({'hrn': hrn, 'type': 'user', 'pointer': person['person_id']})
184         if not existing_records:
185             table.insert(person_record)
186         else:
187             self.logger.info("Import: %s exists, updating " % hrn)
188             existing_record = existing_records[0]
189             person_record['record_id'] = existing_record['record_id']
190             table.update(person_record)
191
192     def import_slice(self, parent_hrn, slice):
193         slicename = slice['name'].split("_",1)[-1]
194         slicename = _cleanup_string(slicename)
195
196         if not slicename:
197             self.logger.error("Import: failed to parse slice name %s" %slice['name'])
198             return
199
200         hrn = parent_hrn + "." + slicename
201         self.logger.info("Import: slice %s"%hrn)
202
203         pkey = Keypair(create=True)
204         urn = hrn_to_urn(hrn, 'slice')
205         slice_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
206         slice_record = SfaRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
207         slice_record['authority'] = get_authority(slice_record['hrn'])
208         table = SfaTable()
209         existing_records = table.find({'hrn': hrn, 'type': 'slice', 'pointer': slice['slice_id']})
210         if not existing_records:
211             table.insert(slice_record)
212         else:
213             self.logger.info("Import: %s exists, updating " % hrn)
214             existing_record = existing_records[0]
215             slice_record['record_id'] = existing_record['record_id']
216             table.update(slice_record)
217
218     def import_node(self, hrn, node):
219         self.logger.info("Import: node %s" % hrn)
220         # ASN.1 will have problems with hrn's longer than 64 characters
221         if len(hrn) > 64:
222             hrn = hrn[:64]
223
224         table = SfaTable()
225         node_record = table.find({'type': 'node', 'hrn': hrn})
226         pkey = Keypair(create=True)
227         urn = hrn_to_urn(hrn, 'node')
228         node_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
229         node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
230         node_record['authority'] = get_authority(node_record['hrn'])
231         existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
232         if not existing_records:
233             table.insert(node_record)
234         else:
235             self.logger.info("Import: %s exists, updating " % hrn)
236             existing_record = existing_records[0]
237             node_record['record_id'] = existing_record['record_id']
238             table.update(node_record)
239
240     
241     def import_site(self, hrn, site):
242         urn = hrn_to_urn(hrn, 'authority')
243         self.logger.info("Import: site %s"%hrn)
244
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)