aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/prelude/statistics/StatisticsSearcher.java
blob: 3606e01ffe59e4f5f6dbe3d68c77e5ddb144bea9 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.statistics;

import com.yahoo.component.chain.dependencies.Before;
import com.yahoo.concurrent.CopyOnWriteHashMap;
import com.yahoo.container.protect.Error;
import com.yahoo.jdisc.Metric;
import com.yahoo.log.LogLevel;
import com.yahoo.metrics.simple.MetricSettings;
import com.yahoo.metrics.simple.MetricReceiver;
import com.yahoo.processing.request.CompoundName;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.result.Coverage;
import com.yahoo.search.result.ErrorHit;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.PhaseNames;
import com.yahoo.statistics.Counter;
import com.yahoo.statistics.Value;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;

import static com.yahoo.container.protect.Error.*;


/**
 * <p>A searcher to gather statistics such as queries completed and query latency.  There
 * may be more than 1 StatisticsSearcher in the Searcher chain, each identified by a
 * Searcher ID.  The statistics accumulated by all StatisticsSearchers are stored
 * in the singleton StatisticsManager object. </p>
 * <p>
 * TODO: Fix events to handle more than one of these searchers properly.
 *
 * @author Gene Meyers
 * @author Steinar Knutsen
 * @author bergum
 */
@Before(PhaseNames.RAW_QUERY)
public class StatisticsSearcher extends Searcher {

    private static final CompoundName IGNORE_QUERY = new CompoundName("metrics.ignore");
    private static final String MAX_QUERY_LATENCY_METRIC = "max_query_latency";
    private static final String EMPTY_RESULTS_METRIC = "empty_results";
    private static final String HITS_PER_QUERY_METRIC = "hits_per_query";
    private static final String TOTALHITS_PER_QUERY_METRIC = "totalhits_per_query";
    private static final String FAILED_QUERIES_METRIC = "failed_queries";
    private static final String MEAN_QUERY_LATENCY_METRIC = "mean_query_latency";
    private static final String QUERY_LATENCY_METRIC = "query_latency";
    private static final String QUERIES_METRIC = "queries";
    private static final String ACTIVE_QUERIES_METRIC = "active_queries";
    private static final String PEAK_QPS_METRIC = "peak_qps";
    private static final String DOCS_COVERED_METRIC = "documents_covered";
    private static final String DOCS_TOTAL_METRIC = "documents_total";
    private static final String DEGRADED_METRIC = "degraded_queries";

    private final Counter queries; // basic counter
    private final Counter failedQueries; // basic counter
    private final Counter nullQueries; // basic counter
    private final Counter illegalQueries; // basic counter
    private final Value queryLatency; // mean pr 5 min
    private final Value queryLatencyBuckets;
    private final Value maxQueryLatency; // separate to avoid name mangling
    @SuppressWarnings("unused") // all the work is done by the callback
    private final Value peakQPS; // peak 1s QPS
    private final Counter emptyResults; // number of results containing no concrete hits
    private final Value hitsPerQuery; // mean number of hits per query

    private final PeakQpsReporter peakQpsReporter;

    // Naming of enums are reflected directly in metric dimensions and should not be changed as they are public API
    private enum DegradedReason { match_phase, adaptive_timeout, timeout, non_ideal_state }

    private Metric metric;
    private Map<String, Metric.Context> chainContexts = new CopyOnWriteHashMap<>();
    private Map<String, Metric.Context> statePageOnlyContexts = new CopyOnWriteHashMap<>();
    private Map<String, Map<DegradedReason, Metric.Context>> degradedReasonContexts = new CopyOnWriteHashMap<>();
    private java.util.Timer scheduler = new java.util.Timer(true);

    private class PeakQpsReporter extends java.util.TimerTask {
        private long prevMaxQPSTime = System.currentTimeMillis();
        private long queriesForQPS = 0;
        private Metric.Context metricContext = null;
        public void setContext(Metric.Context metricContext) {
            if (this.metricContext == null) {
                synchronized(this) {
                    this.metricContext = metricContext;
                }
            }
        }
        @Override
        public void run() {
            long now = System.currentTimeMillis();
            synchronized (this) {
                if (metricContext == null) return;
                flushPeakQps(now);
            }
        }
        private void flushPeakQps(long now) {
            double ms = (double) (now - prevMaxQPSTime);
            final double value = ((double)queriesForQPS) / (ms / 1000.0);
            peakQPS.put(value);
            metric.set(PEAK_QPS_METRIC, value, metricContext);
            prevMaxQPSTime = now;
            queriesForQPS = 0;
        }
        void countQuery() {
            synchronized (this) {
                ++queriesForQPS;
            }
        }
    }

    public StatisticsSearcher(com.yahoo.statistics.Statistics manager, Metric metric, MetricReceiver metricReceiver) {
        this.peakQpsReporter = new PeakQpsReporter();
        this.metric = metric;

        queries = new Counter(QUERIES_METRIC, manager, false);
        failedQueries = new Counter(FAILED_QUERIES_METRIC, manager, false);
        nullQueries = new Counter("null_queries", manager, false);
        illegalQueries = new Counter("illegal_queries", manager, false);
        queryLatency = new Value(MEAN_QUERY_LATENCY_METRIC, manager, new Value.Parameters().setLogRaw(false).setLogMean(true).setNameExtension(false));
        maxQueryLatency = new Value(MAX_QUERY_LATENCY_METRIC, manager, new Value.Parameters().setLogRaw(false).setLogMax(true).setNameExtension(false));
        queryLatencyBuckets = Value.buildValue(QUERY_LATENCY_METRIC, manager, null);
        peakQPS = new Value(PEAK_QPS_METRIC, manager, new Value.Parameters().setLogRaw(false).setLogMax(true).setNameExtension(false));
        hitsPerQuery = new Value(HITS_PER_QUERY_METRIC, manager, new Value.Parameters().setLogRaw(false).setLogMean(true).setNameExtension(false));
        emptyResults = new Counter(EMPTY_RESULTS_METRIC, manager, false);
        metricReceiver.declareGauge(QUERY_LATENCY_METRIC, Optional.empty(), new MetricSettings.Builder().histogram(true).build());

        scheduler.schedule(peakQpsReporter, 1000, 1000);
    }

    @Override
    public void deconstruct() {
        scheduler.cancel();
    }

    private void qps(Metric.Context metricContext) {
        peakQpsReporter.setContext(metricContext);
        peakQpsReporter.countQuery();
    }

    private Metric.Context getChainMetricContext(String chainName) {
        Metric.Context context = chainContexts.get(chainName);
        if (context == null) {
            Map<String, String> dimensions = new HashMap<>();
            dimensions.put("chain", chainName);
            context = this.metric.createContext(dimensions);
            chainContexts.put(chainName, context);
        }
        return context;
    }

    private Metric.Context getDegradedMetricContext(String chainName, Coverage coverage) {
        Map<DegradedReason, Metric.Context> reasons = degradedReasonContexts.get(chainName);
        if (reasons == null) {
            reasons = new HashMap<>(4);
            for (DegradedReason reason : DegradedReason.values() ) {
                Map<String, String> dimensions = new HashMap<>();
                dimensions.put("chain", chainName);
                dimensions.put("reason", reason.toString());
                Metric.Context context = this.metric.createContext(dimensions);
                reasons.put(reason, context);
            }
            degradedReasonContexts.put(chainName, reasons);
        }
        return reasons.get(getMostImportantDegradeReason(coverage));
    }

    private DegradedReason getMostImportantDegradeReason(Coverage coverage) {
        if (coverage.isDegradedByMatchPhase()) {
            return DegradedReason.match_phase;
        }
        if (coverage.isDegradedByTimeout()) {
            return DegradedReason.timeout;
        }
        if (coverage.isDegradedByAdapativeTimeout()) {
            return DegradedReason.adaptive_timeout;
        }
        return DegradedReason.non_ideal_state;
    }

    /**
     * Generate statistics for the query passing through this Searcher
     * 1) Add 1 to total query count
     * 2) Add response time to total response time (time from entry to return)
     * 3) .....
     */
    @Override
    public Result search(Query query, Execution execution) {
        if (query.properties().getBoolean(IGNORE_QUERY,false)) {
            return execution.search(query);
        }

        Metric.Context metricContext = getChainMetricContext(execution.chain().getId().stringValue());

        incrQueryCount(metricContext);
        logQuery(query);
        long start = System.currentTimeMillis(); // Start time, in millisecs.
        qps(metricContext);
        Result result;
        //handle exceptions thrown below in searchers
        try {
            result = execution.search(query); // Pass on down the chain
        } catch (Exception  e) {
            incrErrorCount(null, metricContext);
            throw e;
        }

        long end = System.currentTimeMillis(); // Start time, in millisecs.
        long latency = end - start;
        if (latency >= 0) {
            addLatency(latency, metricContext);
        } else {
            getLogger().log(LogLevel.WARNING,
                            "Apparently negative latency measure, start: " + start
                            + ", end: " + end + ", for query: " + query.toString());
        }
        if (result.hits().getError() != null) {
            incrErrorCount(result, metricContext);
            incrementStatePageOnlyErrors(result);
        }
        Coverage queryCoverage = result.getCoverage(false);
        if (queryCoverage != null) {
            if (queryCoverage.isDegraded()) {
                Metric.Context degradedContext = getDegradedMetricContext(execution.chain().getId().stringValue(), queryCoverage);
                metric.add(DEGRADED_METRIC, 1, degradedContext);
            }
            metric.add(DOCS_COVERED_METRIC, queryCoverage.getDocs(), metricContext);
            metric.add(DOCS_TOTAL_METRIC, queryCoverage.getActive(), metricContext);
        }
        int hitCount = result.getConcreteHitCount();
        hitsPerQuery.put((double) hitCount);
        metric.set(HITS_PER_QUERY_METRIC, (double) hitCount, metricContext);
        metric.set(TOTALHITS_PER_QUERY_METRIC, (double) result.getTotalHitCount(), metricContext);
        if (hitCount == 0) {
            emptyResults.increment();
            metric.add(EMPTY_RESULTS_METRIC, 1, metricContext);
        }

        // Update running averages
        //setAverages();

        return result;
    }

    private void logQuery(com.yahoo.search.Query query) {
        // Don't parse the query if it's not necessary for the logging Query.toString triggers parsing
        if (getLogger().isLoggable(Level.FINER)) {
            getLogger().finer("Query: " + query.toString());
        }
    }

    private void addLatency(long latency, Metric.Context metricContext) {
        //myStats.addLatency(latency);
        queryLatency.put(latency);
        metric.set(QUERY_LATENCY_METRIC, latency, metricContext);
        metric.set(MEAN_QUERY_LATENCY_METRIC, latency, metricContext);
        maxQueryLatency.put(latency);
        metric.set(MAX_QUERY_LATENCY_METRIC, latency, metricContext);
        queryLatencyBuckets.put(latency);
    }

    private void incrQueryCount(Metric.Context metricContext) {
        //myStats.incrQueryCnt();
        queries.increment();
        metric.add(QUERIES_METRIC, 1, metricContext);
    }

    private void incrErrorCount(Result result, Metric.Context metricContext) {
        failedQueries.increment();
        metric.add(FAILED_QUERIES_METRIC, 1, metricContext);

        if (result == null) // the chain threw an exception
            metric.add("error.unhandled_exception", 1, metricContext);
        else if (result.hits().getErrorHit().hasOnlyErrorCode(Error.NULL_QUERY.code))
            nullQueries.increment();
        else if (result.hits().getErrorHit().hasOnlyErrorCode(Error.ILLEGAL_QUERY.code))
            illegalQueries.increment();
    }

    /**
     * Creates error metric for StateHandler only. These metrics are only exposed on /state/v1/metrics page
     * and not forwarded to the log file.
     *
     * @param result The result to check for errors
     */
    private void incrementStatePageOnlyErrors(Result result) {
        if (result == null) return;

        ErrorHit error = result.hits().getErrorHit();
        if (error == null) return;

        for (ErrorMessage m : error.errors()) {
            int code = m.getCode();
            Metric.Context c = getDimensions(m.getSource());
            if (code == TIMEOUT.code) {
                metric.add("error.timeout", 1, c);
            } else if (code == NO_BACKENDS_IN_SERVICE.code) {
                metric.add("error.backends_oos", 1, c);
            } else if (code == ERROR_IN_PLUGIN.code) {
                metric.add("error.plugin_failure", 1, c);
            } else if (code == BACKEND_COMMUNICATION_ERROR.code) {
                metric.add("error.backend_communication_error", 1, c);
            } else if (code == EMPTY_DOCUMENTS.code) {
                metric.add("error.empty_document_summaries", 1, c);
            } else if (code == ILLEGAL_QUERY.code) {
                metric.add("error.illegal_query", 1, c);
            } else if (code == INVALID_QUERY_PARAMETER.code) {
                metric.add("error.invalid_query_parameter", 1, c);
            } else if (code == INTERNAL_SERVER_ERROR.code) {
                metric.add("error.internal_server_error", 1, c);
            } else if (code == SERVER_IS_MISCONFIGURED.code) {
                metric.add("error.misconfigured_server", 1, c);
            } else if (code == INVALID_QUERY_TRANSFORMATION.code) {
                metric.add("error.invalid_query_transformation", 1, c);
            } else if (code == RESULT_HAS_ERRORS.code) {
                metric.add("error.result_with_errors", 1, c);
            } else if (code == UNSPECIFIED.code) {
                metric.add("error.unspecified", 1, c);
            }
        }
    }

    private Metric.Context getDimensions(String source) {
        Metric.Context context = statePageOnlyContexts.get(source == null ? "" : source);
        if (context == null) {
            Map<String, String> dims = new HashMap<>();
            if (source != null) {
                dims.put("source", source);
            }
            context = this.metric.createContext(dims);
            statePageOnlyContexts.put(source == null ? "" : source, context);
        }
        // TODO add other relevant metric dimensions
        // Would be nice to have chain as a dimension as
        // we can separate errors from different chains
        return context;
    }

}