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