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

import com.yahoo.component.chain.Chain;
import com.yahoo.prelude.Pong;
import com.yahoo.processing.Processor;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/**
 * A container for storing time stamps throughout the lifetime of an Execution instance.
 *
 * <p>Check state both when entering and exiting, to allow for arbitrary
 * new queries anywhere inside a search chain.
 *
 * @author Steinar Knutsen
 */
public final class TimeTracker {

    public enum Activity {
        PING,
        SEARCH,
        FILL;
    }

    static class SearcherTimer {
        // Searcher ID
        private final String name;
        // Time spent transforming query/producing result
        private final EnumMap<Activity, Long> invoking = new EnumMap<>(Activity.class);
        // Time spent transforming result
        private final EnumMap<Activity, Long> returning = new EnumMap<>(Activity.class);

        SearcherTimer(String name) {
            this.name = name;
        }

        private void activityRepr(StringBuilder buffer, int preLen,
                Map.Entry<Activity, Long> m) {
            if (buffer.length() != preLen) {
                buffer.append(", ");
            }
            buffer.append(m.getKey()).append(": ").append(m.getValue())
                    .append(" ms");
        }

        void addInvoking(Activity activity, long time) {
            Long storedTillNow = invoking.get(activity);
            long tillNow = getTime(storedTillNow);
            invoking.put(activity, Long.valueOf(tillNow + time));
        }

        void addReturning(Activity activity, long time) {
            Long storedTillNow = returning.get(activity);
            long tillNow = getTime(storedTillNow);
            returning.put(activity, Long.valueOf(tillNow + time));
        }

        Long getInvoking(Activity activity) {
            return invoking.get(activity);
        }

        String getName() {
            return name;
        }

        Long getReturning(Activity activity) {
            return returning.get(activity);
        }

        private long getTime(Long storedTillNow) {
            long tillNow;
            if (storedTillNow == null) {
                tillNow = 0L;
            } else {
                tillNow = storedTillNow.longValue();
            }
            return tillNow;
        }

        public void merge(SearcherTimer other) {
            for (Map.Entry<Activity, Long> invokingEntry : other.invoking.entrySet()) {
                addInvoking(invokingEntry.getKey(), invokingEntry.getValue());
            }
            for (Map.Entry<Activity, Long> returningEntry : other.returning.entrySet()) {
                addReturning(returningEntry.getKey(), returningEntry.getValue());
            }
        }

        public String toString() {
            StringBuilder buffer = new StringBuilder();
            int preLen;
            buffer.append(name).append("(").append("QueryProcessing(");
            preLen = buffer.length();
            for (Map.Entry<Activity, Long> m : invoking.entrySet()) {
                activityRepr(buffer, preLen, m);
            }
            buffer.append("), ResultProcessing(");
            preLen = buffer.length();
            for (Map.Entry<Activity, Long> m : returning.entrySet()) {
                activityRepr(buffer, preLen, m);
            }
            buffer.append("))");
            return buffer.toString();
        }
    }

    static class State {
        public final long start;
        public final Activity activity;

        State(long start, Activity activity) {
            super();
            this.start = start;
            this.activity = activity;
        }
    }

    static class Tag {
        public final long start;
        public final long end;
        public final Activity activity;

        Tag(long start, long end, Activity activity) {
            super();
            this.start = start;
            this.end = end;
            this.activity = activity;
        }
    }

    static class TimeSource {
        long now() {
            return System.currentTimeMillis();
        }
    }

    private State state = null;
    private List<Tag> tags = new ArrayList<>();

    private SearcherTimer[] searcherTracking = null;
    private final Chain<? extends Processor> searchChain;
    // whether the previous state was invoking or returning
    private boolean invoking = true;
    private long last = 0L;
    private final int entryIndex;
    TimeSource timeSource = new TimeSource();

    public TimeTracker(Chain<? extends Searcher> searchChain) {
        this(searchChain, 0);
    }

    public TimeTracker(Chain<? extends Processor> searchChain, int entryIndex) {
        this.searchChain = searchChain;
        this.entryIndex = entryIndex;
    }

    private void concludeState(long now) {
        if (state == null) {
            return;
        }

        tags.add(new Tag(state.start, now, state.activity));
        state = null;
    }

    private void concludeStateOnExit(long now) {
        if (now != 0L) {
            concludeState(now);
        } else {
            concludeState(getNow());
        }
    }

    private long detailedMeasurements(int searcherIndex, boolean calledAsInvoking) {
        long now = getNow();
        if (searcherTracking == null) {
            initBreakdown();
        }
        SearcherTimer timeSpentIn = getPreviouslyRunSearcher(searcherIndex, calledAsInvoking);
        long spent = now - last;
        if (timeSpentIn != null && last != 0L) {
            if (invoking) {
                timeSpentIn.addInvoking(getActivity(), spent);
            } else {
                timeSpentIn.addReturning(getActivity(), spent);
            }
        }
        last = now;
        if (searcherIndex >= searcherTracking.length) {
            // We are now outside the search chain and will go back up with the
            // default result.
            invoking = false;
        } else {
            invoking = calledAsInvoking;
        }
        return now;
    }

    private void enteringState(int searcherIndex, boolean detailed, final Activity activity) {
        long now = 0L;
        if (detailed) {
            now = detailedMeasurements(searcherIndex, true);
        }
        if (isNewState(activity)) {
            if (now == 0L) {
                now = getNow();
            }
            concludeState(now);
            initNewState(now, activity);
        }
    }

    private long fetchTime(Activity filter, Tag container) {
        if (filter == container.activity) {
            return container.end - container.start;
        } else {
            return 0L;
        }
    }

    public long fillTime() {
        return typedSum(Activity.FILL);
    }

    public long first() {
        if (tags.isEmpty()) {
            return 0L;
        } else {
            return tags.get(0).start;
        }
    }

    public long firstFill() {
        for (Tag t : tags) {
            if (t.activity == Activity.FILL) {
                return t.start;
            }
        }
        return 0L;
    }

    private Activity getActivity() {
        if (state == null) {
            throw new IllegalStateException("Trying to measure an interval having only one point.");
        }
        return state.activity;
    }

    private long getNow() {
        return timeSource.now();
    }

    private SearcherTimer getPreviouslyRunSearcher(int searcherIndex, boolean calledAsInvoking) {
        if (calledAsInvoking) {
            searcherIndex -= 1;
            if (searcherIndex < entryIndex) {
                return null;
            } else {
                return searcherTracking[searcherIndex];
            }
        } else {
            return searcherTracking[searcherIndex];
        }
    }

    private void initBreakdown() {
        if (searcherTracking != null) {
            throw new IllegalStateException("initBreakdown invoked"
                    + " when measurement structures are already initialized.");
        }
        List<? extends Processor> searchers = searchChain.components();
        searcherTracking = new SearcherTimer[searchers.size()];
        for (int i = 0; i < searcherTracking.length; ++i) {
            searcherTracking[i] = new SearcherTimer(searchers.get(i).getId().stringValue());
        }
    }

    private void initNewState(long now, Activity activity) {
        state = new State(now, activity);
    }

    void injectTimeSource(TimeSource source) {
        this.timeSource = source;
    }

    private boolean isNewState(Activity callPath) {
        if (state == null) {
            return true;
        } else if (callPath == state.activity) {
            return false;
        } else {
            return true;
        }
    }

    public long last() {
        if (tags.isEmpty()) {
            return 0L;
        } else {
            return tags.get(tags.size() - 1).end;
        }
    }

    public long pingTime() {
        return typedSum(Activity.PING);
    }

    private long returnFromState(int searcherIndex, boolean detailed) {
        if (detailed) {
            return detailedMeasurements(searcherIndex, false);
        } else {
            return 0L;
        }
    }

    public void sampleFill(int searcherIndex, boolean detailed) {
        enteringState(searcherIndex, detailed, Activity.FILL);
    }

    public void sampleFillReturn(int searcherIndex, boolean detailed, Result annotationReference) {
        ElapsedTime elapsed = getElapsedTime(annotationReference);
        sampleReturn(searcherIndex, detailed, elapsed);
    }

    public void samplePing(int searcherIndex, boolean detailed) {
        enteringState(searcherIndex, detailed, Activity.PING);
    }

    public void samplePingReturn(int searcherIndex, boolean detailed, Pong annotationReference) {
        ElapsedTime elapsed = getElapsedTime(annotationReference);
        sampleReturn(searcherIndex, detailed, elapsed);
    }

    public void sampleSearch(int searcherIndex, boolean detailed) {
        enteringState(searcherIndex, detailed, Activity.SEARCH);
    }

    public void sampleSearchReturn(int searcherIndex, boolean detailed, Result annotationReference) {
        ElapsedTime elapsed = getElapsedTime(annotationReference);
        sampleReturn(searcherIndex, detailed, elapsed);
    }

    private void sampleReturn(int searcherIndex, boolean detailed, ElapsedTime elapsed) {
        long now = returnFromState(searcherIndex, detailed);
        if (searcherIndex == entryIndex) {
            concludeStateOnExit(now);
            if (elapsed != null) {
                elapsed.add(this);
            }
        }
    }

    private ElapsedTime getElapsedTime(Result r) {
        return r == null ? null : r.getElapsedTime();
    }

    private ElapsedTime getElapsedTime(Pong p) {
        return p == null ? null : p.getElapsedTime();
    }

    SearcherTimer[] searcherTracking() {
        return searcherTracking;
    }

    public long searchTime() {
        return typedSum(Activity.SEARCH);
    }

    public long totalTime() {
        return last() - first();
    }

    private long typedSum(Activity activity) {
        long sum = 0L;
        for (Tag tag : tags) {
            sum += fetchTime(activity, tag);
        }
        return sum;
    }
}