1 /*******************************************************************************
2 * Copyright (c) 2013, 2014 Ericsson
3 * All rights reserved. This program and the accompanying materials are
4 * made available under the terms of the Eclipse Public License v1.0 which
5 * accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
9 * Alexandre Montplaisir - Initial API and implementation
10 *******************************************************************************/
12 package org
.eclipse
.tracecompass
.internal
.tmf
.core
.statesystem
.backends
.partial
;
15 import java
.io
.FileInputStream
;
16 import java
.io
.PrintWriter
;
17 import java
.util
.List
;
19 import java
.util
.TreeMap
;
20 import java
.util
.concurrent
.CountDownLatch
;
22 import org
.eclipse
.jdt
.annotation
.NonNull
;
23 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystem
;
24 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.IStateHistoryBackend
;
25 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.AttributeNotFoundException
;
26 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.StateSystemDisposedException
;
27 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.TimeRangeException
;
28 import org
.eclipse
.tracecompass
.statesystem
.core
.interval
.ITmfStateInterval
;
29 import org
.eclipse
.tracecompass
.statesystem
.core
.interval
.TmfStateInterval
;
30 import org
.eclipse
.tracecompass
.statesystem
.core
.statevalue
.ITmfStateValue
;
31 import org
.eclipse
.tracecompass
.tmf
.core
.event
.ITmfEvent
;
32 import org
.eclipse
.tracecompass
.tmf
.core
.request
.ITmfEventRequest
;
33 import org
.eclipse
.tracecompass
.tmf
.core
.request
.TmfEventRequest
;
34 import org
.eclipse
.tracecompass
.tmf
.core
.statesystem
.AbstractTmfStateProvider
;
35 import org
.eclipse
.tracecompass
.tmf
.core
.statesystem
.ITmfStateProvider
;
36 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.ITmfTimestamp
;
37 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimeRange
;
38 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimestamp
;
39 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
42 * Partial state history back-end.
44 * This is a shim inserted between the real state system and a "real" history
45 * back-end. It will keep checkpoints, every n trace events (where n is called
46 * the granularity) and will only forward to the real state history the state
47 * intervals that crosses at least one checkpoint. Every other interval will
50 * This would mean that it can only answer queries exactly at the checkpoints.
51 * For any other timestamps (ie, most of the time), it will load the closest
52 * earlier checkpoint, and will re-feed the state-change-input with events from
53 * the trace, to restore the real state at the time that was requested.
55 * @author Alexandre Montplaisir
57 public class PartialHistoryBackend
implements IStateHistoryBackend
{
59 private final @NonNull String fSSID
;
62 * A partial history needs the state input plugin to re-generate state
63 * between checkpoints.
65 private final @NonNull ITmfStateProvider fPartialInput
;
68 * Fake state system that is used for partially rebuilding the states (when
69 * going from a checkpoint to a target query timestamp).
71 private final @NonNull PartialStateSystem fPartialSS
;
73 /** Reference to the "real" state history that is used for storage */
74 private final @NonNull IStateHistoryBackend fInnerHistory
;
76 /** Checkpoints map, <Timestamp, Rank in the trace> */
77 private final @NonNull TreeMap
<Long
, Long
> fCheckpoints
= new TreeMap
<>();
79 /** Latch tracking if the initial checkpoint registration is done */
80 private final @NonNull CountDownLatch fCheckpointsReady
= new CountDownLatch(1);
82 private final long fGranularity
;
84 private long fLatestTime
;
90 * The state system's ID
92 * The state change input object that was used to build the
93 * upstream state system. This partial history will make its own
94 * copy (since they have different targets).
96 * The partial history's inner state system. It should already be
97 * assigned to partialInput.
99 * The real state history back-end to use. It's supposed to be
100 * modular, so it should be able to be of any type.
102 * Configuration parameter indicating how many trace events there
103 * should be between each checkpoint
105 public PartialHistoryBackend(@NonNull String ssid
,
106 ITmfStateProvider partialInput
,
107 PartialStateSystem pss
,
108 IStateHistoryBackend realBackend
,
110 if (granularity
<= 0 || partialInput
== null || pss
== null ||
111 partialInput
.getAssignedStateSystem() != pss
) {
112 throw new IllegalArgumentException();
115 final long startTime
= realBackend
.getStartTime();
118 fPartialInput
= partialInput
;
121 fInnerHistory
= realBackend
;
122 fGranularity
= granularity
;
124 fLatestTime
= startTime
;
126 registerCheckpoints();
129 private void registerCheckpoints() {
130 ITmfEventRequest request
= new CheckpointsRequest(fPartialInput
, fCheckpoints
);
131 fPartialInput
.getTrace().sendRequest(request
);
132 /* The request will countDown the checkpoints latch once it's finished */
136 public String
getSSID() {
141 public long getStartTime() {
142 return fInnerHistory
.getStartTime();
146 public long getEndTime() {
151 public void insertPastState(long stateStartTime
, long stateEndTime
,
152 int quark
, ITmfStateValue value
) throws TimeRangeException
{
153 waitForCheckpoints();
155 /* Update the latest time */
156 if (stateEndTime
> fLatestTime
) {
157 fLatestTime
= stateEndTime
;
161 * Check if the interval intersects the previous checkpoint. If so,
162 * insert it in the real history back-end.
164 * FIXME since intervals are inserted in order of rank, we could avoid
165 * doing a map lookup every time here (just compare with the known
168 if (stateStartTime
<= fCheckpoints
.floorKey(stateEndTime
)) {
169 fInnerHistory
.insertPastState(stateStartTime
, stateEndTime
, quark
, value
);
174 public void finishedBuilding(long endTime
) throws TimeRangeException
{
175 fInnerHistory
.finishedBuilding(endTime
);
179 public FileInputStream
supplyAttributeTreeReader() {
180 return fInnerHistory
.supplyAttributeTreeReader();
184 public File
supplyAttributeTreeWriterFile() {
185 return fInnerHistory
.supplyAttributeTreeWriterFile();
189 public long supplyAttributeTreeWriterFilePosition() {
190 return fInnerHistory
.supplyAttributeTreeWriterFilePosition();
194 public void removeFiles() {
195 fInnerHistory
.removeFiles();
199 public void dispose() {
200 fPartialInput
.dispose();
201 fPartialSS
.dispose();
202 fInnerHistory
.dispose();
206 public void doQuery(List
<ITmfStateInterval
> currentStateInfo
, long t
)
207 throws TimeRangeException
, StateSystemDisposedException
{
208 /* Wait for required steps to be done */
209 waitForCheckpoints();
210 fPartialSS
.getUpstreamSS().waitUntilBuilt();
212 if (!checkValidTime(t
)) {
213 throw new TimeRangeException();
216 /* Reload the previous checkpoint */
217 long checkpointTime
= fCheckpoints
.floorKey(t
);
218 fInnerHistory
.doQuery(currentStateInfo
, checkpointTime
);
221 * Set the initial contents of the partial state system (which is the
222 * contents of the query at the checkpoint).
224 fPartialSS
.takeQueryLock();
225 fPartialSS
.replaceOngoingState(currentStateInfo
);
227 /* Send an event request to update the state system to the target time. */
228 TmfTimeRange range
= new TmfTimeRange(
230 * The state at the checkpoint already includes any state change
231 * caused by the event(s) happening exactly at 'checkpointTime',
232 * if any. We must not include those events in the query.
234 new TmfTimestamp(checkpointTime
+ 1, ITmfTimestamp
.NANOSECOND_SCALE
),
235 new TmfTimestamp(t
, ITmfTimestamp
.NANOSECOND_SCALE
));
236 ITmfEventRequest request
= new PartialStateSystemRequest(fPartialInput
, range
);
237 fPartialInput
.getTrace().sendRequest(request
);
240 request
.waitForCompletion();
241 } catch (InterruptedException e
) {
246 * Now the partial state system should have the ongoing time we are
247 * looking for. However, the method expects a List of *state intervals*,
248 * not state values, so we'll create intervals with a dummy end time.
251 for (int i
= 0; i
< currentStateInfo
.size(); i
++) {
253 ITmfStateValue val
= null;
254 start
= ((ITmfStateSystem
) fPartialSS
).getOngoingStartTime(i
);
255 val
= ((ITmfStateSystem
) fPartialSS
).queryOngoingState(i
);
257 ITmfStateInterval interval
= new TmfStateInterval(start
, t
, i
, val
);
258 currentStateInfo
.set(i
, interval
);
260 } catch (AttributeNotFoundException e
) {
261 /* Should not happen, we iterate over existing values. */
265 fPartialSS
.releaseQueryLock();
269 * Single queries are not supported in partial histories. To get the same
270 * result you can do a full query, then call fullState.get(attribute).
273 public ITmfStateInterval
doSingularQuery(long t
, int attributeQuark
) {
274 throw new UnsupportedOperationException();
277 private boolean checkValidTime(long t
) {
278 return (t
>= getStartTime() && t
<= getEndTime());
282 public void debugPrint(PrintWriter writer
) {
283 // TODO Auto-generated method stub
286 private void waitForCheckpoints() {
288 fCheckpointsReady
.await();
289 } catch (InterruptedException e
) {
294 // ------------------------------------------------------------------------
295 // Event requests types
296 // ------------------------------------------------------------------------
298 private class CheckpointsRequest
extends TmfEventRequest
{
299 private final ITmfTrace trace
;
300 private final Map
<Long
, Long
> checkpts
;
301 private long eventCount
;
302 private long lastCheckpointAt
;
304 public CheckpointsRequest(ITmfStateProvider input
, Map
<Long
, Long
> checkpoints
) {
305 super(ITmfEvent
.class,
306 TmfTimeRange
.ETERNITY
,
308 ITmfEventRequest
.ALL_DATA
,
309 ITmfEventRequest
.ExecutionType
.FOREGROUND
);
311 this.trace
= input
.getTrace();
312 this.checkpts
= checkpoints
;
314 lastCheckpointAt
= 0;
316 /* Insert a checkpoint at the start of the trace */
317 checkpoints
.put(input
.getStartTime(), 0L);
321 public void handleData(final ITmfEvent event
) {
322 super.handleData(event
);
323 if (event
.getTrace() == trace
) {
326 /* Check if we need to register a new checkpoint */
327 if (eventCount
>= lastCheckpointAt
+ fGranularity
) {
328 checkpts
.put(event
.getTimestamp().getValue(), eventCount
);
329 lastCheckpointAt
= eventCount
;
335 public void handleCompleted() {
336 super.handleCompleted();
337 fCheckpointsReady
.countDown();
341 private class PartialStateSystemRequest
extends TmfEventRequest
{
342 private final ITmfStateProvider sci
;
343 private final ITmfTrace trace
;
345 PartialStateSystemRequest(ITmfStateProvider sci
, TmfTimeRange range
) {
346 super(ITmfEvent
.class,
349 ITmfEventRequest
.ALL_DATA
,
350 ITmfEventRequest
.ExecutionType
.BACKGROUND
);
352 this.trace
= sci
.getTrace();
356 public void handleData(final ITmfEvent event
) {
357 super.handleData(event
);
358 if (event
.getTrace() == trace
) {
359 sci
.processEvent(event
);
364 public void handleCompleted() {
366 * If we're using a threaded state provider, we need to make sure
367 * all events have been handled by the state system before doing
370 if (fPartialInput
instanceof AbstractTmfStateProvider
) {
371 ((AbstractTmfStateProvider
) fPartialInput
).waitForEmptyQueue();
373 super.handleCompleted();