|
1 | 1 |
|
2 | 2 |
|
3 | | -import logging |
| 3 | +from sys import stdout, stderr |
4 | 4 |
|
5 | | -from .commands import call |
| 5 | +from .commands import call |
| 6 | +from .output import RED, NONE |
6 | 7 |
|
7 | 8 |
|
8 | 9 | class Nodetool(object): |
9 | 10 | def __init__(self, host, port): |
10 | 11 | self.host = host |
11 | | - self.port = str(port) |
| 12 | + self.port = port |
| 13 | + |
| 14 | + def run(self, *args, **kwargs): |
| 15 | + writer = kwargs.get("output", NodetoolOutputWriter()) |
| 16 | + assert isinstance(writer, NodetoolOutputWriter) |
| 17 | + |
| 18 | + command = ["nodetool", "--host", self.host, "--port", str(self.port)] + list(args) |
| 19 | + (retcode, output, error) = call(*command) |
| 20 | + |
| 21 | + writer.output(output) |
| 22 | + writer.error(error) |
12 | 23 |
|
13 | | - def run(self, *args): |
14 | | - command = ["nodetool", "--host", self.host, "--port", self.port] + list(args) |
15 | | - retcode = call(*command) |
16 | 24 | if retcode != 0: |
17 | | - raise NodetoolCmdException("nodetool returned status {}".format(retcode)) |
| 25 | + raise NodetoolCommandException( |
| 26 | + "nodetool command returned exit code {}".format(retcode), |
| 27 | + retcode) |
| 28 | + |
| 29 | + def __repr__(self): |
| 30 | + return "Nodetool({}, {})".format(self.host, self.port) |
| 31 | + |
| 32 | + def __str__(self): |
| 33 | + return "{}:{}".format(self.host, self.port) |
| 34 | + |
| 35 | +class NodetoolOutputWriter(object): |
| 36 | + def __init__(self, color=None, bold=False, prefix=None): |
| 37 | + self.color = color if color else NONE |
| 38 | + self.bold = bold |
| 39 | + self.prefix = prefix |
| 40 | + |
| 41 | + def output(self, text): |
| 42 | + data = text.rstrip() |
| 43 | + if data: |
| 44 | + for line in data.split('\n'): |
| 45 | + print >>stdout, self.color("{}{}".format(self.__prefix(), line), self.bold) |
| 46 | + |
| 47 | + def error(self, text): |
| 48 | + data = text.rstrip() |
| 49 | + if data: |
| 50 | + for line in data.split('\n'): |
| 51 | + print >>stderr, RED("{}{}".format(self.__prefix(), line), True) |
| 52 | + |
| 53 | + def __prefix(self): |
| 54 | + return "{}: ".format(self.prefix) if self.prefix else "" |
| 55 | + |
| 56 | + def __repr__(self): |
| 57 | + return "NodetoolOutputWriter(prefix={})".format(self.prefix) |
| 58 | + |
| 59 | + def __str__(self): |
| 60 | + return repr(self) |
| 61 | + |
| 62 | +class NodetoolCommandException(Exception): |
| 63 | + def __init__(self, message, retcode): |
| 64 | + self.retcode = retcode |
| 65 | + super(NodetoolCommandException, self).__init__(message) |
18 | 66 |
|
19 | | -class NodetoolCmdException(Exception): |
20 | | - pass |
|
0 commit comments