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