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