implement remove()
[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 SfaRecord 
10 from sfa.client.sfi import save_records_to_file
11 pprinter = PrettyPrinter(indent=4)
12
13
14 def args(*args, **kwargs):
15     def _decorator(func):
16         func.__dict__.setdefault('options', []).insert(0, (args, kwargs))
17         return func
18     return _decorator
19
20 class Commands(object):
21
22     def _get_commands(self):
23         available_methods = []
24         for attrib in dir(self):
25             if callable(getattr(self, attrib)) and not attrib.startswith('_'):
26                 available_methods.append(attrib)
27         return available_methods         
28
29 class RegistryCommands(Commands):
30
31     def __init__(self, *args, **kwds):
32         self.api= Generic.the_flavour().make_api(interface='registry')
33  
34     def version(self):
35         version = self.api.manager.GetVersion(self.api, {})
36         pprinter.pprint(version)
37
38     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn') 
39     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
40     def list(self, xrn, type=None):
41         xrn = Xrn(xrn, type) 
42         records = self.api.manager.List(self.api, xrn.get_hrn())
43         for record in records:
44             if not type or record['type'] == type:
45                 print "%s (%s)" % (record['hrn'], record['type'])
46
47
48     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn') 
49     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
50     @args('-o', '--outfile', dest='outfile', metavar='<outfile>', help='save record to file') 
51     @args('-f', '--format', dest='format', metavar='<display>', type='choice', 
52           choices=('text', 'xml', 'summary'), help='display record in different formats') 
53     def show(self, xrn, type=None, format=None, outfile=None):
54         records = self.api.manager.Resolve(self.api, xrn, type, True)
55         for record in records:
56             sfa_record = SfaRecord(dict=record)
57             sfa_record.dump(format) 
58         if outfile:
59             save_records_to_file(outfile, records)                
60
61     def register(self, record):
62         pass
63
64     def update(self, record):
65         pass
66         
67     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn') 
68     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
69     def remove(self, xrn, type=None):
70         xrn = Xrn(xrn, type)
71         self.api.manager.Remove(self.api, xrn)            
72
73     def credential(self, xrn):
74         pass
75
76     def gid(self, xrn):
77         pass
78
79 class CerficiateCommands(Commands):
80     
81     def import_records(self, xrn):
82         pass
83
84     def export(self, xrn):
85         pass
86
87     def display(self, xrn):
88         pass
89
90     def nuke(self):
91         pass  
92
93 class AggregateCommands(Commands):
94
95     def __init__(self, *args, **kwds):
96         self.api= Generic.the_flavour().make_api(interface='aggregate')
97    
98     def version(self):
99         version = self.api.manager.GetVersion(self.api, {})
100         pprinter.pprint(version)
101
102     def slices(self):
103         print self.api.manager.ListSlices(self.api, [], {})
104
105     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn') 
106     def status(self, xrn):
107         urn = Xrn(xrn, 'slice').get_urn()
108         status = self.api.manager.SliverStatus(self.api, urn, [], {})
109         pprinter.pprint(status)
110  
111     def resources(self, xrn):
112         pass
113
114     def create(self, xrn, rspec):
115         pass
116
117     def delete(self, xrn):
118         pass 
119     
120     def start(self, xrn):
121         pass
122
123     def stop(self, xrn):
124         pass      
125
126     def reset(self, xrn):
127         pass
128
129     def ticket(self):
130         pass
131
132
133 class SliceManagerCommands(AggregateCommands):
134     
135     def __init__(self, *args, **kwds):
136         self.api= Generic().make_api(interface='slicemgr')
137
138
139 CATEGORIES = {'registry': RegistryCommands,
140               'aggregate': AggregateCommands,
141               'slicemgr': SliceManagerCommands}
142
143 def main():
144     argv = copy.deepcopy(sys.argv)
145     script_name = argv.pop(0)
146     if len(argv) < 1:
147         print script_name + " category action [<args>]"
148         print "Available categories:"
149         for k in CATEGORIES:
150             print "\t%s" % k
151         sys.exit(2)
152
153     category = argv.pop(0)
154     usage = "%%prog %s action <args> [options]" % (category)
155     parser = OptionParser(usage=usage)
156     command_class =  CATEGORIES[category]
157     command_instance = command_class()
158     actions = command_instance._get_commands()
159     if len(argv) < 1:
160         if hasattr(command_instance, '__call__'):
161             action = ''
162             command = command_instance.__call__
163         else:
164             print script_name + " category action [<args>]"
165             print "Available actions for %s category:" % category
166             for k in actions:
167                 print "\t%s" % k 
168             sys.exit(2)
169     else:
170         action = argv.pop(0)
171         command = getattr(command_instance, action)
172
173     options = getattr(command, 'options', [])
174     usage = "%%prog %s %s <args> [options]" % (category, action)
175     parser = OptionParser(usage=usage)
176     for arg, kwd in options:
177         parser.add_option(*arg, **kwd)
178     (opts, cmd_args) = parser.parse_args(argv)
179     cmd_kwds = vars(opts)
180
181     # dont overrride meth
182     for k, v in cmd_kwds.items():
183         if v is None:
184             del cmd_kwds[k]
185
186     try:
187         command(*cmd_args, **cmd_kwds)
188         sys.exit(0)
189     except TypeError:
190         print "Possible wrong number of arguments supplied"
191         print command.__doc__
192         parser.print_help()
193         #raise
194         raise
195     except Exception:
196         print "Command failed, please check log for more info"
197         raise
198
199
200 if __name__ == '__main__':
201     main()
202     
203      
204         
205