netcmd: Add errf stream to command instances.
[tridge/samba.git] / source4 / scripting / python / samba / netcmd / __init__.py
1 #!/usr/bin/env python
2
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2009
5 # Copyright (C) Theresa Halloran <theresahalloran@gmail.com> 2011
6 # Copyright (C) Giampaolo Lauria <lauria2@yahoo.com> 2011
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21
22 import optparse, samba
23 from samba import getopt as options
24 from ldb import LdbError
25 import sys, traceback
26
27
28 class Option(optparse.Option):
29     pass
30
31
32
33 class Command(object):
34     """A samba-tool command."""
35    
36     def _get_description(self):
37         return self.__doc__.splitlines()[0].rstrip("\n")
38
39     description = property(_get_description)
40
41     # synopsis must be defined in all subclasses in order to provide the command usage
42     synopsis = "Please provide synopsis for this command."
43     # long_description is a string describing the command in details
44     long_description = ""
45     takes_args = []
46     takes_options = []
47     takes_optiongroups = {
48         "sambaopts": options.SambaOptions,
49         "credopts": options.CredentialsOptions,
50         "versionopts": options.VersionOptions,
51         }
52     outf = sys.stdout
53     errf = sys.stderr
54
55     def usage(self, *args):
56         parser, _ = self._create_parser()
57         parser.print_usage()
58
59     def show_command_error(self, e):
60         '''display a command error'''
61         if isinstance(e, CommandError):
62             (etype, evalue, etraceback) = e.exception_info
63             inner_exception = e.inner_exception
64             message = e.message
65             force_traceback = False
66         else:
67             (etype, evalue, etraceback) = sys.exc_info()
68             inner_exception = e
69             message = "uncaught exception"
70             force_traceback = True
71
72         if isinstance(inner_exception, LdbError):
73             (ldb_ecode, ldb_emsg) = inner_exception
74             self.errf.write("ERROR(ldb): %s - %s\n" % (message, ldb_emsg))
75         elif isinstance(inner_exception, AssertionError):
76             self.errf.write("ERROR(assert): %s\n" % message)
77             force_traceback = True
78         elif isinstance(inner_exception, RuntimeError):
79             self.errf.write("ERROR(runtime): %s - %s\n" % (message, evalue))
80         elif type(inner_exception) is Exception:
81             self.errf.write("ERROR(exception): %s - %s\n" % (message, evalue))
82             force_traceback = True
83         elif inner_exception is None:
84             self.errf.write("ERROR: %s\n" % (message))
85         else:
86             self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
87             force_traceback = True
88
89         if force_traceback or samba.get_debug_level() >= 3:
90             traceback.print_tb(etraceback)
91
92     def _create_parser(self):
93         parser = optparse.OptionParser(usage=self.synopsis, 
94                                        description=self.long_description)
95         parser.add_options(self.takes_options)
96         optiongroups = {}
97         for name, optiongroup in self.takes_optiongroups.iteritems():
98             optiongroups[name] = optiongroup(parser)
99             parser.add_option_group(optiongroups[name])
100         return parser, optiongroups
101
102     def message(self, text):
103         print text
104
105     def _run(self, *argv):
106         parser, optiongroups = self._create_parser()
107         opts, args = parser.parse_args(list(argv))
108         # Filter out options from option groups
109         args = args[1:]
110         kwargs = dict(opts.__dict__)
111         for option_group in parser.option_groups:
112             for option in option_group.option_list:
113                 if option.dest is not None:
114                     del kwargs[option.dest]
115         kwargs.update(optiongroups)
116
117         # Check for a min a max number of allowed arguments, whenever possible
118         # The suffix "?" means zero or one occurence
119         # The suffix "+" means at least one occurence
120         min_args = 0
121         max_args = 0
122         undetermined_max_args = False
123         for i, arg in enumerate(self.takes_args):
124             if arg[-1] != "?":
125                min_args += 1
126             if arg[-1] == "+":
127                undetermined_max_args = True
128             else:
129                max_args += 1
130         if (len(args) < min_args) or (undetermined_max_args == False and len(args) > max_args):
131             parser.print_usage()
132             return -1
133
134         try:
135             return self.run(*args, **kwargs)
136         except Exception, e:
137             self.show_command_error(e)
138             return -1
139
140     def run(self):
141         """Run the command. This should be overriden by all subclasses."""
142         raise NotImplementedError(self.run)
143
144
145
146 class SuperCommand(Command):
147     """A samba-tool command with subcommands."""
148
149     subcommands = {}
150
151     def _run(self, myname, subcommand=None, *args):
152         if subcommand in self.subcommands:
153             return self.subcommands[subcommand]._run(subcommand, *args)
154         
155         if (myname == "samba-tool"):
156             usage = "samba-tool <subcommand>"
157         else:
158             usage = "samba-tool %s <subcommand>" % myname
159         print "Usage: %s [options]" %usage        
160         print "Available subcommands:"
161         subcmds = self.subcommands.keys()
162         subcmds.sort()
163         max_length = max(map(lambda c: len(c), subcmds))
164         for cmd in subcmds:
165             print "  %*s  - %s" % (-max_length, cmd, self.subcommands[cmd].description)
166         if subcommand in [None]:
167             raise CommandError("You must specify a subcommand")
168         if subcommand in ['help', '-h', '--help']:
169             print "For more help on a specific subcommand, please type: %s (-h|--help)" % usage
170             return 0
171         raise CommandError("No such subcommand '%s'" % subcommand)
172
173
174
175 class CommandError(Exception):
176     '''an exception class for samba-tool cmd errors'''
177     def __init__(self, message, inner_exception=None):
178         self.message = message
179         self.inner_exception = inner_exception
180         self.exception_info = sys.exc_info()