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