Completed
Pull Request — master (#303)
by Björn
24:34
created

BaseEventLoop._on_signal()   A

Complexity

Conditions 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 12.192

Importance

Changes 0
Metric Value
cc 4
c 0
b 0
f 0
dl 0
loc 13
ccs 2
cts 10
cp 0.2
crap 12.192
rs 9.2
1
"""Common code for event loop implementations."""
2 5
import logging
3 5
import signal
4 5
import threading
5
6
7 5
logger = logging.getLogger(__name__)
8 5
debug, info, warn = (logger.debug, logger.info, logger.warning,)
9
10
11
# When signals are restored, the event loop library may reset SIGINT to SIG_DFL
12
# which exits the program. To be able to restore the python interpreter to it's
13
# default state, we keep a reference to the default handler
14 5
default_int_handler = signal.getsignal(signal.SIGINT)
15 5
main_thread = threading.current_thread()
16
17
18 5
class BaseEventLoop(object):
19
20
    """Abstract base class for all event loops.
21
22
    Event loops act as the bottom layer for Nvim sessions created by this
23
    library. They hide system/transport details behind a simple interface for
24
    reading/writing bytes to the connected Nvim instance.
25
26
    This class exposes public methods for interacting with the underlying
27
    event loop and delegates implementation-specific work to the following
28
    methods, which subclasses are expected to implement:
29
30
    - `_init()`: Implementation-specific initialization
31
    - `_connect_tcp(address, port)`: connect to Nvim using tcp/ip
32
    - `_connect_socket(path)`: Same as tcp, but use a UNIX domain socket or
33
      or named pipe.
34
    - `_connect_stdio()`: Use stdin/stdout as the connection to Nvim
35
    - `_connect_child(argv)`: Use the argument vector `argv` to spawn an
36
      embedded Nvim that has it's stdin/stdout connected to the event loop.
37
    - `_start_reading()`: Called after any of _connect_* methods. Can be used
38
      to perform any post-connection setup or validation.
39
    - `_send(data)`: Send `data`(byte array) to Nvim. The data is only
40
    - `_run()`: Runs the event loop until stopped or the connection is closed.
41
      calling the following methods when some event happens:
42
      actually sent when the event loop is running.
43
      - `_on_data(data)`: When Nvim sends some data.
44
      - `_on_signal(signum)`: When a signal is received.
45
      - `_on_error(message)`: When a non-recoverable error occurs(eg:
46
        connection lost)
47
    - `_stop()`: Stop the event loop
48
    - `_interrupt(data)`: Like `stop()`, but may be called from other threads
49
      this.
50
    - `_setup_signals(signals)`: Add implementation-specific listeners for
51
      for `signals`, which is a list of OS-specific signal numbers.
52
    - `_teardown_signals()`: Removes signal listeners set by `_setup_signals`
53
    """
54
55 5
    def __init__(self, transport_type, *args):
56
        """Initialize and connect the event loop instance.
57
58
        The only arguments are the transport type and transport-specific
59
        configuration, like this:
60
61
        >>> BaseEventLoop('tcp', '127.0.0.1', 7450)
62
        Traceback (most recent call last):
63
            ...
64
        AttributeError: 'BaseEventLoop' object has no attribute '_init'
65
        >>> BaseEventLoop('socket', '/tmp/nvim-socket')
66
        Traceback (most recent call last):
67
            ...
68
        AttributeError: 'BaseEventLoop' object has no attribute '_init'
69
        >>> BaseEventLoop('stdio')
70
        Traceback (most recent call last):
71
            ...
72
        AttributeError: 'BaseEventLoop' object has no attribute '_init'
73
        >>> BaseEventLoop('child', ['nvim', '--embed', '-u', 'NONE'])
74
        Traceback (most recent call last):
75
            ...
76
        AttributeError: 'BaseEventLoop' object has no attribute '_init'
77
78
        This calls the implementation-specific initialization
79
        `_init`, one of the `_connect_*` methods(based on `transport_type`)
80
        and `_start_reading()`
81
        """
82 5
        self._transport_type = transport_type
83 5
        self._signames = dict((k, v) for v, k in signal.__dict__.items()
84
                              if v.startswith('SIG'))
85 5
        self._on_data = None
86 5
        self._error = None
87 5
        self._init()
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _init.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
88 5
        try:
89 5
            getattr(self, '_connect_{}'.format(transport_type))(*args)
90
        except Exception as e:
91 5
            self.close()
92
            raise e
93
        self._start_reading()
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _start_reading.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
94
95
    def connect_tcp(self, address, port):
96 5
        """Connect to tcp/ip `address`:`port`. Delegated to `_connect_tcp`."""
97
        info('Connecting to TCP address: %s:%d', address, port)
98
        self._connect_tcp(address, port)
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _connect_tcp.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
99
100
    def connect_socket(self, path):
101 5
        """Connect to socket at `path`. Delegated to `_connect_socket`."""
102
        info('Connecting to %s', path)
103
        self._connect_socket(path)
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _connect_socket.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
104
105
    def connect_stdio(self):
106 5
        """Connect using stdin/stdout. Delegated to `_connect_stdio`."""
107
        info('Preparing stdin/stdout for streaming data')
108
        self._connect_stdio()
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _connect_stdio.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
109
110
    def connect_child(self, argv):
111 5
        """Connect a new Nvim instance. Delegated to `_connect_child`."""
112
        info('Spawning a new nvim instance')
113 5
        self._connect_child(argv)
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _connect_child.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
114 5
115
    def send(self, data):
116 5
        """Queue `data` for sending to Nvim."""
117
        debug("Sending '%s'", data)
118
        self._send(data)
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _send.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
119
120
    def threadsafe_call(self, fn):
121
        """Call a function in the event loop thread.
122 5
123
        This is the only safe way to interact with a session from other
124 5
        threads.
125
        """
126 5
        self._threadsafe_call(fn)
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _threadsafe_call.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
127
128
    def run(self, data_cb):
129
        """Run the event loop."""
130
        if self._error:
131
            err = self._error
132
            if isinstance(self._error, KeyboardInterrupt):
133
                # KeyboardInterrupt is not destructive(it may be used in
134
                # the REPL).
135 5
                # After throwing KeyboardInterrupt, cleanup the _error field
136 5
                # so the loop may be started again
137 5
                self._error = None
138 5
            raise err
0 ignored issues
show
Bug introduced by
Raising NoneType while only classes or instances are allowed
Loading history...
139 5
        self._on_data = data_cb
140 5
        if threading.current_thread() == main_thread:
141 5
            self._setup_signals([signal.SIGINT, signal.SIGTERM])
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _setup_signals.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
142 5
        debug('Entering event loop')
143 5
        self._run()
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _run.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
144 5
        debug('Exited event loop')
145
        if threading.current_thread() == main_thread:
146 5
            self._teardown_signals()
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _teardown_signals.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
147
            signal.signal(signal.SIGINT, default_int_handler)
148 5
        self._on_data = None
149 5
150
    def stop(self):
151 5
        """Stop the event loop."""
152
        self._stop()
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _stop.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
153
        debug('Stopped event loop')
154
155
    def close(self):
156
        """Stop the event loop."""
157
        self._close()
0 ignored issues
show
Bug introduced by
The Instance of BaseEventLoop does not seem to have a member named _close.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
158
        debug('Closed event loop')
159
160
    def _on_signal(self, signum):
161
        msg = 'Received {}'.format(self._signames[signum])
162
        debug(msg)
163
        if signum == signal.SIGINT and self._transport_type == 'stdio':
164
            # When the transport is stdio, we are probably running as a Nvim
165 5
            # child process. In that case, we don't want to be killed by
166
            # ctrl+C
167
            return
168
        cls = Exception
169
        if signum == signal.SIGINT:
170 5
            cls = KeyboardInterrupt
171
        self._error = cls(msg)
172
        self.stop()
173
174
    def _on_error(self, error):
175
        debug(error)
176
        self._error = IOError(error)
177
        self.stop()
178
179
    def _on_interrupt(self):
180
        self.stop()
181