~allenap/maas/regiond-leader

« back to all changes in this revision

Viewing changes to src/provisioningserver/utils/introspect.py

  • Committer: MAAS Lander
  • Author(s): Gavin Panella
  • Date: 2015-04-24 17:47:07 UTC
  • mfrom: (3759.4.18 introspect-service)
  • Revision ID: maas_lander-20150424174707-9eqa8y0bedjz0vm2
[r=rbanffy][bug=][author=allenap] Allow interactive introspection of running MAAS daemons.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2014 Canonical Ltd.  This software is licensed under the
 
2
# GNU Affero General Public License version 3 (see the file LICENSE).
 
3
 
 
4
"""Twisted Application Plugin code for the MAAS Region."""
 
5
 
 
6
from __future__ import (
 
7
    absolute_import,
 
8
    print_function,
 
9
    unicode_literals,
 
10
    )
 
11
 
 
12
str = None
 
13
 
 
14
__metaclass__ = type
 
15
__all__ = [
 
16
    "IntrospectionShellService",
 
17
    "serverFromString",
 
18
]
 
19
 
 
20
from twisted.application.internet import StreamServerEndpointService
 
21
from twisted.conch import manhole
 
22
from twisted.conch.insults import insults
 
23
from twisted.internet import (
 
24
    endpoints,
 
25
    reactor,
 
26
)
 
27
from twisted.internet.interfaces import IProtocolFactory
 
28
from zope.interface import implementer
 
29
 
 
30
 
 
31
def byteString(thing):
 
32
    """Convert `string` to a byte string."""
 
33
    if isinstance(thing, bytes):
 
34
        return thing
 
35
    elif isinstance(thing, unicode):
 
36
        return thing.encode("utf-8")
 
37
    else:
 
38
        raise TypeError(
 
39
            "Cannot safely convert %r to a byte string."
 
40
            % (thing,))
 
41
 
 
42
 
 
43
def serverFromString(description):
 
44
    """Parse `description` into an endpoint.
 
45
 
 
46
    Twisted's `endpoints.serverFromString` raises errors that are not
 
47
    particularly user-friendly, so we attempt something better here.
 
48
    """
 
49
    description = byteString(description)
 
50
    try:
 
51
        return endpoints.serverFromString(reactor, description)
 
52
    except ValueError:
 
53
        raise ValueError(
 
54
            "Could not understand server description %r. "
 
55
            "Try something like %r or %r." % (
 
56
                description, b"unix:/path/to/file:mode=660:lockfile=0",
 
57
                b"tcp:1234:interface=127.0.0.1"))
 
58
 
 
59
 
 
60
class Help(object):
 
61
    """Define the builtin 'help'.
 
62
 
 
63
    This is a wrapper around pydoc.help... with a twist, in that it disallows
 
64
    interactive use.
 
65
    """
 
66
 
 
67
    def __repr__(self):
 
68
        message = "Type help(object) for help about object."
 
69
        return message.encode("utf-8")
 
70
 
 
71
    def __call__(self, *args, **kwds):
 
72
        if len(args) == 0:
 
73
            message = "Interactive help has been disabled. %r" % self
 
74
            print(message.encode("utf-8"))
 
75
        else:
 
76
            from pydoc import help
 
77
            return help(*args, **kwds)
 
78
 
 
79
 
 
80
class IntrospectionShell(manhole.ColoredManhole):
 
81
 
 
82
    STYLE_BRIGHT_ON = '\x1b[1m'
 
83
    STYLE_OFF = '\x1b[0m'
 
84
 
 
85
    COLOUR_RED_ON = '\x1b[31m'
 
86
    COLOUR_MAGENTA_ON = '\x1b[35m'
 
87
    COLOUR_OFF = '\x1b[39m'
 
88
 
 
89
    def __init__(self, namespace=None):
 
90
        super(IntrospectionShell, self).__init__(namespace)
 
91
        self.ensureThereIsHelp()
 
92
 
 
93
    def ensureThereIsHelp(self):
 
94
        if self.namespace is None:
 
95
            self.namespace = {"help": Help()}
 
96
        elif "help" in self.namespace:
 
97
            pass  # Don't override.
 
98
        else:
 
99
            self.namespace["help"] = Help()
 
100
 
 
101
    def welcomeMessage(self):
 
102
        return "".join((
 
103
            self.STYLE_BRIGHT_ON,
 
104
            self.COLOUR_MAGENTA_ON,
 
105
            "Welcome to MAAS's Introspection Shell.",
 
106
            self.COLOUR_OFF,
 
107
            self.STYLE_OFF,
 
108
            "\n\n",
 
109
            self.STYLE_BRIGHT_ON,
 
110
            "This is the ",
 
111
            self.COLOUR_RED_ON,
 
112
            self.factory.location.upper(),
 
113
            self.COLOUR_OFF,
 
114
            ".",
 
115
            self.STYLE_OFF,
 
116
        ))
 
117
 
 
118
    def initializeScreen(self):
 
119
        """Override in order to provide welcome message."""
 
120
        self.terminal.reset()
 
121
        self.addOutput(b"\n")
 
122
        self.addOutput(self.welcomeMessage().encode("utf-8"))
 
123
        self.addOutput(b"\n")
 
124
        self.addOutput(b"\n")
 
125
        self.setInsertMode()
 
126
        self.drawInputLine()
 
127
 
 
128
 
 
129
@implementer(IProtocolFactory)
 
130
class IntrospectionShellFactory:
 
131
 
 
132
    def __init__(self, location, namespace):
 
133
        super(IntrospectionShellFactory, self).__init__()
 
134
        self.namespace = namespace
 
135
        self.location = location
 
136
 
 
137
    def buildProtocol(self, addr):
 
138
        proto = insults.ServerProtocol(
 
139
            IntrospectionShell, self.namespace)
 
140
        proto.factory = self
 
141
        return proto
 
142
 
 
143
    def doStart(self):
 
144
        """See `IProtocolFactory`."""
 
145
 
 
146
    def doStop(self):
 
147
        """See `IProtocolFactory`."""
 
148
 
 
149
 
 
150
class IntrospectionShellService(StreamServerEndpointService):
 
151
 
 
152
    def __init__(self, location, endpoint, namespace):
 
153
        factory = IntrospectionShellFactory(location, namespace=namespace)
 
154
        super(IntrospectionShellService, self).__init__(endpoint, factory)