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