5 from pprint import pformat, PrettyPrinter
6 from optparse import OptionParser
8 from sfa.generic import Generic
9 from sfa.util.xrn import Xrn
10 from sfa.storage.record import Record
11 from sfa.client.sfi import save_records_to_file
12 from sfa.trust.hierarchy import Hierarchy
13 from sfa.trust.gid import GID
15 from sfa.client.candidates import Candidates
17 pprinter = PrettyPrinter(indent=4)
20 help_basedir=Hierarchy().basedir
22 help_basedir='*unable to locate Hierarchy().basedir'
24 def optparse_listvalue_callback(option, opt, value, parser):
25 setattr(parser.values, option.dest, value.split(','))
27 def args(*args, **kwargs):
29 func.__dict__.setdefault('options', []).insert(0, (args, kwargs))
33 class Commands(object):
34 def _get_commands(self):
36 for attrib in dir(self):
37 if callable(getattr(self, attrib)) and not attrib.startswith('_'):
38 command_names.append(attrib)
42 class RegistryCommands(Commands):
43 def __init__(self, *args, **kwds):
44 self.api= Generic.the_flavour().make_api(interface='registry')
47 """Display the Registry version"""
48 version = self.api.manager.GetVersion(self.api, {})
49 pprinter.pprint(version)
51 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='authority to list (hrn/urn - mandatory)')
52 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
53 @args('-r', '--recursive', dest='recursive', metavar='<recursive>', help='list all child records',
54 action='store_true', default=False)
55 def list(self, xrn, type=None, recursive=False):
56 """List names registered at a given authority - possibly filtered by type"""
58 options = {'recursive': recursive}
59 records = self.api.manager.List(self.api, xrn.get_hrn(), options=options)
60 for record in records:
61 if not type or record['type'] == type:
62 print "%s (%s)" % (record['hrn'], record['type'])
65 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
66 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
67 @args('-o', '--outfile', dest='outfile', metavar='<outfile>', help='save record to file')
68 @args('-f', '--format', dest='format', metavar='<display>', type='choice',
69 choices=('text', 'xml', 'simple'), help='display record in different formats')
70 def show(self, xrn, type=None, format=None, outfile=None):
71 """Display details for a registered object"""
72 records = self.api.manager.Resolve(self.api, xrn, type, True)
73 for record in records:
74 sfa_record = Record(dict=record)
75 sfa_record.dump(format)
77 save_records_to_file(outfile, records)
80 def _record_dict(self, xrn=None, type=None,
81 url=None, description=None, email='',
83 slices=[], researchers=[], pis=[]):
90 record_dict['urn'] = xrn.get_urn()
91 record_dict['hrn'] = xrn.get_hrn()
92 record_dict['type'] = xrn.get_type()
94 record_dict['url'] = url
96 record_dict['description'] = description
99 pubkey = open(key, 'r').read()
102 record_dict['keys'] = [pubkey]
104 record_dict['slices'] = slices
106 record_dict['researcher'] = researchers
108 record_dict['email'] = email
110 record_dict['pi'] = pis
113 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
114 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
115 @args('-e', '--email', dest='email', default="",
116 help="email (mandatory for users)")
117 @args('-u', '--url', dest='url', metavar='<url>', default=None,
118 help="URL, useful for slices")
119 @args('-d', '--description', dest='description', metavar='<description>',
120 help='Description, useful for slices', default=None)
121 @args('-k', '--key', dest='key', metavar='<key>', help='public key string or file',
123 @args('-s', '--slices', dest='slices', metavar='<slices>', help='slice xrns',
124 default='', type="str", action='callback', callback=optparse_listvalue_callback)
125 @args('-r', '--researchers', dest='researchers', metavar='<researchers>', help='slice researchers',
126 default='', type="str", action='callback', callback=optparse_listvalue_callback)
127 @args('-p', '--pis', dest='pis', metavar='<PIs>',
128 help='Principal Investigators/Project Managers ',
129 default='', type="str", action='callback', callback=optparse_listvalue_callback)
130 def register(self, xrn, type=None, url=None, description=None, key=None, slices='',
131 pis='', researchers='',email=''):
132 """Create a new Registry record"""
133 record_dict = self._record_dict(xrn=xrn, type=type, url=url, key=key,
134 slices=slices, researchers=researchers, email=email, pis=pis)
135 self.api.manager.Register(self.api, record_dict)
138 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
139 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
140 @args('-u', '--url', dest='url', metavar='<url>', help='URL', default=None)
141 @args('-d', '--description', dest='description', metavar='<description>',
142 help='Description', default=None)
143 @args('-k', '--key', dest='key', metavar='<key>', help='public key string or file',
145 @args('-s', '--slices', dest='slices', metavar='<slices>', help='slice xrns',
146 default='', type="str", action='callback', callback=optparse_listvalue_callback)
147 @args('-r', '--researchers', dest='researchers', metavar='<researchers>', help='slice researchers',
148 default='', type="str", action='callback', callback=optparse_listvalue_callback)
149 @args('-p', '--pis', dest='pis', metavar='<PIs>',
150 help='Principal Investigators/Project Managers ',
151 default='', type="str", action='callback', callback=optparse_listvalue_callback)
152 def update(self, xrn, type=None, url=None, description=None, key=None, slices='',
153 pis='', researchers=''):
154 """Update an existing Registry record"""
155 record_dict = self._record_dict(xrn=xrn, type=type, url=url, description=description,
156 key=key, slices=slices, researchers=researchers, pis=pis)
157 self.api.manager.Update(self.api, record_dict)
159 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
160 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
161 def remove(self, xrn, type=None):
162 """Remove given object from the registry"""
164 self.api.manager.Remove(self.api, xrn)
167 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
168 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
169 def credential(self, xrn, type=None):
170 """Invoke GetCredential"""
171 cred = self.api.manager.GetCredential(self.api, xrn, type, self.api.hrn)
175 def import_registry(self):
176 """Run the importer"""
177 from sfa.importer import Importer
178 importer = Importer()
182 """Initiailize or upgrade the db"""
183 from sfa.storage.dbschema import DBSchema
185 dbschema.init_or_upgrade
187 @args('-a', '--all', dest='all', metavar='<all>', action='store_true', default=False,
188 help='Remove all registry records and all files in %s area' % help_basedir)
189 @args('-c', '--certs', dest='certs', metavar='<certs>', action='store_true', default=False,
190 help='Remove all cached certs/gids found in %s' % help_basedir )
191 @args('-0', '--no-reinit', dest='reinit', metavar='<reinit>', action='store_false', default=True,
192 help='Prevents new DB schema from being installed after cleanup')
193 def nuke(self, all=False, certs=False, reinit=True):
194 """Cleanup local registry DB, plus various additional filesystem cleanups optionally"""
195 from sfa.storage.dbschema import DBSchema
196 from sfa.util.sfalogging import _SfaLogger
197 logger = _SfaLogger(logfile='/var/log/sfa_import.log', loggername='importlog')
198 logger.setLevelFromOptVerbose(self.api.config.SFA_API_LOGLEVEL)
199 logger.info("Purging SFA records from database")
203 # for convenience we re-create the schema here, so there's no need for an explicit
204 # service sfa restart
205 # however in some (upgrade) scenarios this might be wrong
207 logger.info("re-creating empty schema")
208 dbschema.init_or_upgrade()
210 # remove the server certificate and all gids found in /var/lib/sfa/authorities
212 logger.info("Purging cached certificates")
213 for (dir, _, files) in os.walk('/var/lib/sfa/authorities'):
215 if file.endswith('.gid') or file == 'server.cert':
219 # just remove all files that do not match 'server.key' or 'server.cert'
221 logger.info("Purging registry filesystem cache")
222 preserved_files = [ 'server.key', 'server.cert']
223 for (dir,_,files) in os.walk(Hierarchy().basedir):
225 if file in preserved_files: continue
230 class CertCommands(Commands):
232 def import_gid(self, xrn):
235 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
236 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
237 @args('-o', '--outfile', dest='outfile', metavar='<outfile>', help='output file', default=None)
238 def export(self, xrn, type=None, outfile=None):
239 """Fetch an object's GID from the Registry"""
240 from sfa.storage.alchemy import dbsession
241 from sfa.storage.model import RegRecord
242 hrn = Xrn(xrn).get_hrn()
243 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
244 if type: request = request.filter_by(type=type)
245 record=request.first()
247 gid = GID(string=record.gid)
249 # check the authorities hierarchy
250 hierarchy = Hierarchy()
252 auth_info = hierarchy.get_auth_info(hrn)
253 gid = auth_info.gid_object
255 print "Record: %s not found" % hrn
259 outfile = os.path.abspath('./%s.gid' % gid.get_hrn())
260 gid.save_to_file(outfile, save_parents=True)
262 @args('-g', '--gidfile', dest='gid', metavar='<gid>', help='path of gid file to display (mandatory)')
263 def display(self, gidfile):
264 """Print contents of a GID file"""
265 gid_path = os.path.abspath(gidfile)
266 if not gid_path or not os.path.isfile(gid_path):
267 print "No such gid file: %s" % gidfile
269 gid = GID(filename=gid_path)
270 gid.dump(dump_parents=True)
273 class AggregateCommands(Commands):
275 def __init__(self, *args, **kwds):
276 self.api= Generic.the_flavour().make_api(interface='aggregate')
279 """Display the Aggregate version"""
280 version = self.api.manager.GetVersion(self.api, {})
281 pprinter.pprint(version)
284 """List the running slices at this Aggregate"""
285 print self.api.manager.ListSlices(self.api, [], {})
287 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
288 def status(self, xrn):
289 """Display the status of a slice or slivers"""
290 urn = Xrn(xrn, 'slice').get_urn()
291 status = self.api.manager.SliverStatus(self.api, urn, [], {})
292 pprinter.pprint(status)
294 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
295 @args('-r', '--rspec-version', dest='rspec_version', metavar='<rspec_version>',
296 default='GENI', help='version/format of the resulting rspec response')
297 def resources(self, xrn=None, rspec_version='GENI'):
298 """Display the available resources at an aggregate
299 or the resources allocated by a slice"""
300 options = {'geni_rspec_version': rspec_version}
302 options['geni_slice_urn'] = Xrn(xrn, 'slice').get_urn()
304 resources = self.api.manager.ListResources(self.api, [], options)
307 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
308 @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='rspec file (mandatory)')
309 @args('-u', '--user', dest='user', metavar='<user>', help='hrn/urn of slice user (mandatory)')
310 @args('-k', '--key', dest='key', metavar='<key>', help="path to user's public key file (mandatory)")
311 def create(self, xrn, rspec, user, key):
312 """Allocate slivers"""
313 xrn = Xrn(xrn, 'slice')
314 slice_urn=xrn.get_urn()
315 rspec_string = open(rspec).read()
316 user_xrn = Xrn(user, 'user')
317 user_urn = user_xrn.get_urn()
318 user_key_string = open(key).read()
319 users = [{'urn': user_urn, 'keys': [user_key_string]}]
321 self.api.manager.CreateSliver(self, slice_urn, [], rspec_string, users, options)
323 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
324 def delete(self, xrn):
326 self.api.manager.DeleteSliver(self.api, xrn, [], {})
328 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
329 def start(self, xrn):
331 self.api.manager.start_slice(self.api, xrn, [])
333 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
336 self.api.manager.stop_slice(self.api, xrn, [])
338 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
339 def reset(self, xrn):
341 self.api.manager.reset_slice(self.api, xrn)
344 # @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
345 # @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='request rspec', default=None)
346 # def ticket(self, xrn, rspec):
351 class SliceManagerCommands(AggregateCommands):
353 def __init__(self, *args, **kwds):
354 self.api= Generic.the_flavour().make_api(interface='slicemgr')
359 CATEGORIES = {'certificate': CertCommands,
360 'registry': RegistryCommands,
361 'aggregate': AggregateCommands,
362 'slicemgr': SliceManagerCommands}
364 # returns (name,class) or (None,None)
365 def find_category (self, input):
366 full_name=Candidates (SfaAdmin.CATEGORIES.keys()).only_match(input)
367 if not full_name: return (None,None)
368 return (full_name,SfaAdmin.CATEGORIES[full_name])
370 def summary_usage (self, category=None):
371 print "Usage:", self.script_name + " category command [<options>]"
372 if category and category in SfaAdmin.CATEGORIES:
373 categories=[category]
375 categories=SfaAdmin.CATEGORIES
377 cls=SfaAdmin.CATEGORIES[c]
378 print "==================== category=%s"%c
379 names=cls.__dict__.keys()
382 method=cls.__dict__[name]
383 if name.startswith('_'): continue
385 format="%%-%ds"%margin
387 doc=getattr(method,'__doc__',None)
389 print "<missing __doc__>"
391 lines=[line.strip() for line in doc.split("\n")]
394 for extra_line in lines: print margin*" ",extra_line
398 argv = copy.deepcopy(sys.argv)
399 self.script_name = argv.pop(0)
400 # ensure category is specified
404 # ensure category is valid
405 category_input = argv.pop(0)
406 (category_name, category_class) = self.find_category (category_input)
407 if not category_name or not category_class:
408 self.summary_usage(category_name)
410 usage = "%%prog %s command [options]" % (category_name)
411 parser = OptionParser(usage=usage)
413 # ensure command is valid
414 category_instance = category_class()
415 commands = category_instance._get_commands()
417 # xxx what is this about ?
418 command_name = '__call__'
420 command_input = argv.pop(0)
421 command_name = Candidates (commands).only_match (command_input)
423 if command_name and hasattr(category_instance, command_name):
424 command = getattr(category_instance, command_name)
426 self.summary_usage(category_name)
428 # ensure options are valid
429 options = getattr(command, 'options', [])
430 usage = "%%prog %s %s [options]" % (category_name, command_name)
431 parser = OptionParser(usage=usage)
432 for arg, kwd in options:
433 parser.add_option(*arg, **kwd)
434 (opts, cmd_args) = parser.parse_args(argv)
435 cmd_kwds = vars(opts)
437 # dont overrride meth
438 for k, v in cmd_kwds.items():
444 #print "invoking %s *=%s **=%s"%(command.__name__,cmd_args, cmd_kwds)
445 command(*cmd_args, **cmd_kwds)
448 print "Possible wrong number of arguments supplied"
450 #traceback.print_exc()
451 print command.__doc__
455 print "Command failed, please check log for more info"