blob: 00a44a4aa1996471e615dfd98e2d77ce9b6867aa [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>
Andy Hung3ab1b322020-05-18 10:47:31 -070021#include <mutex>
Andy Hung06f3aba2019-12-03 16:36:42 -080022#include <sstream>
23#include <string>
24#include <variant>
25#include <vector>
26
Andy Hungf7c14102020-04-18 14:54:08 -070027#include <android-base/thread_annotations.h>
Ray Essickf27e9872019-12-07 06:28:46 -080028#include <media/MediaMetricsItem.h>
Andy Hung06f3aba2019-12-03 16:36:42 -080029#include <utils/Timers.h>
30
31namespace android::mediametrics {
32
33// define a way of printing the monostate
34inline std::ostream & operator<< (std::ostream& s,
35 std::monostate const& v __unused) {
36 s << "none_item";
37 return s;
38}
39
Andy Hunge8989ae2020-01-03 12:20:43 -080040// define a way of printing a std::pair.
41template <typename T, typename U>
42std::ostream & operator<< (std::ostream& s,
43 const std::pair<T, U>& v) {
44 s << "{ " << v.first << ", " << v.second << " }";
45 return s;
46}
47
Andy Hung06f3aba2019-12-03 16:36:42 -080048// define a way of printing a variant
49// see https://en.cppreference.com/w/cpp/utility/variant/visit
50template <typename T0, typename ... Ts>
51std::ostream & operator<< (std::ostream& s,
52 std::variant<T0, Ts...> const& v) {
53 std::visit([&s](auto && arg){ s << std::forward<decltype(arg)>(arg); }, v);
54 return s;
55}
56
57/**
58 * The TimeMachine is used to record timing changes of MediaAnalyticItem
59 * properties.
60 *
Andy Hung8f069622020-02-10 15:44:01 -080061 * Any URL that ends with '#' (AMEDIAMETRICS_PROP_SUFFIX_CHAR_DUPLICATES_ALLOWED)
62 * will have a time sequence that keeps duplicates.
Andy Hung06f3aba2019-12-03 16:36:42 -080063 *
64 * The TimeMachine is NOT thread safe.
65 */
Andy Hunga8f1c6e2020-01-02 18:25:41 -080066class TimeMachine final { // made final as we have copy constructor instead of dup() override.
Andy Hunge8989ae2020-01-03 12:20:43 -080067public:
68 using Elem = Item::Prop::Elem; // use the Item property element.
Andy Hung06f3aba2019-12-03 16:36:42 -080069 using PropertyHistory = std::multimap<int64_t /* time */, Elem>;
70
Andy Hunge8989ae2020-01-03 12:20:43 -080071private:
72
Andy Hung06f3aba2019-12-03 16:36:42 -080073 // KeyHistory contains no lock.
74 // Access is through the TimeMachine, and a hash-striped lock is used
75 // before calling into KeyHistory.
76 class KeyHistory {
77 public:
78 template <typename T>
Andy Hungd203eb62020-04-27 09:12:46 -070079 KeyHistory(T key, uid_t allowUid, int64_t time)
Andy Hung06f3aba2019-12-03 16:36:42 -080080 : mKey(key)
Andy Hungd203eb62020-04-27 09:12:46 -070081 , mAllowUid(allowUid)
Andy Hung06f3aba2019-12-03 16:36:42 -080082 , mCreationTime(time)
83 , mLastModificationTime(time)
84 {
Andy Hung3ab1b322020-05-18 10:47:31 -070085 (void)mCreationTime; // suppress unused warning.
86
Andy Hungd203eb62020-04-27 09:12:46 -070087 // allowUid allows an untrusted client with a matching uid to set properties
88 // in this key.
89 // If allowUid == (uid_t)-1, no untrusted client may set properties in the key.
90 if (allowUid != (uid_t)-1) {
91 // Set ALLOWUID property here; does not change after key creation.
92 putValue(AMEDIAMETRICS_PROP_ALLOWUID, (int32_t)allowUid, time);
93 }
Andy Hung06f3aba2019-12-03 16:36:42 -080094 }
95
Andy Hunga8f1c6e2020-01-02 18:25:41 -080096 KeyHistory(const KeyHistory &other) = default;
97
Andy Hungd203eb62020-04-27 09:12:46 -070098 // Return NO_ERROR only if the passed in uidCheck is -1 or matches
99 // the internal mAllowUid.
100 // An external submit will always have a valid uidCheck parameter.
101 // An internal get request within mediametrics will have a uidCheck == -1 which
102 // we allow to proceed.
Andy Hung06f3aba2019-12-03 16:36:42 -0800103 status_t checkPermission(uid_t uidCheck) const {
Andy Hungd203eb62020-04-27 09:12:46 -0700104 return uidCheck != (uid_t)-1 && uidCheck != mAllowUid ? PERMISSION_DENIED : NO_ERROR;
Andy Hung06f3aba2019-12-03 16:36:42 -0800105 }
106
107 template <typename T>
Andy Hungf7c14102020-04-18 14:54:08 -0700108 status_t getValue(const std::string &property, T* value, int64_t time = 0) const
109 REQUIRES(mPseudoKeyHistoryLock) {
Andy Hunged416da2020-03-05 18:42:55 -0800110 if (time == 0) time = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung06f3aba2019-12-03 16:36:42 -0800111 const auto tsptr = mPropertyMap.find(property);
112 if (tsptr == mPropertyMap.end()) return BAD_VALUE;
113 const auto& timeSequence = tsptr->second;
114 auto eptr = timeSequence.upper_bound(time);
115 if (eptr == timeSequence.begin()) return BAD_VALUE;
116 --eptr;
117 if (eptr == timeSequence.end()) return BAD_VALUE;
118 const T* vptr = std::get_if<T>(&eptr->second);
119 if (vptr == nullptr) return BAD_VALUE;
120 *value = *vptr;
121 return NO_ERROR;
122 }
123
124 template <typename T>
Andy Hungf7c14102020-04-18 14:54:08 -0700125 status_t getValue(const std::string &property, T defaultValue, int64_t time = 0) const
126 REQUIRES(mPseudoKeyHistoryLock){
Andy Hung06f3aba2019-12-03 16:36:42 -0800127 T value;
128 return getValue(property, &value, time) != NO_ERROR ? defaultValue : value;
129 }
130
131 void putProp(
Andy Hungf7c14102020-04-18 14:54:08 -0700132 const std::string &name, const mediametrics::Item::Prop &prop, int64_t time = 0)
133 REQUIRES(mPseudoKeyHistoryLock) {
Andy Hunge8989ae2020-01-03 12:20:43 -0800134 //alternatively: prop.visit([&](auto value) { putValue(name, value, time); });
135 putValue(name, prop.get(), time);
Andy Hung06f3aba2019-12-03 16:36:42 -0800136 }
137
138 template <typename T>
Andy Hungf7c14102020-04-18 14:54:08 -0700139 void putValue(const std::string &property, T&& e, int64_t time = 0)
140 REQUIRES(mPseudoKeyHistoryLock) {
Andy Hunged416da2020-03-05 18:42:55 -0800141 if (time == 0) time = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung06f3aba2019-12-03 16:36:42 -0800142 mLastModificationTime = time;
Andy Hung5d3f2d12020-03-04 19:55:03 -0800143 if (mPropertyMap.size() >= kKeyMaxProperties &&
144 !mPropertyMap.count(property)) {
145 ALOGV("%s: too many properties, rejecting %s", __func__, property.c_str());
146 return;
147 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800148 auto& timeSequence = mPropertyMap[property];
149 Elem el{std::forward<T>(e)};
150 if (timeSequence.empty() // no elements
Andy Hung8f069622020-02-10 15:44:01 -0800151 || property.back() == AMEDIAMETRICS_PROP_SUFFIX_CHAR_DUPLICATES_ALLOWED
Andy Hung06f3aba2019-12-03 16:36:42 -0800152 || timeSequence.rbegin()->second != el) { // value changed
Andy Hung7d391082020-04-18 15:03:51 -0700153 timeSequence.emplace_hint(timeSequence.end(), time, std::move(el));
Andy Hung5d3f2d12020-03-04 19:55:03 -0800154
155 if (timeSequence.size() > kTimeSequenceMaxElements) {
156 ALOGV("%s: restricting maximum elements (discarding oldest) for %s",
157 __func__, property.c_str());
158 timeSequence.erase(timeSequence.begin());
159 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800160 }
161 }
162
Andy Hungf7c14102020-04-18 14:54:08 -0700163 std::pair<std::string, int32_t> dump(int32_t lines, int64_t time) const
164 REQUIRES(mPseudoKeyHistoryLock) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800165 std::stringstream ss;
166 int32_t ll = lines;
167 for (auto& tsPair : mPropertyMap) {
168 if (ll <= 0) break;
Andy Hung709b91e2020-04-04 14:23:36 -0700169 std::string s = dump(mKey, tsPair, time);
170 if (s.size() > 0) {
171 --ll;
Andy Hungb744faf2020-04-09 13:09:26 -0700172 ss << s;
Andy Hung709b91e2020-04-04 14:23:36 -0700173 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800174 }
175 return { ss.str(), lines - ll };
176 }
177
Andy Hungf7c14102020-04-18 14:54:08 -0700178 int64_t getLastModificationTime() const REQUIRES(mPseudoKeyHistoryLock) {
179 return mLastModificationTime;
180 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800181
182 private:
183 static std::string dump(
184 const std::string &key,
185 const std::pair<std::string /* prop */, PropertyHistory>& tsPair,
186 int64_t time) {
187 const auto timeSequence = tsPair.second;
188 auto eptr = timeSequence.lower_bound(time);
189 if (eptr == timeSequence.end()) {
Andy Hung709b91e2020-04-04 14:23:36 -0700190 return {}; // don't dump anything. tsPair.first + "={};\n";
Andy Hung06f3aba2019-12-03 16:36:42 -0800191 }
192 std::stringstream ss;
193 ss << key << "." << tsPair.first << "={";
Andy Hung3b4c1f02020-01-23 18:58:32 -0800194
195 time_string_t last_timestring{}; // last timestring used.
196 while (true) {
197 const time_string_t timestring = mediametrics::timeStringFromNs(eptr->first);
198 // find common prefix offset.
199 const size_t offset = commonTimePrefixPosition(timestring.time,
200 last_timestring.time);
201 last_timestring = timestring;
202 ss << "(" << (offset == 0 ? "" : "~") << &timestring.time[offset]
203 << ") " << eptr->second;
204 if (++eptr == timeSequence.end()) {
Andy Hung3b4c1f02020-01-23 18:58:32 -0800205 break;
206 }
207 ss << ", ";
208 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800209 ss << "};\n";
210 return ss.str();
211 }
212
213 const std::string mKey;
Andy Hungd203eb62020-04-27 09:12:46 -0700214 const uid_t mAllowUid;
Andy Hung3ab1b322020-05-18 10:47:31 -0700215 const int64_t mCreationTime;
Andy Hung06f3aba2019-12-03 16:36:42 -0800216
217 int64_t mLastModificationTime;
218 std::map<std::string /* property */, PropertyHistory> mPropertyMap;
219 };
220
221 using History = std::map<std::string /* key */, std::shared_ptr<KeyHistory>>;
222
Andy Hung5d3f2d12020-03-04 19:55:03 -0800223 static inline constexpr size_t kTimeSequenceMaxElements = 100;
224 static inline constexpr size_t kKeyMaxProperties = 100;
Andy Hung06f3aba2019-12-03 16:36:42 -0800225 static inline constexpr size_t kKeyLowWaterMark = 500;
226 static inline constexpr size_t kKeyHighWaterMark = 1000;
227
228 // Estimated max data space usage is 3KB * kKeyHighWaterMark.
229
230public:
231
232 TimeMachine() = default;
233 TimeMachine(size_t keyLowWaterMark, size_t keyHighWaterMark)
234 : mKeyLowWaterMark(keyLowWaterMark)
235 , mKeyHighWaterMark(keyHighWaterMark) {
236 LOG_ALWAYS_FATAL_IF(keyHighWaterMark <= keyLowWaterMark,
237 "%s: required that keyHighWaterMark:%zu > keyLowWaterMark:%zu",
238 __func__, keyHighWaterMark, keyLowWaterMark);
239 }
240
Andy Hunga8f1c6e2020-01-02 18:25:41 -0800241 // The TimeMachine copy constructor/assignment uses a deep copy,
242 // though the snapshot is not instantaneous nor isochronous.
243 //
244 // If there are concurrent operations ongoing in the other TimeMachine
245 // then there may be some history more recent than others (a time shear).
246 // This is expected to be a benign addition in history as small number of
247 // future elements are incorporated.
248 TimeMachine(const TimeMachine& other) {
249 *this = other;
250 }
251 TimeMachine& operator=(const TimeMachine& other) {
252 std::lock_guard lock(mLock);
253 mHistory.clear();
254
255 {
256 std::lock_guard lock2(other.mLock);
257 mHistory = other.mHistory;
258 }
259
260 // Now that we safely have our own shared pointers, let's dup them
261 // to ensure they are decoupled. We do this by acquiring the other lock.
262 for (const auto &[lkey, lhist] : mHistory) {
263 std::lock_guard lock2(other.getLockForKey(lkey));
264 mHistory[lkey] = std::make_shared<KeyHistory>(*lhist);
265 }
266 return *this;
267 }
268
Andy Hung06f3aba2019-12-03 16:36:42 -0800269 /**
270 * Put all the properties from an item into the Time Machine log.
271 */
Ray Essickf27e9872019-12-07 06:28:46 -0800272 status_t put(const std::shared_ptr<const mediametrics::Item>& item, bool isTrusted = false) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800273 const int64_t time = item->getTimestamp();
274 const std::string &key = item->getKey();
275
Andy Hung5d3f2d12020-03-04 19:55:03 -0800276 ALOGV("%s(%zu, %zu): key: %s isTrusted:%d size:%zu",
277 __func__, mKeyLowWaterMark, mKeyHighWaterMark,
278 key.c_str(), (int)isTrusted, item->count());
Andy Hung06f3aba2019-12-03 16:36:42 -0800279 std::shared_ptr<KeyHistory> keyHistory;
280 {
281 std::vector<std::any> garbage;
282 std::lock_guard lock(mLock);
283
284 auto it = mHistory.find(key);
285 if (it == mHistory.end()) {
286 if (!isTrusted) return PERMISSION_DENIED;
287
Andy Hungf7c14102020-04-18 14:54:08 -0700288 (void)gc(garbage);
Andy Hung06f3aba2019-12-03 16:36:42 -0800289
Andy Hungd203eb62020-04-27 09:12:46 -0700290 // We set the allowUid for client access on key creation.
291 int32_t allowUid = -1;
292 (void)item->get(AMEDIAMETRICS_PROP_ALLOWUID, &allowUid);
Andy Hung06f3aba2019-12-03 16:36:42 -0800293 // no keylock needed here as we are sole owner
294 // until placed on mHistory.
295 keyHistory = std::make_shared<KeyHistory>(
Andy Hungd203eb62020-04-27 09:12:46 -0700296 key, allowUid, time);
Andy Hung06f3aba2019-12-03 16:36:42 -0800297 mHistory[key] = keyHistory;
298 } else {
299 keyHistory = it->second;
300 }
301 }
302
303 // deferred contains remote properties (for other keys) to do later.
Ray Essickf27e9872019-12-07 06:28:46 -0800304 std::vector<const mediametrics::Item::Prop *> deferred;
Andy Hung06f3aba2019-12-03 16:36:42 -0800305 {
306 // handle local properties
307 std::lock_guard lock(getLockForKey(key));
308 if (!isTrusted) {
309 status_t status = keyHistory->checkPermission(item->getUid());
310 if (status != NO_ERROR) return status;
311 }
312
313 for (const auto &prop : *item) {
314 const std::string &name = prop.getName();
315 if (name.size() == 0 || name[0] == '_') continue;
316
317 // Cross key settings are with [key]property
318 if (name[0] == '[') {
319 if (!isTrusted) continue;
320 deferred.push_back(&prop);
321 } else {
322 keyHistory->putProp(name, prop, time);
323 }
324 }
325 }
326
327 // handle remote properties, if any
328 for (const auto propptr : deferred) {
329 const auto &prop = *propptr;
330 const std::string &name = prop.getName();
331 size_t end = name.find_first_of(']'); // TODO: handle nested [] or escape?
332 if (end == 0) continue;
333 std::string remoteKey = name.substr(1, end - 1);
334 std::string remoteName = name.substr(end + 1);
335 if (remoteKey.size() == 0 || remoteName.size() == 0) continue;
336 std::shared_ptr<KeyHistory> remoteKeyHistory;
337 {
338 std::lock_guard lock(mLock);
339 auto it = mHistory.find(remoteKey);
340 if (it == mHistory.end()) continue;
341 remoteKeyHistory = it->second;
342 }
Andy Hungb744faf2020-04-09 13:09:26 -0700343 std::lock_guard lock(getLockForKey(remoteKey));
Andy Hung06f3aba2019-12-03 16:36:42 -0800344 remoteKeyHistory->putProp(remoteName, prop, time);
345 }
346 return NO_ERROR;
347 }
348
349 template <typename T>
350 status_t get(const std::string &key, const std::string &property,
351 T* value, int32_t uidCheck = -1, int64_t time = 0) const {
352 std::shared_ptr<KeyHistory> keyHistory;
353 {
354 std::lock_guard lock(mLock);
355 const auto it = mHistory.find(key);
356 if (it == mHistory.end()) return BAD_VALUE;
357 keyHistory = it->second;
358 }
359 std::lock_guard lock(getLockForKey(key));
360 return keyHistory->checkPermission(uidCheck)
361 ?: keyHistory->getValue(property, value, time);
362 }
363
364 /**
365 * Individual property put.
366 *
Andy Hunged416da2020-03-05 18:42:55 -0800367 * Put takes in a time (if none is provided then SYSTEM_TIME_REALTIME is used).
Andy Hung06f3aba2019-12-03 16:36:42 -0800368 */
369 template <typename T>
370 status_t put(const std::string &url, T &&e, int64_t time = 0) {
371 std::string key;
372 std::string prop;
373 std::shared_ptr<KeyHistory> keyHistory =
374 getKeyHistoryFromUrl(url, &key, &prop);
375 if (keyHistory == nullptr) return BAD_VALUE;
Andy Hunged416da2020-03-05 18:42:55 -0800376 if (time == 0) time = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung06f3aba2019-12-03 16:36:42 -0800377 std::lock_guard lock(getLockForKey(key));
378 keyHistory->putValue(prop, std::forward<T>(e), time);
379 return NO_ERROR;
380 }
381
382 /**
383 * Individual property get
384 */
385 template <typename T>
386 status_t get(const std::string &url, T* value, int32_t uidCheck, int64_t time = 0) const {
387 std::string key;
388 std::string prop;
389 std::shared_ptr<KeyHistory> keyHistory =
390 getKeyHistoryFromUrl(url, &key, &prop);
391 if (keyHistory == nullptr) return BAD_VALUE;
392
393 std::lock_guard lock(getLockForKey(key));
394 return keyHistory->checkPermission(uidCheck)
395 ?: keyHistory->getValue(prop, value, time);
396 }
397
398 /**
399 * Individual property get with default
400 */
401 template <typename T>
402 T get(const std::string &url, const T &defaultValue, int32_t uidCheck,
403 int64_t time = 0) const {
404 T value;
405 return get(url, &value, uidCheck, time) == NO_ERROR
406 ? value : defaultValue;
407 }
408
409 /**
410 * Returns number of keys in the Time Machine.
411 */
412 size_t size() const {
413 std::lock_guard lock(mLock);
414 return mHistory.size();
415 }
416
417 /**
418 * Clears all properties from the Time Machine.
419 */
420 void clear() {
421 std::lock_guard lock(mLock);
422 mHistory.clear();
423 }
424
425 /**
426 * Returns a pair consisting of the TimeMachine state as a string
427 * and the number of lines in the string.
428 *
429 * The number of lines in the returned pair is used as an optimization
430 * for subsequent line limiting.
431 *
432 * \param lines the maximum number of lines in the string returned.
433 * \param key selects only that key.
Andy Hung709b91e2020-04-04 14:23:36 -0700434 * \param sinceNs the nanoseconds since Unix epoch to start dump (0 shows all)
435 * \param prefix the desired key prefix to match (nullptr shows all)
Andy Hung06f3aba2019-12-03 16:36:42 -0800436 */
437 std::pair<std::string, int32_t> dump(
Andy Hung709b91e2020-04-04 14:23:36 -0700438 int32_t lines = INT32_MAX, int64_t sinceNs = 0, const char *prefix = nullptr) const {
Andy Hung06f3aba2019-12-03 16:36:42 -0800439 std::lock_guard lock(mLock);
Andy Hung06f3aba2019-12-03 16:36:42 -0800440 std::stringstream ss;
441 int32_t ll = lines;
Andy Hung709b91e2020-04-04 14:23:36 -0700442
443 for (auto it = prefix != nullptr ? mHistory.lower_bound(prefix) : mHistory.begin();
444 it != mHistory.end();
445 ++it) {
446 if (ll <= 0) break;
447 if (prefix != nullptr && !startsWith(it->first, prefix)) break;
Andy Hung3ab1b322020-05-18 10:47:31 -0700448 std::lock_guard lock2(getLockForKey(it->first));
Andy Hung709b91e2020-04-04 14:23:36 -0700449 auto [s, l] = it->second->dump(ll, sinceNs);
Andy Hungb744faf2020-04-09 13:09:26 -0700450 ss << s;
Andy Hung06f3aba2019-12-03 16:36:42 -0800451 ll -= l;
452 }
453 return { ss.str(), lines - ll };
454 }
455
456private:
457
458 // Obtains the lock for a KeyHistory.
Andy Hungf7c14102020-04-18 14:54:08 -0700459 std::mutex &getLockForKey(const std::string &key) const
460 RETURN_CAPABILITY(mPseudoKeyHistoryLock) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800461 return mKeyLocks[std::hash<std::string>{}(key) % std::size(mKeyLocks)];
462 }
463
464 // Finds a KeyHistory from a URL. Returns nullptr if not found.
465 std::shared_ptr<KeyHistory> getKeyHistoryFromUrl(
Andy Hungb744faf2020-04-09 13:09:26 -0700466 const std::string& url, std::string* key, std::string *prop) const {
Andy Hung06f3aba2019-12-03 16:36:42 -0800467 std::lock_guard lock(mLock);
468
469 auto it = mHistory.upper_bound(url);
470 if (it == mHistory.begin()) {
471 return nullptr;
472 }
473 --it; // go to the actual key, if it exists.
474
475 const std::string& itKey = it->first;
476 if (strncmp(itKey.c_str(), url.c_str(), itKey.size())) {
477 return nullptr;
478 }
479 if (key) *key = itKey;
480 if (prop) *prop = url.substr(itKey.size() + 1);
481 return it->second;
482 }
483
Andy Hung06f3aba2019-12-03 16:36:42 -0800484 /**
485 * Garbage collects if the TimeMachine size exceeds the high water mark.
486 *
Andy Hung5d3f2d12020-03-04 19:55:03 -0800487 * This GC operation limits the number of keys stored (not the size of properties
488 * stored in each key).
489 *
Andy Hung06f3aba2019-12-03 16:36:42 -0800490 * \param garbage a type-erased vector of elements to be destroyed
491 * outside of lock. Move large items to be destroyed here.
492 *
493 * \return true if garbage collection was done.
494 */
Andy Hungf7c14102020-04-18 14:54:08 -0700495 bool gc(std::vector<std::any>& garbage) REQUIRES(mLock) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800496 // TODO: something better than this for garbage collection.
497 if (mHistory.size() < mKeyHighWaterMark) return false;
498
499 ALOGD("%s: garbage collection", __func__);
500
501 // erase everything explicitly expired.
502 std::multimap<int64_t, std::string> accessList;
503 // use a stale vector with precise type to avoid type erasure overhead in garbage
504 std::vector<std::shared_ptr<KeyHistory>> stale;
505
506 for (auto it = mHistory.begin(); it != mHistory.end();) {
507 const std::string& key = it->first;
508 std::shared_ptr<KeyHistory> &keyHist = it->second;
509
510 std::lock_guard lock(getLockForKey(it->first));
511 int64_t expireTime = keyHist->getValue("_expire", -1 /* default */);
512 if (expireTime != -1) {
513 stale.emplace_back(std::move(it->second));
514 it = mHistory.erase(it);
515 } else {
516 accessList.emplace(keyHist->getLastModificationTime(), key);
517 ++it;
518 }
519 }
520
521 if (mHistory.size() > mKeyLowWaterMark) {
522 const size_t toDelete = mHistory.size() - mKeyLowWaterMark;
523 auto it = accessList.begin();
524 for (size_t i = 0; i < toDelete; ++i) {
525 auto it2 = mHistory.find(it->second);
526 stale.emplace_back(std::move(it2->second));
527 mHistory.erase(it2);
528 ++it;
529 }
530 }
531 garbage.emplace_back(std::move(accessList));
532 garbage.emplace_back(std::move(stale));
533
534 ALOGD("%s(%zu, %zu): key size:%zu",
535 __func__, mKeyLowWaterMark, mKeyHighWaterMark,
536 mHistory.size());
537 return true;
538 }
539
540 const size_t mKeyLowWaterMark = kKeyLowWaterMark;
541 const size_t mKeyHighWaterMark = kKeyHighWaterMark;
542
543 /**
544 * Locking Strategy
545 *
546 * Each key in the History has a KeyHistory. To get a shared pointer to
547 * the KeyHistory requires a lookup of mHistory under mLock. Once the shared
548 * pointer to KeyHistory is obtained, the mLock for mHistory can be released.
549 *
550 * Once the shared pointer to the key's KeyHistory is obtained, the KeyHistory
551 * can be locked for read and modification through the method getLockForKey().
552 *
553 * Instead of having a mutex per KeyHistory, we use a hash striped lock
554 * which assigns a mutex based on the hash of the key string.
555 *
556 * Once the last shared pointer reference to KeyHistory is released, it is
557 * destroyed. This is done through the garbage collection method.
558 *
559 * This two level locking allows multiple threads to access the TimeMachine
560 * in parallel.
561 */
562
563 mutable std::mutex mLock; // Lock for mHistory
Andy Hungf7c14102020-04-18 14:54:08 -0700564 History mHistory GUARDED_BY(mLock);
Andy Hung06f3aba2019-12-03 16:36:42 -0800565
566 // KEY_LOCKS is the number of mutexes for keys.
567 // It need not be a power of 2, but faster that way.
568 static inline constexpr size_t KEY_LOCKS = 256;
569 mutable std::mutex mKeyLocks[KEY_LOCKS]; // Hash-striped lock for KeyHistory based on key.
Andy Hungf7c14102020-04-18 14:54:08 -0700570
571 // Used for thread-safety analysis, we create a fake mutex object to represent
572 // the hash stripe lock mechanism, which is then tracked by the compiler.
573 class CAPABILITY("mutex") PseudoLock {};
574 static inline PseudoLock mPseudoKeyHistoryLock;
Andy Hung06f3aba2019-12-03 16:36:42 -0800575};
576
577} // namespace android::mediametrics