blob: 29adeae4d3ada5e18b13312c36ee630656b69523 [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
Ray Essickf27e9872019-12-07 06:28:46 -080026#include <media/MediaMetricsItem.h>
Andy Hung06f3aba2019-12-03 16:36:42 -080027#include <utils/Timers.h>
28
29namespace android::mediametrics {
30
31// define a way of printing the monostate
32inline std::ostream & operator<< (std::ostream& s,
33 std::monostate const& v __unused) {
34 s << "none_item";
35 return s;
36}
37
Andy Hunge8989ae2020-01-03 12:20:43 -080038// define a way of printing a std::pair.
39template <typename T, typename U>
40std::ostream & operator<< (std::ostream& s,
41 const std::pair<T, U>& v) {
42 s << "{ " << v.first << ", " << v.second << " }";
43 return s;
44}
45
Andy Hung06f3aba2019-12-03 16:36:42 -080046// define a way of printing a variant
47// see https://en.cppreference.com/w/cpp/utility/variant/visit
48template <typename T0, typename ... Ts>
49std::ostream & operator<< (std::ostream& s,
50 std::variant<T0, Ts...> const& v) {
51 std::visit([&s](auto && arg){ s << std::forward<decltype(arg)>(arg); }, v);
52 return s;
53}
54
55/**
56 * The TimeMachine is used to record timing changes of MediaAnalyticItem
57 * properties.
58 *
Andy Hung8f069622020-02-10 15:44:01 -080059 * Any URL that ends with '#' (AMEDIAMETRICS_PROP_SUFFIX_CHAR_DUPLICATES_ALLOWED)
60 * will have a time sequence that keeps duplicates.
Andy Hung06f3aba2019-12-03 16:36:42 -080061 *
62 * The TimeMachine is NOT thread safe.
63 */
Andy Hunga8f1c6e2020-01-02 18:25:41 -080064class TimeMachine final { // made final as we have copy constructor instead of dup() override.
Andy Hunge8989ae2020-01-03 12:20:43 -080065public:
66 using Elem = Item::Prop::Elem; // use the Item property element.
Andy Hung06f3aba2019-12-03 16:36:42 -080067 using PropertyHistory = std::multimap<int64_t /* time */, Elem>;
68
Andy Hunge8989ae2020-01-03 12:20:43 -080069private:
70
Andy Hung06f3aba2019-12-03 16:36:42 -080071 // KeyHistory contains no lock.
72 // Access is through the TimeMachine, and a hash-striped lock is used
73 // before calling into KeyHistory.
74 class KeyHistory {
75 public:
76 template <typename T>
77 KeyHistory(T key, pid_t pid, uid_t uid, int64_t time)
78 : mKey(key)
79 , mPid(pid)
80 , mUid(uid)
81 , mCreationTime(time)
82 , mLastModificationTime(time)
83 {
Andy Hung611268d2019-12-19 13:54:02 -080084 putValue(BUNDLE_PID, (int32_t)pid, time);
85 putValue(BUNDLE_UID, (int32_t)uid, time);
Andy Hung06f3aba2019-12-03 16:36:42 -080086 }
87
Andy Hunga8f1c6e2020-01-02 18:25:41 -080088 KeyHistory(const KeyHistory &other) = default;
89
Andy Hung06f3aba2019-12-03 16:36:42 -080090 status_t checkPermission(uid_t uidCheck) const {
91 return uidCheck != (uid_t)-1 && uidCheck != mUid ? PERMISSION_DENIED : NO_ERROR;
92 }
93
94 template <typename T>
95 status_t getValue(const std::string &property, T* value, int64_t time = 0) const {
Andy Hunged416da2020-03-05 18:42:55 -080096 if (time == 0) time = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung06f3aba2019-12-03 16:36:42 -080097 const auto tsptr = mPropertyMap.find(property);
98 if (tsptr == mPropertyMap.end()) return BAD_VALUE;
99 const auto& timeSequence = tsptr->second;
100 auto eptr = timeSequence.upper_bound(time);
101 if (eptr == timeSequence.begin()) return BAD_VALUE;
102 --eptr;
103 if (eptr == timeSequence.end()) return BAD_VALUE;
104 const T* vptr = std::get_if<T>(&eptr->second);
105 if (vptr == nullptr) return BAD_VALUE;
106 *value = *vptr;
107 return NO_ERROR;
108 }
109
110 template <typename T>
111 status_t getValue(const std::string &property, T defaultValue, int64_t time = 0) const {
112 T value;
113 return getValue(property, &value, time) != NO_ERROR ? defaultValue : value;
114 }
115
116 void putProp(
Ray Essickf27e9872019-12-07 06:28:46 -0800117 const std::string &name, const mediametrics::Item::Prop &prop, int64_t time = 0) {
Andy Hunge8989ae2020-01-03 12:20:43 -0800118 //alternatively: prop.visit([&](auto value) { putValue(name, value, time); });
119 putValue(name, prop.get(), time);
Andy Hung06f3aba2019-12-03 16:36:42 -0800120 }
121
122 template <typename T>
123 void putValue(const std::string &property,
124 T&& e, int64_t time = 0) {
Andy Hunged416da2020-03-05 18:42:55 -0800125 if (time == 0) time = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung06f3aba2019-12-03 16:36:42 -0800126 mLastModificationTime = time;
Andy Hung5d3f2d12020-03-04 19:55:03 -0800127 if (mPropertyMap.size() >= kKeyMaxProperties &&
128 !mPropertyMap.count(property)) {
129 ALOGV("%s: too many properties, rejecting %s", __func__, property.c_str());
130 return;
131 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800132 auto& timeSequence = mPropertyMap[property];
133 Elem el{std::forward<T>(e)};
134 if (timeSequence.empty() // no elements
Andy Hung8f069622020-02-10 15:44:01 -0800135 || property.back() == AMEDIAMETRICS_PROP_SUFFIX_CHAR_DUPLICATES_ALLOWED
Andy Hung06f3aba2019-12-03 16:36:42 -0800136 || timeSequence.rbegin()->second != el) { // value changed
137 timeSequence.emplace(time, std::move(el));
Andy Hung5d3f2d12020-03-04 19:55:03 -0800138
139 if (timeSequence.size() > kTimeSequenceMaxElements) {
140 ALOGV("%s: restricting maximum elements (discarding oldest) for %s",
141 __func__, property.c_str());
142 timeSequence.erase(timeSequence.begin());
143 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800144 }
145 }
146
Andy Hung06f3aba2019-12-03 16:36:42 -0800147 std::pair<std::string, int32_t> dump(int32_t lines, int64_t time) const {
148 std::stringstream ss;
149 int32_t ll = lines;
150 for (auto& tsPair : mPropertyMap) {
151 if (ll <= 0) break;
Andy Hung709b91e2020-04-04 14:23:36 -0700152 std::string s = dump(mKey, tsPair, time);
153 if (s.size() > 0) {
154 --ll;
Andy Hungb744faf2020-04-09 13:09:26 -0700155 ss << s;
Andy Hung709b91e2020-04-04 14:23:36 -0700156 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800157 }
158 return { ss.str(), lines - ll };
159 }
160
161 int64_t getLastModificationTime() const { return mLastModificationTime; }
162
163 private:
164 static std::string dump(
165 const std::string &key,
166 const std::pair<std::string /* prop */, PropertyHistory>& tsPair,
167 int64_t time) {
168 const auto timeSequence = tsPair.second;
169 auto eptr = timeSequence.lower_bound(time);
170 if (eptr == timeSequence.end()) {
Andy Hung709b91e2020-04-04 14:23:36 -0700171 return {}; // don't dump anything. tsPair.first + "={};\n";
Andy Hung06f3aba2019-12-03 16:36:42 -0800172 }
173 std::stringstream ss;
174 ss << key << "." << tsPair.first << "={";
Andy Hung3b4c1f02020-01-23 18:58:32 -0800175
176 time_string_t last_timestring{}; // last timestring used.
177 while (true) {
178 const time_string_t timestring = mediametrics::timeStringFromNs(eptr->first);
179 // find common prefix offset.
180 const size_t offset = commonTimePrefixPosition(timestring.time,
181 last_timestring.time);
182 last_timestring = timestring;
183 ss << "(" << (offset == 0 ? "" : "~") << &timestring.time[offset]
184 << ") " << eptr->second;
185 if (++eptr == timeSequence.end()) {
Andy Hung3b4c1f02020-01-23 18:58:32 -0800186 break;
187 }
188 ss << ", ";
189 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800190 ss << "};\n";
191 return ss.str();
192 }
193
194 const std::string mKey;
195 const pid_t mPid __unused;
196 const uid_t mUid;
197 const int64_t mCreationTime __unused;
198
199 int64_t mLastModificationTime;
200 std::map<std::string /* property */, PropertyHistory> mPropertyMap;
201 };
202
203 using History = std::map<std::string /* key */, std::shared_ptr<KeyHistory>>;
204
Andy Hung5d3f2d12020-03-04 19:55:03 -0800205 static inline constexpr size_t kTimeSequenceMaxElements = 100;
206 static inline constexpr size_t kKeyMaxProperties = 100;
Andy Hung06f3aba2019-12-03 16:36:42 -0800207 static inline constexpr size_t kKeyLowWaterMark = 500;
208 static inline constexpr size_t kKeyHighWaterMark = 1000;
209
210 // Estimated max data space usage is 3KB * kKeyHighWaterMark.
211
212public:
213
214 TimeMachine() = default;
215 TimeMachine(size_t keyLowWaterMark, size_t keyHighWaterMark)
216 : mKeyLowWaterMark(keyLowWaterMark)
217 , mKeyHighWaterMark(keyHighWaterMark) {
218 LOG_ALWAYS_FATAL_IF(keyHighWaterMark <= keyLowWaterMark,
219 "%s: required that keyHighWaterMark:%zu > keyLowWaterMark:%zu",
220 __func__, keyHighWaterMark, keyLowWaterMark);
221 }
222
Andy Hunga8f1c6e2020-01-02 18:25:41 -0800223 // The TimeMachine copy constructor/assignment uses a deep copy,
224 // though the snapshot is not instantaneous nor isochronous.
225 //
226 // If there are concurrent operations ongoing in the other TimeMachine
227 // then there may be some history more recent than others (a time shear).
228 // This is expected to be a benign addition in history as small number of
229 // future elements are incorporated.
230 TimeMachine(const TimeMachine& other) {
231 *this = other;
232 }
233 TimeMachine& operator=(const TimeMachine& other) {
234 std::lock_guard lock(mLock);
235 mHistory.clear();
236
237 {
238 std::lock_guard lock2(other.mLock);
239 mHistory = other.mHistory;
240 }
241
242 // Now that we safely have our own shared pointers, let's dup them
243 // to ensure they are decoupled. We do this by acquiring the other lock.
244 for (const auto &[lkey, lhist] : mHistory) {
245 std::lock_guard lock2(other.getLockForKey(lkey));
246 mHistory[lkey] = std::make_shared<KeyHistory>(*lhist);
247 }
248 return *this;
249 }
250
Andy Hung06f3aba2019-12-03 16:36:42 -0800251 /**
252 * Put all the properties from an item into the Time Machine log.
253 */
Ray Essickf27e9872019-12-07 06:28:46 -0800254 status_t put(const std::shared_ptr<const mediametrics::Item>& item, bool isTrusted = false) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800255 const int64_t time = item->getTimestamp();
256 const std::string &key = item->getKey();
257
Andy Hung5d3f2d12020-03-04 19:55:03 -0800258 ALOGV("%s(%zu, %zu): key: %s isTrusted:%d size:%zu",
259 __func__, mKeyLowWaterMark, mKeyHighWaterMark,
260 key.c_str(), (int)isTrusted, item->count());
Andy Hung06f3aba2019-12-03 16:36:42 -0800261 std::shared_ptr<KeyHistory> keyHistory;
262 {
263 std::vector<std::any> garbage;
264 std::lock_guard lock(mLock);
265
266 auto it = mHistory.find(key);
267 if (it == mHistory.end()) {
268 if (!isTrusted) return PERMISSION_DENIED;
269
270 (void)gc_l(garbage);
271
272 // no keylock needed here as we are sole owner
273 // until placed on mHistory.
274 keyHistory = std::make_shared<KeyHistory>(
275 key, item->getPid(), item->getUid(), time);
276 mHistory[key] = keyHistory;
277 } else {
278 keyHistory = it->second;
279 }
280 }
281
282 // deferred contains remote properties (for other keys) to do later.
Ray Essickf27e9872019-12-07 06:28:46 -0800283 std::vector<const mediametrics::Item::Prop *> deferred;
Andy Hung06f3aba2019-12-03 16:36:42 -0800284 {
285 // handle local properties
286 std::lock_guard lock(getLockForKey(key));
287 if (!isTrusted) {
288 status_t status = keyHistory->checkPermission(item->getUid());
289 if (status != NO_ERROR) return status;
290 }
291
292 for (const auto &prop : *item) {
293 const std::string &name = prop.getName();
294 if (name.size() == 0 || name[0] == '_') continue;
295
296 // Cross key settings are with [key]property
297 if (name[0] == '[') {
298 if (!isTrusted) continue;
299 deferred.push_back(&prop);
300 } else {
301 keyHistory->putProp(name, prop, time);
302 }
303 }
304 }
305
306 // handle remote properties, if any
307 for (const auto propptr : deferred) {
308 const auto &prop = *propptr;
309 const std::string &name = prop.getName();
310 size_t end = name.find_first_of(']'); // TODO: handle nested [] or escape?
311 if (end == 0) continue;
312 std::string remoteKey = name.substr(1, end - 1);
313 std::string remoteName = name.substr(end + 1);
314 if (remoteKey.size() == 0 || remoteName.size() == 0) continue;
315 std::shared_ptr<KeyHistory> remoteKeyHistory;
316 {
317 std::lock_guard lock(mLock);
318 auto it = mHistory.find(remoteKey);
319 if (it == mHistory.end()) continue;
320 remoteKeyHistory = it->second;
321 }
Andy Hungb744faf2020-04-09 13:09:26 -0700322 std::lock_guard lock(getLockForKey(remoteKey));
Andy Hung06f3aba2019-12-03 16:36:42 -0800323 remoteKeyHistory->putProp(remoteName, prop, time);
324 }
325 return NO_ERROR;
326 }
327
328 template <typename T>
329 status_t get(const std::string &key, const std::string &property,
330 T* value, int32_t uidCheck = -1, int64_t time = 0) const {
331 std::shared_ptr<KeyHistory> keyHistory;
332 {
333 std::lock_guard lock(mLock);
334 const auto it = mHistory.find(key);
335 if (it == mHistory.end()) return BAD_VALUE;
336 keyHistory = it->second;
337 }
338 std::lock_guard lock(getLockForKey(key));
339 return keyHistory->checkPermission(uidCheck)
340 ?: keyHistory->getValue(property, value, time);
341 }
342
343 /**
344 * Individual property put.
345 *
Andy Hunged416da2020-03-05 18:42:55 -0800346 * Put takes in a time (if none is provided then SYSTEM_TIME_REALTIME is used).
Andy Hung06f3aba2019-12-03 16:36:42 -0800347 */
348 template <typename T>
349 status_t put(const std::string &url, T &&e, int64_t time = 0) {
350 std::string key;
351 std::string prop;
352 std::shared_ptr<KeyHistory> keyHistory =
353 getKeyHistoryFromUrl(url, &key, &prop);
354 if (keyHistory == nullptr) return BAD_VALUE;
Andy Hunged416da2020-03-05 18:42:55 -0800355 if (time == 0) time = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung06f3aba2019-12-03 16:36:42 -0800356 std::lock_guard lock(getLockForKey(key));
357 keyHistory->putValue(prop, std::forward<T>(e), time);
358 return NO_ERROR;
359 }
360
361 /**
362 * Individual property get
363 */
364 template <typename T>
365 status_t get(const std::string &url, T* value, int32_t uidCheck, int64_t time = 0) const {
366 std::string key;
367 std::string prop;
368 std::shared_ptr<KeyHistory> keyHistory =
369 getKeyHistoryFromUrl(url, &key, &prop);
370 if (keyHistory == nullptr) return BAD_VALUE;
371
372 std::lock_guard lock(getLockForKey(key));
373 return keyHistory->checkPermission(uidCheck)
374 ?: keyHistory->getValue(prop, value, time);
375 }
376
377 /**
378 * Individual property get with default
379 */
380 template <typename T>
381 T get(const std::string &url, const T &defaultValue, int32_t uidCheck,
382 int64_t time = 0) const {
383 T value;
384 return get(url, &value, uidCheck, time) == NO_ERROR
385 ? value : defaultValue;
386 }
387
388 /**
389 * Returns number of keys in the Time Machine.
390 */
391 size_t size() const {
392 std::lock_guard lock(mLock);
393 return mHistory.size();
394 }
395
396 /**
397 * Clears all properties from the Time Machine.
398 */
399 void clear() {
400 std::lock_guard lock(mLock);
401 mHistory.clear();
402 }
403
404 /**
405 * Returns a pair consisting of the TimeMachine state as a string
406 * and the number of lines in the string.
407 *
408 * The number of lines in the returned pair is used as an optimization
409 * for subsequent line limiting.
410 *
411 * \param lines the maximum number of lines in the string returned.
412 * \param key selects only that key.
Andy Hung709b91e2020-04-04 14:23:36 -0700413 * \param sinceNs the nanoseconds since Unix epoch to start dump (0 shows all)
414 * \param prefix the desired key prefix to match (nullptr shows all)
Andy Hung06f3aba2019-12-03 16:36:42 -0800415 */
416 std::pair<std::string, int32_t> dump(
Andy Hung709b91e2020-04-04 14:23:36 -0700417 int32_t lines = INT32_MAX, int64_t sinceNs = 0, const char *prefix = nullptr) const {
Andy Hung06f3aba2019-12-03 16:36:42 -0800418 std::lock_guard lock(mLock);
Andy Hung06f3aba2019-12-03 16:36:42 -0800419 std::stringstream ss;
420 int32_t ll = lines;
Andy Hung709b91e2020-04-04 14:23:36 -0700421
422 for (auto it = prefix != nullptr ? mHistory.lower_bound(prefix) : mHistory.begin();
423 it != mHistory.end();
424 ++it) {
425 if (ll <= 0) break;
426 if (prefix != nullptr && !startsWith(it->first, prefix)) break;
427 std::lock_guard lock(getLockForKey(it->first));
428 auto [s, l] = it->second->dump(ll, sinceNs);
Andy Hungb744faf2020-04-09 13:09:26 -0700429 ss << s;
Andy Hung06f3aba2019-12-03 16:36:42 -0800430 ll -= l;
431 }
432 return { ss.str(), lines - ll };
433 }
434
435private:
436
437 // Obtains the lock for a KeyHistory.
438 std::mutex &getLockForKey(const std::string &key) const {
439 return mKeyLocks[std::hash<std::string>{}(key) % std::size(mKeyLocks)];
440 }
441
442 // Finds a KeyHistory from a URL. Returns nullptr if not found.
443 std::shared_ptr<KeyHistory> getKeyHistoryFromUrl(
Andy Hungb744faf2020-04-09 13:09:26 -0700444 const std::string& url, std::string* key, std::string *prop) const {
Andy Hung06f3aba2019-12-03 16:36:42 -0800445 std::lock_guard lock(mLock);
446
447 auto it = mHistory.upper_bound(url);
448 if (it == mHistory.begin()) {
449 return nullptr;
450 }
451 --it; // go to the actual key, if it exists.
452
453 const std::string& itKey = it->first;
454 if (strncmp(itKey.c_str(), url.c_str(), itKey.size())) {
455 return nullptr;
456 }
457 if (key) *key = itKey;
458 if (prop) *prop = url.substr(itKey.size() + 1);
459 return it->second;
460 }
461
462 // GUARDED_BY mLock
463 /**
464 * Garbage collects if the TimeMachine size exceeds the high water mark.
465 *
Andy Hung5d3f2d12020-03-04 19:55:03 -0800466 * This GC operation limits the number of keys stored (not the size of properties
467 * stored in each key).
468 *
Andy Hung06f3aba2019-12-03 16:36:42 -0800469 * \param garbage a type-erased vector of elements to be destroyed
470 * outside of lock. Move large items to be destroyed here.
471 *
472 * \return true if garbage collection was done.
473 */
474 bool gc_l(std::vector<std::any>& garbage) {
475 // TODO: something better than this for garbage collection.
476 if (mHistory.size() < mKeyHighWaterMark) return false;
477
478 ALOGD("%s: garbage collection", __func__);
479
480 // erase everything explicitly expired.
481 std::multimap<int64_t, std::string> accessList;
482 // use a stale vector with precise type to avoid type erasure overhead in garbage
483 std::vector<std::shared_ptr<KeyHistory>> stale;
484
485 for (auto it = mHistory.begin(); it != mHistory.end();) {
486 const std::string& key = it->first;
487 std::shared_ptr<KeyHistory> &keyHist = it->second;
488
489 std::lock_guard lock(getLockForKey(it->first));
490 int64_t expireTime = keyHist->getValue("_expire", -1 /* default */);
491 if (expireTime != -1) {
492 stale.emplace_back(std::move(it->second));
493 it = mHistory.erase(it);
494 } else {
495 accessList.emplace(keyHist->getLastModificationTime(), key);
496 ++it;
497 }
498 }
499
500 if (mHistory.size() > mKeyLowWaterMark) {
501 const size_t toDelete = mHistory.size() - mKeyLowWaterMark;
502 auto it = accessList.begin();
503 for (size_t i = 0; i < toDelete; ++i) {
504 auto it2 = mHistory.find(it->second);
505 stale.emplace_back(std::move(it2->second));
506 mHistory.erase(it2);
507 ++it;
508 }
509 }
510 garbage.emplace_back(std::move(accessList));
511 garbage.emplace_back(std::move(stale));
512
513 ALOGD("%s(%zu, %zu): key size:%zu",
514 __func__, mKeyLowWaterMark, mKeyHighWaterMark,
515 mHistory.size());
516 return true;
517 }
518
519 const size_t mKeyLowWaterMark = kKeyLowWaterMark;
520 const size_t mKeyHighWaterMark = kKeyHighWaterMark;
521
522 /**
523 * Locking Strategy
524 *
525 * Each key in the History has a KeyHistory. To get a shared pointer to
526 * the KeyHistory requires a lookup of mHistory under mLock. Once the shared
527 * pointer to KeyHistory is obtained, the mLock for mHistory can be released.
528 *
529 * Once the shared pointer to the key's KeyHistory is obtained, the KeyHistory
530 * can be locked for read and modification through the method getLockForKey().
531 *
532 * Instead of having a mutex per KeyHistory, we use a hash striped lock
533 * which assigns a mutex based on the hash of the key string.
534 *
535 * Once the last shared pointer reference to KeyHistory is released, it is
536 * destroyed. This is done through the garbage collection method.
537 *
538 * This two level locking allows multiple threads to access the TimeMachine
539 * in parallel.
540 */
541
542 mutable std::mutex mLock; // Lock for mHistory
543 History mHistory; // GUARDED_BY mLock
544
545 // KEY_LOCKS is the number of mutexes for keys.
546 // It need not be a power of 2, but faster that way.
547 static inline constexpr size_t KEY_LOCKS = 256;
548 mutable std::mutex mKeyLocks[KEY_LOCKS]; // Hash-striped lock for KeyHistory based on key.
549};
550
551} // namespace android::mediametrics