276943b63515368577c8ca5f4aecdd1ee64ac626
[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 = {'registry': RegistryCommands,
242               'aggregate': AggregateCommands,
243               'slicemgr': SliceManagerCommands}
244
245 def main():
246     argv = copy.deepcopy(sys.argv)
247     script_name = argv.pop(0)
248     if len(argv) < 1:
249         print script_name + " category action [<args>]"
250         print "Available categories:"
251         for k in CATEGORIES:
252             print "\t%s" % k
253         sys.exit(2)
254
255     category = argv.pop(0)
256     usage = "%%prog %s action <args> [options]" % (category)
257     parser = OptionParser(usage=usage)
258     command_class =  CATEGORIES[category]
259     command_instance = command_class()
260     actions = command_instance._get_commands()
261     if len(argv) < 1:
262         if hasattr(command_instance, '__call__'):
263             action = ''
264             command = command_instance.__call__
265         else:
266             print script_name + " category action [<args>]"
267             print "Available actions for %s category:" % category
268             for k in actions:
269                 print "\t%s" % k 
270             sys.exit(2)
271     else:
272         action = argv.pop(0)
273         command = getattr(command_instance, action)
274
275     options = getattr(command, 'options', [])
276     usage = "%%prog %s %s <args> [options]" % (category, action)
277     parser = OptionParser(usage=usage)
278     for arg, kwd in options:
279         parser.add_option(*arg, **kwd)
280     (opts, cmd_args) = parser.parse_args(argv)
281     cmd_kwds = vars(opts)
282
283     # dont overrride meth
284     for k, v in cmd_kwds.items():
285         if v is None:
286             del cmd_kwds[k]
287
288     try:
289         command(*cmd_args, **cmd_kwds)
290         sys.exit(0)
291     except TypeError:
292         print "Possible wrong number of arguments supplied"
293         print command.__doc__
294         parser.print_help()
295         #raise
296         raise
297     except Exception:
298         print "Command failed, please check log for more info"
299         raise
300
301
302 if __name__ == '__main__':
303     main()
304     
305      
306         
307