4 from pprint import pformat
5 from sfa.generic import Generic
6 from optparse import OptionParser
7 from pprint import PrettyPrinter
8 from sfa.util.xrn import Xrn
9 from sfa.storage.record import Record
10 from sfa.client.sfi import save_records_to_file
11 from sfa.trust.hierarchy import Hierarchy
12 from sfa.trust.gid import GID
14 pprinter = PrettyPrinter(indent=4)
16 def args(*args, **kwargs):
18 func.__dict__.setdefault('options', []).insert(0, (args, kwargs))
22 class Commands(object):
24 def _get_commands(self):
25 available_methods = []
26 for attrib in dir(self):
27 if callable(getattr(self, attrib)) and not attrib.startswith('_'):
28 available_methods.append(attrib)
29 return available_methods
32 class RegistryCommands(Commands):
33 def __init__(self, *args, **kwds):
34 self.api= Generic.the_flavour().make_api(interface='registry')
37 version = self.api.manager.GetVersion(self.api, {})
38 pprinter.pprint(version)
40 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
41 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
42 def list(self, xrn, type=None):
44 records = self.api.manager.List(self.api, xrn.get_hrn())
45 for record in records:
46 if not type or record['type'] == type:
47 print "%s (%s)" % (record['hrn'], record['type'])
50 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
51 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
52 @args('-o', '--outfile', dest='outfile', metavar='<outfile>', help='save record to file')
53 @args('-f', '--format', dest='format', metavar='<display>', type='choice',
54 choices=('text', 'xml', 'simple'), help='display record in different formats')
55 def show(self, xrn, type=None, format=None, outfile=None):
56 records = self.api.manager.Resolve(self.api, xrn, type, True)
57 for record in records:
58 sfa_record = Record(dict=record)
59 sfa_record.dump(format)
61 save_records_to_file(outfile, records)
63 def register(self, record):
66 def update(self, record):
69 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
70 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
71 def remove(self, xrn, type=None):
73 self.api.manager.Remove(self.api, xrn)
76 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
77 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
78 def credential(self, xrn, type=None):
79 cred = self.api.manager.GetCredential(self.api, xrn, type, self.api.hrn)
83 def import_registry(self):
87 @args('-a', '--all', dest='all', metavar='<all>', action='store_true', default=False,
88 help='Remove all registry records and all files in %s area' % Hierarchy().basedir)
89 @args('-c', '--certs', dest='certs', metavar='<certs>', action='store_true', default=False,
90 help='Remove all cached certs/gids found in %s' % Hierarchy().basedir )
91 @args('-0', '--no-reinit', dest='reinit', metavar='<reinit>', action='store_false', default=True,
92 help='By default a new DB schema is installed after the cleanup; this option prevents that')
93 def nuke(self, all=False, certs=False, reinit=True):
94 from sfa.storage.dbschema import DBSchema
95 from sfa.util.sfalogging import _SfaLogger
96 logger = _SfaLogger(logfile='/var/log/sfa_import.log', loggername='importlog')
97 logger.setLevelFromOptVerbose(self.api.config.SFA_API_LOGLEVEL)
98 logger.info("Purging SFA records from database")
102 # for convenience we re-create the schema here, so there's no need for an explicit
103 # service sfa restart
104 # however in some (upgrade) scenarios this might be wrong
106 logger.info("re-creating empty schema")
107 dbschema.init_or_upgrade()
109 # remove the server certificate and all gids found in /var/lib/sfa/authorities
110 if options.clean_certs:
111 logger.info("Purging cached certificates")
112 for (dir, _, files) in os.walk('/var/lib/sfa/authorities'):
114 if file.endswith('.gid') or file == 'server.cert':
118 # just remove all files that do not match 'server.key' or 'server.cert'
120 logger.info("Purging registry filesystem cache")
121 preserved_files = [ 'server.key', 'server.cert']
122 for (dir,_,files) in os.walk(Hierarchy().basedir):
124 if file in preserved_files: continue
129 class CertCommands(Commands):
131 def import_gid(self, xrn):
134 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
135 @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
136 @args('-o', '--outfile', dest='outfile', metavar='<outfile>', help='output file', default=None)
137 def export(self, xrn, type=None, outfile=None):
138 from sfa.storage.alchemy import dbsession
139 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
140 if type: request = request.filter_by(type=type)
141 record=request.first()
143 gid = GID(string=record.gid)
145 # check the authorities hierarchy
146 hierarchy = Hierarchy()
148 auth_info = hierarchy.get_auth_info(hrn)
149 gid = auth_info.gid_object
151 print "Record: %s not found" % hrn
155 outfile = os.path.abspath('./%s.gid' % gid.get_hrn())
156 gid.save_to_file(outfile, save_parents=True)
158 @args('-g', '--gidfile', dest='gid', metavar='<gid>', help='path of gid file to display')
159 def display(self, gidfile):
160 gid_path = os.path.abspath(gidfile)
161 if not gid_path or not os.path.isfile(gid_path):
162 print "No such gid file: %s" % gidfile
164 gid = GID(filename=gid_path)
165 gid.dump(dump_parents=True)
168 class AggregateCommands(Commands):
170 def __init__(self, *args, **kwds):
171 self.api= Generic.the_flavour().make_api(interface='aggregate')
174 version = self.api.manager.GetVersion(self.api, {})
175 pprinter.pprint(version)
178 print self.api.manager.ListSlices(self.api, [], {})
180 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
181 def status(self, xrn):
182 urn = Xrn(xrn, 'slice').get_urn()
183 status = self.api.manager.SliverStatus(self.api, urn, [], {})
184 pprinter.pprint(status)
186 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
187 @args('-r', '--rspec-version', dest='rspec_version', metavar='<rspec_version>',
188 default='GENI', help='version/format of the resulting rspec response')
189 def resources(self, xrn=None, rspec_version='GENI'):
190 options = {'geni_rspec_version': rspec_version}
192 options['geni_slice_urn'] = xrn
193 resources = self.api.manager.ListResources(self.api, [], options)
194 pprinter.pprint(resources)
196 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
197 @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='rspec file')
198 @args('-u', '--user', dest='user', metavar='<user>', help='hrn/urn of slice user')
199 @args('-k', '--key', dest='key', metavar='<key>', help="path to user's public key file")
200 def create(self, xrn, rspec, user, key):
202 slice_urn=xrn.get_urn()
203 slice_hrn=xrn.get_hrn()
204 rspec_string = open(rspec).read()
205 user_xrn = Xrn(user, 'user')
206 user_urn = user_xrn.get_urn()
207 user_key_string = open(key).read()
208 users = [{'urn': user_urn, 'keys': [user_key_string]}]
210 self.api.manager.CreateSliver(self, slice_urn, slice_hrn, [], rspec_string, users, options)
212 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
213 def delete(self, xrn):
214 self.api.manager.DeleteSliver(self.api, xrn, [], {})
216 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
217 def start(self, xrn):
218 self.api.manager.start_slice(self.api, xrn, [])
220 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
222 self.api.manager.stop_slice(self.api, xrn, [])
224 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
225 def reset(self, xrn):
226 self.api.manager.reset_slice(self.api, xrn)
229 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
230 @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='request rspec', default=None)
231 def ticket(self, xrn, rspec):
236 class SliceManagerCommands(AggregateCommands):
238 def __init__(self, *args, **kwds):
239 self.api= Generic.the_flavour().make_api(interface='slicemgr')
242 CATEGORIES = {'cert': CertCommands,
243 'registry': RegistryCommands,
244 'aggregate': AggregateCommands,
245 'slicemgr': SliceManagerCommands}
247 def category_usage():
248 print "Available categories:"
253 argv = copy.deepcopy(sys.argv)
254 script_name = argv.pop(0)
255 # ensure category is specified
257 print script_name + " category action [<args>]"
261 # ensure category is valid
262 category = argv.pop(0)
263 usage = "%%prog %s action <args> [options]" % (category)
264 parser = OptionParser(usage=usage)
265 command_class = CATEGORIES.get(category, None)
266 if not command_class:
267 print "no such category %s " % category
271 # ensure command is valid
272 command_instance = command_class()
273 actions = command_instance._get_commands()
275 if hasattr(command_instance, '__call__'):
277 command = command_instance.__call__
279 print script_name + " category action [<args>]"
280 print "Available actions for %s category:" % category
286 command = getattr(command_instance, action)
288 # ensure options are valid
289 options = getattr(command, 'options', [])
290 usage = "%%prog %s %s <args> [options]" % (category, action)
291 parser = OptionParser(usage=usage)
292 for arg, kwd in options:
293 parser.add_option(*arg, **kwd)
294 (opts, cmd_args) = parser.parse_args(argv)
295 cmd_kwds = vars(opts)
297 # dont overrride meth
298 for k, v in cmd_kwds.items():
304 command(*cmd_args, **cmd_kwds)
307 print "Possible wrong number of arguments supplied"
308 print command.__doc__
313 print "Command failed, please check log for more info"
317 if __name__ == '__main__':