aboutsummaryrefslogtreecommitdiffstats
path: root/vespaclient-container-plugin/src/main/java/com/yahoo/vespa/http/server/ClientFeederV3.java
blob: 92a9c4df27df17d62d3e02285ea26976286b4f41 (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.http.server;

import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.document.DocumentTypeManager;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.ReferencedResource;
import com.yahoo.jdisc.ResourceReference;
import com.yahoo.messagebus.Message;
import com.yahoo.messagebus.ReplyHandler;
import com.yahoo.messagebus.Result;
import com.yahoo.messagebus.shared.SharedSourceSession;
import com.yahoo.net.HostName;
import com.yahoo.vespaxmlparser.FeedOperation;
import com.yahoo.yolean.Exceptions;

import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * An instance of this class handles all requests from one client using VespaHttpClient.
 *
 * The implementation is based on the code from V2, but the object model is rewritten to simplify the logic and
 * avoid using a threadpool that has no effect with all the extra that comes with it. V2 has one instance per thread
 * on the client, while this is one instance for all threads.
 *
 * @author dybis
 */
class ClientFeederV3 {

    protected static final Logger log = Logger.getLogger(ClientFeederV3.class.getName());
    // This is for all clients on this gateway, for load balancing from client.
    private final static AtomicInteger outstandingOperations = new AtomicInteger(0);
    private final BlockingQueue<OperationStatus> feedReplies = new LinkedBlockingQueue<>();
    private final ReferencedResource<SharedSourceSession> sourceSession;
    private final String clientId;
    private final ReplyHandler feedReplyHandler;
    private final Metric metric;
    private Instant prevOpsPerSecTime = Instant.now();
    private double operationsForOpsPerSec = 0d;
    private final Object monitor = new Object();
    private final StreamReaderV3 streamReaderV3;
    private final AtomicInteger ongoingRequests = new AtomicInteger(0);
    private final String hostName;

    ClientFeederV3(ReferencedResource<SharedSourceSession> sourceSession,
                   FeedReaderFactory feedReaderFactory,
                   DocumentTypeManager docTypeManager,
                   String clientId,
                   Metric metric,
                   ReplyHandler feedReplyHandler) {
        this.sourceSession = sourceSession;
        this.clientId = clientId;
        this.feedReplyHandler = feedReplyHandler;
        this.metric = metric;
        this.streamReaderV3 = new StreamReaderV3(feedReaderFactory, docTypeManager);
        this.hostName = HostName.getLocalhost();
    }

    boolean timedOut() {
        synchronized (monitor) {
            return Instant.now().isAfter(prevOpsPerSecTime.plusSeconds(6000)) && ongoingRequests.get() == 0;
        }
    }

    void kill() {
        try (ResourceReference ignored = sourceSession.getReference()) {
            // No new requests should be sent to this object, but there can be old one, even though this is very unlikely.
            while (ongoingRequests.get() > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    return;
                }
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "Failed to close reference to source session", e);
        }
    }

    private void transferPreviousRepliesToResponse(BlockingQueue<OperationStatus> operations) throws InterruptedException {
        OperationStatus status = feedReplies.poll();
        while (status != null) {
            outstandingOperations.decrementAndGet();
            operations.put(status);
            status = feedReplies.poll();
        }
    }

    HttpResponse handleRequest(HttpRequest request) throws IOException {
        ongoingRequests.incrementAndGet();
        try {
            FeederSettings feederSettings = new FeederSettings(request);
            InputStream inputStream = StreamReaderV3.unzipStreamIfNeeded(request);
            BlockingQueue<OperationStatus> replies = new LinkedBlockingQueue<>();
            try {
                feed(feederSettings, inputStream, replies);
                synchronized (monitor) {
                    // Handshake requests do not have DATA_FORMAT, we do not want to give responses to
                    // handshakes as it won't be processed by the client.
                    if (request.getJDiscRequest().headers().get(Headers.DATA_FORMAT) != null) {
                        transferPreviousRepliesToResponse(replies);
                    }
                }
            } catch (InterruptedException e) {
                log.log(Level.FINE, e, () -> "Feed handler was interrupted: " + e.getMessage());
                // NOP, just terminate
            } catch (Throwable e) {
                log.log(Level.WARNING, "Unhandled exception while feeding: " + Exceptions.toMessageString(e), e);
            } finally {
                replies.add(createOperationStatus("-", "-", ErrorCode.END_OF_FEED, null));
            }
            return new FeedResponse(200, replies, 3, clientId, outstandingOperations.get(), hostName);
        } finally {
            ongoingRequests.decrementAndGet();
        }
    }

    private Optional<DocumentOperationMessageV3> pullMessageFromRequest(FeederSettings settings,
                                                                        InputStream requestInputStream,
                                                                        BlockingQueue<OperationStatus> repliesFromOldMessages) {
        while (true) {
            Optional<String> operationId;
            try {
                operationId = streamReaderV3.getNextOperationId(requestInputStream);
                if (operationId.isEmpty()) return Optional.empty();
            } catch (IOException ioe) {
                log.log(Level.FINE, () -> Exceptions.toMessageString(ioe));
                return Optional.empty();
            }

            try {
                DocumentOperationMessageV3 message = getNextMessage(operationId.get(), requestInputStream, settings);
                if (message != null)
                    setRoute(message, settings);
                return Optional.ofNullable(message);
            } catch (Exception e) {
                log.log(Level.WARNING, () -> Exceptions.toMessageString(e));
                metric.add(MetricNames.PARSE_ERROR, 1, null);

                repliesFromOldMessages.add(new OperationStatus(Exceptions.toMessageString(e),
                                                               operationId.get(),
                                                               ErrorCode.ERROR,
                                                               false,
                                                               ""));
            }
        }
    }

    private Result sendMessage(DocumentOperationMessageV3 msg) throws InterruptedException {
        msg.getMessage().pushHandler(feedReplyHandler);
        return sourceSession.getResource().sendMessageBlocking(msg.getMessage());
    }

    private void feed(FeederSettings settings,
                      InputStream requestInputStream,
                      BlockingQueue<OperationStatus> repliesFromOldMessages) throws InterruptedException {
        while (true) {
            Optional<DocumentOperationMessageV3> message = pullMessageFromRequest(settings,
                                                                                  requestInputStream,
                                                                                  repliesFromOldMessages);

            if (message.isEmpty()) break;
            setMessageParameters(message.get(), settings);

            Result result;
            try {
                result = sendMessage(message.get());

            } catch  (RuntimeException e) {
                repliesFromOldMessages.add(createOperationStatus(message.get().getOperationId(),
                                                                 Exceptions.toMessageString(e),
                                                                 ErrorCode.ERROR,
                                                                 message.get().getMessage()));
                continue;
            }

            if (result.isAccepted()) {
                outstandingOperations.incrementAndGet();
                updateOpsPerSec();
                log(Level.FINE, "Sent message successfully, document id: ", message.get().getOperationId());
            } else {
                var err = result.getError();
                var msg = message.get();
                repliesFromOldMessages.add(
                        createOperationStatus(
                                msg.getOperationId(), err.getMessage(), ErrorCode.fromBusError(err), msg.getMessage()));
            }
        }
    }

    private OperationStatus createOperationStatus(String id, String message, ErrorCode code, Message msg) {
        String traceMessage = msg != null && msg.getTrace() != null &&  msg.getTrace().getLevel() > 0
                ? msg.getTrace().toString()
                : "";
        return new OperationStatus(message, id, code, false, traceMessage);
    }

    // protected for mocking
    /** Returns the next message in the stream, or null if none */
    protected DocumentOperationMessageV3 getNextMessage(String operationId,
                                                        InputStream requestInputStream,
                                                        FeederSettings settings) throws Exception {
        FeedOperation operation = streamReaderV3.getNextOperation(requestInputStream, settings);

        // This is a bit hard to set up while testing, so we accept that things are not perfect.
        if (sourceSession.getResource().session() != null) {
            metric.set(MetricNames.PENDING, (double) sourceSession.getResource().session().getPendingCount(), null);
        }

        DocumentOperationMessageV3 message = DocumentOperationMessageV3.create(operation, operationId, metric);
        if (message == null) {
            // typical end of feed
            return null;
        }
        metric.add(MetricNames.NUM_OPERATIONS, 1, null);
        log(Level.FINE, "Successfully deserialized document id: ", message.getOperationId());
        return message;
    }

    private void setMessageParameters(DocumentOperationMessageV3 msg, FeederSettings settings) {
        msg.getMessage().setContext(new ReplyContext(msg.getOperationId(), feedReplies));
        if (settings.traceLevel != null) {
            msg.getMessage().getTrace().setLevel(settings.traceLevel);
        }
    }

    private void setRoute(DocumentOperationMessageV3 msg, FeederSettings settings) {
        if (settings.route != null) {
            msg.getMessage().setRoute(settings.route);
        }
    }

    protected final void log(Level level, Object... msgParts) {
        if (!log.isLoggable(level)) return;

        StringBuilder s = new StringBuilder();
        for (Object part : msgParts)
            s.append(part.toString());
        log.log(level, s.toString());
    }

    private void updateOpsPerSec() {
        Instant now = Instant.now();
        synchronized (monitor) {
            if (now.plusSeconds(1).isAfter(prevOpsPerSecTime)) {
                Duration duration = Duration.between(now, prevOpsPerSecTime);
                double opsPerSec = operationsForOpsPerSec / (duration.toMillis() / 1000.);
                metric.set(MetricNames.OPERATIONS_PER_SEC, opsPerSec, null);
                operationsForOpsPerSec = 1.0d;
                prevOpsPerSecTime = now;
            } else {
                operationsForOpsPerSec += 1.0d;
            }
        }
    }

}