~cr3/checkbox/core

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#
# Copyright (c) 2012 Canonical
#
# This file is part of Checkbox.
#
# Storm is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# Storm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
__metaclass__ = type

__all__ = [
    "Pipe",
    ]

import logging

from checkbox.lib.file import File

from checkbox.io.selector import (
    Selector,
    SelectorIO,
    )
from checkbox.io.stream import Stream


# Number of bytes in atomic write to a pipe.
PIPE_BUF = 2 ** 12


class Pipe(Stream):

    __slots__ = (
        "_fd",
        "_bytes",
        "_reader",
        "_writer",
        "_watchdog_client",
        "_watchdog_server",
        )

    _buffer_size = PIPE_BUF

    def __init__(self):
        super(Pipe, self).__init__()
        self._fd = None
        self._bytes = ""
        self._reader = File()
        self._writer = File()
        self._watchdog_client = None
        self._watchdog_server = None

    def fileno(self):
        return self._fd

    def get_description(self):
        if self._fd is None:
            return None

        return "fd:%d" % self._fd

    def connect_to_fd(self, fd):
        self._fd = fd
        return self._writer.initialize_from_fd(fd, "w")

    def listen_on_fd(self, fd):
        self._fd = fd
        return self._reader.initialize_from_fd(fd, "r")

    def handle_incoming_message(self):
        """Receive messages from the reader and buffer them.

        :return: Whether a message becomes ready.
        """
        bytes = self.get_bytes_raw(PIPE_BUF)
        if bytes is None:
            return False

        self._bytes += bytes

        return True

    def get_bytes(self, size=-1):
        """See Stream.get_bytes"""
        if size < 0:
            size = self._buffer_size
        else:
            size = min(size, self._buffer_size)

        while size > len(self._bytes):
            if not self.handle_incoming_message():
                break

        size = min(size, len(self._bytes))
        bytes = self._bytes[:size]
        self._bytes = self._bytes[size:]

        return bytes

    def get_bytes_raw(self, size):
        """Get bytes directly from the source.

        :param size: Number of bytes to get.
        :return: Bytes gotten.
        """
        read_fd = self._reader.fileno()

        selector = Selector()
        selector.set_timeout(self._timeout)
        selector.add_fd(read_fd, SelectorIO.READ)

        # Select with both the real and watchdog descriptors
        if self._watchdog_client:
            selector.add_fd(self._watchdog_client.fileno(), SelectorIO.READ)

        selector.execute()

        if selector.has_timed_out:
            return None
        elif not selector.has_ready:
            return None

        if (self._watchdog_client and
            selector.check_fd(
                self._watchdog_client.fileno(), SelectorIO.READ) and
            not selector.check_fd(read_fd, SelectorIO.READ)):
            logging.info("Error reading from source, watchdog side closed")
            return None

        bytes = self._reader.read(size)
        if bytes is None:
            logging.info(
                "Error reading from source, errno %d", self._reader.errno)

        return bytes

    def get_end(self):
        return True

    def peek(self):
        """See Stream.peek"""
        while not self._bytes:
            if not self.handle_incoming_message():
                return None

        return self._bytes[0]

    def search(self, sub):
        """See Stream.search"""
        bytes = ""
        position = 0
        while True:
            index = self._bytes.find(sub, position)
            if index >= 0:
                bytes = self._bytes[:index]
                self._bytes = self._bytes[index + len(sub):]
                break

            position = len(self._bytes)

            if not self.handle_incoming_message():
                return None

        return bytes

    def put_bytes(self, bytes):
        """See Stream.put_bytes"""
        if len(bytes) > self._buffer_size:
            bytes = bytes[:self._buffer_size]

        return self.put_bytes_raw(bytes)

    def put_bytes_raw(self, bytes):
        """Put bytes directly onto the destination.

        :param bytes: Bytes to put.
        :return: Number of bytes put.
        """
        # Select with both the real and watchdog descriptors
        if self._watchdog_client:
            writer_fd = self._writer.fileno()
            watchdog_fd = self._watchdog_client.fileno()

            selector = Selector()
            selector.add_fd(writer_fd, SelectorIO.WRITE)
            selector.add_fd(watchdog_fd, SelectorIO.READ)

            selector.execute()

            if not selector.has_ready:
                logging.info("Put bytes failed")
                return -1

            if selector.check_fd(watchdog_fd, SelectorIO.READ):
                logging.info("Error writing to fifo, watchdog side closed")
                return -1

        size = self._writer.write(bytes)
        if size < 0:
            logging.info(
                "Error writing to fifo, errno %d", self._writer.errno)

        return size

    def put_end(self):
        return True