5 from pprint import pformat
6 from sfa.generic import Generic
7 from optparse import OptionParser
8 from pprint import PrettyPrinter
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 pprinter = PrettyPrinter(indent=4)
17 def args(*args, **kwargs):
19 func.__dict__.setdefault('options', []).insert(0, (args, kwargs))
23 class Commands(object):
25 def _get_commands(self):
26 available_methods = []
27 for attrib in dir(self):
28 if callable(getattr(self, attrib)) and not attrib.startswith('_'):
29 available_methods.append(attrib)
30 return available_methods
33 class RegistryCommands(Commands):
34 def __init__(self, *args, **kwds):
35 self.api= Generic.the_flavour().make_api(interface='registry')
38 version = self.api.manager.GetVersion(self.api, {})
39 pprinter.pprint(version)
41 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
42 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
43 def list(self, xrn, type=None):
45 records = self.api.manager.List(self.api, xrn.get_hrn())
46 for record in records:
47 if not type or record['type'] == type:
48 print "%s (%s)" % (record['hrn'], record['type'])
51 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
52 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
53 @args('-o', '--outfile', dest='outfile', metavar='<outfile>', help='save record to file')
54 @args('-f', '--format', dest='format', metavar='<display>', type='choice',
55 choices=('text', 'xml', 'simple'), help='display record in different formats')
56 def show(self, xrn, type=None, format=None, outfile=None):
57 records = self.api.manager.Resolve(self.api, xrn, type, True)
58 for record in records:
59 sfa_record = Record(dict=record)
60 sfa_record.dump(format)
62 save_records_to_file(outfile, records)
64 def register(self, record):
67 def update(self, record):
70 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
71 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
72 def remove(self, xrn, type=None):
74 self.api.manager.Remove(self.api, xrn)
77 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
78 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
79 def credential(self, xrn, type=None):
80 cred = self.api.manager.GetCredential(self.api, xrn, type, self.api.hrn)
84 def import_registry(self):
85 from sfa.importer import Importer
89 @args('-a', '--all', dest='all', metavar='<all>', action='store_true', default=False,
90 help='Remove all registry records and all files in %s area' % Hierarchy().basedir)
91 @args('-c', '--certs', dest='certs', metavar='<certs>', action='store_true', default=False,
92 help='Remove all cached certs/gids found in %s' % Hierarchy().basedir )
93 @args('-0', '--no-reinit', dest='reinit', metavar='<reinit>', action='store_false', default=True,
94 help='Prevents new DB schema from being installed after cleanup')
95 def nuke(self, all=False, certs=False, reinit=True):
96 from sfa.storage.dbschema import DBSchema
97 from sfa.util.sfalogging import _SfaLogger
98 logger = _SfaLogger(logfile='/var/log/sfa_import.log', loggername='importlog')
99 logger.setLevelFromOptVerbose(self.api.config.SFA_API_LOGLEVEL)
100 logger.info("Purging SFA records from database")
104 # for convenience we re-create the schema here, so there's no need for an explicit
105 # service sfa restart
106 # however in some (upgrade) scenarios this might be wrong
108 logger.info("re-creating empty schema")
109 dbschema.init_or_upgrade()
111 # remove the server certificate and all gids found in /var/lib/sfa/authorities
113 logger.info("Purging cached certificates")
114 for (dir, _, files) in os.walk('/var/lib/sfa/authorities'):
116 if file.endswith('.gid') or file == 'server.cert':
120 # just remove all files that do not match 'server.key' or 'server.cert'
122 logger.info("Purging registry filesystem cache")
123 preserved_files = [ 'server.key', 'server.cert']
124 for (dir,_,files) in os.walk(Hierarchy().basedir):
126 if file in preserved_files: continue
131 class CertCommands(Commands):
133 def import_gid(self, xrn):
136 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
137 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
138 @args('-o', '--outfile', dest='outfile', metavar='<outfile>', help='output file', default=None)
139 def export(self, xrn, type=None, outfile=None):
140 from sfa.storage.alchemy import dbsession
141 from sfa.storage.model import RegRecord
142 hrn = Xrn(xrn).get_hrn()
143 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
144 if type: request = request.filter_by(type=type)
145 record=request.first()
147 gid = GID(string=record.gid)
149 # check the authorities hierarchy
150 hierarchy = Hierarchy()
152 auth_info = hierarchy.get_auth_info(hrn)
153 gid = auth_info.gid_object
155 print "Record: %s not found" % hrn
159 outfile = os.path.abspath('./%s.gid' % gid.get_hrn())
160 gid.save_to_file(outfile, save_parents=True)
162 @args('-g', '--gidfile', dest='gid', metavar='<gid>', help='path of gid file to display')
163 def display(self, gidfile):
164 gid_path = os.path.abspath(gidfile)
165 if not gid_path or not os.path.isfile(gid_path):
166 print "No such gid file: %s" % gidfile
168 gid = GID(filename=gid_path)
169 gid.dump(dump_parents=True)
172 class AggregateCommands(Commands):
174 def __init__(self, *args, **kwds):
175 self.api= Generic.the_flavour().make_api(interface='aggregate')
178 version = self.api.manager.GetVersion(self.api, {})
179 pprinter.pprint(version)
182 print self.api.manager.ListSlices(self.api, [], {})
184 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
185 def status(self, xrn):
186 urn = Xrn(xrn, 'slice').get_urn()
187 status = self.api.manager.SliverStatus(self.api, urn, [], {})
188 pprinter.pprint(status)
190 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
191 @args('-r', '--rspec-version', dest='rspec_version', metavar='<rspec_version>',
192 default='GENI', help='version/format of the resulting rspec response')
193 def resources(self, xrn=None, rspec_version='GENI'):
194 options = {'geni_rspec_version': rspec_version}
196 options['geni_slice_urn'] = xrn
197 resources = self.api.manager.ListResources(self.api, [], options)
200 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
201 @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='rspec file')
202 @args('-u', '--user', dest='user', metavar='<user>', help='hrn/urn of slice user')
203 @args('-k', '--key', dest='key', metavar='<key>', help="path to user's public key file")
204 def create(self, xrn, rspec, user, key):
205 xrn = Xrn(xrn, 'slice')
206 slice_urn=xrn.get_urn()
207 rspec_string = open(rspec).read()
208 user_xrn = Xrn(user, 'user')
209 user_urn = user_xrn.get_urn()
210 user_key_string = open(key).read()
211 users = [{'urn': user_urn, 'keys': [user_key_string]}]
213 self.api.manager.CreateSliver(self, slice_urn, [], rspec_string, users, options)
215 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
216 def delete(self, xrn):
217 self.api.manager.DeleteSliver(self.api, xrn, [], {})
219 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
220 def start(self, xrn):
221 self.api.manager.start_slice(self.api, xrn, [])
223 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
225 self.api.manager.stop_slice(self.api, xrn, [])
227 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
228 def reset(self, xrn):
229 self.api.manager.reset_slice(self.api, xrn)
232 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
233 @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='request rspec', default=None)
234 def ticket(self, xrn, rspec):
239 class SliceManagerCommands(AggregateCommands):
241 def __init__(self, *args, **kwds):
242 self.api= Generic.the_flavour().make_api(interface='slicemgr')
245 CATEGORIES = {'cert': CertCommands,
246 'registry': RegistryCommands,
247 'aggregate': AggregateCommands,
248 'slicemgr': SliceManagerCommands}
250 def category_usage():
251 print "Available categories:"
256 argv = copy.deepcopy(sys.argv)
257 script_name = argv.pop(0)
258 # ensure category is specified
260 print script_name + " category action [<args>]"
264 # ensure category is valid
265 category = argv.pop(0)
266 usage = "%%prog %s action <args> [options]" % (category)
267 parser = OptionParser(usage=usage)
268 command_class = CATEGORIES.get(category, None)
269 if not command_class:
270 print "no such category %s " % category
274 # ensure command is valid
275 command_instance = command_class()
276 actions = command_instance._get_commands()
282 if hasattr(command_instance, action):
283 command = getattr(command_instance, action)
285 print script_name + " category action [<args>]"
286 print "Available actions for %s category:" % category
291 # ensure options are valid
292 options = getattr(command, 'options', [])
293 usage = "%%prog %s %s <args> [options]" % (category, action)
294 parser = OptionParser(usage=usage)
295 for arg, kwd in options:
296 parser.add_option(*arg, **kwd)
297 (opts, cmd_args) = parser.parse_args(argv)
298 cmd_kwds = vars(opts)
300 # dont overrride meth
301 for k, v in cmd_kwds.items():
307 command(*cmd_args, **cmd_kwds)
310 print "Possible wrong number of arguments supplied"
311 print command.__doc__
316 print "Command failed, please check log for more info"
320 if __name__ == '__main__':