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