9a5113e2f92a6b9de0c5b2c7b1ae419d7b9f4832
[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.record import *
16 from sfa.util.table import SfaTable
17 from sfa.util.namespace import *
18 from sfa.util.config import Config
19 from sfa.util.report import trace, error
20 from sfa.trust.certificate import convert_public_key, Keypair
21 from sfa.trust.trustedroot import *
22 from sfa.trust.hierarchy import *
23 from sfa.trust.gid import create_uuid
24
25
26 def un_unicode(str):
27    if isinstance(str, unicode):
28        return str.encode("ascii", "ignore")
29    else:
30        return str
31
32 def cleanup_string(str):
33     # pgsql has a fit with strings that have high ascii in them, so filter it
34     # out when generating the hrns.
35     tmp = ""
36     for c in str:
37         if ord(c) < 128:
38             tmp = tmp + c
39     str = tmp
40
41     str = un_unicode(str)
42     str = str.replace(" ", "_")
43     str = str.replace(".", "_")
44     str = str.replace("(", "_")
45     str = str.replace("'", "_")
46     str = str.replace(")", "_")
47     str = str.replace('"', "_")
48     return str
49
50 class sfaImport:
51
52     def __init__(self, logger=None):
53         self.logger = logger
54         self.AuthHierarchy = Hierarchy()
55         self.config = Config()
56         self.TrustedRoots = TrustedRootList(Config.get_trustedroots_dir(self.config))
57         self.plc_auth = self.config.get_plc_auth()
58         self.root_auth = self.config.SFA_REGISTRY_ROOT_AUTH
59         
60         # connect to planetlab
61         self.shell = None
62         if "Url" in self.plc_auth:
63             from sfa.plc.remoteshell import RemoteShell
64             self.shell = RemoteShell()
65         else:
66             import PLC.Shell
67             self.shell = PLC.Shell.Shell(globals = globals())        
68
69
70     def create_top_level_auth_records(self, hrn):
71         AuthHierarchy = self.AuthHierarchy
72         urn = hrn_to_urn(hrn, 'authority')
73         # make sure parent exists
74         parent_hrn = get_authority(hrn)
75         if not parent_hrn:
76             parent_hrn = hrn
77         if not parent_hrn == hrn:
78             self.create_top_level_auth_records(parent_hrn)
79
80         # create the authority if it doesnt already exist 
81         if not AuthHierarchy.auth_exists(urn):
82             trace("Import: creating top level authorites", self.logger)
83             AuthHierarchy.create_auth(urn)
84         
85         # create the db record if it doesnt already exist    
86         auth_info = AuthHierarchy.get_auth_info(hrn)
87         table = SfaTable()
88         auth_record = table.find({'type': 'authority', 'hrn': hrn})
89
90         if not auth_record:
91             auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
92             auth_record['authority'] = get_authority(auth_record['hrn'])
93             trace("Import: inserting authority record for " + hrn, self.logger)
94             table.insert(auth_record)
95
96
97     def import_person(self, parent_hrn, person):
98         AuthHierarchy = self.AuthHierarchy
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         trace("Import: importing person " + hrn, self.logger)
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             trace("   person " + hrn + " does not have a PL public key", self.logger)
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 = 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             trace("Import: %s exists, updating " % hrn, self.logger)
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         AuthHierarchy = self.AuthHierarchy
140         slicename = slice['name'].split("_",1)[-1]
141         slicename = cleanup_string(slicename)
142
143         if not slicename:
144             error("Import_Slice: failed to parse slice name " + slice['name'], self.logger)
145             return
146
147         hrn = parent_hrn + "." + slicename
148         trace("Import: importing slice " + hrn, self.logger)
149
150         pkey = Keypair(create=True)
151         urn = hrn_to_urn(hrn, 'slice')
152         slice_gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
153         slice_record = SfaRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
154         slice_record['authority'] = get_authority(slice_record['hrn'])
155         table = SfaTable()
156         existing_records = table.find({'hrn': hrn, 'type': 'slice', 'pointer': slice['slice_id']})
157         if not existing_records:
158             table.insert(slice_record)
159         else:
160             trace("Import: %s exists, updating " % hrn, self.logger)
161             existing_record = existing_records[0]
162             slice_record['record_id'] = existing_record['record_id']
163             table.update(slice_record)
164
165     def import_node(self, parent_hrn, node):
166         AuthHierarchy = self.AuthHierarchy
167         nodename = node['hostname'].split(".")[0]
168         nodename = cleanup_string(nodename)
169         
170         if not nodename:
171             error("Import_node: failed to parse node name " + node['hostname'], self.logger)
172             return
173
174         hrn = parent_hrn + "." + nodename
175         trace("Import: importing node " + hrn, self.logger)
176         # ASN.1 will have problems with hrn's longer than 64 characters
177         if len(hrn) > 64:
178             hrn = hrn[:64]
179
180         table = SfaTable()
181         node_record = table.find({'type': 'node', 'hrn': hrn})
182         pkey = Keypair(create=True)
183         urn = hrn_to_urn(hrn, 'node')
184         node_gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
185         node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
186         node_record['authority'] = get_authority(node_record['hrn'])
187         existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
188         if not existing_records:
189             table.insert(node_record)
190         else:
191             trace("Import: %s exists, updating " % hrn, self.logger)
192             existing_record = existing_records[0]
193             node_record['record_id'] = existing_record['record_id']
194             table.update(node_record)
195
196     
197     def import_site(self, parent_hrn, site):
198         AuthHierarchy = self.AuthHierarchy
199         shell = self.shell
200         plc_auth = self.plc_auth
201         sitename = site['login_base']
202         sitename = cleanup_string(sitename)
203         hrn = parent_hrn + "." + sitename
204         urn = hrn_to_urn(hrn, 'authority')
205         # Hardcode 'internet2' into the hrn for sites hosting
206         # internet2 nodes. This is a special operation for some vini
207         # sites only
208         if ".vini" in parent_hrn and parent_hrn.endswith('vini'):
209             if sitename.startswith("i2"):
210                 #sitename = sitename.replace("ii", "")
211                 hrn = ".".join([parent_hrn, "internet2", sitename])
212             elif sitename.startswith("nlr"):
213                 #sitename = sitename.replace("nlr", "")
214                 hrn = ".".join([parent_hrn, "internet2", sitename])
215
216         trace("Import: importing site " + hrn, self.logger)
217
218         # create the authority
219         if not AuthHierarchy.auth_exists(urn):
220             AuthHierarchy.create_auth(urn)
221
222         auth_info = AuthHierarchy.get_auth_info(urn)
223
224         table = SfaTable()
225         auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
226         auth_record['authority'] = get_authority(auth_record['hrn'])
227         existing_records = table.find({'hrn': hrn, 'type': 'authority', 'pointer': site['site_id']})
228         if not existing_records:
229             table.insert(auth_record)
230         else:
231             trace("Import: %s exists, updating " % hrn, self.logger)
232             existing_record = existing_records[0]
233             auth_record['record_id'] = existing_record['record_id']
234             table.update(auth_record)
235
236         return hrn
237
238
239     def delete_record(self, hrn, type):
240         # delete the record
241         table = SfaTable()
242         record_list = table.find({'type': type, 'hrn': hrn})
243         for record in record_list:
244             trace("Import: Removing record %s %s" % (type, hrn), self.logger)
245             table.remove(record)