blob: c82778b28f426f3db5a6cd1f593e60d208c7b245 [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#include <variant>
24#include <vector>
25
Andy Hungf7c14102020-04-18 14:54:08 -070026#include <android-base/thread_annotations.h>
Ray Essickf27e9872019-12-07 06:28:46 -080027#include <media/MediaMetricsItem.h>
Andy Hung06f3aba2019-12-03 16:36:42 -080028#include <utils/Timers.h>
29
30namespace android::mediametrics {
31
32// define a way of printing the monostate
33inline std::ostream & operator<< (std::ostream& s,
34 std::monostate const& v __unused) {
35 s << "none_item";
36 return s;
37}
38
Andy Hunge8989ae2020-01-03 12:20:43 -080039// define a way of printing a std::pair.
40template <typename T, typename U>
41std::ostream & operator<< (std::ostream& s,
42 const std::pair<T, U>& v) {
43 s << "{ " << v.first << ", " << v.second << " }";
44 return s;
45}
46
Andy Hung06f3aba2019-12-03 16:36:42 -080047// define a way of printing a variant
48// see https://en.cppreference.com/w/cpp/utility/variant/visit
49template <typename T0, typename ... Ts>
50std::ostream & operator<< (std::ostream& s,
51 std::variant<T0, Ts...> const& v) {
52 std::visit([&s](auto && arg){ s << std::forward<decltype(arg)>(arg); }, v);
53 return s;
54}
55
56/**
57 * The TimeMachine is used to record timing changes of MediaAnalyticItem
58 * properties.
59 *
Andy Hung8f069622020-02-10 15:44:01 -080060 * Any URL that ends with '#' (AMEDIAMETRICS_PROP_SUFFIX_CHAR_DUPLICATES_ALLOWED)
61 * will have a time sequence that keeps duplicates.
Andy Hung06f3aba2019-12-03 16:36:42 -080062 *
63 * The TimeMachine is NOT thread safe.
64 */
Andy Hunga8f1c6e2020-01-02 18:25:41 -080065class TimeMachine final { // made final as we have copy constructor instead of dup() override.
Andy Hunge8989ae2020-01-03 12:20:43 -080066public:
67 using Elem = Item::Prop::Elem; // use the Item property element.
Andy Hung06f3aba2019-12-03 16:36:42 -080068 using PropertyHistory = std::multimap<int64_t /* time */, Elem>;
69
Andy Hunge8989ae2020-01-03 12:20:43 -080070private:
71
Andy Hung06f3aba2019-12-03 16:36:42 -080072 // KeyHistory contains no lock.
73 // Access is through the TimeMachine, and a hash-striped lock is used
74 // before calling into KeyHistory.
75 class KeyHistory {
76 public:
77 template <typename T>
Andy Hungd203eb62020-04-27 09:12:46 -070078 KeyHistory(T key, uid_t allowUid, int64_t time)
Andy Hung06f3aba2019-12-03 16:36:42 -080079 : mKey(key)
Andy Hungd203eb62020-04-27 09:12:46 -070080 , mAllowUid(allowUid)
Andy Hung06f3aba2019-12-03 16:36:42 -080081 , mCreationTime(time)
82 , mLastModificationTime(time)
83 {
Andy Hungd203eb62020-04-27 09:12:46 -070084 // allowUid allows an untrusted client with a matching uid to set properties
85 // in this key.
86 // If allowUid == (uid_t)-1, no untrusted client may set properties in the key.
87 if (allowUid != (uid_t)-1) {
88 // Set ALLOWUID property here; does not change after key creation.
89 putValue(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)allowUid, time);
90 }
Andy Hung06f3aba2019-12-03 16:36:42 -080091 }
92
Andy Hunga8f1c6e2020-01-02 18:25:41 -080093 KeyHistory(const KeyHistory &other) = default;
94
Andy Hungd203eb62020-04-27 09:12:46 -070095 // Return NO_ERROR only if the passed in uidCheck is -1 or matches
96 // the internal mAllowUid.
97 // An external submit will always have a valid uidCheck parameter.
98 // An internal get request within mediametrics will have a uidCheck == -1 which
99 // we allow to proceed.
Andy Hung06f3aba2019-12-03 16:36:42 -0800100 status_t checkPermission(uid_t uidCheck) const {
Andy Hungd203eb62020-04-27 09:12:46 -0700101 return uidCheck != (uid_t)-1 && uidCheck != mAllowUid ? PERMISSION_DENIED : NO_ERROR;
Andy Hung06f3aba2019-12-03 16:36:42 -0800102 }
103
104 template <typename T>
Andy Hungf7c14102020-04-18 14:54:08 -0700105 status_t getValue(const std::string &property, T* value, int64_t time = 0) const
106 REQUIRES(mPseudoKeyHistoryLock) {
Andy Hunged416da2020-03-05 18:42:55 -0800107 if (time == 0) time = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung06f3aba2019-12-03 16:36:42 -0800108 const auto tsptr = mPropertyMap.find(property);
109 if (tsptr == mPropertyMap.end()) return BAD_VALUE;
110 const auto& timeSequence = tsptr->second;
111 auto eptr = timeSequence.upper_bound(time);
112 if (eptr == timeSequence.begin()) return BAD_VALUE;
113 --eptr;
114 if (eptr == timeSequence.end()) return BAD_VALUE;
115 const T* vptr = std::get_if<T>(&eptr->second);
116 if (vptr == nullptr) return BAD_VALUE;
117 *value = *vptr;
118 return NO_ERROR;
119 }
120
121 template <typename T>
Andy Hungf7c14102020-04-18 14:54:08 -0700122 status_t getValue(const std::string &property, T defaultValue, int64_t time = 0) const
123 REQUIRES(mPseudoKeyHistoryLock){
Andy Hung06f3aba2019-12-03 16:36:42 -0800124 T value;
125 return getValue(property, &value, time) != NO_ERROR ? defaultValue : value;
126 }
127
128 void putProp(
Andy Hungf7c14102020-04-18 14:54:08 -0700129 const std::string &name, const mediametrics::Item::Prop &prop, int64_t time = 0)
130 REQUIRES(mPseudoKeyHistoryLock) {
Andy Hunge8989ae2020-01-03 12:20:43 -0800131 //alternatively: prop.visit([&](auto value) { putValue(name, value, time); });
132 putValue(name, prop.get(), time);
Andy Hung06f3aba2019-12-03 16:36:42 -0800133 }
134
135 template <typename T>
Andy Hungf7c14102020-04-18 14:54:08 -0700136 void putValue(const std::string &property, T&& e, int64_t time = 0)
137 REQUIRES(mPseudoKeyHistoryLock) {
Andy Hunged416da2020-03-05 18:42:55 -0800138 if (time == 0) time = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung06f3aba2019-12-03 16:36:42 -0800139 mLastModificationTime = time;
Andy Hung5d3f2d12020-03-04 19:55:03 -0800140 if (mPropertyMap.size() >= kKeyMaxProperties &&
141 !mPropertyMap.count(property)) {
142 ALOGV("%s: too many properties, rejecting %s", __func__, property.c_str());
143 return;
144 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800145 auto& timeSequence = mPropertyMap[property];
146 Elem el{std::forward<T>(e)};
147 if (timeSequence.empty() // no elements
Andy Hung8f069622020-02-10 15:44:01 -0800148 || property.back() == AMEDIAMETRICS_PROP_SUFFIX_CHAR_DUPLICATES_ALLOWED
Andy Hung06f3aba2019-12-03 16:36:42 -0800149 || timeSequence.rbegin()->second != el) { // value changed
Andy Hung7d391082020-04-18 15:03:51 -0700150 timeSequence.emplace_hint(timeSequence.end(), time, std::move(el));
Andy Hung5d3f2d12020-03-04 19:55:03 -0800151
152 if (timeSequence.size() > kTimeSequenceMaxElements) {
153 ALOGV("%s: restricting maximum elements (discarding oldest) for %s",
154 __func__, property.c_str());
155 timeSequence.erase(timeSequence.begin());
156 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800157 }
158 }
159
Andy Hungf7c14102020-04-18 14:54:08 -0700160 std::pair<std::string, int32_t> dump(int32_t lines, int64_t time) const
161 REQUIRES(mPseudoKeyHistoryLock) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800162 std::stringstream ss;
163 int32_t ll = lines;
164 for (auto& tsPair : mPropertyMap) {
165 if (ll <= 0) break;
Andy Hung709b91e2020-04-04 14:23:36 -0700166 std::string s = dump(mKey, tsPair, time);
167 if (s.size() > 0) {
168 --ll;
Andy Hungb744faf2020-04-09 13:09:26 -0700169 ss << s;
Andy Hung709b91e2020-04-04 14:23:36 -0700170 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800171 }
172 return { ss.str(), lines - ll };
173 }
174
Andy Hungf7c14102020-04-18 14:54:08 -0700175 int64_t getLastModificationTime() const REQUIRES(mPseudoKeyHistoryLock) {
176 return mLastModificationTime;
177 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800178
179 private:
180 static std::string dump(
181 const std::string &key,
182 const std::pair<std::string /* prop */, PropertyHistory>& tsPair,
183 int64_t time) {
184 const auto timeSequence = tsPair.second;
185 auto eptr = timeSequence.lower_bound(time);
186 if (eptr == timeSequence.end()) {
Andy Hung709b91e2020-04-04 14:23:36 -0700187 return {}; // don't dump anything. tsPair.first + "={};\n";
Andy Hung06f3aba2019-12-03 16:36:42 -0800188 }
189 std::stringstream ss;
190 ss << key << "." << tsPair.first << "={";
Andy Hung3b4c1f02020-01-23 18:58:32 -0800191
192 time_string_t last_timestring{}; // last timestring used.
193 while (true) {
194 const time_string_t timestring = mediametrics::timeStringFromNs(eptr->first);
195 // find common prefix offset.
196 const size_t offset = commonTimePrefixPosition(timestring.time,
197 last_timestring.time);
198 last_timestring = timestring;
199 ss << "(" << (offset == 0 ? "" : "~") << &timestring.time[offset]
200 << ") " << eptr->second;
201 if (++eptr == timeSequence.end()) {
Andy Hung3b4c1f02020-01-23 18:58:32 -0800202 break;
203 }
204 ss << ", ";
205 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800206 ss << "};\n";
207 return ss.str();
208 }
209
210 const std::string mKey;
Andy Hungd203eb62020-04-27 09:12:46 -0700211 const uid_t mAllowUid;
Andy Hung06f3aba2019-12-03 16:36:42 -0800212 const int64_t mCreationTime __unused;
213
214 int64_t mLastModificationTime;
215 std::map<std::string /* property */, PropertyHistory> mPropertyMap;
216 };
217
218 using History = std::map<std::string /* key */, std::shared_ptr<KeyHistory>>;
219
Andy Hung5d3f2d12020-03-04 19:55:03 -0800220 static inline constexpr size_t kTimeSequenceMaxElements = 100;
221 static inline constexpr size_t kKeyMaxProperties = 100;
Andy Hung06f3aba2019-12-03 16:36:42 -0800222 static inline constexpr size_t kKeyLowWaterMark = 500;
223 static inline constexpr size_t kKeyHighWaterMark = 1000;
224
225 // Estimated max data space usage is 3KB * kKeyHighWaterMark.
226
227public:
228
229 TimeMachine() = default;
230 TimeMachine(size_t keyLowWaterMark, size_t keyHighWaterMark)
231 : mKeyLowWaterMark(keyLowWaterMark)
232 , mKeyHighWaterMark(keyHighWaterMark) {
233 LOG_ALWAYS_FATAL_IF(keyHighWaterMark <= keyLowWaterMark,
234 "%s: required that keyHighWaterMark:%zu > keyLowWaterMark:%zu",
235 __func__, keyHighWaterMark, keyLowWaterMark);
236 }
237
Andy Hunga8f1c6e2020-01-02 18:25:41 -0800238 // The TimeMachine copy constructor/assignment uses a deep copy,
239 // though the snapshot is not instantaneous nor isochronous.
240 //
241 // If there are concurrent operations ongoing in the other TimeMachine
242 // then there may be some history more recent than others (a time shear).
243 // This is expected to be a benign addition in history as small number of
244 // future elements are incorporated.
245 TimeMachine(const TimeMachine& other) {
246 *this = other;
247 }
248 TimeMachine& operator=(const TimeMachine& other) {
249 std::lock_guard lock(mLock);
250 mHistory.clear();
251
252 {
253 std::lock_guard lock2(other.mLock);
254 mHistory = other.mHistory;
255 }
256
257 // Now that we safely have our own shared pointers, let's dup them
258 // to ensure they are decoupled. We do this by acquiring the other lock.
259 for (const auto &[lkey, lhist] : mHistory) {
260 std::lock_guard lock2(other.getLockForKey(lkey));
261 mHistory[lkey] = std::make_shared<KeyHistory>(*lhist);
262 }
263 return *this;
264 }
265
Andy Hung06f3aba2019-12-03 16:36:42 -0800266 /**
267 * Put all the properties from an item into the Time Machine log.
268 */
Ray Essickf27e9872019-12-07 06:28:46 -0800269 status_t put(const std::shared_ptr<const mediametrics::Item>& item, bool isTrusted = false) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800270 const int64_t time = item->getTimestamp();
271 const std::string &key = item->getKey();
272
Andy Hung5d3f2d12020-03-04 19:55:03 -0800273 ALOGV("%s(%zu, %zu): key: %s isTrusted:%d size:%zu",
274 __func__, mKeyLowWaterMark, mKeyHighWaterMark,
275 key.c_str(), (int)isTrusted, item->count());
Andy Hung06f3aba2019-12-03 16:36:42 -0800276 std::shared_ptr<KeyHistory> keyHistory;
277 {
278 std::vector<std::any> garbage;
279 std::lock_guard lock(mLock);
280
281 auto it = mHistory.find(key);
282 if (it == mHistory.end()) {
283 if (!isTrusted) return PERMISSION_DENIED;
284
Andy Hungf7c14102020-04-18 14:54:08 -0700285 (void)gc(garbage);
Andy Hung06f3aba2019-12-03 16:36:42 -0800286
Andy Hungd203eb62020-04-27 09:12:46 -0700287 // We set the allowUid for client access on key creation.
288 int32_t allowUid = -1;
289 (void)item->get(AMEDIAMETRICS_PROP_ALLOWUID, &allowUid);
Andy Hung06f3aba2019-12-03 16:36:42 -0800290 // no keylock needed here as we are sole owner
291 // until placed on mHistory.
292 keyHistory = std::make_shared<KeyHistory>(
Andy Hungd203eb62020-04-27 09:12:46 -0700293 key, allowUid, time);
Andy Hung06f3aba2019-12-03 16:36:42 -0800294 mHistory[key] = keyHistory;
295 } else {
296 keyHistory = it->second;
297 }
298 }
299
300 // deferred contains remote properties (for other keys) to do later.
Ray Essickf27e9872019-12-07 06:28:46 -0800301 std::vector<const mediametrics::Item::Prop *> deferred;
Andy Hung06f3aba2019-12-03 16:36:42 -0800302 {
303 // handle local properties
304 std::lock_guard lock(getLockForKey(key));
305 if (!isTrusted) {
306 status_t status = keyHistory->checkPermission(item->getUid());
307 if (status != NO_ERROR) return status;
308 }
309
310 for (const auto &prop : *item) {
311 const std::string &name = prop.getName();
312 if (name.size() == 0 || name[0] == '_') continue;
313
314 // Cross key settings are with [key]property
315 if (name[0] == '[') {
316 if (!isTrusted) continue;
317 deferred.push_back(&prop);
318 } else {
319 keyHistory->putProp(name, prop, time);
320 }
321 }
322 }
323
324 // handle remote properties, if any
325 for (const auto propptr : deferred) {
326 const auto &prop = *propptr;
327 const std::string &name = prop.getName();
328 size_t end = name.find_first_of(']'); // TODO: handle nested [] or escape?
329 if (end == 0) continue;
330 std::string remoteKey = name.substr(1, end - 1);
331 std::string remoteName = name.substr(end + 1);
332 if (remoteKey.size() == 0 || remoteName.size() == 0) continue;
333 std::shared_ptr<KeyHistory> remoteKeyHistory;
334 {
335 std::lock_guard lock(mLock);
336 auto it = mHistory.find(remoteKey);
337 if (it == mHistory.end()) continue;
338 remoteKeyHistory = it->second;
339 }
Andy Hungb744faf2020-04-09 13:09:26 -0700340 std::lock_guard lock(getLockForKey(remoteKey));
Andy Hung06f3aba2019-12-03 16:36:42 -0800341 remoteKeyHistory->putProp(remoteName, prop, time);
342 }
343 return NO_ERROR;
344 }
345
346 template <typename T>
347 status_t get(const std::string &key, const std::string &property,
348 T* value, int32_t uidCheck = -1, int64_t time = 0) const {
349 std::shared_ptr<KeyHistory> keyHistory;
350 {
351 std::lock_guard lock(mLock);
352 const auto it = mHistory.find(key);
353 if (it == mHistory.end()) return BAD_VALUE;
354 keyHistory = it->second;
355 }
356 std::lock_guard lock(getLockForKey(key));
357 return keyHistory->checkPermission(uidCheck)
358 ?: keyHistory->getValue(property, value, time);
359 }
360
361 /**
362 * Individual property put.
363 *
Andy Hunged416da2020-03-05 18:42:55 -0800364 * Put takes in a time (if none is provided then SYSTEM_TIME_REALTIME is used).
Andy Hung06f3aba2019-12-03 16:36:42 -0800365 */
366 template <typename T>
367 status_t put(const std::string &url, T &&e, int64_t time = 0) {
368 std::string key;
369 std::string prop;
370 std::shared_ptr<KeyHistory> keyHistory =
371 getKeyHistoryFromUrl(url, &key, &prop);
372 if (keyHistory == nullptr) return BAD_VALUE;
Andy Hunged416da2020-03-05 18:42:55 -0800373 if (time == 0) time = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung06f3aba2019-12-03 16:36:42 -0800374 std::lock_guard lock(getLockForKey(key));
375 keyHistory->putValue(prop, std::forward<T>(e), time);
376 return NO_ERROR;
377 }
378
379 /**
380 * Individual property get
381 */
382 template <typename T>
383 status_t get(const std::string &url, T* value, int32_t uidCheck, int64_t time = 0) const {
384 std::string key;
385 std::string prop;
386 std::shared_ptr<KeyHistory> keyHistory =
387 getKeyHistoryFromUrl(url, &key, &prop);
388 if (keyHistory == nullptr) return BAD_VALUE;
389
390 std::lock_guard lock(getLockForKey(key));
391 return keyHistory->checkPermission(uidCheck)
392 ?: keyHistory->getValue(prop, value, time);
393 }
394
395 /**
396 * Individual property get with default
397 */
398 template <typename T>
399 T get(const std::string &url, const T &defaultValue, int32_t uidCheck,
400 int64_t time = 0) const {
401 T value;
402 return get(url, &value, uidCheck, time) == NO_ERROR
403 ? value : defaultValue;
404 }
405
406 /**
407 * Returns number of keys in the Time Machine.
408 */
409 size_t size() const {
410 std::lock_guard lock(mLock);
411 return mHistory.size();
412 }
413
414 /**
415 * Clears all properties from the Time Machine.
416 */
417 void clear() {
418 std::lock_guard lock(mLock);
419 mHistory.clear();
420 }
421
422 /**
423 * Returns a pair consisting of the TimeMachine state as a string
424 * and the number of lines in the string.
425 *
426 * The number of lines in the returned pair is used as an optimization
427 * for subsequent line limiting.
428 *
429 * \param lines the maximum number of lines in the string returned.
430 * \param key selects only that key.
Andy Hung709b91e2020-04-04 14:23:36 -0700431 * \param sinceNs the nanoseconds since Unix epoch to start dump (0 shows all)
432 * \param prefix the desired key prefix to match (nullptr shows all)
Andy Hung06f3aba2019-12-03 16:36:42 -0800433 */
434 std::pair<std::string, int32_t> dump(
Andy Hung709b91e2020-04-04 14:23:36 -0700435 int32_t lines = INT32_MAX, int64_t sinceNs = 0, const char *prefix = nullptr) const {
Andy Hung06f3aba2019-12-03 16:36:42 -0800436 std::lock_guard lock(mLock);
Andy Hung06f3aba2019-12-03 16:36:42 -0800437 std::stringstream ss;
438 int32_t ll = lines;
Andy Hung709b91e2020-04-04 14:23:36 -0700439
440 for (auto it = prefix != nullptr ? mHistory.lower_bound(prefix) : mHistory.begin();
441 it != mHistory.end();
442 ++it) {
443 if (ll <= 0) break;
444 if (prefix != nullptr && !startsWith(it->first, prefix)) break;
445 std::lock_guard lock(getLockForKey(it->first));
446 auto [s, l] = it->second->dump(ll, sinceNs);
Andy Hungb744faf2020-04-09 13:09:26 -0700447 ss << s;
Andy Hung06f3aba2019-12-03 16:36:42 -0800448 ll -= l;
449 }
450 return { ss.str(), lines - ll };
451 }
452
453private:
454
455 // Obtains the lock for a KeyHistory.
Andy Hungf7c14102020-04-18 14:54:08 -0700456 std::mutex &getLockForKey(const std::string &key) const
457 RETURN_CAPABILITY(mPseudoKeyHistoryLock) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800458 return mKeyLocks[std::hash<std::string>{}(key) % std::size(mKeyLocks)];
459 }
460
461 // Finds a KeyHistory from a URL. Returns nullptr if not found.
462 std::shared_ptr<KeyHistory> getKeyHistoryFromUrl(
Andy Hungb744faf2020-04-09 13:09:26 -0700463 const std::string& url, std::string* key, std::string *prop) const {
Andy Hung06f3aba2019-12-03 16:36:42 -0800464 std::lock_guard lock(mLock);
465
466 auto it = mHistory.upper_bound(url);
467 if (it == mHistory.begin()) {
468 return nullptr;
469 }
470 --it; // go to the actual key, if it exists.
471
472 const std::string& itKey = it->first;
473 if (strncmp(itKey.c_str(), url.c_str(), itKey.size())) {
474 return nullptr;
475 }
476 if (key) *key = itKey;
477 if (prop) *prop = url.substr(itKey.size() + 1);
478 return it->second;
479 }
480
Andy Hung06f3aba2019-12-03 16:36:42 -0800481 /**
482 * Garbage collects if the TimeMachine size exceeds the high water mark.
483 *
Andy Hung5d3f2d12020-03-04 19:55:03 -0800484 * This GC operation limits the number of keys stored (not the size of properties
485 * stored in each key).
486 *
Andy Hung06f3aba2019-12-03 16:36:42 -0800487 * \param garbage a type-erased vector of elements to be destroyed
488 * outside of lock. Move large items to be destroyed here.
489 *
490 * \return true if garbage collection was done.
491 */
Andy Hungf7c14102020-04-18 14:54:08 -0700492 bool gc(std::vector<std::any>& garbage) REQUIRES(mLock) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800493 // TODO: something better than this for garbage collection.
494 if (mHistory.size() < mKeyHighWaterMark) return false;
495
496 ALOGD("%s: garbage collection", __func__);
497
498 // erase everything explicitly expired.
499 std::multimap<int64_t, std::string> accessList;
500 // use a stale vector with precise type to avoid type erasure overhead in garbage
501 std::vector<std::shared_ptr<KeyHistory>> stale;
502
503 for (auto it = mHistory.begin(); it != mHistory.end();) {
504 const std::string& key = it->first;
505 std::shared_ptr<KeyHistory> &keyHist = it->second;
506
507 std::lock_guard lock(getLockForKey(it->first));
508 int64_t expireTime = keyHist->getValue("_expire", -1 /* default */);
509 if (expireTime != -1) {
510 stale.emplace_back(std::move(it->second));
511 it = mHistory.erase(it);
512 } else {
513 accessList.emplace(keyHist->getLastModificationTime(), key);
514 ++it;
515 }
516 }
517
518 if (mHistory.size() > mKeyLowWaterMark) {
519 const size_t toDelete = mHistory.size() - mKeyLowWaterMark;
520 auto it = accessList.begin();
521 for (size_t i = 0; i < toDelete; ++i) {
522 auto it2 = mHistory.find(it->second);
523 stale.emplace_back(std::move(it2->second));
524 mHistory.erase(it2);
525 ++it;
526 }
527 }
528 garbage.emplace_back(std::move(accessList));
529 garbage.emplace_back(std::move(stale));
530
531 ALOGD("%s(%zu, %zu): key size:%zu",
532 __func__, mKeyLowWaterMark, mKeyHighWaterMark,
533 mHistory.size());
534 return true;
535 }
536
537 const size_t mKeyLowWaterMark = kKeyLowWaterMark;
538 const size_t mKeyHighWaterMark = kKeyHighWaterMark;
539
540 /**
541 * Locking Strategy
542 *
543 * Each key in the History has a KeyHistory. To get a shared pointer to
544 * the KeyHistory requires a lookup of mHistory under mLock. Once the shared
545 * pointer to KeyHistory is obtained, the mLock for mHistory can be released.
546 *
547 * Once the shared pointer to the key's KeyHistory is obtained, the KeyHistory
548 * can be locked for read and modification through the method getLockForKey().
549 *
550 * Instead of having a mutex per KeyHistory, we use a hash striped lock
551 * which assigns a mutex based on the hash of the key string.
552 *
553 * Once the last shared pointer reference to KeyHistory is released, it is
554 * destroyed. This is done through the garbage collection method.
555 *
556 * This two level locking allows multiple threads to access the TimeMachine
557 * in parallel.
558 */
559
560 mutable std::mutex mLock; // Lock for mHistory
Andy Hungf7c14102020-04-18 14:54:08 -0700561 History mHistory GUARDED_BY(mLock);
Andy Hung06f3aba2019-12-03 16:36:42 -0800562
563 // KEY_LOCKS is the number of mutexes for keys.
564 // It need not be a power of 2, but faster that way.
565 static inline constexpr size_t KEY_LOCKS = 256;
566 mutable std::mutex mKeyLocks[KEY_LOCKS]; // Hash-striped lock for KeyHistory based on key.
Andy Hungf7c14102020-04-18 14:54:08 -0700567
568 // Used for thread-safety analysis, we create a fake mutex object to represent
569 // the hash stripe lock mechanism, which is then tracked by the compiler.
570 class CAPABILITY("mutex") PseudoLock {};
571 static inline PseudoLock mPseudoKeyHistoryLock;
Andy Hung06f3aba2019-12-03 16:36:42 -0800572};
573
574} // namespace android::mediametrics