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