6d7bb6ddece6bb93e1b9c6c2f2a9a8347aaaac06
[sfa.git] / sfa / managers / registry_manager.py
1 import types
2 # for get_key_from_incoming_ip
3 import tempfile
4 import os
5 import commands
6
7 from sfa.util.faults import RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority, \
8     UnknownSfaType, ExistingRecord, NonExistingRecord
9 from sfa.util.sfatime import utcparse, datetime_to_epoch
10 from sfa.util.prefixTree import prefixTree
11 from sfa.util.xrn import Xrn, get_authority, hrn_to_urn, urn_to_hrn
12 from sfa.util.version import version_core
13 from sfa.util.sfalogging import logger
14
15 from sfa.util.printable import printable
16
17 from sfa.trust.gid import GID 
18 from sfa.trust.credential import Credential
19 from sfa.trust.certificate import Certificate, Keypair, convert_public_key
20 from sfa.trust.gid import create_uuid
21
22 from sfa.storage.model import make_record, RegRecord, RegAuthority, RegUser, RegSlice, RegKey, \
23     augment_with_sfa_builtins
24 ### the types that we need to exclude from sqlobjects before being able to dump
25 # them on the xmlrpc wire
26 from sqlalchemy.orm.collections import InstrumentedList
27
28 ### historical note -- april 2014
29 # the myslice chaps rightfully complained about the following discrepancy
30 # they found that
31 # * read operations (resolve) expose stuff like e.g. 
32 #   'reg-researchers', or 'reg-pis', but that
33 # * write operations (register, update) need e.g. 
34 #   'researcher' or 'pi' to be set - reg-* are just ignored
35 #
36 # the '_normalize_input' helper functions below aim at ironing this out
37 # however in order to break as few code as possible we essentially make sure that *both* fields are set
38 # upon entering the write methods (so again register and update) for legacy, as some driver code
39 # might depend on the presence of, say, 'researcher'
40
41 # normalize an input record to a write method - register or update
42 # e.g. registry calls this 'reg-researchers'
43 # while some drivers call this 'researcher'
44 # we need to make sure that both keys appear and are the same
45 def _normalize_input (record, reg_key, driver_key):
46     # this looks right, use this for both keys
47     if reg_key in record:
48         # and issue a warning if they were both set and different
49         # as we're overwriting some user data here
50         if driver_key in record:
51             logger.warning ("normalize_input: incoming record has both values, using %s"%reg_key)
52         record[driver_key]=record[reg_key]
53     # we only have one key set, duplicate for the other one
54     elif driver_key in record:
55         logger.warning ("normalize_input: you should use '%s' instead of '%s'"%(reg_key,driver_key))
56         record[reg_key]=record[driver_key]
57
58 def normalize_input_record (record):
59     _normalize_input (record, 'reg-researchers','researcher')
60     _normalize_input (record, 'reg-pis','pi')
61     _normalize_input (record, 'reg-keys','keys')
62     # xxx the keys thing could use a little bit more attention:
63     # some parts of the code are using 'keys' while they should use 'reg-keys' 
64     # but I run out of time for now
65     if 'reg-keys' in record: record['keys']=record['reg-keys']
66     return record
67
68 class RegistryManager:
69
70     def __init__ (self, config): 
71         logger.info("Creating RegistryManager[%s]"%id(self))
72
73     # The GENI GetVersion call
74     def GetVersion(self, api, options):
75         peers = dict ( [ (hrn,interface.get_url()) for (hrn,interface) in api.registries.iteritems() 
76                        if hrn != api.hrn])
77         xrn=Xrn(api.hrn,type='authority')
78         return version_core({'interface':'registry',
79                              'sfa': 3,
80                              'hrn':xrn.get_hrn(),
81                              'urn':xrn.get_urn(),
82                              'peers':peers})
83     
84     def GetCredential(self, api, xrn, input_type, caller_xrn=None):
85         # convert xrn to hrn     
86         if input_type:
87             hrn, _ = urn_to_hrn(xrn)
88             type = input_type
89         else:
90             hrn, type = urn_to_hrn(xrn)
91
92         # Slivers don't have credentials but users should be able to 
93         # specify a sliver xrn and receive the slice's credential
94         # However if input_type is specified
95         if type == 'sliver' or ( not input_type and '-' in Xrn(hrn).leaf):
96             slice_xrn = api.driver.sliver_to_slice_xrn(hrn)
97             hrn = slice_xrn.hrn 
98   
99         # Is this a root or sub authority
100         auth_hrn = api.auth.get_authority(hrn)
101         if not auth_hrn or hrn == api.config.SFA_INTERFACE_HRN:
102             auth_hrn = hrn
103         auth_info = api.auth.get_auth_info(auth_hrn)
104
105         # get record info
106         dbsession = api.dbsession()
107         record=dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
108         if not record:
109             raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
110
111         # get the callers gid
112         # if caller_xrn is not specified assume the caller is the record
113         # object itself.
114         if not caller_xrn:
115             caller_hrn = hrn
116             caller_gid = record.get_gid_object()
117         else:
118             caller_hrn, caller_type = urn_to_hrn(caller_xrn)
119             if caller_type:
120                 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn,type=caller_type).first()
121             else:
122                 caller_record = dbsession.query(RegRecord).filter_by(hrn=caller_hrn).first()
123             if not caller_record:
124                 raise RecordNotFound("Unable to associated caller (hrn=%s, type=%s) with credential for (hrn: %s, type: %s)"%(caller_hrn, caller_type, hrn, type))
125             caller_gid = GID(string=caller_record.gid)
126  
127         object_hrn = record.get_gid_object().get_hrn()
128         # call the builtin authorization/credential generation engine
129         rights = api.auth.determine_user_rights(caller_hrn, record)
130         # make sure caller has rights to this object
131         if rights.is_empty():
132             raise PermissionError("%s has no rights to %s (%s)" % \
133                                   (caller_hrn, object_hrn, xrn))    
134         object_gid = GID(string=record.gid)
135         new_cred = Credential(subject = object_gid.get_subject())
136         new_cred.set_gid_caller(caller_gid)
137         new_cred.set_gid_object(object_gid)
138         new_cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
139         #new_cred.set_pubkey(object_gid.get_pubkey())
140         new_cred.set_privileges(rights)
141         new_cred.get_privileges().delegate_all_privileges(True)
142         if hasattr(record,'expires'):
143             date = utcparse(record.expires)
144             expires = datetime_to_epoch(date)
145             new_cred.set_expiration(int(expires))
146         auth_kind = "authority,ma,sa"
147         # Parent not necessary, verify with certs
148         #new_cred.set_parent(api.auth.hierarchy.get_auth_cred(auth_hrn, kind=auth_kind))
149         new_cred.encode()
150         new_cred.sign()
151     
152         return new_cred.save_to_string(save_parents=True)
153     
154     
155     # the default for full, which means 'dig into the testbed as well', should be false
156     def Resolve(self, api, xrns, type=None, details=False):
157     
158         dbsession = api.dbsession()
159         if not isinstance(xrns, types.ListType):
160             # try to infer type if not set and we get a single input
161             if not type:
162                 type = Xrn(xrns).get_type()
163             xrns = [xrns]
164         hrns = [urn_to_hrn(xrn)[0] for xrn in xrns] 
165
166         # load all known registry names into a prefix tree and attempt to find
167         # the longest matching prefix
168         # create a dict where key is a registry hrn and its value is a list
169         # of hrns at that registry (determined by the known prefix tree).  
170         xrn_dict = {}
171         registries = api.registries
172         tree = prefixTree()
173         registry_hrns = registries.keys()
174         tree.load(registry_hrns)
175         for xrn in xrns:
176             registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
177             if registry_hrn not in xrn_dict:
178                 xrn_dict[registry_hrn] = []
179             xrn_dict[registry_hrn].append(xrn)
180             
181         records = [] 
182         for registry_hrn in xrn_dict:
183             # skip the hrn without a registry hrn
184             # XX should we let the user know the authority is unknown?       
185             if not registry_hrn:
186                 continue
187     
188             # if the best match (longest matching hrn) is not the local registry,
189             # forward the request
190             xrns = xrn_dict[registry_hrn]
191             if registry_hrn != api.hrn:
192                 credential = api.getCredential()
193                 interface = api.registries[registry_hrn]
194                 server_proxy = api.server_proxy(interface, credential)
195                 # should propagate the details flag but that's not supported in the xmlrpc interface yet
196                 #peer_records = server_proxy.Resolve(xrns, credential,type, details=details)
197                 peer_records = server_proxy.Resolve(xrns, credential)
198                 # pass foreign records as-is
199                 # previous code used to read
200                 # records.extend([SfaRecord(dict=record).as_dict() for record in peer_records])
201                 # not sure why the records coming through xmlrpc had to be processed at all
202                 records.extend(peer_records)
203     
204         # try resolving the remaining unfound records at the local registry
205         local_hrns = list ( set(hrns).difference([record['hrn'] for record in records]) )
206         # 
207         local_records = dbsession.query(RegRecord).filter(RegRecord.hrn.in_(local_hrns))
208         if type:
209             local_records = local_records.filter_by(type=type)
210         local_records=local_records.all()
211         
212         for local_record in local_records:
213             augment_with_sfa_builtins (local_record)
214
215         logger.info("Resolve, (details=%s,type=%s) local_records=%s "%(details,type,local_records))
216         local_dicts = [ record.__dict__ for record in local_records ]
217         
218         if details:
219             # in details mode we get as much info as we can, which involves contacting the 
220             # testbed for getting implementation details about the record
221             api.driver.augment_records_with_testbed_info(local_dicts)
222             # also we fill the 'url' field for known authorities
223             # used to be in the driver code, sounds like a poorman thing though
224             def solve_neighbour_url (record):
225                 if not record.type.startswith('authority'): return 
226                 hrn=record.hrn
227                 for neighbour_dict in [ api.aggregates, api.registries ]:
228                     if hrn in neighbour_dict:
229                         record.url=neighbour_dict[hrn].get_url()
230                         return 
231             for record in local_records: solve_neighbour_url (record)
232         
233         # convert local record objects to dicts for xmlrpc
234         # xxx somehow here calling dict(record) issues a weird error
235         # however record.todict() seems to work fine
236         # records.extend( [ dict(record) for record in local_records ] )
237         records.extend( [ record.todict(exclude_types=[InstrumentedList]) for record in local_records ] )
238
239         if not records:
240             raise RecordNotFound(str(hrns))
241     
242         return records
243     
244     def List (self, api, xrn, origin_hrn=None, options=None):
245         if options is None: options={}
246         dbsession=api.dbsession()
247         # load all know registry names into a prefix tree and attempt to find
248         # the longest matching prefix
249         hrn, type = urn_to_hrn(xrn)
250         registries = api.registries
251         registry_hrns = registries.keys()
252         tree = prefixTree()
253         tree.load(registry_hrns)
254         registry_hrn = tree.best_match(hrn)
255        
256         #if there was no match then this record belongs to an unknow registry
257         if not registry_hrn:
258             raise MissingAuthority(xrn)
259         # if the best match (longest matching hrn) is not the local registry,
260         # forward the request
261         record_dicts = []    
262         if registry_hrn != api.hrn:
263             credential = api.getCredential()
264             interface = api.registries[registry_hrn]
265             server_proxy = api.server_proxy(interface, credential)
266             record_list = server_proxy.List(xrn, credential, options)
267             # same as above, no need to process what comes from through xmlrpc
268             # pass foreign records as-is
269             record_dicts = record_list
270         
271         # if we still have not found the record yet, try the local registry
272 #        logger.debug("before trying local records, %d foreign records"% len(record_dicts))
273         if not record_dicts:
274             recursive = False
275             if ('recursive' in options and options['recursive']):
276                 recursive = True
277             elif hrn.endswith('*'):
278                 hrn = hrn[:-1]
279                 recursive = True
280
281             if not api.auth.hierarchy.auth_exists(hrn):
282                 raise MissingAuthority(hrn)
283             if recursive:
284                 records = dbsession.query(RegRecord).filter(RegRecord.hrn.startswith(hrn)).all()
285 #                logger.debug("recursive mode, found %d local records"%(len(records)))
286             else:
287                 records = dbsession.query(RegRecord).filter_by(authority=hrn).all()
288 #                logger.debug("non recursive mode, found %d local records"%(len(records)))
289             # so that sfi list can show more than plain names...
290             for record in records: augment_with_sfa_builtins (record)
291             record_dicts=[ record.todict(exclude_types=[InstrumentedList]) for record in records ]
292     
293         return record_dicts
294     
295     
296     def CreateGid(self, api, xrn, cert):
297         # get the authority
298         authority = Xrn(xrn=xrn).get_authority_hrn()
299         auth_info = api.auth.get_auth_info(authority)
300         if not cert:
301             pkey = Keypair(create=True)
302         else:
303             certificate = Certificate(string=cert)
304             pkey = certificate.get_pubkey()    
305         gid = api.auth.hierarchy.create_gid(xrn, create_uuid(), pkey) 
306         return gid.save_to_string(save_parents=True)
307     
308     ####################
309     # utility for handling relationships among the SFA objects 
310     
311     # subject_record describes the subject of the relationships
312     # ref_record contains the target values for the various relationships we need to manage
313     # (to begin with, this is just the slice x person (researcher) and authority x person (pi) relationships)
314     def update_driver_relations (self, api, subject_obj, ref_obj):
315         type=subject_obj.type
316         #for (k,v) in subject_obj.__dict__.items(): print k,'=',v
317         if type=='slice' and hasattr(ref_obj,'researcher'):
318             self.update_driver_relation(api, subject_obj, ref_obj.researcher, 'user', 'researcher')
319         elif type=='authority' and hasattr(ref_obj,'pi'):
320             self.update_driver_relation(api, subject_obj,ref_obj.pi, 'user', 'pi')
321         
322     # field_key is the name of one field in the record, typically 'researcher' for a 'slice' record
323     # hrns is the list of hrns that should be linked to the subject from now on
324     # target_type would be e.g. 'user' in the 'slice' x 'researcher' example
325     def update_driver_relation (self, api, record_obj, hrns, target_type, relation_name):
326         dbsession=api.dbsession()
327         # locate the linked objects in our db
328         subject_type=record_obj.type
329         subject_id=record_obj.pointer
330         # get the 'pointer' field of all matching records
331         link_id_tuples = dbsession.query(RegRecord.pointer).filter_by(type=target_type).filter(RegRecord.hrn.in_(hrns)).all()
332         # sqlalchemy returns named tuples for columns
333         link_ids = [ tuple.pointer for tuple in link_id_tuples ]
334         api.driver.update_relation (subject_type, target_type, relation_name, subject_id, link_ids)
335
336     def Register(self, api, record_dict):
337     
338         logger.debug("Register: entering with record_dict=%s"%printable(record_dict))
339         normalize_input_record (record_dict)
340         logger.debug("Register: normalized record_dict=%s"%printable(record_dict))
341
342         dbsession=api.dbsession()
343         hrn, type = record_dict['hrn'], record_dict['type']
344         urn = hrn_to_urn(hrn,type)
345         # validate the type
346         if type not in ['authority', 'slice', 'node', 'user']:
347             raise UnknownSfaType(type) 
348         
349         # check if record_dict already exists
350         existing_records = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).all()
351         if existing_records:
352             raise ExistingRecord(hrn)
353            
354         assert ('type' in record_dict)
355         # returns the right type of RegRecord according to type in record
356         record = make_record(dict=record_dict)
357         record.just_created()
358         record.authority = get_authority(record.hrn)
359         auth_info = api.auth.get_auth_info(record.authority)
360         pub_key = None
361         # make sure record has a gid
362         if not record.gid:
363             uuid = create_uuid()
364             pkey = Keypair(create=True)
365             pub_key=getattr(record,'reg-keys',None)
366             if pub_key is not None:
367                 # use only first key in record
368                 if pub_key and isinstance(pub_key, types.ListType): pub_key = pub_key[0]
369                 pkey = convert_public_key(pub_key)
370     
371             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
372             gid = gid_object.save_to_string(save_parents=True)
373             record.gid = gid
374     
375         if isinstance (record, RegAuthority):
376             # update the tree
377             if not api.auth.hierarchy.auth_exists(hrn):
378                 api.auth.hierarchy.create_auth(hrn_to_urn(hrn,'authority'))
379     
380             # get the GID from the newly created authority
381             auth_info = api.auth.get_auth_info(hrn)
382             gid = auth_info.get_gid_object()
383             record.gid=gid.save_to_string(save_parents=True)
384
385             # locate objects for relationships
386             pi_hrns = getattr(record,'reg-pis',None)
387             if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
388
389         elif isinstance (record, RegSlice):
390             researcher_hrns = getattr(record,'reg-researchers',None)
391             if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
392         
393         elif isinstance (record, RegUser):
394             # create RegKey objects for incoming keys
395             if hasattr(record,'reg-keys'):
396                 keys=getattr(record,'reg-keys')
397                 # some people send the key as a string instead of a list of strings
398                 if isinstance(keys,types.StringTypes): keys=[keys]
399                 logger.debug ("creating %d keys for user %s"%(len(keys),record.hrn))
400                 record.reg_keys = [ RegKey (key) for key in keys ]
401             
402         # update testbed-specific data if needed
403         pointer = api.driver.register (record.__dict__, hrn, pub_key)
404
405         record.pointer=pointer
406         dbsession.add(record)
407         dbsession.commit()
408     
409         # update membership for researchers, pis, owners, operators
410         self.update_driver_relations (api, record, record)
411         
412         return record.get_gid_object().save_to_string(save_parents=True)
413     
414     def Update(self, api, record_dict):
415
416         logger.debug("Update: entering with record_dict=%s"%printable(record_dict))
417         normalize_input_record (record_dict)
418         logger.debug("Update: normalized record_dict=%s"%printable(record_dict))
419
420         dbsession=api.dbsession()
421         assert ('type' in record_dict)
422         new_record=make_record(dict=record_dict)
423         (type,hrn) = (new_record.type, new_record.hrn)
424         
425         # make sure the record exists
426         record = dbsession.query(RegRecord).filter_by(type=type,hrn=hrn).first()
427         if not record:
428             raise RecordNotFound("hrn=%s, type=%s"%(hrn,type))
429         record.just_updated()
430     
431         # Use the pointer from the existing record, not the one that the user
432         # gave us. This prevents the user from inserting a forged pointer
433         pointer = record.pointer
434     
435         # is there a change in keys ?
436         new_key=None
437         if type=='user':
438             if getattr(new_record,'keys',None):
439                 new_key=new_record.keys
440                 if isinstance (new_key,types.ListType):
441                     new_key=new_key[0]
442
443         # take new_key into account
444         if new_key:
445             # update the openssl key and gid
446             pkey = convert_public_key(new_key)
447             uuid = create_uuid()
448             urn = hrn_to_urn(hrn,type)
449             gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
450             gid = gid_object.save_to_string(save_parents=True)
451         
452         # xxx should do side effects from new_record to record
453         # not too sure how to do that
454         # not too big a deal with planetlab as the driver is authoritative, but...
455
456         # update native relations
457         if isinstance (record, RegSlice):
458             researcher_hrns = getattr(new_record,'reg-researchers',None)
459             if researcher_hrns is not None: record.update_researchers (researcher_hrns, dbsession)
460
461         elif isinstance (record, RegAuthority):
462             pi_hrns = getattr(new_record,'reg-pis',None)
463             if pi_hrns is not None: record.update_pis (pi_hrns, dbsession)
464         
465         # update the PLC information that was specified with the record
466         # xxx oddly enough, without this useless statement, 
467         # record.__dict__ as received by the driver seems to be off
468         # anyway the driver should receive an object 
469         # (and then extract __dict__ itself if needed)
470         print "DO NOT REMOVE ME before driver.update, record=%s"%record
471         new_key_pointer = -1
472         try:
473            (pointer, new_key_pointer) = api.driver.update (record.__dict__, new_record.__dict__, hrn, new_key)
474         except:
475            pass
476         if new_key and new_key_pointer:
477             record.reg_keys=[ RegKey (new_key, new_key_pointer)]
478             record.gid = gid
479
480         dbsession.commit()
481         # update membership for researchers, pis, owners, operators
482         self.update_driver_relations (api, record, new_record)
483         
484         return 1 
485     
486     # expecting an Xrn instance
487     def Remove(self, api, xrn, origin_hrn=None):
488         dbsession=api.dbsession()
489         hrn=xrn.get_hrn()
490         type=xrn.get_type()
491         request=dbsession.query(RegRecord).filter_by(hrn=hrn)
492         if type and type not in ['all', '*']:
493             request=request.filter_by(type=type)
494     
495         record = request.first()
496         if not record:
497             msg="Could not find hrn %s"%hrn
498             if type: msg += " type=%s"%type
499             raise RecordNotFound(msg)
500
501         type = record.type
502         if type not in ['slice', 'user', 'node', 'authority'] :
503             raise UnknownSfaType(type)
504
505         credential = api.getCredential()
506         registries = api.registries
507     
508         # Try to remove the object from the PLCDB of federated agg.
509         # This is attempted before removing the object from the local agg's PLCDB and sfa table
510         if hrn.startswith(api.hrn) and type in ['user', 'slice', 'authority']:
511             for registry in registries:
512                 if registry not in [api.hrn]:
513                     try:
514                         result=registries[registry].remove_peer_object(credential, record, origin_hrn)
515                     except:
516                         pass
517
518         # call testbed callback first
519         # IIUC this is done on the local testbed TOO because of the refreshpeer link
520         if not api.driver.remove(record.__dict__):
521             logger.warning("driver.remove failed")
522
523         # delete from sfa db
524         dbsession.delete(record)
525         dbsession.commit()
526     
527         return 1
528
529     # This is a PLC-specific thing, won't work with other platforms
530     def get_key_from_incoming_ip (self, api):
531         dbsession=api.dbsession()
532         # verify that the callers's ip address exist in the db and is an interface
533         # for a node in the db
534         (ip, port) = api.remote_addr
535         interfaces = api.driver.shell.GetInterfaces({'ip': ip}, ['node_id'])
536         if not interfaces:
537             raise NonExistingRecord("no such ip %(ip)s" % locals())
538         nodes = api.driver.shell.GetNodes([interfaces[0]['node_id']], ['node_id', 'hostname'])
539         if not nodes:
540             raise NonExistingRecord("no such node using ip %(ip)s" % locals())
541         node = nodes[0]
542        
543         # look up the sfa record
544         record=dbsession.query(RegRecord).filter_by(type='node',pointer=node['node_id']).first()
545         if not record:
546             raise RecordNotFound("node with pointer %s"%node['node_id'])
547         
548         # generate a new keypair and gid
549         uuid = create_uuid()
550         pkey = Keypair(create=True)
551         urn = hrn_to_urn(record.hrn, record.type)
552         gid_object = api.auth.hierarchy.create_gid(urn, uuid, pkey)
553         gid = gid_object.save_to_string(save_parents=True)
554         record.gid = gid
555
556         # update the record
557         dbsession.commit()
558   
559         # attempt the scp the key
560         # and gid onto the node
561         # this will only work for planetlab based components
562         (kfd, key_filename) = tempfile.mkstemp() 
563         (gfd, gid_filename) = tempfile.mkstemp() 
564         pkey.save_to_file(key_filename)
565         gid_object.save_to_file(gid_filename, save_parents=True)
566         host = node['hostname']
567         key_dest="/etc/sfa/node.key"
568         gid_dest="/etc/sfa/node.gid" 
569         scp = "/usr/bin/scp" 
570         #identity = "/etc/planetlab/root_ssh_key.rsa"
571         identity = "/etc/sfa/root_ssh_key"
572         scp_options=" -i %(identity)s " % locals()
573         scp_options+="-o StrictHostKeyChecking=no " % locals()
574         scp_key_command="%(scp)s %(scp_options)s %(key_filename)s root@%(host)s:%(key_dest)s" %\
575                          locals()
576         scp_gid_command="%(scp)s %(scp_options)s %(gid_filename)s root@%(host)s:%(gid_dest)s" %\
577                          locals()    
578
579         all_commands = [scp_key_command, scp_gid_command]
580         
581         for command in all_commands:
582             (status, output) = commands.getstatusoutput(command)
583             if status:
584                 raise Exception, output
585
586         for filename in [key_filename, gid_filename]:
587             os.unlink(filename)
588
589         return 1