blob: d64acf39a921e962707cea05b8da40697727b6a2 [file] [log] [blame]
Andy Hung06f3aba2019-12-03 16:36:42 -08001/*
2 * Copyright (C) 2019 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
17#pragma once
18
19#include <any>
20#include <map>
21#include <sstream>
22#include <string>
23
Andy Hungf7c14102020-04-18 14:54:08 -070024#include <android-base/thread_annotations.h>
Ray Essickf27e9872019-12-07 06:28:46 -080025#include <media/MediaMetricsItem.h>
Andy Hung06f3aba2019-12-03 16:36:42 -080026
27namespace android::mediametrics {
28
29/**
Ray Essickf27e9872019-12-07 06:28:46 -080030 * The TransactionLog is used to record mediametrics::Items to present
Andy Hung06f3aba2019-12-03 16:36:42 -080031 * different views on the time information (selected by audio, and sorted by key).
32 *
33 * The TransactionLog will always present data in timestamp order. (Perhaps we
34 * just make this submit order).
35 *
36 * These Views have a cost in shared pointer storage, so they aren't quite free.
37 *
38 * The TransactionLog is NOT thread safe.
39 */
Andy Hungcd24cca2020-01-02 18:27:43 -080040class TransactionLog final { // made final as we have copy constructor instead of dup() override.
Andy Hung06f3aba2019-12-03 16:36:42 -080041public:
42 // In long term run, the garbage collector aims to keep the
43 // Transaction Log between the Low Water Mark and the High Water Mark.
44
45 // low water mark
46 static inline constexpr size_t kLogItemsLowWater = 5000;
47 // high water mark
48 static inline constexpr size_t kLogItemsHighWater = 10000;
49
50 // Estimated max data usage is 1KB * kLogItemsHighWater.
51
52 TransactionLog() = default;
53
54 TransactionLog(size_t lowWaterMark, size_t highWaterMark)
55 : mLowWaterMark(lowWaterMark)
56 , mHighWaterMark(highWaterMark) {
57 LOG_ALWAYS_FATAL_IF(highWaterMark <= lowWaterMark,
58 "%s: required that highWaterMark:%zu > lowWaterMark:%zu",
59 __func__, highWaterMark, lowWaterMark);
60 }
61
Andy Hungcd24cca2020-01-02 18:27:43 -080062 // The TransactionLog copy constructor/assignment is effectively an
63 // instantaneous, isochronous snapshot of the other TransactionLog.
64 //
65 // The contents of the Transaction Log are shared pointers to immutable instances -
66 // std::shared_ptr<const mediametrics::Item>, so we use a shallow copy,
67 // which is more efficient in space and execution time than a deep copy,
68 // and gives the same results.
69
70 TransactionLog(const TransactionLog &other) {
71 *this = other;
72 }
73
74 TransactionLog& operator=(const TransactionLog &other) {
75 std::lock_guard lock(mLock);
76 mLog.clear();
77 mItemMap.clear();
78
79 std::lock_guard lock2(other.mLock);
80 mLog = other.mLog;
81 mItemMap = other.mItemMap;
82
83 return *this;
84 }
85
Andy Hung06f3aba2019-12-03 16:36:42 -080086 /**
87 * Put an item in the TransactionLog.
88 */
Ray Essickf27e9872019-12-07 06:28:46 -080089 status_t put(const std::shared_ptr<const mediametrics::Item>& item) {
Andy Hung06f3aba2019-12-03 16:36:42 -080090 const std::string& key = item->getKey();
91 const int64_t time = item->getTimestamp();
92
93 std::vector<std::any> garbage; // objects destroyed after lock.
94 std::lock_guard lock(mLock);
95
Andy Hungf7c14102020-04-18 14:54:08 -070096 (void)gc(garbage);
Andy Hung06f3aba2019-12-03 16:36:42 -080097 mLog.emplace(time, item);
98 mItemMap[key].emplace(time, item);
99 return NO_ERROR; // no errors for now.
100 }
101
102 /**
103 * Returns all records within [startTime, endTime]
104 */
Ray Essickf27e9872019-12-07 06:28:46 -0800105 std::vector<std::shared_ptr<const mediametrics::Item>> get(
Andy Hung06f3aba2019-12-03 16:36:42 -0800106 int64_t startTime = 0, int64_t endTime = INT64_MAX) const {
107 std::lock_guard lock(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700108 return getItemsInRange(mLog, startTime, endTime);
Andy Hung06f3aba2019-12-03 16:36:42 -0800109 }
110
111 /**
112 * Returns all records for a key within [startTime, endTime]
113 */
Ray Essickf27e9872019-12-07 06:28:46 -0800114 std::vector<std::shared_ptr<const mediametrics::Item>> get(
Andy Hung06f3aba2019-12-03 16:36:42 -0800115 const std::string& key,
116 int64_t startTime = 0, int64_t endTime = INT64_MAX) const {
117 std::lock_guard lock(mLock);
118 auto mapIt = mItemMap.find(key);
119 if (mapIt == mItemMap.end()) return {};
Andy Hungf7c14102020-04-18 14:54:08 -0700120 return getItemsInRange(mapIt->second, startTime, endTime);
Andy Hung06f3aba2019-12-03 16:36:42 -0800121 }
122
123 /**
124 * Returns a pair consisting of the Transaction Log as a string
125 * and the number of lines in the string.
126 *
127 * The number of lines in the returned pair is used as an optimization
128 * for subsequent line limiting.
129 *
130 * \param lines the maximum number of lines in the string returned.
Andy Hung709b91e2020-04-04 14:23:36 -0700131 * \param sinceNs the nanoseconds since Unix epoch to start dump (0 shows all)
132 * \param prefix the desired key prefix to match (nullptr shows all)
Andy Hung06f3aba2019-12-03 16:36:42 -0800133 */
Andy Hung709b91e2020-04-04 14:23:36 -0700134 std::pair<std::string, int32_t> dump(
135 int32_t lines, int64_t sinceNs, const char *prefix = nullptr) const {
Andy Hung06f3aba2019-12-03 16:36:42 -0800136 std::stringstream ss;
137 int32_t ll = lines;
138 std::lock_guard lock(mLock);
139
140 // All audio items in time order.
141 if (ll > 0) {
142 ss << "Consolidated:\n";
143 --ll;
144 }
Andy Hung709b91e2020-04-04 14:23:36 -0700145 auto [s, l] = dumpMapTimeItem(mLog, ll, sinceNs, prefix);
Andy Hungb744faf2020-04-09 13:09:26 -0700146 ss << s;
Andy Hung709b91e2020-04-04 14:23:36 -0700147 ll -= l;
Andy Hung06f3aba2019-12-03 16:36:42 -0800148
149 // Grouped by item key (category)
150 if (ll > 0) {
151 ss << "Categorized:\n";
152 --ll;
153 }
Andy Hung709b91e2020-04-04 14:23:36 -0700154
155 for (auto it = prefix != nullptr ? mItemMap.lower_bound(prefix) : mItemMap.begin();
156 it != mItemMap.end();
157 ++it) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800158 if (ll <= 0) break;
Andy Hung709b91e2020-04-04 14:23:36 -0700159 if (prefix != nullptr && !startsWith(it->first, prefix)) break;
160 auto [s, l] = dumpMapTimeItem(it->second, ll - 1, sinceNs, prefix);
161 if (l == 0) continue; // don't show empty groups (due to sinceNs).
Andy Hungb744faf2020-04-09 13:09:26 -0700162 ss << " " << it->first << "\n" << s;
Andy Hung709b91e2020-04-04 14:23:36 -0700163 ll -= l + 1;
Andy Hung06f3aba2019-12-03 16:36:42 -0800164 }
165 return { ss.str(), lines - ll };
166 }
167
168 /**
169 * Returns number of Items in the TransactionLog.
170 */
171 size_t size() const {
172 std::lock_guard lock(mLock);
173 return mLog.size();
174 }
175
176 /**
177 * Clears all Items from the TransactionLog.
178 */
179 // TODO: Garbage Collector, sweep and expire old values
180 void clear() {
181 std::lock_guard lock(mLock);
182 mLog.clear();
183 mItemMap.clear();
184 }
185
186private:
187 using MapTimeItem =
Ray Essickf27e9872019-12-07 06:28:46 -0800188 std::multimap<int64_t /* time */, std::shared_ptr<const mediametrics::Item>>;
Andy Hung06f3aba2019-12-03 16:36:42 -0800189
Andy Hung709b91e2020-04-04 14:23:36 -0700190 static std::pair<std::string, int32_t> dumpMapTimeItem(
191 const MapTimeItem& mapTimeItem,
192 int32_t lines, int64_t sinceNs = 0, const char *prefix = nullptr) {
193 std::stringstream ss;
194 int32_t ll = lines;
195 // Note: for our data, mapTimeItem.lower_bound(0) == mapTimeItem.begin().
196 for (auto it = mapTimeItem.lower_bound(sinceNs);
197 it != mapTimeItem.end(); ++it) {
198 if (ll <= 0) break;
199 if (prefix != nullptr && !startsWith(it->second->getKey(), prefix)) {
200 continue;
201 }
202 ss << " " << it->second->toString() << "\n";
203 --ll;
204 }
205 return { ss.str(), lines - ll };
206 }
207
Andy Hung06f3aba2019-12-03 16:36:42 -0800208 /**
209 * Garbage collects if the TimeMachine size exceeds the high water mark.
210 *
211 * \param garbage a type-erased vector of elements to be destroyed
212 * outside of lock. Move large items to be destroyed here.
213 *
214 * \return true if garbage collection was done.
215 */
Andy Hungf7c14102020-04-18 14:54:08 -0700216 bool gc(std::vector<std::any>& garbage) REQUIRES(mLock) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800217 if (mLog.size() < mHighWaterMark) return false;
218
219 ALOGD("%s: garbage collection", __func__);
220
221 auto eraseEnd = mLog.begin();
222 size_t toRemove = mLog.size() - mLowWaterMark;
223 // remove at least those elements.
224
225 // use a stale vector with precise type to avoid type erasure overhead in garbage
Ray Essickf27e9872019-12-07 06:28:46 -0800226 std::vector<std::shared_ptr<const mediametrics::Item>> stale;
Andy Hung06f3aba2019-12-03 16:36:42 -0800227
228 for (size_t i = 0; i < toRemove; ++i) {
229 stale.emplace_back(std::move(eraseEnd->second));
230 ++eraseEnd; // amortized O(1)
231 }
232 // ensure that eraseEnd is an lower bound on timeToErase.
233 const int64_t timeToErase = eraseEnd->first;
234 while (eraseEnd != mLog.end()) {
235 auto it = eraseEnd;
236 --it; // amortized O(1)
237 if (it->first != timeToErase) {
238 break; // eraseEnd represents a unique time jump.
239 }
240 stale.emplace_back(std::move(eraseEnd->second));
241 ++eraseEnd;
242 }
243
244 mLog.erase(mLog.begin(), eraseEnd); // O(ptr_diff)
245
246 size_t itemMapCount = 0;
247 for (auto it = mItemMap.begin(); it != mItemMap.end();) {
248 auto &keyHist = it->second;
249 auto it2 = keyHist.lower_bound(timeToErase);
250 if (it2 == keyHist.end()) {
251 garbage.emplace_back(std::move(keyHist)); // directly move keyhist to garbage
252 it = mItemMap.erase(it);
253 } else {
254 for (auto it3 = keyHist.begin(); it3 != it2; ++it3) {
255 stale.emplace_back(std::move(it3->second));
256 }
257 keyHist.erase(keyHist.begin(), it2);
258 itemMapCount += keyHist.size();
259 ++it;
260 }
261 }
262
263 garbage.emplace_back(std::move(stale));
264
265 ALOGD("%s(%zu, %zu): log size:%zu item map size:%zu, item map items:%zu",
266 __func__, mLowWaterMark, mHighWaterMark,
267 mLog.size(), mItemMap.size(), itemMapCount);
268 return true;
269 }
270
Andy Hungf7c14102020-04-18 14:54:08 -0700271 static std::vector<std::shared_ptr<const mediametrics::Item>> getItemsInRange(
Andy Hung06f3aba2019-12-03 16:36:42 -0800272 const MapTimeItem& map,
273 int64_t startTime = 0, int64_t endTime = INT64_MAX) {
274 auto it = map.lower_bound(startTime);
275 if (it == map.end()) return {};
276
277 auto it2 = map.upper_bound(endTime);
278
Ray Essickf27e9872019-12-07 06:28:46 -0800279 std::vector<std::shared_ptr<const mediametrics::Item>> ret;
Andy Hung06f3aba2019-12-03 16:36:42 -0800280 while (it != it2) {
281 ret.push_back(it->second);
282 ++it;
283 }
284 return ret;
285 }
286
Andy Hung5d3f2d12020-03-04 19:55:03 -0800287 const size_t mLowWaterMark = kLogItemsLowWater;
Andy Hung06f3aba2019-12-03 16:36:42 -0800288 const size_t mHighWaterMark = kLogItemsHighWater;
289
290 mutable std::mutex mLock;
291
Andy Hungf7c14102020-04-18 14:54:08 -0700292 MapTimeItem mLog GUARDED_BY(mLock);
293 std::map<std::string /* item_key */, MapTimeItem> mItemMap GUARDED_BY(mLock);
Andy Hung06f3aba2019-12-03 16:36:42 -0800294};
295
296} // namespace android::mediametrics