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
.linuxtools
.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
.linuxtools
.statesystem
.core
.ITmfStateSystem
;
24 import org
.eclipse
.linuxtools
.statesystem
.core
.backend
.IStateHistoryBackend
;
25 import org
.eclipse
.linuxtools
.statesystem
.core
.exceptions
.AttributeNotFoundException
;
26 import org
.eclipse
.linuxtools
.statesystem
.core
.exceptions
.StateSystemDisposedException
;
27 import org
.eclipse
.linuxtools
.statesystem
.core
.exceptions
.TimeRangeException
;
28 import org
.eclipse
.linuxtools
.statesystem
.core
.interval
.ITmfStateInterval
;
29 import org
.eclipse
.linuxtools
.statesystem
.core
.interval
.TmfStateInterval
;
30 import org
.eclipse
.linuxtools
.statesystem
.core
.statevalue
.ITmfStateValue
;
31 import org
.eclipse
.linuxtools
.tmf
.core
.event
.ITmfEvent
;
32 import org
.eclipse
.linuxtools
.tmf
.core
.request
.ITmfEventRequest
;
33 import org
.eclipse
.linuxtools
.tmf
.core
.request
.TmfEventRequest
;
34 import org
.eclipse
.linuxtools
.tmf
.core
.statesystem
.AbstractTmfStateProvider
;
35 import org
.eclipse
.linuxtools
.tmf
.core
.statesystem
.ITmfStateProvider
;
36 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.ITmfTimestamp
;
37 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfTimeRange
;
38 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfTimestamp
;
39 import org
.eclipse
.linuxtools
.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
{
60 * A partial history needs the state input plugin to re-generate state
61 * between checkpoints.
63 private final @NonNull ITmfStateProvider partialInput
;
66 * Fake state system that is used for partially rebuilding the states (when
67 * going from a checkpoint to a target query timestamp).
69 private final @NonNull PartialStateSystem partialSS
;
71 /** Reference to the "real" state history that is used for storage */
72 private final @NonNull IStateHistoryBackend innerHistory
;
74 /** Checkpoints map, <Timestamp, Rank in the trace> */
75 private final @NonNull TreeMap
<Long
, Long
> checkpoints
= new TreeMap
<>();
77 /** Latch tracking if the initial checkpoint registration is done */
78 private final @NonNull CountDownLatch checkpointsReady
= new CountDownLatch(1);
80 private final long granularity
;
82 private long latestTime
;
88 * The state change input object that was used to build the
89 * upstream state system. This partial history will make its own
90 * copy (since they have different targets).
92 * The partial history's inner state system. It should already be
93 * assigned to partialInput.
95 * The real state history back-end to use. It's supposed to be
96 * modular, so it should be able to be of any type.
98 * Configuration parameter indicating how many trace events there
99 * should be between each checkpoint
101 public PartialHistoryBackend(ITmfStateProvider partialInput
, PartialStateSystem pss
,
102 IStateHistoryBackend realBackend
, long granularity
) {
103 if (granularity
<= 0 || partialInput
== null || pss
== null ||
104 partialInput
.getAssignedStateSystem() != pss
) {
105 throw new IllegalArgumentException();
108 final long startTime
= realBackend
.getStartTime();
110 this.partialInput
= partialInput
;
111 this.partialSS
= pss
;
113 this.innerHistory
= realBackend
;
114 this.granularity
= granularity
;
116 latestTime
= startTime
;
118 registerCheckpoints();
121 private void registerCheckpoints() {
122 ITmfEventRequest request
= new CheckpointsRequest(partialInput
, checkpoints
);
123 partialInput
.getTrace().sendRequest(request
);
124 /* The request will countDown the checkpoints latch once it's finished */
128 public long getStartTime() {
129 return innerHistory
.getStartTime();
133 public long getEndTime() {
138 public void insertPastState(long stateStartTime
, long stateEndTime
,
139 int quark
, ITmfStateValue value
) throws TimeRangeException
{
140 waitForCheckpoints();
142 /* Update the latest time */
143 if (stateEndTime
> latestTime
) {
144 latestTime
= stateEndTime
;
148 * Check if the interval intersects the previous checkpoint. If so,
149 * insert it in the real history back-end.
151 * FIXME since intervals are inserted in order of rank, we could avoid
152 * doing a map lookup every time here (just compare with the known
155 if (stateStartTime
<= checkpoints
.floorKey(stateEndTime
)) {
156 innerHistory
.insertPastState(stateStartTime
, stateEndTime
, quark
, value
);
161 public void finishedBuilding(long endTime
) throws TimeRangeException
{
162 innerHistory
.finishedBuilding(endTime
);
166 public FileInputStream
supplyAttributeTreeReader() {
167 return innerHistory
.supplyAttributeTreeReader();
171 public File
supplyAttributeTreeWriterFile() {
172 return innerHistory
.supplyAttributeTreeWriterFile();
176 public long supplyAttributeTreeWriterFilePosition() {
177 return innerHistory
.supplyAttributeTreeWriterFilePosition();
181 public void removeFiles() {
182 innerHistory
.removeFiles();
186 public void dispose() {
187 partialInput
.dispose();
189 innerHistory
.dispose();
193 public void doQuery(List
<ITmfStateInterval
> currentStateInfo
, long t
)
194 throws TimeRangeException
, StateSystemDisposedException
{
195 /* Wait for required steps to be done */
196 waitForCheckpoints();
197 partialSS
.getUpstreamSS().waitUntilBuilt();
199 if (!checkValidTime(t
)) {
200 throw new TimeRangeException();
203 /* Reload the previous checkpoint */
204 long checkpointTime
= checkpoints
.floorKey(t
);
205 innerHistory
.doQuery(currentStateInfo
, checkpointTime
);
208 * Set the initial contents of the partial state system (which is the
209 * contents of the query at the checkpoint).
211 partialSS
.takeQueryLock();
212 partialSS
.replaceOngoingState(currentStateInfo
);
214 /* Send an event request to update the state system to the target time. */
215 TmfTimeRange range
= new TmfTimeRange(
217 * The state at the checkpoint already includes any state change
218 * caused by the event(s) happening exactly at 'checkpointTime',
219 * if any. We must not include those events in the query.
221 new TmfTimestamp(checkpointTime
+ 1, ITmfTimestamp
.NANOSECOND_SCALE
),
222 new TmfTimestamp(t
, ITmfTimestamp
.NANOSECOND_SCALE
));
223 ITmfEventRequest request
= new PartialStateSystemRequest(partialInput
, range
);
224 partialInput
.getTrace().sendRequest(request
);
227 request
.waitForCompletion();
228 } catch (InterruptedException e
) {
233 * Now the partial state system should have the ongoing time we are
234 * looking for. However, the method expects a List of *state intervals*,
235 * not state values, so we'll create intervals with a dummy end time.
238 for (int i
= 0; i
< currentStateInfo
.size(); i
++) {
240 ITmfStateValue val
= null;
241 start
= ((ITmfStateSystem
) partialSS
).getOngoingStartTime(i
);
242 val
= ((ITmfStateSystem
) partialSS
).queryOngoingState(i
);
244 ITmfStateInterval interval
= new TmfStateInterval(start
, t
, i
, val
);
245 currentStateInfo
.set(i
, interval
);
247 } catch (AttributeNotFoundException e
) {
248 /* Should not happen, we iterate over existing values. */
252 partialSS
.releaseQueryLock();
256 * Single queries are not supported in partial histories. To get the same
257 * result you can do a full query, then call fullState.get(attribute).
260 public ITmfStateInterval
doSingularQuery(long t
, int attributeQuark
) {
261 throw new UnsupportedOperationException();
265 public boolean checkValidTime(long t
) {
266 return (t
>= getStartTime() && t
<= getEndTime());
270 public void debugPrint(PrintWriter writer
) {
271 // TODO Auto-generated method stub
274 private void waitForCheckpoints() {
276 checkpointsReady
.await();
277 } catch (InterruptedException e
) {
282 // ------------------------------------------------------------------------
283 // Event requests types
284 // ------------------------------------------------------------------------
286 private class CheckpointsRequest
extends TmfEventRequest
{
287 private final ITmfTrace trace
;
288 private final Map
<Long
, Long
> checkpts
;
289 private long eventCount
;
290 private long lastCheckpointAt
;
292 public CheckpointsRequest(ITmfStateProvider input
, Map
<Long
, Long
> checkpoints
) {
293 super(input
.getExpectedEventType(),
294 TmfTimeRange
.ETERNITY
,
296 ITmfEventRequest
.ALL_DATA
,
297 ITmfEventRequest
.ExecutionType
.FOREGROUND
);
299 this.trace
= input
.getTrace();
300 this.checkpts
= checkpoints
;
302 lastCheckpointAt
= 0;
304 /* Insert a checkpoint at the start of the trace */
305 checkpoints
.put(input
.getStartTime(), 0L);
309 public void handleData(final ITmfEvent event
) {
310 super.handleData(event
);
311 if (event
.getTrace() == trace
) {
314 /* Check if we need to register a new checkpoint */
315 if (eventCount
>= lastCheckpointAt
+ granularity
) {
316 checkpts
.put(event
.getTimestamp().getValue(), eventCount
);
317 lastCheckpointAt
= eventCount
;
323 public void handleCompleted() {
324 super.handleCompleted();
325 checkpointsReady
.countDown();
329 private class PartialStateSystemRequest
extends TmfEventRequest
{
330 private final ITmfStateProvider sci
;
331 private final ITmfTrace trace
;
333 PartialStateSystemRequest(ITmfStateProvider sci
, TmfTimeRange range
) {
334 super(sci
.getExpectedEventType(),
337 ITmfEventRequest
.ALL_DATA
,
338 ITmfEventRequest
.ExecutionType
.BACKGROUND
);
340 this.trace
= sci
.getTrace();
344 public void handleData(final ITmfEvent event
) {
345 super.handleData(event
);
346 if (event
.getTrace() == trace
) {
347 sci
.processEvent(event
);
352 public void handleCompleted() {
354 * If we're using a threaded state provider, we need to make sure
355 * all events have been handled by the state system before doing
358 if (partialInput
instanceof AbstractTmfStateProvider
) {
359 ((AbstractTmfStateProvider
) partialInput
).waitForEmptyQueue();
361 super.handleCompleted();