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