8bcf4205e7c4fd3960bcad1e0576f84094a0f300
[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         self.level1_auth = self.config.SFA_REGISTRY_LEVEL1_AUTH
60         if not self.level1_auth or self.level1_auth in ['']:
61             self.level1_auth = None
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()
68         else:
69             import PLC.Shell
70             self.shell = PLC.Shell.Shell(globals = globals())        
71
72
73     def create_top_level_auth_records(self, hrn):
74         AuthHierarchy = self.AuthHierarchy
75         urn = hrn_to_urn(hrn, 'authority')
76         # if auth records for this hrn dont exist, create it
77         if not AuthHierarchy.auth_exists(urn):
78             trace("Import: creating top level authorites", self.logger)
79             AuthHierarchy.create_auth(urn)
80         
81
82         # get the auth info of the newly created root auth (parent)
83         # or level1_auth if it exists
84         if self.level1_auth:
85             auth_info = AuthHierarchy.get_auth_info(hrn)
86             parent_hrn = hrn
87         else:
88             parent_hrn = get_authority(hrn)
89             if not parent_hrn:
90                 parent_hrn = hrn
91             auth_info = AuthHierarchy.get_auth_info(parent_hrn)
92             
93         table = SfaTable()
94         auth_record = table.find({'type': 'authority', 'hrn': hrn})
95
96         if not auth_record:
97             auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=-1)
98             auth_record['authority'] = get_authority(auth_record['hrn'])
99             trace("Import: inserting authority record for " + hrn, self.logger)
100             table.insert(auth_record)
101
102
103     def import_person(self, parent_hrn, person):
104         AuthHierarchy = self.AuthHierarchy
105         hrn = email_to_hrn(parent_hrn, person['email'])
106
107         # ASN.1 will have problems with hrn's longer than 64 characters
108         if len(hrn) > 64:
109             hrn = hrn[:64]
110
111         trace("Import: importing person " + hrn, self.logger)
112         key_ids = []
113         if 'key_ids' in person and person['key_ids']:
114             key_ids = person["key_ids"]
115             # get the user's private key from the SSH keys they have uploaded
116             # to planetlab
117             keys = self.shell.GetKeys(self.plc_auth, key_ids)
118             key = keys[0]['key']
119             pkey = convert_public_key(key)
120             if not pkey:
121                 pkey = Keypair(create=True)
122         else:
123             # the user has no keys
124             trace("   person " + hrn + " does not have a PL public key", self.logger)
125             # if a key is unavailable, then we still need to put something in the
126             # user's GID. So make one up.
127             pkey = Keypair(create=True)
128
129         # create the gid
130         urn = hrn_to_urn(hrn, 'user')
131         person_gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
132         table = SfaTable()
133         person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", pointer=person['person_id'])
134         person_record['authority'] = get_authority(person_record['hrn'])
135         existing_records = table.find({'hrn': hrn, 'type': 'user', 'pointer': person['person_id']})
136         if not existing_records:
137             table.insert(person_record)
138         else:
139             trace("Import: %s exists, updating " % hrn, self.logger)
140             existing_record = existing_records[0]
141             person_record['record_id'] = existing_record['record_id']
142             table.update(person_record)
143
144     def import_slice(self, parent_hrn, slice):
145         AuthHierarchy = self.AuthHierarchy
146         slicename = slice['name'].split("_",1)[-1]
147         slicename = cleanup_string(slicename)
148
149         if not slicename:
150             error("Import_Slice: failed to parse slice name " + slice['name'], self.logger)
151             return
152
153         hrn = parent_hrn + "." + slicename
154         trace("Import: importing slice " + hrn, self.logger)
155
156         pkey = Keypair(create=True)
157         urn = hrn_to_urn(hrn, 'slice')
158         slice_gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
159         slice_record = SfaRecord(hrn=hrn, gid=slice_gid, type="slice", pointer=slice['slice_id'])
160         slice_record['authority'] = get_authority(slice_record['hrn'])
161         table = SfaTable()
162         existing_records = table.find({'hrn': hrn, 'type': 'slice', 'pointer': slice['slice_id']})
163         if not existing_records:
164             table.insert(slice_record)
165         else:
166             trace("Import: %s exists, updating " % hrn, self.logger)
167             existing_record = existing_records[0]
168             slice_record['record_id'] = existing_record['record_id']
169             table.update(slice_record)
170
171     def import_node(self, parent_hrn, node):
172         AuthHierarchy = self.AuthHierarchy
173         nodename = node['hostname'].split(".")[0]
174         nodename = cleanup_string(nodename)
175         
176         if not nodename:
177             error("Import_node: failed to parse node name " + node['hostname'], self.logger)
178             return
179
180         hrn = parent_hrn + "." + nodename
181         trace("Import: importing node " + hrn, self.logger)
182         # ASN.1 will have problems with hrn's longer than 64 characters
183         if len(hrn) > 64:
184             hrn = hrn[:64]
185
186         table = SfaTable()
187         node_record = table.find({'type': 'node', 'hrn': hrn})
188         pkey = Keypair(create=True)
189         urn = hrn_to_urn(hrn, 'node')
190         node_gid = AuthHierarchy.create_gid(urn, create_uuid(), pkey)
191         node_record = SfaRecord(hrn=hrn, gid=node_gid, type="node", pointer=node['node_id'])
192         node_record['authority'] = get_authority(node_record['hrn'])
193         existing_records = table.find({'hrn': hrn, 'type': 'node', 'pointer': node['node_id']})
194         if not existing_records:
195             table.insert(node_record)
196         else:
197             trace("Import: %s exists, updating " % hrn, self.logger)
198             existing_record = existing_records[0]
199             node_record['record_id'] = existing_record['record_id']
200             table.update(node_record)
201
202     
203     def import_site(self, parent_hrn, site):
204         AuthHierarchy = self.AuthHierarchy
205         shell = self.shell
206         plc_auth = self.plc_auth
207         sitename = site['login_base']
208         sitename = cleanup_string(sitename)
209         hrn = parent_hrn + "." + sitename
210         urn = hrn_to_urn(hrn, 'authority')
211         # Hardcode 'internet2' into the hrn for sites hosting
212         # internet2 nodes. This is a special operation for some vini
213         # sites only
214         if ".vini" in parent_hrn and parent_hrn.endswith('vini'):
215             if sitename.startswith("i2"):
216                 #sitename = sitename.replace("ii", "")
217                 hrn = ".".join([parent_hrn, "internet2", sitename])
218             elif sitename.startswith("nlr"):
219                 #sitename = sitename.replace("nlr", "")
220                 hrn = ".".join([parent_hrn, "internet2", sitename])
221
222         trace("Import: importing site " + hrn, self.logger)
223
224         # create the authority
225         if not AuthHierarchy.auth_exists(urn):
226             AuthHierarchy.create_auth(urn)
227
228         auth_info = AuthHierarchy.get_auth_info(urn)
229
230         table = SfaTable()
231         auth_record = SfaRecord(hrn=hrn, gid=auth_info.get_gid_object(), type="authority", pointer=site['site_id'])
232         auth_record['authority'] = get_authority(auth_record['hrn'])
233         existing_records = table.find({'hrn': hrn, 'type': 'authority', 'pointer': site['site_id']})
234         if not existing_records:
235             table.insert(auth_record)
236         else:
237             trace("Import: %s exists, updating " % hrn, self.logger)
238             existing_record = existing_records[0]
239             auth_record['record_id'] = existing_record['record_id']
240             table.update(auth_record)
241
242         return hrn
243
244
245     def delete_record(self, hrn, type):
246         # delete the record
247         table = SfaTable()
248         record_list = table.find({'type': type, 'hrn': hrn})
249         for record in record_list:
250             trace("Import: Removing record %s %s" % (type, hrn), self.logger)
251             table.remove(record)