really fixed the redundant logging issue this time.
[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 _SfaLogger
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        self.logger = _SfaLogger(logfile='/var/log/sfa_import.log', loggername='importlog')
56        self.AuthHierarchy = Hierarchy()
57        self.config = Config()
58        self.TrustedRoots = TrustedRootList(Config.get_trustedroots_dir(self.config))
59        self.plc_auth = self.config.get_plc_auth()
60        self.root_auth = self.config.SFA_REGISTRY_ROOT_AUTH
61         
62        # connect to planetlab
63        self.shell = None
64        if "Url" in self.plc_auth:
65           from sfa.plc.remoteshell import RemoteShell
66           self.shell = RemoteShell(self.logger)
67        else:
68           import PLC.Shell
69           self.shell = PLC.Shell.Shell(globals = globals())        
70
71     def create_top_level_auth_records(self, hrn):
72         """
73         Create top level records (includes root and sub authorities (local/remote)
74         """
75         urn = hrn_to_urn(hrn, 'authority')
76         # make sure parent exists
77         parent_hrn = get_authority(hrn)
78         if not parent_hrn:
79             parent_hrn = hrn
80         if not parent_hrn == hrn:
81             self.create_top_level_auth_records(parent_hrn)
82
83         # create the authority if it doesnt already exist 
84         if not self.AuthHierarchy.auth_exists(urn):
85             self.logger.info("Import: creating top level authorities")
86             self.AuthHierarchy.create_auth(urn)
87         
88         # create the db record if it doesnt already exist    
89         auth_info = self.AuthHierarchy.get_auth_info(hrn)
90         table = SfaTable()
91         auth_record = table.find({'type': 'authority', 'hrn': hrn})
92
93         if not auth_record:
94             auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
95             auth_record['authority'] = get_authority(auth_record['hrn'])
96             self.logger.info("Import: inserting authority record for %s"%hrn)
97             table.insert(auth_record)
98
99     def create_interface_records(self):
100         """
101         Create a record for each SFA interface
102         """
103         # just create certs for all sfa interfaces even if they
104         # arent enabled
105         interface_hrn = self.config.SFA_INTERFACE_HRN
106         interfaces = ['authority+sa', 'authority+am', 'authority+sm']
107         table = SfaTable()
108         auth_info = self.AuthHierarchy.get_auth_info(interface_hrn)
109         pkey = auth_info.get_pkey_object()
110         for interface in interfaces:
111             interface_record = table.find({'type': interface, 'hrn': interface_hrn})
112             if not interface_record:
113                 self.logger.info("Import: interface %s %s " % (interface_hrn, interface))
114                 urn = hrn_to_urn(interface_hrn, interface)
115                 gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
116                 record = SfaRecord(hrn=interface_hrn, gid=gid, type=interface, pointer=-1)  
117                 record['authority'] = get_authority(interface_hrn)
118                 table.insert(record) 
119
120     def import_person(self, parent_hrn, person):
121         """
122         Register a user record 
123         """
124         hrn = email_to_hrn(parent_hrn, person['email'])
125
126         # ASN.1 will have problems with hrn's longer than 64 characters
127         if len(hrn) > 64:
128             hrn = hrn[:64]
129
130         self.logger.info("Import: person %s"%hrn)
131         key_ids = []
132         if 'key_ids' in person and person['key_ids']:
133             key_ids = person["key_ids"]
134             # get the user's private key from the SSH keys they have uploaded
135             # to planetlab
136             keys = self.shell.GetKeys(self.plc_auth, key_ids)
137             key = keys[0]['key']
138             pkey = convert_public_key(key)
139             if not pkey:
140                 pkey = Keypair(create=True)
141         else:
142             # the user has no keys
143             self.logger.warning("Import: person %s does not have a PL public key"%hrn)
144             # if a key is unavailable, then we still need to put something in the
145             # user's GID. So make one up.
146             pkey = Keypair(create=True)
147
148         # create the gid
149         urn = hrn_to_urn(hrn, 'user')
150         person_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
151         table = SfaTable()
152         person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
153         person_record['authority'] = get_authority(person_record['hrn'])
154         existing_records = table.find({'hrn': hrn, 'type': 'user', 'pointer': person['person_id']})
155         if not existing_records:
156             table.insert(person_record)
157         else:
158             self.logger.info("Import: %s exists, updating " % hrn)
159             existing_record = existing_records[0]
160             person_record['record_id'] = existing_record['record_id']
161             table.update(person_record)
162
163     def import_slice(self, parent_hrn, slice):
164         slicename = slice['name'].split("_",1)[-1]
165         slicename = _cleanup_string(slicename)
166
167         if not slicename:
168             self.logger.error("Import: failed to parse slice name %s" %slice['name'])
169             return
170
171         hrn = parent_hrn + "." + slicename
172         self.logger.info("Import: slice %s"%hrn)
173
174         pkey = Keypair(create=True)
175         urn = hrn_to_urn(hrn, 'slice')
176         slice_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
177         slice_record = SfaRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
178         slice_record['authority'] = get_authority(slice_record['hrn'])
179         table = SfaTable()
180         existing_records = table.find({'hrn': hrn, 'type': 'slice', 'pointer': slice['slice_id']})
181         if not existing_records:
182             table.insert(slice_record)
183         else:
184             self.logger.info("Import: %s exists, updating " % hrn)
185             existing_record = existing_records[0]
186             slice_record['record_id'] = existing_record['record_id']
187             table.update(slice_record)
188
189     def import_node(self, hrn, node):
190         self.logger.info("Import: node %s" % hrn)
191         # ASN.1 will have problems with hrn's longer than 64 characters
192         if len(hrn) > 64:
193             hrn = hrn[:64]
194
195         table = SfaTable()
196         node_record = table.find({'type': 'node', 'hrn': hrn})
197         pkey = Keypair(create=True)
198         urn = hrn_to_urn(hrn, 'node')
199         node_gid = self.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
200         node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
201         node_record['authority'] = get_authority(node_record['hrn'])
202         existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
203         if not existing_records:
204             table.insert(node_record)
205         else:
206             self.logger.info("Import: %s exists, updating " % hrn)
207             existing_record = existing_records[0]
208             node_record['record_id'] = existing_record['record_id']
209             table.update(node_record)
210
211     
212     def import_site(self, parent_hrn, site):
213         shell = self.shell
214         plc_auth = self.plc_auth
215         sitename = site['login_base']
216         sitename = _cleanup_string(sitename)
217         hrn = parent_hrn + "." + sitename
218         # Hardcode 'internet2' into the hrn for sites hosting
219         # internet2 nodes. This is a special operation for some vini
220         # sites only
221         if ".vini" in parent_hrn and parent_hrn.endswith('vini'):
222             if sitename.startswith("i2"):
223                 #sitename = sitename.replace("ii", "")
224                 hrn = ".".join([parent_hrn, "internet2", sitename])
225             elif sitename.startswith("nlr"):
226                 #sitename = sitename.replace("nlr", "")
227                 hrn = ".".join([parent_hrn, "internet2", sitename])
228
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)