Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 96ac649a8963a673f0440b0b22c6e869ac6a52bb (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
/*******************************************************************************
 * Copyright (c) 2014, 2015 École Polytechnique de Montréal and others.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Geneviève Bastien - Initial API and implementation
 *******************************************************************************/

package org.eclipse.tracecompass.analysis.os.linux.core.cpuusage;

import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.tracecompass.analysis.os.linux.core.tid.TidAnalysisModule;
import org.eclipse.tracecompass.analysis.os.linux.core.trace.DefaultEventLayout;
import org.eclipse.tracecompass.analysis.os.linux.core.trace.IKernelAnalysisEventLayout;
import org.eclipse.tracecompass.analysis.os.linux.core.trace.IKernelTrace;
import org.eclipse.tracecompass.analysis.os.linux.core.trace.KernelEventLayoutRequirement;
import org.eclipse.tracecompass.common.core.NonNullUtils;
import org.eclipse.tracecompass.common.core.log.TraceCompassLog;
import org.eclipse.tracecompass.common.core.log.TraceCompassLogUtils;
import org.eclipse.tracecompass.common.core.log.TraceCompassLogUtils.ScopeLog;
import org.eclipse.tracecompass.internal.analysis.os.linux.core.Activator;
import org.eclipse.tracecompass.internal.analysis.os.linux.core.kernel.Attributes;
import org.eclipse.tracecompass.statesystem.core.ITmfStateSystem;
import org.eclipse.tracecompass.statesystem.core.exceptions.AttributeNotFoundException;
import org.eclipse.tracecompass.statesystem.core.exceptions.StateSystemDisposedException;
import org.eclipse.tracecompass.statesystem.core.exceptions.StateValueTypeException;
import org.eclipse.tracecompass.statesystem.core.exceptions.TimeRangeException;
import org.eclipse.tracecompass.statesystem.core.interval.ITmfStateInterval;
import org.eclipse.tracecompass.tmf.core.analysis.IAnalysisModule;
import org.eclipse.tracecompass.tmf.core.analysis.requirements.TmfAbstractAnalysisRequirement;
import org.eclipse.tracecompass.tmf.core.analysis.requirements.TmfAbstractAnalysisRequirement.PriorityLevel;
import org.eclipse.tracecompass.tmf.core.statesystem.ITmfStateProvider;
import org.eclipse.tracecompass.tmf.core.statesystem.TmfStateSystemAnalysisModule;
import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
import org.eclipse.tracecompass.tmf.core.trace.TmfTraceUtils;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.SetMultimap;

/**
 * This analysis module computes the CPU usage of a system from a kernel trace.
 * It requires the LTTng Kernel analysis module to have accurate CPU usage data.
 *
 * @author Geneviève Bastien
 */
public class KernelCpuUsageAnalysis extends TmfStateSystemAnalysisModule {

    /** The ID of this analysis */
    public static final String ID = "org.eclipse.tracecompass.analysis.os.linux.cpuusage"; //$NON-NLS-1$

    /** Text used to identify 'total' entries in the returned maps */
    public static final String TOTAL = "total"; //$NON-NLS-1$
    /** String used to separate elements in the returned maps */
    public static final String SPLIT_STRING = "/"; //$NON-NLS-1$
    /** Idle process thread ID */
    public static final String TID_ZERO = "0"; //$NON-NLS-1$

    /** The requirements as an immutable set */
    private static final KernelEventLayoutRequirement LAYOUT_REQUIREMENT;
    private static final SetMultimap<IKernelAnalysisEventLayout, TmfAbstractAnalysisRequirement> LAYOUT_REQ_MAP = NonNullUtils.checkNotNull(HashMultimap.create());

    static {
        LAYOUT_REQUIREMENT = new KernelEventLayoutRequirement(ImmutableSet.of((l) -> l.eventSchedSwitch()), PriorityLevel.MANDATORY);
    }

    private static final Logger LOGGER = TraceCompassLog.getLogger(KernelCpuUsageAnalysis.class);

    private static IKernelAnalysisEventLayout getLayout(@Nullable ITmfTrace trace) {
        IKernelAnalysisEventLayout layout;

        if (trace instanceof IKernelTrace) {
            layout = ((IKernelTrace) trace).getKernelEventLayout();
        } else {
            /* Fall-back to the base LttngEventLayout */
            layout = DefaultEventLayout.getInstance();
        }
        return layout;
    }

    @Override
    protected ITmfStateProvider createStateProvider() {
        ITmfTrace trace = checkNotNull(getTrace());
        IKernelAnalysisEventLayout layout = getLayout(trace);

        return new KernelCpuUsageStateProvider(trace, layout);
    }

    @Override
    protected StateSystemBackendType getBackendType() {
        return StateSystemBackendType.FULL;
    }

    @Override
    protected Iterable<IAnalysisModule> getDependentAnalyses() {
        Set<IAnalysisModule> modules = new HashSet<>();

        ITmfTrace trace = getTrace();
        if (trace == null) {
            throw new IllegalStateException("Analysis requires a trace"); //$NON-NLS-1$
        }
        /*
         * This analysis depends on the LTTng kernel analysis, so it's added to
         * dependent modules.
         */
        Iterable<TidAnalysisModule> kernelModules = TmfTraceUtils.getAnalysisModulesOfClass(trace, TidAnalysisModule.class);
        for (TidAnalysisModule kernelModule : kernelModules) {
            /* Only add the first one we find, if there is one */
            modules.add(kernelModule);
            break;
        }
        return modules;
    }

    /**
     * Gets the maximum number of cores detected
     *
     * @return the number of cores
     * @since 2.0
     */
    public int getNumberOfCores() {

        ITmfStateSystem cpuSs = getStateSystem();
        if (cpuSs != null) {
            try {
                int cpusNode = cpuSs.getQuarkAbsolute(Attributes.CPUS);
                final @NonNull List<@NonNull Integer> subAttributes = cpuSs.getSubAttributes(cpusNode, false);
                int cpus = Integer.MIN_VALUE;
                for (Integer quark : subAttributes) {
                    cpus = Math.max(Integer.parseInt(cpuSs.getAttributeName(quark)), cpus);
                }
                return Math.max(subAttributes.size(), cpus);
            } catch (AttributeNotFoundException e) {
                Activator.getDefault().logError("Error: getting number of core " + e.getMessage(), e); //$NON-NLS-1$
            }
        }
        return -1;

    }

    /**
     * Get a map of time spent on CPU by various threads during a time range.
     *
     * @param cpus
     *            A set of the desired CPUs to get. An empty set gets all the
     *            cores
     * @param start
     *            Start time of requested range
     * @param end
     *            End time of requested range
     * @return A map of TID -> time spent on CPU in the [start, end] interval
     * @since 2.0
     */
    public Map<String, Long> getCpuUsageInRange(Set<@NonNull Integer> cpus, long start, long end) {
        Map<String, Long> map = new HashMap<>();
        Map<String, Long> totalMap = new HashMap<>();

        ITmfTrace trace = getTrace();
        ITmfStateSystem cpuSs = getStateSystem();
        if (trace == null || cpuSs == null) {
            return map;
        }
        ITmfStateSystem kernelSs = TmfStateSystemAnalysisModule.getStateSystem(trace, TidAnalysisModule.ID);
        if (kernelSs == null) {
            return map;
        }

        /*
         * Make sure the start/end times are within the state history, so we
         * don't get TimeRange exceptions.
         */
        long startTime = Math.max(start, cpuSs.getStartTime());
        startTime = Math.max(startTime, kernelSs.getStartTime());
        long endTime = Math.min(end, cpuSs.getCurrentEndTime());
        endTime = Math.min(endTime, kernelSs.getCurrentEndTime());
        long totalTime = 0;
        if (endTime < startTime) {
            return map;
        }

        try (ScopeLog scopeLog = new ScopeLog(LOGGER, Level.FINE, "KernelCpuUsageAnalysis#getCpuUsageInRange")) { //$NON-NLS-1$
            /* Get the list of quarks for each CPU and CPU's TIDs */
            int cpusNode = cpuSs.getQuarkAbsolute(Attributes.CPUS);
            Map<Integer, List<Integer>> tidsPerCpu = new HashMap<>();
            for (int cpuNode : cpuSs.getSubAttributes(cpusNode, false)) {
                final @NonNull List<@NonNull Integer> cpuSubAttributes = cpuSs.getSubAttributes(cpuNode, false);
                if (cpus.isEmpty() || cpus.contains(Integer.parseInt(cpuSs.getAttributeName(cpuNode)))) {
                    tidsPerCpu.put(cpuNode, cpuSubAttributes);
                }
            }

            /* Query full states at start and end times */
            List<ITmfStateInterval> kernelEndState = kernelSs.queryFullState(endTime);
            List<ITmfStateInterval> endState = cpuSs.queryFullState(endTime);
            List<ITmfStateInterval> kernelStartState = kernelSs.queryFullState(startTime);
            List<ITmfStateInterval> startState = cpuSs.queryFullState(startTime);

            long countAtStart, countAtEnd;

            for (Entry<Integer, List<Integer>> entry : tidsPerCpu.entrySet()) {
                int cpuNode = Objects.requireNonNull(entry.getKey());
                List<Integer> tidNodes = Objects.requireNonNull(entry.getValue());

                String curCpuName = cpuSs.getAttributeName(cpuNode);
                long cpuTotal = 0;

                /* Get the quark of the thread running on this CPU */
                int currentThreadQuark = kernelSs.getQuarkAbsolute(curCpuName);
                /* Get the currently running thread on this CPU */
                int startThread = kernelStartState.get(currentThreadQuark).getStateValue().unboxInt();
                int endThread = kernelEndState.get(currentThreadQuark).getStateValue().unboxInt();

                for (int tidNode : tidNodes) {
                    String curTidName = cpuSs.getAttributeName(tidNode);
                    int tid = Integer.parseInt(curTidName);

                    countAtEnd = endState.get(tidNode).getStateValue().unboxLong();
                    countAtStart = startState.get(tidNode).getStateValue().unboxLong();
                    if (countAtStart == -1) {
                        countAtStart = 0;
                    }
                    if (countAtEnd == -1) {
                        countAtEnd = 0;
                    }

                    /*
                     * Interpolate start and end time of threads running at
                     * those times
                     */
                    if (tid == startThread || startThread == -1) {
                        ITmfStateInterval threadState = kernelStartState.get(currentThreadQuark);
                        long runningTime = threadState.getEndTime() - threadState.getStartTime();
                        long runningEnd = threadState.getEndTime();

                        countAtStart = interpolateCount(countAtStart, startTime, runningEnd, runningTime);
                    }
                    if (tid == endThread) {
                        long runningTime = kernelEndState.get(currentThreadQuark).getEndTime() - kernelEndState.get(currentThreadQuark).getStartTime();
                        long runningEnd = kernelEndState.get(currentThreadQuark).getEndTime();

                        countAtEnd = interpolateCount(countAtEnd, endTime, runningEnd, runningTime);
                    }
                    /*
                     * If startThread is -1, we made the hypothesis that the
                     * process running at start was the current one. If the
                     * count is negative, we were wrong in this hypothesis. Also
                     * if the time at end is 0, it either means the process
                     * hasn't been on the CPU or that we still don't know who is
                     * running. In both cases, that invalidates the hypothesis.
                     */
                    if ((startThread == -1) && ((countAtEnd - countAtStart < 0) || (countAtEnd == 0))) {
                        countAtStart = 0;
                    }

                    long currentCount = countAtEnd - countAtStart;
                    if (currentCount < 0) {
                        TraceCompassLogUtils.traceInstant(LOGGER, Level.FINE, "Negative count", //$NON-NLS-1$
                                "CPU", curCpuName, //$NON-NLS-1$
                                "tid", curTidName, //$NON-NLS-1$
                                "startTime", startTime, //$NON-NLS-1$
                                "endTime", endTime, //$NON-NLS-1$
                                "countAtStart", countAtStart, //$NON-NLS-1$
                                "countAtEnd", countAtEnd); //$NON-NLS-1$
                        currentCount = 0;
                    } else if (currentCount > endTime - startTime) {
                        TraceCompassLogUtils.traceInstant(LOGGER, Level.FINE, "CPU usage over 100%", //$NON-NLS-1$
                                "CPU", curCpuName, //$NON-NLS-1$
                                "tid", curTidName, //$NON-NLS-1$
                                "startTime", startTime, //$NON-NLS-1$
                                "CPU time", currentCount, //$NON-NLS-1$
                                "elapsed time", endTime - startTime, //$NON-NLS-1$
                                "usage", currentCount * 100.0 / (endTime - startTime)); //$NON-NLS-1$
                        currentCount = 0;
                    }
                    cpuTotal += currentCount;
                    map.put(curCpuName + SPLIT_STRING + curTidName, currentCount);
                    addToMap(totalMap, curTidName, currentCount);
                    totalTime += (currentCount);
                }
                map.put(curCpuName, cpuTotal);
            }

            /* Add the totals to the map */
            for (Entry<String, Long> entry : totalMap.entrySet()) {
                map.put(TOTAL + SPLIT_STRING + entry.getKey(), entry.getValue());
            }
            map.put(TOTAL, totalTime);

        } catch (TimeRangeException | AttributeNotFoundException e) {
            /*
             * Assume there is no events or the attribute does not exist yet,
             * nothing will be put in the map.
             */
        } catch (StateValueTypeException | StateSystemDisposedException e) {
            /*
             * These other exception types would show a logic problem, so they
             * should not happen.
             */
            Activator.getDefault().logError("Error getting CPU usage in a time range", e); //$NON-NLS-1$
        }

        return map;
    }

    private static long interpolateCount(long count, long ts, long runningEnd, long runningTime) {
        long newCount = count;

        /* sanity check */
        if (runningTime > 0) {

            long runningStart = runningEnd - runningTime;

            if (ts < runningStart) {
                /*
                 * This interval was not started, this can happen if the current
                 * running thread is unknown and we execute this method. It just
                 * means that this process was not the one running
                 */
                return newCount;
            }
            newCount += (ts - runningStart);
        }
        return newCount;
    }

    /*
     * Add the value to the previous value in the map. If the key was not set,
     * assume 0
     */
    private static void addToMap(Map<String, Long> map, String key, Long value) {
        Long addTo = map.get(key);
        if (addTo == null) {
            map.put(key, value);
        } else {
            map.put(key, addTo + value);
        }
    }

    @Override
    public Iterable<TmfAbstractAnalysisRequirement> getAnalysisRequirements() {
        ITmfTrace trace = getTrace();
        IKernelAnalysisEventLayout layout = getLayout(trace);
        Set<TmfAbstractAnalysisRequirement> reqs = LAYOUT_REQ_MAP.get(layout);
        if (reqs.isEmpty()) {
            reqs = ImmutableSet.of(LAYOUT_REQUIREMENT.instanciateRequirements(layout));
            LAYOUT_REQ_MAP.putAll(layout, reqs);
        }
        return reqs;
    }

}

Back to the top