d69314a8f864299bee0386957be7c78376c389ad
[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', 'simple'), 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
74     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn') 
75     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
76     def credential(self, xrn, type=None):
77         cred = self.api.manager.GetCredential(self.api, xrn, type, self.api.hrn)
78         print cred
79
80     def gid(self, xrn):
81         pass
82
83 class CerficiateCommands(Commands):
84     
85     def import_records(self, xrn):
86         pass
87
88     def export(self, xrn):
89         pass
90
91     def display(self, xrn):
92         pass
93
94     def nuke(self):
95         pass  
96
97 class AggregateCommands(Commands):
98
99     def __init__(self, *args, **kwds):
100         self.api= Generic.the_flavour().make_api(interface='aggregate')
101    
102     def version(self):
103         version = self.api.manager.GetVersion(self.api, {})
104         pprinter.pprint(version)
105
106     def slices(self):
107         print self.api.manager.ListSlices(self.api, [], {})
108
109     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn') 
110     def status(self, xrn):
111         urn = Xrn(xrn, 'slice').get_urn()
112         status = self.api.manager.SliverStatus(self.api, urn, [], {})
113         pprinter.pprint(status)
114  
115     def resources(self, xrn):
116         pass
117
118     def create(self, xrn, rspec):
119         pass
120
121     def delete(self, xrn):
122         pass 
123     
124     def start(self, xrn):
125         pass
126
127     def stop(self, xrn):
128         pass      
129
130     def reset(self, xrn):
131         pass
132
133     def ticket(self):
134         pass
135
136
137 class SliceManagerCommands(AggregateCommands):
138     
139     def __init__(self, *args, **kwds):
140         self.api= Generic().make_api(interface='slicemgr')
141
142
143 CATEGORIES = {'registry': RegistryCommands,
144               'aggregate': AggregateCommands,
145               'slicemgr': SliceManagerCommands}
146
147 def main():
148     argv = copy.deepcopy(sys.argv)
149     script_name = argv.pop(0)
150     if len(argv) < 1:
151         print script_name + " category action [<args>]"
152         print "Available categories:"
153         for k in CATEGORIES:
154             print "\t%s" % k
155         sys.exit(2)
156
157     category = argv.pop(0)
158     usage = "%%prog %s action <args> [options]" % (category)
159     parser = OptionParser(usage=usage)
160     command_class =  CATEGORIES[category]
161     command_instance = command_class()
162     actions = command_instance._get_commands()
163     if len(argv) < 1:
164         if hasattr(command_instance, '__call__'):
165             action = ''
166             command = command_instance.__call__
167         else:
168             print script_name + " category action [<args>]"
169             print "Available actions for %s category:" % category
170             for k in actions:
171                 print "\t%s" % k 
172             sys.exit(2)
173     else:
174         action = argv.pop(0)
175         command = getattr(command_instance, action)
176
177     options = getattr(command, 'options', [])
178     usage = "%%prog %s %s <args> [options]" % (category, action)
179     parser = OptionParser(usage=usage)
180     for arg, kwd in options:
181         parser.add_option(*arg, **kwd)
182     (opts, cmd_args) = parser.parse_args(argv)
183     cmd_kwds = vars(opts)
184
185     # dont overrride meth
186     for k, v in cmd_kwds.items():
187         if v is None:
188             del cmd_kwds[k]
189
190     try:
191         command(*cmd_args, **cmd_kwds)
192         sys.exit(0)
193     except TypeError:
194         print "Possible wrong number of arguments supplied"
195         print command.__doc__
196         parser.print_help()
197         #raise
198         raise
199     except Exception:
200         print "Command failed, please check log for more info"
201         raise
202
203
204 if __name__ == '__main__':
205     main()
206     
207      
208         
209