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