aboutsummaryrefslogtreecommitdiffstats
path: root/docproc/src/main/java/com/yahoo/docproc/jdisc/DocumentProcessingTask.java
blob: 4849086985e0828b0d008e3a19d9f28528adf87f (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.docproc.jdisc;

import com.yahoo.collections.Tuple2;
import com.yahoo.docproc.Call;
import com.yahoo.docproc.CallStack;
import com.yahoo.docproc.DocprocExecutor;
import com.yahoo.docproc.DocprocService;
import com.yahoo.docproc.DocumentProcessor;
import com.yahoo.docproc.HandledProcessingException;
import com.yahoo.docproc.Processing;
import com.yahoo.log.LogLevel;
import com.yahoo.yolean.Exceptions;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author <a href="mailto:einarmr@yahoo-inc.com">Einar M R Rosenvinge</a>
 */
public class DocumentProcessingTask implements Comparable<DocumentProcessingTask>, Runnable {
    private static Logger log = Logger.getLogger(DocumentProcessingTask.class.getName());
    private final List<Processing> processings = new ArrayList<>();
    private final List<Processing> processingsDone = new ArrayList<>();

    private final DocumentProcessingHandler docprocHandler;
    private RequestContext requestContext;
    private int waitCounter;

    private final static AtomicLong seq = new AtomicLong();
    private final long seqNum;
    private final DocprocService service;

    public DocumentProcessingTask(RequestContext requestContext, DocumentProcessingHandler docprocHandler,
                                  DocprocService service) {
        seqNum = seq.getAndIncrement();
        this.requestContext = requestContext;
        this.docprocHandler = docprocHandler;
        this.waitCounter = 10;
        this.service = service;
    }

    @Override
    public void run() {
        try {
            try {
                processings.addAll(requestContext.getProcessings());
            } catch (Exception e) {
                //deserialization failed:
                log.log(LogLevel.WARNING, "Deserialization of message failed.", e);
                requestContext.processingFailed(e);
                return;
            }

            DocprocExecutor executor = service.getExecutor();
            DocumentProcessor.Progress progress = process(executor);

            if (DocumentProcessor.Progress.LATER.equals(progress) && !processings.isEmpty()) {
                DocumentProcessor.LaterProgress laterProgress = (DocumentProcessor.LaterProgress) progress;
                docprocHandler.submit(this, laterProgress.getDelay());
            }
        } catch (Error error) {
            try {
                log.log(LogLevel.FATAL, Exceptions.toMessageString(error), error);
            } catch (Throwable t) {
                // do nothing
            } finally {
                Runtime.getRuntime().halt(1);
            }
        }
    }

    /**
     * Used by DocprocThreadManager. If a ProcessingTask has been taken by a thread, it can wait() no longer than
     * waitCounter (currently 10) times before being executed. This is to prevent large tasks from being delayed
     * forever.
     *
     * @return true if this task can wait, false if it must run NOW.
     */
    boolean doWait() {
        --waitCounter;
        return (waitCounter > 0);
    }

    /**
     * Processes a single Processing, and fails the message if this processing fails.
     *
     * @param executor the DocprocService to use for processing
     */
    private DocumentProcessor.Progress process(DocprocExecutor executor) {
        Iterator<Processing> iterator = processings.iterator();
        List<Tuple2<DocumentProcessor.Progress, Processing>> later = new ArrayList<>();
        while (iterator.hasNext()) {
            Processing processing = iterator.next();
            iterator.remove();
            if (requestContext.hasExpired()) {
                DocumentProcessor.Progress progress = DocumentProcessor.Progress.FAILED;
                final String location;
                if (processing != null) {
                    final CallStack callStack = processing.callStack();
                    if (callStack != null) {
                        final Call lastPopped = callStack.getLastPopped();
                        if (lastPopped != null) {
                            location = lastPopped.toString();
                        } else {
                            location = "empty call stack or no processors popped";
                        }
                    } else {
                        location = "no call stack";
                    }
                } else {
                    location = "no processing instance";
                }
                String errorMsg = processing + " failed, " + location;
                log.log(Level.FINE, "Time is up for '" + errorMsg + "'.");
                requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE, "Time is up.");
                return progress;
            }

            DocumentProcessor.Progress progress = DocumentProcessor.Progress.FAILED;
            try {
                progress = executor.process(processing);
            } catch (Exception e) {
                logProcessingFailure(processing, e);
                requestContext.processingFailed(e);
                return progress;
            }

            if (DocumentProcessor.Progress.LATER.equals(progress)) {
                later.add(new Tuple2<>(progress, processing));
            } else if (DocumentProcessor.Progress.DONE.equals(progress)) {
                processingsDone.add(processing);
            } else if (DocumentProcessor.Progress.FAILED.equals(progress)) {
                logProcessingFailure(processing, null);
                requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
                        progress.getReason().orElse("Document processing failed."));
                return progress;
            } else if (DocumentProcessor.Progress.PERMANENT_FAILURE.equals(progress)) {
                logProcessingFailure(processing, null);
                requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
                        progress.getReason().orElse("Document processing failed."));
                return progress;
            }
        }

        // Processings that have FAILED will have made this method terminate by now.
        // We now have successful Processings in 'processingsDone' and
        // the ones that have returned LATER in 'later'.

        if (!later.isEmpty()) {
            // Outdated comment:
            // "if this was a multioperationmessage and more than one of the processings returned LATER,
            // return the one with the lowest timeout:"
            // As multioperation is removed this can probably be simplified?
            DocumentProcessor.LaterProgress shortestDelay = (DocumentProcessor.LaterProgress) later.get(0).first;
            for (Tuple2<DocumentProcessor.Progress, Processing> tuple : later) {
                // re-add the LATER one to processings
                processings.add(tuple.second);
                // check to see if this one had a lower timeout than the previous one:
                if (((DocumentProcessor.LaterProgress) tuple.first).getDelay() < shortestDelay.getDelay()) {
                    shortestDelay = (DocumentProcessor.LaterProgress) tuple.first;
                }
            }
            return shortestDelay;
        } else {
            requestContext.processingDone(processingsDone);
            return DocumentProcessor.Progress.DONE;
        }
    }


    void queueFull() {
        requestContext.processingFailed(RequestContext.ErrorCode.ERROR_BUSY,
                                        "Queue temporarily full. Returning message " + requestContext +
                                        ". Will be automatically resent.");
    }

    public int compareTo(DocumentProcessingTask other) {
        int ourPriority = requestContext.getPriority();
        int otherPriority = other.requestContext.getPriority();
        int res = (ourPriority == otherPriority) ? 0 : ((ourPriority < otherPriority) ? -1 : 1);
        if (res == 0) {
            res = (seqNum == other.seqNum) ? 0 : ((seqNum < other.seqNum) ? -1 : 1);
        }
        return res;
    }

    @Override
    public String toString() {
        return "ProcessingTask{" +
               "processings=" + processings +
               ", processingsDone=" + processingsDone +
               ", requestContext=" + requestContext +
               ", seqNum=" + seqNum +
               '}';
    }

    public int getApproxSize() {
        return requestContext.getApproxSize();
    }

    final long getSeqNum() {
        return seqNum;
    }

    private static void logProcessingFailure(Processing processing, Exception exception) {
        //LOGGING ONLY:
        String errorMsg = processing + " failed at " + processing.callStack().getLastPopped();
        if (exception != null) {
            if (exception instanceof HandledProcessingException) {
                errorMsg += ". Error message: " + exception.getMessage();
                log.log(Level.WARNING, errorMsg);
                log.log(Level.FINE, "Chained exception:", exception);
            } else {
                log.log(Level.WARNING, errorMsg, exception);
            }
        } else {
            log.log(Level.WARNING, errorMsg);
        }
        //LOGGING OF STACK TRACE:
        if (exception != null) {
            StringWriter backtrace = new StringWriter();
            exception.printStackTrace(new PrintWriter(backtrace));
            log.log(LogLevel.DEBUG, "Failed to process " + processing + ": " + backtrace.toString());
        }
    }
}