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