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 CerficiateCommands(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 request=dbsession.query(RegRecord).filter_by(hrn=hrn)
139 if type: request = request.filter_by(type=type)
140 record=request.first()
142 gid = GID(string=record.gid)
144 # check the authorities hierarchy
145 hierarchy = Hierarchy()
147 auth_info = hierarchy.get_auth_info(hrn)
148 gid = auth_info.gid_object
150 print "Record: %s not found" % hrn
154 outfile = os.path.abspath('./%s.gid' % gid.get_hrn())
155 gid.save_to_file(outfile, save_parents=True)
157 @args('-g', '--gidfile', dest='gid', metavar='<gid>', help='path of gid file to display')
158 def display(self, gidfile):
159 gid_path = os.path.abspath(gidfile)
160 if not gid_path or not os.path.isfile(gid_path):
161 print "No such gid file: %s" % gidfile
163 gid = GID(filename=gid_path)
164 gid.dump(dump_parents=True)
167 class AggregateCommands(Commands):
169 def __init__(self, *args, **kwds):
170 self.api= Generic.the_flavour().make_api(interface='aggregate')
173 version = self.api.manager.GetVersion(self.api, {})
174 pprinter.pprint(version)
177 print self.api.manager.ListSlices(self.api, [], {})
179 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn')
180 def status(self, xrn):
181 urn = Xrn(xrn, 'slice').get_urn()
182 status = self.api.manager.SliverStatus(self.api, urn, [], {})
183 pprinter.pprint(status)
185 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
186 @args('-r', '--rspec-version', dest='rspec_version', metavar='<rspec_version>',
187 default='GENI', help='version/format of the resulting rspec response')
188 def resources(self, xrn=None, rspec_version='GENI'):
189 options = {'geni_rspec_version': rspec_version}
191 options['geni_slice_urn'] = xrn
192 resources = self.api.manager.ListResources(self.api, [], options)
193 pprinter.pprint(resources)
195 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
196 @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='rspec file')
197 @args('-u', '--user', dest='user', metavar='<user>', help='hrn/urn of slice user')
198 @args('-k', '--key', dest='key', metavar='<key>', help="path to user's public key file")
199 def create(self, xrn, rspec, user, key):
201 slice_urn=xrn.get_urn()
202 slice_hrn=xrn.get_hrn()
203 rspec_string = open(rspec).read()
204 user_xrn = Xrn(user, 'user')
205 user_urn = user_xrn.get_urn()
206 user_key_string = open(key).read()
207 users = [{'urn': user_urn, 'keys': [user_key_string]}]
209 self.api.manager.CreateSliver(self, slice_urn, slice_hrn, [], rspec_string, users, options)
211 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
212 def delete(self, xrn):
213 self.api.manager.DeleteSliver(self.api, xrn, [], {})
215 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
216 def start(self, xrn):
217 self.api.manager.start_slice(self.api, xrn, [])
219 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
221 self.api.manager.stop_slice(self.api, xrn, [])
223 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
224 def reset(self, xrn):
225 self.api.manager.reset_slice(self.api, xrn)
228 @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
229 @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='request rspec', default=None)
230 def ticket(self, xrn, rspec):
235 class SliceManagerCommands(AggregateCommands):
237 def __init__(self, *args, **kwds):
238 self.api= Generic.the_flavour().make_api(interface='slicemgr')
241 CATEGORIES = {'cert': CertificateCommands,
242 'registry': RegistryCommands,
243 'aggregate': AggregateCommands,
244 'slicemgr': SliceManagerCommands}
246 def category_usage():
247 print "Available categories:"
252 argv = copy.deepcopy(sys.argv)
253 script_name = argv.pop(0)
254 # ensure category is specified
256 print script_name + " category action [<args>]"
260 # ensure category is valid
261 category = argv.pop(0)
262 usage = "%%prog %s action <args> [options]" % (category)
263 parser = OptionParser(usage=usage)
264 command_class = CATEGORIES.get(category, None)
265 if not command_class:
266 print "no such category %s " % category
270 # ensure command is valid
271 command_instance = command_class()
272 actions = command_instance._get_commands()
274 if hasattr(command_instance, '__call__'):
276 command = command_instance.__call__
278 print script_name + " category action [<args>]"
279 print "Available actions for %s category:" % category
285 command = getattr(command_instance, action)
287 # ensure options are valid
288 options = getattr(command, 'options', [])
289 usage = "%%prog %s %s <args> [options]" % (category, action)
290 parser = OptionParser(usage=usage)
291 for arg, kwd in options:
292 parser.add_option(*arg, **kwd)
293 (opts, cmd_args) = parser.parse_args(argv)
294 cmd_kwds = vars(opts)
296 # dont overrride meth
297 for k, v in cmd_kwds.items():
303 command(*cmd_args, **cmd_kwds)
306 print "Possible wrong number of arguments supplied"
307 print command.__doc__
312 print "Command failed, please check log for more info"
316 if __name__ == '__main__':