fix import 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 CertCommands(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         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()
142         if record:
143             gid = GID(string=record.gid)
144         else:
145             # check the authorities hierarchy
146             hierarchy = Hierarchy()
147             try:
148                 auth_info = hierarchy.get_auth_info(hrn)
149                 gid = auth_info.gid_object
150             except:
151                 print "Record: %s not found" % hrn
152                 sys.exit(1)
153         # save to file
154         if not outfile:
155             outfile = os.path.abspath('./%s.gid' % gid.get_hrn())
156         gid.save_to_file(outfile, save_parents=True)
157         
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
163             sys.exit(1)
164         gid = GID(filename=gid_path)
165         gid.dump(dump_parents=True)
166     
167
168 class AggregateCommands(Commands):
169
170     def __init__(self, *args, **kwds):
171         self.api= Generic.the_flavour().make_api(interface='aggregate')
172    
173     def version(self):
174         version = self.api.manager.GetVersion(self.api, {})
175         pprinter.pprint(version)
176
177     def slices(self):
178         print self.api.manager.ListSlices(self.api, [], {})
179
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)
185  
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}
191         if xrn:
192             options['geni_slice_urn'] = xrn
193         resources = self.api.manager.ListResources(self.api, [], options)
194         pprinter.pprint(resources)
195         
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):
201         xrn = Xrn(xrn)
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]}]
209         options={}
210         self.api.manager.CreateSliver(self, slice_urn, slice_hrn, [], rspec_string, users, options) 
211
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, [], {})
215  
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, [])
219
220     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
221     def stop(self, xrn):
222         self.api.manager.stop_slice(self.api, xrn, [])      
223
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)
227
228
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):
232         pass
233
234
235
236 class SliceManagerCommands(AggregateCommands):
237     
238     def __init__(self, *args, **kwds):
239         self.api= Generic.the_flavour().make_api(interface='slicemgr')
240
241
242 CATEGORIES = {'cert': CertCommands,
243               'registry': RegistryCommands,
244               'aggregate': AggregateCommands,
245               'slicemgr': SliceManagerCommands}
246
247 def category_usage():
248     print "Available categories:"
249     for k in CATEGORIES:
250         print "\t%s" % k
251
252 def main():
253     argv = copy.deepcopy(sys.argv)
254     script_name = argv.pop(0)
255     # ensure category is specified    
256     if len(argv) < 1:
257         print script_name + " category action [<args>]"
258         category_usage()
259         sys.exit(2)
260
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
268         category_usage()
269         sys.exit(2)  
270     
271     # ensure command is valid      
272     command_instance = command_class()
273     actions = command_instance._get_commands()
274     if len(argv) < 1:
275         if hasattr(command_instance, '__call__'):
276             action = ''
277             command = command_instance.__call__
278         else:
279             print script_name + " category action [<args>]"
280             print "Available actions for %s category:" % category
281             for k in actions:
282                 print "\t%s" % k 
283             sys.exit(2)
284     else:
285         action = argv.pop(0)
286         command = getattr(command_instance, action)
287
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)
296
297     # dont overrride meth
298     for k, v in cmd_kwds.items():
299         if v is None:
300             del cmd_kwds[k]
301
302     # execute commadn
303     try:
304         command(*cmd_args, **cmd_kwds)
305         sys.exit(0)
306     except TypeError:
307         print "Possible wrong number of arguments supplied"
308         print command.__doc__
309         parser.print_help()
310         #raise
311         raise
312     except Exception:
313         print "Command failed, please check log for more info"
314         raise
315
316
317 if __name__ == '__main__':
318     main()
319     
320      
321         
322