blob: f254327fcc160550784c09289b858fb3268809f6 [file] [log] [blame]
Yao Chenb3561512017-11-21 18:07:17 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#pragma once
17
18#include "config/ConfigKey.h"
19#include "frameworks/base/cmds/statsd/src/stats_log.pb.h"
Chenjie Yub038b702017-12-18 15:15:34 -080020#include "statslog.h"
Yao Chenb3561512017-11-21 18:07:17 -080021
Yao Chen69f1baf2017-11-27 17:25:36 -080022#include <gtest/gtest_prod.h>
David Chend9269e22017-12-05 13:43:51 -080023#include <log/log_time.h>
Yao Chenf6723df2018-01-08 15:11:58 -080024#include <list>
Yao Chenb3561512017-11-21 18:07:17 -080025#include <mutex>
26#include <string>
27#include <vector>
28
29namespace android {
30namespace os {
31namespace statsd {
32
33// Keeps track of stats of statsd.
34// Single instance shared across the process. All methods are thread safe.
35class StatsdStats {
36public:
37 static StatsdStats& getInstance();
38 ~StatsdStats(){};
39
40 // TODO: set different limit if the device is low ram.
41 const static int kDimensionKeySizeSoftLimit = 300;
42 const static int kDimensionKeySizeHardLimit = 500;
43
44 const static int kMaxConfigCount = 10;
45 const static int kMaxConditionCountPerConfig = 200;
46 const static int kMaxMetricCountPerConfig = 300;
47 const static int kMaxMatcherCountPerConfig = 500;
48
Yao Chenf6723df2018-01-08 15:11:58 -080049 // The max number of old config stats we keep.
50 const static int kMaxIceBoxSize = 20;
51
Yao Chen884c8c12018-01-26 10:36:25 -080052 const static int kMaxLoggerErrors = 10;
53
Yao Chen0fac5b12017-11-28 16:07:02 -080054 const static int kMaxTimestampCount = 20;
55
Yao Chend10f7b12017-12-18 12:53:50 -080056 const static int kMaxLogSourceCount = 50;
57
David Chend9269e22017-12-05 13:43:51 -080058 // Max memory allowed for storing metrics per configuration. When this limit is approached,
59 // statsd will send a broadcast so that the client can fetch the data and clear this memory.
60 static const size_t kMaxMetricsBytesPerConfig = 128 * 1024;
61
David Chenc136f452017-11-27 11:52:26 -080062 // Cap the UID map's memory usage to this. This should be fairly high since the UID information
63 // is critical for understanding the metrics.
64 const static size_t kMaxBytesUsedUidMap = 50 * 1024;
65
David Chend9269e22017-12-05 13:43:51 -080066 /* Minimum period between two broadcasts in nanoseconds. */
67 static const unsigned long long kMinBroadcastPeriodNs = 60 * NS_PER_SEC;
68
69 /* Min period between two checks of byte size per config key in nanoseconds. */
70 static const unsigned long long kMinByteSizeCheckPeriodNs = 10 * NS_PER_SEC;
71
Chenjie Yub038b702017-12-18 15:15:34 -080072 // Default minimum interval between pulls for an atom. Pullers can return cached values if
73 // another pull request happens within this interval.
74 static std::map<int, long> kPullerCooldownMap;
75
76 // Default cooldown time for a puller
77 static const long kDefaultPullerCooldown = 1;
78
yro98a28502018-01-18 17:00:14 -080079 // Maximum age (30 days) that files on disk can exist in seconds.
80 static const int kMaxAgeSecond = 60 * 60 * 24 * 30;
81
82 // Maximum number of files (1000) that can be in stats directory on disk.
83 static const int kMaxFileNumber = 1000;
84
85 // Maximum size of all files that can be written to stats directory on disk.
86 static const int kMaxFileSize = 50 * 1024 * 1024;
87
Chenjie Yufa22d652018-02-05 14:37:48 -080088 // How long to try to clear puller cache from last time
89 static const long kPullerCacheClearIntervalSec = 1;
90
Yao Chenb3561512017-11-21 18:07:17 -080091 /**
92 * Report a new config has been received and report the static stats about the config.
93 *
94 * The static stats include: the count of metrics, conditions, matchers, and alerts.
95 * If the config is not valid, this config stats will be put into icebox immediately.
96 */
97 void noteConfigReceived(const ConfigKey& key, int metricsCount, int conditionsCount,
98 int matchersCount, int alertCount, bool isValid);
99 /**
100 * Report a config has been removed.
101 */
102 void noteConfigRemoved(const ConfigKey& key);
103
104 /**
105 * Report a broadcast has been sent to a config owner to collect the data.
106 */
107 void noteBroadcastSent(const ConfigKey& key);
108
109 /**
110 * Report a config's metrics data has been dropped.
111 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800112 void noteDataDropped(const ConfigKey& key);
113
114 /**
115 * Report metrics data report has been sent.
116 *
117 * The report may be requested via StatsManager API, or through adb cmd.
118 */
119 void noteMetricsReportSent(const ConfigKey& key);
Yao Chenb3561512017-11-21 18:07:17 -0800120
121 /**
122 * Report the size of output tuple of a condition.
123 *
124 * Note: only report when the condition has an output dimension, and the tuple
125 * count > kDimensionKeySizeSoftLimit.
126 *
127 * [key]: The config key that this condition belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800128 * [id]: The id of the condition.
Yao Chenb3561512017-11-21 18:07:17 -0800129 * [size]: The output tuple size.
130 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800131 void noteConditionDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800132
133 /**
134 * Report the size of output tuple of a metric.
135 *
136 * Note: only report when the metric has an output dimension, and the tuple
137 * count > kDimensionKeySizeSoftLimit.
138 *
139 * [key]: The config key that this metric belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800140 * [id]: The id of the metric.
Yao Chenb3561512017-11-21 18:07:17 -0800141 * [size]: The output tuple size.
142 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800143 void noteMetricDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800144
145 /**
146 * Report a matcher has been matched.
147 *
148 * [key]: The config key that this matcher belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800149 * [id]: The id of the matcher.
Yao Chenb3561512017-11-21 18:07:17 -0800150 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800151 void noteMatcherMatched(const ConfigKey& key, const int64_t& id);
Yao Chenb3561512017-11-21 18:07:17 -0800152
153 /**
Bookatz8f2f3d82017-12-07 13:53:21 -0800154 * Report that an anomaly detection alert has been declared.
155 *
156 * [key]: The config key that this alert belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800157 * [id]: The id of the alert.
Bookatz8f2f3d82017-12-07 13:53:21 -0800158 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800159 void noteAnomalyDeclared(const ConfigKey& key, const int64_t& id);
Bookatz8f2f3d82017-12-07 13:53:21 -0800160
161 /**
Yao Chenb3561512017-11-21 18:07:17 -0800162 * Report an atom event has been logged.
163 */
164 void noteAtomLogged(int atomId, int32_t timeSec);
165
166 /**
Bookatz1d0136d2017-12-01 11:13:32 -0800167 * Report that statsd modified the anomaly alarm registered with StatsCompanionService.
168 */
169 void noteRegisteredAnomalyAlarmChanged();
170
171 /**
David Chenc136f452017-11-27 11:52:26 -0800172 * Records the number of snapshot and delta entries that are being dropped from the uid map.
173 */
174 void noteUidMapDropped(int snapshots, int deltas);
175
176 /**
177 * Updates the number of snapshots currently stored in the uid map.
178 */
179 void setUidMapSnapshots(int snapshots);
180 void setUidMapChanges(int changes);
181 void setCurrentUidMapMemory(int bytes);
182
Chenjie Yub038b702017-12-18 15:15:34 -0800183 // Update minimum interval between pulls for an pulled atom
184 void updateMinPullIntervalSec(int pullAtomId, long intervalSec);
185
186 // Notify pull request for an atom
187 void notePull(int pullAtomId);
188
189 // Notify pull request for an atom served from cached data
190 void notePullFromCache(int pullAtomId);
191
David Chenc136f452017-11-27 11:52:26 -0800192 /**
Yao Chen884c8c12018-01-26 10:36:25 -0800193 * Records statsd met an error while reading from logd.
194 */
195 void noteLoggerError(int error);
196
197 /**
Yao Chenb3561512017-11-21 18:07:17 -0800198 * Reset the historical stats. Including all stats in icebox, and the tracked stats about
199 * metrics, matchers, and atoms. The active configs will be kept and StatsdStats will continue
200 * to collect stats after reset() has been called.
201 */
202 void reset();
203
204 /**
205 * Output the stats in protobuf binary format to [buffer].
206 *
207 * [reset]: whether to clear the historical stats after the call.
208 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800209 void dumpStats(std::vector<uint8_t>* buffer, bool reset);
Yao Chenb3561512017-11-21 18:07:17 -0800210
Yao Chenf5acabe2018-01-17 14:10:34 -0800211 /**
212 * Output statsd stats in human readable format to [out] file.
213 */
214 void dumpStats(FILE* out) const;
215
Chenjie Yub038b702017-12-18 15:15:34 -0800216 typedef struct {
217 long totalPull;
218 long totalPullFromCache;
219 long minPullIntervalSec;
220 } PulledAtomStats;
221
Yao Chenb3561512017-11-21 18:07:17 -0800222private:
223 StatsdStats();
224
225 mutable std::mutex mLock;
226
Yao Chen69f1baf2017-11-27 17:25:36 -0800227 int32_t mStartTimeSec;
Yao Chenb3561512017-11-21 18:07:17 -0800228
David Chenc136f452017-11-27 11:52:26 -0800229 // Track the number of dropped entries used by the uid map.
230 StatsdStatsReport_UidMapStats mUidMapStats;
231
Yao Chenb3561512017-11-21 18:07:17 -0800232 // The stats about the configs that are still in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800233 // The map size is capped by kMaxConfigCount.
Yao Chenb3561512017-11-21 18:07:17 -0800234 std::map<const ConfigKey, StatsdStatsReport_ConfigStats> mConfigStats;
235
236 // Stores the stats for the configs that are no longer in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800237 // The size of the vector is capped by kMaxIceBoxSize.
238 std::list<const StatsdStatsReport_ConfigStats> mIceBox;
Yao Chenb3561512017-11-21 18:07:17 -0800239
240 // Stores the number of output tuple of condition trackers when it's bigger than
241 // kDimensionKeySizeSoftLimit. When you see the number is kDimensionKeySizeHardLimit +1,
Yao Chenf6723df2018-01-08 15:11:58 -0800242 // it means some data has been dropped. The map size is capped by kMaxConfigCount.
Yangster-mac94e197c2018-01-02 16:03:03 -0800243 std::map<const ConfigKey, std::map<const int64_t, int>> mConditionStats;
Yao Chenb3561512017-11-21 18:07:17 -0800244
245 // Stores the number of output tuple of metric producers when it's bigger than
246 // kDimensionKeySizeSoftLimit. When you see the number is kDimensionKeySizeHardLimit +1,
Yao Chenf6723df2018-01-08 15:11:58 -0800247 // it means some data has been dropped. The map size is capped by kMaxConfigCount.
Yangster-mac94e197c2018-01-02 16:03:03 -0800248 std::map<const ConfigKey, std::map<const int64_t, int>> mMetricsStats;
Yao Chenb3561512017-11-21 18:07:17 -0800249
250 // Stores the number of times a pushed atom is logged.
251 // The size of the vector is the largest pushed atom id in atoms.proto + 1. Atoms
252 // out of that range will be dropped (it's either pulled atoms or test atoms).
253 // This is a vector, not a map because it will be accessed A LOT -- for each stats log.
254 std::vector<int> mPushedAtomStats;
255
Yao Chenf6723df2018-01-08 15:11:58 -0800256 // Maps PullAtomId to its stats. The size is capped by the puller atom counts.
Chenjie Yub038b702017-12-18 15:15:34 -0800257 std::map<int, PulledAtomStats> mPulledAtomStats;
258
Yao Chen884c8c12018-01-26 10:36:25 -0800259 // Logd errors. Size capped by kMaxLoggerErrors.
260 std::list<const std::pair<int, int>> mLoggerErrors;
261
Bookatz1d0136d2017-12-01 11:13:32 -0800262 // Stores the number of times statsd modified the anomaly alarm registered with
263 // StatsCompanionService.
264 int mAnomalyAlarmRegisteredStats = 0;
265
Bookatz8f2f3d82017-12-07 13:53:21 -0800266 // Stores the number of times an anomaly detection alert has been declared
Yao Chenf6723df2018-01-08 15:11:58 -0800267 // (per config, per alert name). The map size is capped by kMaxConfigCount.
Yangster-mac94e197c2018-01-02 16:03:03 -0800268 std::map<const ConfigKey, std::map<const int64_t, int>> mAlertStats;
Bookatz8f2f3d82017-12-07 13:53:21 -0800269
Yao Chenf6723df2018-01-08 15:11:58 -0800270 // Stores how many times a matcher have been matched. The map size is capped by kMaxConfigCount.
Yangster-mac94e197c2018-01-02 16:03:03 -0800271 std::map<const ConfigKey, std::map<const int64_t, int>> mMatcherStats;
Yao Chenb3561512017-11-21 18:07:17 -0800272
273 void noteConfigRemovedInternalLocked(const ConfigKey& key);
274
275 void resetInternalLocked();
276
Bookatz8f2f3d82017-12-07 13:53:21 -0800277 void addSubStatsToConfigLocked(const ConfigKey& key,
278 StatsdStatsReport_ConfigStats& configStats);
Yao Chen69f1baf2017-11-27 17:25:36 -0800279
Yao Chen0fac5b12017-11-28 16:07:02 -0800280 void noteDataDropped(const ConfigKey& key, int32_t timeSec);
281
282 void noteMetricsReportSent(const ConfigKey& key, int32_t timeSec);
283
284 void noteBroadcastSent(const ConfigKey& key, int32_t timeSec);
285
Yao Chenf6723df2018-01-08 15:11:58 -0800286 void addToIceBoxLocked(const StatsdStatsReport_ConfigStats& stats);
287
Yao Chen69f1baf2017-11-27 17:25:36 -0800288 FRIEND_TEST(StatsdStatsTest, TestValidConfigAdd);
289 FRIEND_TEST(StatsdStatsTest, TestInvalidConfigAdd);
290 FRIEND_TEST(StatsdStatsTest, TestConfigRemove);
291 FRIEND_TEST(StatsdStatsTest, TestSubStats);
292 FRIEND_TEST(StatsdStatsTest, TestAtomLog);
Yao Chen0fac5b12017-11-28 16:07:02 -0800293 FRIEND_TEST(StatsdStatsTest, TestTimestampThreshold);
Bookatz1d0136d2017-12-01 11:13:32 -0800294 FRIEND_TEST(StatsdStatsTest, TestAnomalyMonitor);
Yao Chenb3561512017-11-21 18:07:17 -0800295};
296
297} // namespace statsd
298} // namespace os
Stefan Lafonc6f2fa22018-01-04 22:03:29 -0800299} // namespace android