Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 91f0dee799400e04a958583687df24ff76264400 (plain) (blame)
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//
//  ========================================================================
//  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.fcgi.client.http;

import java.io.EOFException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpConnection;
import org.eclipse.jetty.client.HttpDestination;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.fcgi.FCGI;
import org.eclipse.jetty.fcgi.generator.Flusher;
import org.eclipse.jetty.fcgi.parser.ClientParser;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.CompletableCallback;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

public class HttpConnectionOverFCGI extends AbstractConnection implements Connection
{
    private static final Logger LOG = Log.getLogger(HttpConnectionOverFCGI.class);

    private final LinkedList<Integer> requests = new LinkedList<>();
    private final Map<Integer, HttpChannelOverFCGI> channels = new ConcurrentHashMap<>();
    private final AtomicBoolean closed = new AtomicBoolean();
    private final Flusher flusher;
    private final HttpDestination destination;
    private final boolean multiplexed;
    private final Delegate delegate;
    private final ClientParser parser;
    private ByteBuffer buffer;

    public HttpConnectionOverFCGI(EndPoint endPoint, HttpDestination destination, boolean multiplexed)
    {
        super(endPoint, destination.getHttpClient().getExecutor(), destination.getHttpClient().isDispatchIO());
        this.destination = destination;
        this.multiplexed = multiplexed;
        this.flusher = new Flusher(endPoint);
        this.delegate = new Delegate(destination);
        this.parser = new ClientParser(new ResponseListener());
        requests.addLast(0);
    }

    public HttpDestination getHttpDestination()
    {
        return destination;
    }

    @Override
    public void send(Request request, Response.CompleteListener listener)
    {
        delegate.send(request, listener);
    }

    protected void send(HttpExchange exchange)
    {
        delegate.send(exchange);
    }

    @Override
    public void onOpen()
    {
        super.onOpen();
        fillInterested();
    }

    @Override
    public void onFillable()
    {
        HttpClient client = destination.getHttpClient();
        ByteBufferPool bufferPool = client.getByteBufferPool();
        buffer = bufferPool.acquire(client.getResponseBufferSize(), true);
        process();
    }

    private void process()
    {
        if (readAndParse())
        {
            HttpClient client = destination.getHttpClient();
            ByteBufferPool bufferPool = client.getByteBufferPool();
            bufferPool.release(buffer);
            // Don't linger the buffer around if we are idle.
            buffer = null;
        }
    }

    private boolean readAndParse()
    {
        EndPoint endPoint = getEndPoint();
        ByteBuffer buffer = this.buffer;
        while (true)
        {
            try
            {
                if (parse(buffer))
                    return false;

                int read = endPoint.fill(buffer);
                if (LOG.isDebugEnabled()) // Avoid boxing of variable 'read'.
                    LOG.debug("Read {} bytes from {}", read, endPoint);
                if (read > 0)
                {
                    if (parse(buffer))
                        return false;
                }
                else if (read == 0)
                {
                    fillInterested();
                    return true;
                }
                else
                {
                    shutdown();
                    return true;
                }
            }
            catch (Exception x)
            {
                if (LOG.isDebugEnabled())
                    LOG.debug(x);
                close(x);
                return false;
            }
        }
    }

    private boolean parse(ByteBuffer buffer)
    {
        return parser.parse(buffer);
    }

    private void shutdown()
    {
        // Close explicitly only if we are idle, since the request may still
        // be in progress, otherwise close only if we can fail the responses.
        if (channels.isEmpty())
            close();
        else
            failAndClose(new EOFException());
    }

    @Override
    protected boolean onReadTimeout()
    {
        close(new TimeoutException());
        return false;
    }

    protected void release(HttpChannelOverFCGI channel)
    {
        channels.remove(channel.getRequest());
        destination.release(this);
    }

    @Override
    public void close()
    {
        close(new AsynchronousCloseException());
    }

    protected void close(Throwable failure)
    {
        if (closed.compareAndSet(false, true))
        {
            // First close then abort, to be sure that the connection cannot be reused
            // from an onFailure() handler or by blocking code waiting for completion.
            getHttpDestination().close(this);
            getEndPoint().shutdownOutput();
            if (LOG.isDebugEnabled())
                LOG.debug("{} oshut", this);
            getEndPoint().close();
            if (LOG.isDebugEnabled())
                LOG.debug("{} closed", this);

            abort(failure);
        }
    }

    protected boolean closeByHTTP(HttpFields fields)
    {
        if (multiplexed)
            return false;
        if (!fields.contains(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()))
            return false;
        close();
        return true;
    }

    protected void abort(Throwable failure)
    {
        for (HttpChannelOverFCGI channel : channels.values())
        {
            HttpExchange exchange = channel.getHttpExchange();
            if (exchange != null)
                exchange.getRequest().abort(failure);
        }
        channels.clear();
    }

    private void failAndClose(Throwable failure)
    {
        boolean result = false;
        for (HttpChannelOverFCGI channel : channels.values())
            result |= channel.responseFailure(failure);
        if (result)
            close(failure);
    }

    private int acquireRequest()
    {
        synchronized (requests)
        {
            int last = requests.getLast();
            int request = last + 1;
            requests.addLast(request);
            return request;
        }
    }

    private void releaseRequest(int request)
    {
        synchronized (requests)
        {
            requests.removeFirstOccurrence(request);
        }
    }

    @Override
    public String toString()
    {
        return String.format("%s@%h(l:%s <-> r:%s)",
                getClass().getSimpleName(),
                this,
                getEndPoint().getLocalAddress(),
                getEndPoint().getRemoteAddress());
    }

    private class Delegate extends HttpConnection
    {
        private Delegate(HttpDestination destination)
        {
            super(destination);
        }

        @Override
        protected void send(HttpExchange exchange)
        {
            Request request = exchange.getRequest();
            normalizeRequest(request);

            // FCGI may be multiplexed, so create one channel for each request.
            int id = acquireRequest();
            HttpChannelOverFCGI channel = new HttpChannelOverFCGI(HttpConnectionOverFCGI.this, flusher, id, request.getIdleTimeout());
            channels.put(id, channel);
            channel.associate(exchange);
            channel.send();
        }

        @Override
        public void close()
        {
            HttpConnectionOverFCGI.this.close();
        }

        @Override
        public String toString()
        {
            return HttpConnectionOverFCGI.this.toString();
        }
    }

    private class ResponseListener implements ClientParser.Listener
    {
        @Override
        public void onBegin(int request, int code, String reason)
        {
            HttpChannelOverFCGI channel = channels.get(request);
            if (channel != null)
                channel.responseBegin(code, reason);
            else
                noChannel(request);
        }

        @Override
        public void onHeader(int request, HttpField field)
        {
            HttpChannelOverFCGI channel = channels.get(request);
            if (channel != null)
                channel.responseHeader(field);
            else
                noChannel(request);
        }

        @Override
        public void onHeaders(int request)
        {
            HttpChannelOverFCGI channel = channels.get(request);
            if (channel != null)
                channel.responseHeaders();
            else
                noChannel(request);
        }

        @Override
        public boolean onContent(int request, FCGI.StreamType stream, ByteBuffer buffer)
        {
            switch (stream)
            {
                case STD_OUT:
                {
                    HttpChannelOverFCGI channel = channels.get(request);
                    if (channel != null)
                    {
                        CompletableCallback callback = new CompletableCallback()
                        {
                            @Override
                            public void resume()
                            {
                                if (LOG.isDebugEnabled())
                                    LOG.debug("Content consumed asynchronously, resuming processing");
                                process();
                            }

                            @Override
                            public void abort(Throwable x)
                            {
                                close(x);
                            }
                        };
                        if (!channel.content(buffer, callback))
                            return true;
                        return callback.tryComplete();
                    }
                    else
                    {
                        noChannel(request);
                    }
                    break;
                }
                case STD_ERR:
                {
                    LOG.info(BufferUtil.toUTF8String(buffer));
                    break;
                }
                default:
                {
                    throw new IllegalArgumentException();
                }
            }
            return false;
        }

        @Override
        public void onEnd(int request)
        {
            HttpChannelOverFCGI channel = channels.get(request);
            if (channel != null)
            {
                if (channel.responseSuccess())
                    releaseRequest(request);
            }
            else
            {
                noChannel(request);
            }
        }

        @Override
        public void onFailure(int request, Throwable failure)
        {
            HttpChannelOverFCGI channel = channels.get(request);
            if (channel != null)
            {
                if (channel.responseFailure(failure))
                    releaseRequest(request);
            }
            else
            {
                noChannel(request);
            }
        }

        private void noChannel(int request)
        {
            if (LOG.isDebugEnabled())
                LOG.debug("Channel not found for request {}", request);
        }
    }
}

Back to the top