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