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
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.
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.
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/>.
22 import optparse, samba
23 from samba import getopt as options
24 from ldb import LdbError
29 class Option(optparse.Option):
34 class Command(object):
35 """A samba-tool command."""
37 def _get_short_description(self):
38 return self.__doc__.splitlines()[0].rstrip("\n")
40 short_description = property(_get_short_description)
42 def _get_full_description(self):
43 lines = self.__doc__.split("\n")
44 return lines[0] + "\n" + textwrap.dedent("\n".join(lines[1:]))
46 full_description = property(_get_full_description)
49 name = self.__class__.__name__
50 if name.startswith("cmd_"):
54 name = property(_get_name)
56 # synopsis must be defined in all subclasses in order to provide the
61 takes_optiongroups = {
62 "sambaopts": options.SambaOptions,
63 "credopts": options.CredentialsOptions,
64 "versionopts": options.VersionOptions,
69 def usage(self, *args):
70 parser, _ = self._create_parser()
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
79 force_traceback = False
81 (etype, evalue, etraceback) = sys.exc_info()
83 message = "uncaught exception"
84 force_traceback = True
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))
100 self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
101 force_traceback = True
103 if force_traceback or samba.get_debug_level() >= 3:
104 traceback.print_tb(etraceback)
106 def _create_parser(self):
107 parser = optparse.OptionParser(usage=self.synopsis,
108 description=self.full_description)
109 parser.add_options(self.takes_options)
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
116 def message(self, text):
117 self.outf.write(text+"\n")
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
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)
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
136 undetermined_max_args = False
137 for i, arg in enumerate(self.takes_args):
141 undetermined_max_args = True
144 if (len(args) < min_args) or (undetermined_max_args == False and len(args) > max_args):
149 return self.run(*args, **kwargs)
151 self.show_command_error(e)
155 """Run the command. This should be overriden by all subclasses."""
156 raise NotImplementedError(self.run)
158 def get_logger(self, name="netcmd"):
159 """Get a logger object."""
161 logger = logging.getLogger(name)
162 logger.addHandler(logging.StreamHandler(self.outf))
166 class SuperCommand(Command):
167 """A samba-tool command with subcommands."""
171 def _run(self, myname, subcommand=None, *args):
172 if subcommand in self.subcommands:
173 return self.subcommands[subcommand]._run(subcommand, *args)
175 if myname == "samba-tool":
176 usage = "samba-tool <subcommand>"
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()
183 max_length = max([len(c) for c 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)
192 raise CommandError("No such subcommand '%s'" % subcommand)
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()