samba.netcmd: Reintroduce Command.name.
[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 import textwrap
27
28
29 class Option(optparse.Option):
30     pass
31
32
33
34 class Command(object):
35     """A samba-tool command."""
36
37     def _get_short_description(self):
38         return self.__doc__.splitlines()[0].rstrip("\n")
39
40     short_description = property(_get_short_description)
41
42     def _get_full_description(self):
43         lines = self.__doc__.split("\n")
44         return lines[0] + "\n" + textwrap.dedent("\n".join(lines[1:]))
45
46     full_description = property(_get_full_description)
47
48     def _get_name(self):
49         name = self.__class__.__name__
50         if name.startswith("cmd_"):
51             return name[4:]
52         return name
53
54     name = property(_get_name)
55
56     # synopsis must be defined in all subclasses in order to provide the
57     # command usage
58     synopsis = None
59     takes_args = []
60     takes_options = []
61     takes_optiongroups = {
62         "sambaopts": options.SambaOptions,
63         "credopts": options.CredentialsOptions,
64         "versionopts": options.VersionOptions,
65         }
66     outf = sys.stdout
67     errf = sys.stderr
68
69     def usage(self, *args):
70         parser, _ = self._create_parser()
71         parser.print_usage()
72
73     def show_command_error(self, e):
74         '''display a command error'''
75         if isinstance(e, CommandError):
76             (etype, evalue, etraceback) = e.exception_info
77             inner_exception = e.inner_exception
78             message = e.message
79             force_traceback = False
80         else:
81             (etype, evalue, etraceback) = sys.exc_info()
82             inner_exception = e
83             message = "uncaught exception"
84             force_traceback = True
85
86         if isinstance(inner_exception, LdbError):
87             (ldb_ecode, ldb_emsg) = inner_exception
88             self.errf.write("ERROR(ldb): %s - %s\n" % (message, ldb_emsg))
89         elif isinstance(inner_exception, AssertionError):
90             self.errf.write("ERROR(assert): %s\n" % message)
91             force_traceback = True
92         elif isinstance(inner_exception, RuntimeError):
93             self.errf.write("ERROR(runtime): %s - %s\n" % (message, evalue))
94         elif type(inner_exception) is Exception:
95             self.errf.write("ERROR(exception): %s - %s\n" % (message, evalue))
96             force_traceback = True
97         elif inner_exception is None:
98             self.errf.write("ERROR: %s\n" % (message))
99         else:
100             self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
101             force_traceback = True
102
103         if force_traceback or samba.get_debug_level() >= 3:
104             traceback.print_tb(etraceback)
105
106     def _create_parser(self):
107         parser = optparse.OptionParser(usage=self.synopsis, 
108                                        description=self.full_description)
109         parser.add_options(self.takes_options)
110         optiongroups = {}
111         for name, optiongroup in self.takes_optiongroups.iteritems():
112             optiongroups[name] = optiongroup(parser)
113             parser.add_option_group(optiongroups[name])
114         return parser, optiongroups
115
116     def message(self, text):
117         self.outf.write(text+"\n")
118
119     def _run(self, *argv):
120         parser, optiongroups = self._create_parser()
121         opts, args = parser.parse_args(list(argv))
122         # Filter out options from option groups
123         args = args[1:]
124         kwargs = dict(opts.__dict__)
125         for option_group in parser.option_groups:
126             for option in option_group.option_list:
127                 if option.dest is not None:
128                     del kwargs[option.dest]
129         kwargs.update(optiongroups)
130
131         # Check for a min a max number of allowed arguments, whenever possible
132         # The suffix "?" means zero or one occurence
133         # The suffix "+" means at least one occurence
134         min_args = 0
135         max_args = 0
136         undetermined_max_args = False
137         for i, arg in enumerate(self.takes_args):
138             if arg[-1] != "?":
139                min_args += 1
140             if arg[-1] == "+":
141                undetermined_max_args = True
142             else:
143                max_args += 1
144         if (len(args) < min_args) or (undetermined_max_args == False and len(args) > max_args):
145             parser.print_usage()
146             return -1
147
148         try:
149             return self.run(*args, **kwargs)
150         except Exception, e:
151             self.show_command_error(e)
152             return -1
153
154     def run(self):
155         """Run the command. This should be overriden by all subclasses."""
156         raise NotImplementedError(self.run)
157
158     def get_logger(self, name="netcmd"):
159         """Get a logger object."""
160         import logging
161         logger = logging.getLogger(name)
162         logger.addHandler(logging.StreamHandler(self.outf))
163         return logger
164
165
166 class SuperCommand(Command):
167     """A samba-tool command with subcommands."""
168
169     subcommands = {}
170
171     def _run(self, myname, subcommand=None, *args):
172         if subcommand in self.subcommands:
173             return self.subcommands[subcommand]._run(subcommand, *args)
174
175         if myname == "samba-tool":
176             usage = "samba-tool <subcommand>"
177         else:
178             usage = "samba-tool %s <subcommand>" % myname
179         self.outf.write("Usage: %s [options]\n" % usage)
180         self.outf.write("Available subcommands:\n")
181         subcmds = self.subcommands.keys()
182         subcmds.sort()
183         max_length = max([len(c) for c in subcmds])
184         for cmd in subcmds:
185             self.outf.write("  %*s  - %s\n" % (
186                 -max_length, cmd, self.subcommands[cmd].short_description))
187         if subcommand in [None]:
188             raise CommandError("You must specify a subcommand")
189         if subcommand in ['help', '-h', '--help']:
190             self.outf.write("For more help on a specific subcommand, please type: %s (-h|--help)\n" % usage)
191             return 0
192         raise CommandError("No such subcommand '%s'" % subcommand)
193
194
195
196 class CommandError(Exception):
197     '''an exception class for samba-tool cmd errors'''
198     def __init__(self, message, inner_exception=None):
199         self.message = message
200         self.inner_exception = inner_exception
201         self.exception_info = sys.exc_info()