blob: 0c5d12b0d4ce6b77e3665d9f0040469a7a4e8a5c [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
Ray Essickf27e9872019-12-07 06:28:46 -080024#include <media/MediaMetricsItem.h>
Andy Hung06f3aba2019-12-03 16:36:42 -080025
26namespace android::mediametrics {
27
28/**
Ray Essickf27e9872019-12-07 06:28:46 -080029 * The TransactionLog is used to record mediametrics::Items to present
Andy Hung06f3aba2019-12-03 16:36:42 -080030 * different views on the time information (selected by audio, and sorted by key).
31 *
32 * The TransactionLog will always present data in timestamp order. (Perhaps we
33 * just make this submit order).
34 *
35 * These Views have a cost in shared pointer storage, so they aren't quite free.
36 *
37 * The TransactionLog is NOT thread safe.
38 */
Andy Hungcd24cca2020-01-02 18:27:43 -080039class TransactionLog final { // made final as we have copy constructor instead of dup() override.
Andy Hung06f3aba2019-12-03 16:36:42 -080040public:
41 // In long term run, the garbage collector aims to keep the
42 // Transaction Log between the Low Water Mark and the High Water Mark.
43
44 // low water mark
45 static inline constexpr size_t kLogItemsLowWater = 5000;
46 // high water mark
47 static inline constexpr size_t kLogItemsHighWater = 10000;
48
49 // Estimated max data usage is 1KB * kLogItemsHighWater.
50
51 TransactionLog() = default;
52
53 TransactionLog(size_t lowWaterMark, size_t highWaterMark)
54 : mLowWaterMark(lowWaterMark)
55 , mHighWaterMark(highWaterMark) {
56 LOG_ALWAYS_FATAL_IF(highWaterMark <= lowWaterMark,
57 "%s: required that highWaterMark:%zu > lowWaterMark:%zu",
58 __func__, highWaterMark, lowWaterMark);
59 }
60
Andy Hungcd24cca2020-01-02 18:27:43 -080061 // The TransactionLog copy constructor/assignment is effectively an
62 // instantaneous, isochronous snapshot of the other TransactionLog.
63 //
64 // The contents of the Transaction Log are shared pointers to immutable instances -
65 // std::shared_ptr<const mediametrics::Item>, so we use a shallow copy,
66 // which is more efficient in space and execution time than a deep copy,
67 // and gives the same results.
68
69 TransactionLog(const TransactionLog &other) {
70 *this = other;
71 }
72
73 TransactionLog& operator=(const TransactionLog &other) {
74 std::lock_guard lock(mLock);
75 mLog.clear();
76 mItemMap.clear();
77
78 std::lock_guard lock2(other.mLock);
79 mLog = other.mLog;
80 mItemMap = other.mItemMap;
81
82 return *this;
83 }
84
Andy Hung06f3aba2019-12-03 16:36:42 -080085 /**
86 * Put an item in the TransactionLog.
87 */
Ray Essickf27e9872019-12-07 06:28:46 -080088 status_t put(const std::shared_ptr<const mediametrics::Item>& item) {
Andy Hung06f3aba2019-12-03 16:36:42 -080089 const std::string& key = item->getKey();
90 const int64_t time = item->getTimestamp();
91
92 std::vector<std::any> garbage; // objects destroyed after lock.
93 std::lock_guard lock(mLock);
94
95 (void)gc_l(garbage);
96 mLog.emplace(time, item);
97 mItemMap[key].emplace(time, item);
98 return NO_ERROR; // no errors for now.
99 }
100
101 /**
102 * Returns all records within [startTime, endTime]
103 */
Ray Essickf27e9872019-12-07 06:28:46 -0800104 std::vector<std::shared_ptr<const mediametrics::Item>> get(
Andy Hung06f3aba2019-12-03 16:36:42 -0800105 int64_t startTime = 0, int64_t endTime = INT64_MAX) const {
106 std::lock_guard lock(mLock);
107 return getItemsInRange_l(mLog, startTime, endTime);
108 }
109
110 /**
111 * Returns all records for a key within [startTime, endTime]
112 */
Ray Essickf27e9872019-12-07 06:28:46 -0800113 std::vector<std::shared_ptr<const mediametrics::Item>> get(
Andy Hung06f3aba2019-12-03 16:36:42 -0800114 const std::string& key,
115 int64_t startTime = 0, int64_t endTime = INT64_MAX) const {
116 std::lock_guard lock(mLock);
117 auto mapIt = mItemMap.find(key);
118 if (mapIt == mItemMap.end()) return {};
119 return getItemsInRange_l(mapIt->second, startTime, endTime);
120 }
121
122 /**
123 * Returns a pair consisting of the Transaction Log as a string
124 * and the number of lines in the string.
125 *
126 * The number of lines in the returned pair is used as an optimization
127 * for subsequent line limiting.
128 *
129 * \param lines the maximum number of lines in the string returned.
130 */
131 std::pair<std::string, int32_t> dump(int32_t lines) const {
132 std::stringstream ss;
133 int32_t ll = lines;
134 std::lock_guard lock(mLock);
135
136 // All audio items in time order.
137 if (ll > 0) {
138 ss << "Consolidated:\n";
139 --ll;
140 }
141 for (const auto &log : mLog) {
142 if (ll <= 0) break;
143 ss << " " << log.second->toString() << "\n";
144 --ll;
145 }
146
147 // Grouped by item key (category)
148 if (ll > 0) {
149 ss << "Categorized:\n";
150 --ll;
151 }
152 for (const auto &itemMap : mItemMap) {
153 if (ll <= 0) break;
154 ss << " " << itemMap.first << "\n";
155 --ll;
156 for (const auto &item : itemMap.second) {
157 if (ll <= 0) break;
158 ss << " { " << item.first << ", " << item.second->toString() << " }\n";
159 --ll;
160 }
161 }
162 return { ss.str(), lines - ll };
163 }
164
165 /**
166 * Returns number of Items in the TransactionLog.
167 */
168 size_t size() const {
169 std::lock_guard lock(mLock);
170 return mLog.size();
171 }
172
173 /**
174 * Clears all Items from the TransactionLog.
175 */
176 // TODO: Garbage Collector, sweep and expire old values
177 void clear() {
178 std::lock_guard lock(mLock);
179 mLog.clear();
180 mItemMap.clear();
181 }
182
183private:
184 using MapTimeItem =
Ray Essickf27e9872019-12-07 06:28:46 -0800185 std::multimap<int64_t /* time */, std::shared_ptr<const mediametrics::Item>>;
Andy Hung06f3aba2019-12-03 16:36:42 -0800186
187 // GUARDED_BY mLock
188 /**
189 * Garbage collects if the TimeMachine size exceeds the high water mark.
190 *
191 * \param garbage a type-erased vector of elements to be destroyed
192 * outside of lock. Move large items to be destroyed here.
193 *
194 * \return true if garbage collection was done.
195 */
196 bool gc_l(std::vector<std::any>& garbage) {
197 if (mLog.size() < mHighWaterMark) return false;
198
199 ALOGD("%s: garbage collection", __func__);
200
201 auto eraseEnd = mLog.begin();
202 size_t toRemove = mLog.size() - mLowWaterMark;
203 // remove at least those elements.
204
205 // use a stale vector with precise type to avoid type erasure overhead in garbage
Ray Essickf27e9872019-12-07 06:28:46 -0800206 std::vector<std::shared_ptr<const mediametrics::Item>> stale;
Andy Hung06f3aba2019-12-03 16:36:42 -0800207
208 for (size_t i = 0; i < toRemove; ++i) {
209 stale.emplace_back(std::move(eraseEnd->second));
210 ++eraseEnd; // amortized O(1)
211 }
212 // ensure that eraseEnd is an lower bound on timeToErase.
213 const int64_t timeToErase = eraseEnd->first;
214 while (eraseEnd != mLog.end()) {
215 auto it = eraseEnd;
216 --it; // amortized O(1)
217 if (it->first != timeToErase) {
218 break; // eraseEnd represents a unique time jump.
219 }
220 stale.emplace_back(std::move(eraseEnd->second));
221 ++eraseEnd;
222 }
223
224 mLog.erase(mLog.begin(), eraseEnd); // O(ptr_diff)
225
226 size_t itemMapCount = 0;
227 for (auto it = mItemMap.begin(); it != mItemMap.end();) {
228 auto &keyHist = it->second;
229 auto it2 = keyHist.lower_bound(timeToErase);
230 if (it2 == keyHist.end()) {
231 garbage.emplace_back(std::move(keyHist)); // directly move keyhist to garbage
232 it = mItemMap.erase(it);
233 } else {
234 for (auto it3 = keyHist.begin(); it3 != it2; ++it3) {
235 stale.emplace_back(std::move(it3->second));
236 }
237 keyHist.erase(keyHist.begin(), it2);
238 itemMapCount += keyHist.size();
239 ++it;
240 }
241 }
242
243 garbage.emplace_back(std::move(stale));
244
245 ALOGD("%s(%zu, %zu): log size:%zu item map size:%zu, item map items:%zu",
246 __func__, mLowWaterMark, mHighWaterMark,
247 mLog.size(), mItemMap.size(), itemMapCount);
248 return true;
249 }
250
Ray Essickf27e9872019-12-07 06:28:46 -0800251 static std::vector<std::shared_ptr<const mediametrics::Item>> getItemsInRange_l(
Andy Hung06f3aba2019-12-03 16:36:42 -0800252 const MapTimeItem& map,
253 int64_t startTime = 0, int64_t endTime = INT64_MAX) {
254 auto it = map.lower_bound(startTime);
255 if (it == map.end()) return {};
256
257 auto it2 = map.upper_bound(endTime);
258
Ray Essickf27e9872019-12-07 06:28:46 -0800259 std::vector<std::shared_ptr<const mediametrics::Item>> ret;
Andy Hung06f3aba2019-12-03 16:36:42 -0800260 while (it != it2) {
261 ret.push_back(it->second);
262 ++it;
263 }
264 return ret;
265 }
266
267 const size_t mLowWaterMark = kLogItemsHighWater;
268 const size_t mHighWaterMark = kLogItemsHighWater;
269
270 mutable std::mutex mLock;
271
272 // GUARDED_BY mLock
273 MapTimeItem mLog;
274
275 // GUARDED_BY mLock
276 std::map<std::string /* item_key */, MapTimeItem> mItemMap;
277};
278
279} // namespace android::mediametrics