summaryrefslogtreecommitdiff
path: root/distbuild-helper
blob: cdc1873e4c1cac3c84d7dd228bbb144442dc7b97 (plain)
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#!/usr/bin/python
#
# distbuild-helper -- helper process for Morph distributed building
#
# Copyright (C) 2014  Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA..

import cliapp
import errno
import fcntl
import httplib
import logging
import os
import signal
import socket
import subprocess
import sys
import time
import urlparse

import distbuild


class FileReadable(object):

    def __init__(self, request_id, p, f):
        self.request_id = request_id
        self.process = p
        self.file = f


class FileWriteable(object):

    def __init__(self, request_id, p, f):
        self.request_id = request_id
        self.process = p
        self.file = f


class SubprocessEventSource(distbuild.EventSource):

    def __init__(self):
        self.procs = []
        self.closed = False

    def get_select_params(self):
        r = []
        w = []
        for requst_id, p in self.procs:
            if p.stdin_contents is not None:
                w.append(p.stdin)
            if p.stdout is not None:
                r.append(p.stdout)
            if p.stderr is not None:
                r.append(p.stderr)
        return r, w, [], None

    def get_events(self, r, w, x):
        events = []

        for request_id, p in self.procs:
            if p.stdin in w:
                events.append(FileWriteable(request_id, p, p.stdin))
            if p.stdout in r:
                events.append(FileReadable(request_id, p, p.stdout))
            if p.stderr in r:
                events.append(FileReadable(request_id, p, p.stderr))

        return events

    def add(self, request_id, process):

        self.procs.append((request_id, process))
        distbuild.set_nonblocking(process.stdin)
        distbuild.set_nonblocking(process.stdout)
        distbuild.set_nonblocking(process.stderr)

    def remove(self, process):
        self.procs = [t for t in self.procs if t[1] != process]

    def kill_by_id(self, request_id):
        logging.debug('SES: Killing all processes for %s', request_id)
        for id, process in self.procs:
            if id == request_id:
                logging.debug('SES: killing %s', repr(process))
                process.kill()

    def close(self):
        self.procs = []
        self.closed = True

    def is_finished(self):
        return self.closed


class HelperMachine(distbuild.StateMachine):

    def __init__(self, conn):
        distbuild.StateMachine.__init__(self, 'waiting')
        self.conn = conn
        self.debug_messages = False

    def setup(self):
        distbuild.crash_point()

        jm = self.jm = distbuild.JsonMachine(self.conn)
        self.mainloop.add_state_machine(jm)

        p = self.procsrc = SubprocessEventSource()
        self.mainloop.add_event_source(p)

        self.send_helper_ready(jm)

        spec = [
            ('waiting', jm, distbuild.JsonNewMessage, 'waiting', self.do),
            ('waiting', jm, distbuild.JsonEof, None, self._eofed),
            ('waiting', p, FileReadable, 'waiting', self._relay_exec_output),
            ('waiting', p, FileWriteable, 'waiting', self._feed_stdin),
        ]
        self.add_transitions(spec)

    def send_helper_ready(self, jm):
        msg = {
            'type': 'helper-ready',
        }
        jm.send(msg)
        logging.debug('HelperMachine: sent: %s', repr(msg))

    def do(self, parent, event):
        distbuild.crash_point()

        logging.debug('JsonMachine: got: %s', repr(event.msg))
        handlers = {
            'http-request': self.do_http_request,
            'exec-request': self.do_exec_request,
            'exec-cancel': self.do_exec_cancel,
        }
        handler = handlers.get(event.msg['type'])
        handler(parent, event.msg)

    def do_http_request(self, parent, msg):
        distbuild.crash_point()

        url = msg['url']
        method = msg['method']
        headers = msg['headers']
        body = msg['body']
        assert method in ('HEAD', 'GET', 'POST')

        logging.debug('JsonMachine: http request: %s %s' % (method, url))

        schema, netloc, path, query, fragment = urlparse.urlsplit(url)
        assert schema == 'http'
        if query:
            path += '?' + query

        try:
            conn = httplib.HTTPConnection(netloc)

            if headers:
                conn.request(method, path, body, headers)
            else:
                conn.request(method, path, body)
        except (socket.error, httplib.HTTPException), e:
            status = 418 # teapot
            data = str(e)
        else:
            res = conn.getresponse()
            status = res.status
            data = res.read()
        conn.close()

        response = {
            'type': 'http-response',
            'id': msg['id'],
            'status': status,
            'body': data,
        }
        parent.send(response)
        logging.debug('JsonMachine: sent to parent: %s', repr(response))
        self.send_helper_ready(parent)

    def do_exec_request(self, parent, msg):
        distbuild.crash_point()

        argv = msg['argv']
        stdin_contents = msg.get('stdin_contents', '')
        logging.debug('JsonMachine: exec request: argv=%s', repr(argv))
        logging.debug(
            'JsonMachine: exec request: stdin=%s', repr(stdin_contents))

        p = subprocess.Popen(argv,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

        p.stdin_contents = stdin_contents

        self.procsrc.add(msg['id'], p)

    def do_exec_cancel(self, parent, msg):
        distbuild.crash_point()

        self.procsrc.kill_by_id(msg['id'])

    def _relay_exec_output(self, event_source, event):
        distbuild.crash_point()

        buf_size = 16 * 1024
        fd = event.file.fileno()
        data = os.read(fd, buf_size)
        if data:
            if event.file == event.process.stdout:
                stream = 'stdout'
                other = 'stderr'
            else:
                stream = 'stderr'
                other = 'stdout'
            msg = {
                'type': 'exec-output',
                'id': event.request_id,
                stream: data,
                other: '',
            }
            logging.debug('JsonMachine: sent to parent: %s', repr(msg))
            self.jm.send(msg)
        else:
            if event.file == event.process.stdout:
                event.process.stdout.close()
                event.process.stdout = None
            else:
                event.process.stderr.close()
                event.process.stderr = None

            if event.process.stdout == event.process.stderr == None:
                event.process.wait()
                self.procsrc.remove(event.process)
                msg = {
                    'type': 'exec-response',
                    'id': event.request_id,
                    'exit': event.process.returncode,
                }
                logging.debug('JsonMachine: sent to parent: %s', repr(msg))
                self.jm.send(msg)
                self.send_helper_ready(self.jm)

    def _feed_stdin(self, event_source, event):
        distbuild.crash_point()

        fd = event.file.fileno()
        try:
            n = os.write(fd, event.process.stdin_contents)
        except os.error, e:
            # If other end closed the read end, stop writing.
            if e.errno == errno.EPIPE:
                logging.debug('JsonMachine: reader closed pipe')
                event.process.stdin_contents = ''
            else:
                raise
        else:
            logging.debug('JsonMachine: fed %d bytes to stdin', n)
            event.process.stdin_contents = event.process.stdin_contents[n:]
        if event.process.stdin_contents == '':
            logging.debug('JsonMachine: stdin contents finished, closing')
            event.file.close()
            event.process.stdin_contents = None

    def _eofed(self, event_source, event):
        distbuild.crash_point()
        logging.info('eof from parent, closing')
        event_source.close()
        self.procsrc.close()


class DistributedBuildHelper(cliapp.Application):

    def add_settings(self):
        self.settings.string(
            ['parent-address'],
            'address (hostname/ip address) for parent',
            metavar='HOSTNAME',
            default='localhost')
        self.settings.integer(
            ['parent-port'],
            'port number for parent',
            metavar='PORT',
            default=3434)
        self.settings.boolean(
            ['debug-messages'],
            'log messages that are received?')
        self.settings.string_list(
            ['crash-condition'],
            'add FILENAME:FUNCNAME:MAXCALLS to list of crash conditions '
                '(this is for testing only)',
            metavar='FILENAME:FUNCNAME:MAXCALLS')

    def process_args(self, args):
        distbuild.add_crash_conditions(self.settings['crash-condition'])

        # We don't want SIGPIPE, ever. It just kills us. We handle EPIPE
        # instead.
        signal.signal(signal.SIGPIPE, signal.SIG_IGN)

        addr = self.settings['parent-address']
        port = self.settings['parent-port']
        conn = distbuild.create_socket()
        conn.connect((addr, port))
        helper = HelperMachine(conn)
        helper.debug_messages = self.settings['debug-messages']
        loop = distbuild.MainLoop()
        loop.add_state_machine(helper)
        loop.run()


DistributedBuildHelper().run()