fix indent error
[sfa.git] / sfa / clientbin / sfaadmin.py
1 #!/usr/bin/python
2 import sys
3 import copy
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
13
14 pprinter = PrettyPrinter(indent=4)
15
16 def args(*args, **kwargs):
17     def _decorator(func):
18         func.__dict__.setdefault('options', []).insert(0, (args, kwargs))
19         return func
20     return _decorator
21
22 class Commands(object):
23
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         
30
31
32 class RegistryCommands(Commands):
33     def __init__(self, *args, **kwds):
34         self.api= Generic.the_flavour().make_api(interface='registry')
35  
36     def version(self):
37         version = self.api.manager.GetVersion(self.api, {})
38         pprinter.pprint(version)
39
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):
43         xrn = Xrn(xrn, type) 
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'])
48
49
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) 
60         if outfile:
61             save_records_to_file(outfile, records)                
62
63     def register(self, record):
64         pass
65
66     def update(self, record):
67         pass
68         
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):
72         xrn = Xrn(xrn, type)
73         self.api.manager.Remove(self.api, xrn)            
74
75
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)
80         print cred
81    
82
83     def import_registry(self):
84         pass
85  
86     
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")
99         dbschema=DBSchema()
100         dbschema.nuke()
101
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
105         if options.reinit:
106             logger.info("re-creating empty schema")
107             dbschema.init_or_upgrade()
108
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'):
113                 for file in files:
114                     if file.endswith('.gid') or file == 'server.cert':
115                         path=dir+os.sep+file
116                         os.unlink(path)
117
118         # just remove all files that do not match 'server.key' or 'server.cert'
119         if options.all:
120             logger.info("Purging registry filesystem cache")
121             preserved_files = [ 'server.key', 'server.cert']
122             for (dir,_,files) in os.walk(Hierarchy().basedir):
123                 for file in files:
124                     if file in preserved_files: continue
125                     path=dir+os.sep+file
126                     os.unlink(path)
127         
128     
129 class CerficiateCommands(Commands):
130     
131     def import_gid(self, xrn):
132         pass
133
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()
141         if record:
142             gid = GID(string=record.gid)
143         else:
144             # check the authorities hierarchy
145             hierarchy = Hierarchy()
146             try:
147                 auth_info = hierarchy.get_auth_info(hrn)
148                 gid = auth_info.gid_object
149             except:
150                 print "Record: %s not found" % hrn
151                 sys.exit(1)
152         # save to file
153         if not outfile:
154             outfile = os.path.abspath('./%s.gid' % gid.get_hrn())
155         gid.save_to_file(outfile, save_parents=True)
156         
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
162             sys.exit(1)
163         gid = GID(filename=gid_path)
164         gid.dump(dump_parents=True)
165     
166
167 class AggregateCommands(Commands):
168
169     def __init__(self, *args, **kwds):
170         self.api= Generic.the_flavour().make_api(interface='aggregate')
171    
172     def version(self):
173         version = self.api.manager.GetVersion(self.api, {})
174         pprinter.pprint(version)
175
176     def slices(self):
177         print self.api.manager.ListSlices(self.api, [], {})
178
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)
184  
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}
190         if xrn:
191             options['geni_slice_urn'] = xrn
192         resources = self.api.manager.ListResources(self.api, [], options)
193         pprinter.pprint(resources)
194         
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):
200         xrn = Xrn(xrn)
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]}]
208         options={}
209         self.api.manager.CreateSliver(self, slice_urn, slice_hrn, [], rspec_string, users, options) 
210
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, [], {})
214  
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, [])
218
219     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
220     def stop(self, xrn):
221         self.api.manager.stop_slice(self.api, xrn, [])      
222
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)
226
227
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):
231         pass
232
233
234
235 class SliceManagerCommands(AggregateCommands):
236     
237     def __init__(self, *args, **kwds):
238         self.api= Generic.the_flavour().make_api(interface='slicemgr')
239
240
241 CATEGORIES = {'cert': CertificateCommands,
242               'registry': RegistryCommands,
243               'aggregate': AggregateCommands,
244               'slicemgr': SliceManagerCommands}
245
246 def category_usage():
247     print "Available categories:"
248     for k in CATEGORIES:
249         print "\t%s" % k
250
251 def main():
252     argv = copy.deepcopy(sys.argv)
253     script_name = argv.pop(0)
254     # ensure category is specified    
255     if len(argv) < 1:
256         print script_name + " category action [<args>]"
257         category_usage()
258         sys.exit(2)
259
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
267         category_usage()
268         sys.exit(2)  
269     
270     # ensure command is valid      
271     command_instance = command_class()
272     actions = command_instance._get_commands()
273     if len(argv) < 1:
274         if hasattr(command_instance, '__call__'):
275             action = ''
276             command = command_instance.__call__
277         else:
278             print script_name + " category action [<args>]"
279             print "Available actions for %s category:" % category
280             for k in actions:
281                 print "\t%s" % k 
282             sys.exit(2)
283     else:
284         action = argv.pop(0)
285         command = getattr(command_instance, action)
286
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)
295
296     # dont overrride meth
297     for k, v in cmd_kwds.items():
298         if v is None:
299             del cmd_kwds[k]
300
301     # execute commadn
302     try:
303         command(*cmd_args, **cmd_kwds)
304         sys.exit(0)
305     except TypeError:
306         print "Possible wrong number of arguments supplied"
307         print command.__doc__
308         parser.print_help()
309         #raise
310         raise
311     except Exception:
312         print "Command failed, please check log for more info"
313         raise
314
315
316 if __name__ == '__main__':
317     main()
318     
319      
320         
321