blob: f0bb2fb773c09e7a84add0216c74fba1769ad703 [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 {
96 if (time == 0) time = systemTime(SYSTEM_TIME_BOOTTIME);
97 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) {
125 if (time == 0) time = systemTime(SYSTEM_TIME_BOOTTIME);
126 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;
152 ss << dump(mKey, tsPair, time);
153 --ll;
154 }
155 return { ss.str(), lines - ll };
156 }
157
158 int64_t getLastModificationTime() const { return mLastModificationTime; }
159
160 private:
161 static std::string dump(
162 const std::string &key,
163 const std::pair<std::string /* prop */, PropertyHistory>& tsPair,
164 int64_t time) {
165 const auto timeSequence = tsPair.second;
166 auto eptr = timeSequence.lower_bound(time);
167 if (eptr == timeSequence.end()) {
168 return tsPair.first + "={};\n";
169 }
170 std::stringstream ss;
171 ss << key << "." << tsPair.first << "={";
Andy Hung3b4c1f02020-01-23 18:58:32 -0800172
173 time_string_t last_timestring{}; // last timestring used.
174 while (true) {
175 const time_string_t timestring = mediametrics::timeStringFromNs(eptr->first);
176 // find common prefix offset.
177 const size_t offset = commonTimePrefixPosition(timestring.time,
178 last_timestring.time);
179 last_timestring = timestring;
180 ss << "(" << (offset == 0 ? "" : "~") << &timestring.time[offset]
181 << ") " << eptr->second;
182 if (++eptr == timeSequence.end()) {
Andy Hung3b4c1f02020-01-23 18:58:32 -0800183 break;
184 }
185 ss << ", ";
186 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800187 ss << "};\n";
188 return ss.str();
189 }
190
191 const std::string mKey;
192 const pid_t mPid __unused;
193 const uid_t mUid;
194 const int64_t mCreationTime __unused;
195
196 int64_t mLastModificationTime;
197 std::map<std::string /* property */, PropertyHistory> mPropertyMap;
198 };
199
200 using History = std::map<std::string /* key */, std::shared_ptr<KeyHistory>>;
201
Andy Hung5d3f2d12020-03-04 19:55:03 -0800202 static inline constexpr size_t kTimeSequenceMaxElements = 100;
203 static inline constexpr size_t kKeyMaxProperties = 100;
Andy Hung06f3aba2019-12-03 16:36:42 -0800204 static inline constexpr size_t kKeyLowWaterMark = 500;
205 static inline constexpr size_t kKeyHighWaterMark = 1000;
206
207 // Estimated max data space usage is 3KB * kKeyHighWaterMark.
208
209public:
210
211 TimeMachine() = default;
212 TimeMachine(size_t keyLowWaterMark, size_t keyHighWaterMark)
213 : mKeyLowWaterMark(keyLowWaterMark)
214 , mKeyHighWaterMark(keyHighWaterMark) {
215 LOG_ALWAYS_FATAL_IF(keyHighWaterMark <= keyLowWaterMark,
216 "%s: required that keyHighWaterMark:%zu > keyLowWaterMark:%zu",
217 __func__, keyHighWaterMark, keyLowWaterMark);
218 }
219
Andy Hunga8f1c6e2020-01-02 18:25:41 -0800220 // The TimeMachine copy constructor/assignment uses a deep copy,
221 // though the snapshot is not instantaneous nor isochronous.
222 //
223 // If there are concurrent operations ongoing in the other TimeMachine
224 // then there may be some history more recent than others (a time shear).
225 // This is expected to be a benign addition in history as small number of
226 // future elements are incorporated.
227 TimeMachine(const TimeMachine& other) {
228 *this = other;
229 }
230 TimeMachine& operator=(const TimeMachine& other) {
231 std::lock_guard lock(mLock);
232 mHistory.clear();
233
234 {
235 std::lock_guard lock2(other.mLock);
236 mHistory = other.mHistory;
237 }
238
239 // Now that we safely have our own shared pointers, let's dup them
240 // to ensure they are decoupled. We do this by acquiring the other lock.
241 for (const auto &[lkey, lhist] : mHistory) {
242 std::lock_guard lock2(other.getLockForKey(lkey));
243 mHistory[lkey] = std::make_shared<KeyHistory>(*lhist);
244 }
245 return *this;
246 }
247
Andy Hung06f3aba2019-12-03 16:36:42 -0800248 /**
249 * Put all the properties from an item into the Time Machine log.
250 */
Ray Essickf27e9872019-12-07 06:28:46 -0800251 status_t put(const std::shared_ptr<const mediametrics::Item>& item, bool isTrusted = false) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800252 const int64_t time = item->getTimestamp();
253 const std::string &key = item->getKey();
254
Andy Hung5d3f2d12020-03-04 19:55:03 -0800255 ALOGV("%s(%zu, %zu): key: %s isTrusted:%d size:%zu",
256 __func__, mKeyLowWaterMark, mKeyHighWaterMark,
257 key.c_str(), (int)isTrusted, item->count());
Andy Hung06f3aba2019-12-03 16:36:42 -0800258 std::shared_ptr<KeyHistory> keyHistory;
259 {
260 std::vector<std::any> garbage;
261 std::lock_guard lock(mLock);
262
263 auto it = mHistory.find(key);
264 if (it == mHistory.end()) {
265 if (!isTrusted) return PERMISSION_DENIED;
266
267 (void)gc_l(garbage);
268
269 // no keylock needed here as we are sole owner
270 // until placed on mHistory.
271 keyHistory = std::make_shared<KeyHistory>(
272 key, item->getPid(), item->getUid(), time);
273 mHistory[key] = keyHistory;
274 } else {
275 keyHistory = it->second;
276 }
277 }
278
279 // deferred contains remote properties (for other keys) to do later.
Ray Essickf27e9872019-12-07 06:28:46 -0800280 std::vector<const mediametrics::Item::Prop *> deferred;
Andy Hung06f3aba2019-12-03 16:36:42 -0800281 {
282 // handle local properties
283 std::lock_guard lock(getLockForKey(key));
284 if (!isTrusted) {
285 status_t status = keyHistory->checkPermission(item->getUid());
286 if (status != NO_ERROR) return status;
287 }
288
289 for (const auto &prop : *item) {
290 const std::string &name = prop.getName();
291 if (name.size() == 0 || name[0] == '_') continue;
292
293 // Cross key settings are with [key]property
294 if (name[0] == '[') {
295 if (!isTrusted) continue;
296 deferred.push_back(&prop);
297 } else {
298 keyHistory->putProp(name, prop, time);
299 }
300 }
301 }
302
303 // handle remote properties, if any
304 for (const auto propptr : deferred) {
305 const auto &prop = *propptr;
306 const std::string &name = prop.getName();
307 size_t end = name.find_first_of(']'); // TODO: handle nested [] or escape?
308 if (end == 0) continue;
309 std::string remoteKey = name.substr(1, end - 1);
310 std::string remoteName = name.substr(end + 1);
311 if (remoteKey.size() == 0 || remoteName.size() == 0) continue;
312 std::shared_ptr<KeyHistory> remoteKeyHistory;
313 {
314 std::lock_guard lock(mLock);
315 auto it = mHistory.find(remoteKey);
316 if (it == mHistory.end()) continue;
317 remoteKeyHistory = it->second;
318 }
319 std::lock_guard(getLockForKey(remoteKey));
320 remoteKeyHistory->putProp(remoteName, prop, time);
321 }
322 return NO_ERROR;
323 }
324
325 template <typename T>
326 status_t get(const std::string &key, const std::string &property,
327 T* value, int32_t uidCheck = -1, int64_t time = 0) const {
328 std::shared_ptr<KeyHistory> keyHistory;
329 {
330 std::lock_guard lock(mLock);
331 const auto it = mHistory.find(key);
332 if (it == mHistory.end()) return BAD_VALUE;
333 keyHistory = it->second;
334 }
335 std::lock_guard lock(getLockForKey(key));
336 return keyHistory->checkPermission(uidCheck)
337 ?: keyHistory->getValue(property, value, time);
338 }
339
340 /**
341 * Individual property put.
342 *
343 * Put takes in a time (if none is provided then BOOTTIME is used).
344 */
345 template <typename T>
346 status_t put(const std::string &url, T &&e, int64_t time = 0) {
347 std::string key;
348 std::string prop;
349 std::shared_ptr<KeyHistory> keyHistory =
350 getKeyHistoryFromUrl(url, &key, &prop);
351 if (keyHistory == nullptr) return BAD_VALUE;
352 if (time == 0) time = systemTime(SYSTEM_TIME_BOOTTIME);
353 std::lock_guard lock(getLockForKey(key));
354 keyHistory->putValue(prop, std::forward<T>(e), time);
355 return NO_ERROR;
356 }
357
358 /**
359 * Individual property get
360 */
361 template <typename T>
362 status_t get(const std::string &url, T* value, int32_t uidCheck, int64_t time = 0) const {
363 std::string key;
364 std::string prop;
365 std::shared_ptr<KeyHistory> keyHistory =
366 getKeyHistoryFromUrl(url, &key, &prop);
367 if (keyHistory == nullptr) return BAD_VALUE;
368
369 std::lock_guard lock(getLockForKey(key));
370 return keyHistory->checkPermission(uidCheck)
371 ?: keyHistory->getValue(prop, value, time);
372 }
373
374 /**
375 * Individual property get with default
376 */
377 template <typename T>
378 T get(const std::string &url, const T &defaultValue, int32_t uidCheck,
379 int64_t time = 0) const {
380 T value;
381 return get(url, &value, uidCheck, time) == NO_ERROR
382 ? value : defaultValue;
383 }
384
385 /**
386 * Returns number of keys in the Time Machine.
387 */
388 size_t size() const {
389 std::lock_guard lock(mLock);
390 return mHistory.size();
391 }
392
393 /**
394 * Clears all properties from the Time Machine.
395 */
396 void clear() {
397 std::lock_guard lock(mLock);
398 mHistory.clear();
399 }
400
401 /**
402 * Returns a pair consisting of the TimeMachine state as a string
403 * and the number of lines in the string.
404 *
405 * The number of lines in the returned pair is used as an optimization
406 * for subsequent line limiting.
407 *
408 * \param lines the maximum number of lines in the string returned.
409 * \param key selects only that key.
410 * \param time to start the dump from.
411 */
412 std::pair<std::string, int32_t> dump(
413 int32_t lines = INT32_MAX, const std::string &key = {}, int64_t time = 0) const {
414 std::lock_guard lock(mLock);
415 if (!key.empty()) { // use std::regex
416 const auto it = mHistory.find(key);
417 if (it == mHistory.end()) return {};
418 std::lock_guard lock(getLockForKey(it->first));
419 return it->second->dump(lines, time);
420 }
421
422 std::stringstream ss;
423 int32_t ll = lines;
Andy Hunge8989ae2020-01-03 12:20:43 -0800424 for (const auto &[lkey, lhist] : mHistory) {
425 std::lock_guard lock(getLockForKey(lkey));
Andy Hung06f3aba2019-12-03 16:36:42 -0800426 if (lines <= 0) break;
Andy Hunge8989ae2020-01-03 12:20:43 -0800427 auto [s, l] = lhist->dump(ll, time);
Andy Hung06f3aba2019-12-03 16:36:42 -0800428 ss << s;
429 ll -= l;
430 }
431 return { ss.str(), lines - ll };
432 }
433
434private:
435
436 // Obtains the lock for a KeyHistory.
437 std::mutex &getLockForKey(const std::string &key) const {
438 return mKeyLocks[std::hash<std::string>{}(key) % std::size(mKeyLocks)];
439 }
440
441 // Finds a KeyHistory from a URL. Returns nullptr if not found.
442 std::shared_ptr<KeyHistory> getKeyHistoryFromUrl(
443 std::string url, std::string* key, std::string *prop) const {
444 std::lock_guard lock(mLock);
445
446 auto it = mHistory.upper_bound(url);
447 if (it == mHistory.begin()) {
448 return nullptr;
449 }
450 --it; // go to the actual key, if it exists.
451
452 const std::string& itKey = it->first;
453 if (strncmp(itKey.c_str(), url.c_str(), itKey.size())) {
454 return nullptr;
455 }
456 if (key) *key = itKey;
457 if (prop) *prop = url.substr(itKey.size() + 1);
458 return it->second;
459 }
460
461 // GUARDED_BY mLock
462 /**
463 * Garbage collects if the TimeMachine size exceeds the high water mark.
464 *
Andy Hung5d3f2d12020-03-04 19:55:03 -0800465 * This GC operation limits the number of keys stored (not the size of properties
466 * stored in each key).
467 *
Andy Hung06f3aba2019-12-03 16:36:42 -0800468 * \param garbage a type-erased vector of elements to be destroyed
469 * outside of lock. Move large items to be destroyed here.
470 *
471 * \return true if garbage collection was done.
472 */
473 bool gc_l(std::vector<std::any>& garbage) {
474 // TODO: something better than this for garbage collection.
475 if (mHistory.size() < mKeyHighWaterMark) return false;
476
477 ALOGD("%s: garbage collection", __func__);
478
479 // erase everything explicitly expired.
480 std::multimap<int64_t, std::string> accessList;
481 // use a stale vector with precise type to avoid type erasure overhead in garbage
482 std::vector<std::shared_ptr<KeyHistory>> stale;
483
484 for (auto it = mHistory.begin(); it != mHistory.end();) {
485 const std::string& key = it->first;
486 std::shared_ptr<KeyHistory> &keyHist = it->second;
487
488 std::lock_guard lock(getLockForKey(it->first));
489 int64_t expireTime = keyHist->getValue("_expire", -1 /* default */);
490 if (expireTime != -1) {
491 stale.emplace_back(std::move(it->second));
492 it = mHistory.erase(it);
493 } else {
494 accessList.emplace(keyHist->getLastModificationTime(), key);
495 ++it;
496 }
497 }
498
499 if (mHistory.size() > mKeyLowWaterMark) {
500 const size_t toDelete = mHistory.size() - mKeyLowWaterMark;
501 auto it = accessList.begin();
502 for (size_t i = 0; i < toDelete; ++i) {
503 auto it2 = mHistory.find(it->second);
504 stale.emplace_back(std::move(it2->second));
505 mHistory.erase(it2);
506 ++it;
507 }
508 }
509 garbage.emplace_back(std::move(accessList));
510 garbage.emplace_back(std::move(stale));
511
512 ALOGD("%s(%zu, %zu): key size:%zu",
513 __func__, mKeyLowWaterMark, mKeyHighWaterMark,
514 mHistory.size());
515 return true;
516 }
517
518 const size_t mKeyLowWaterMark = kKeyLowWaterMark;
519 const size_t mKeyHighWaterMark = kKeyHighWaterMark;
520
521 /**
522 * Locking Strategy
523 *
524 * Each key in the History has a KeyHistory. To get a shared pointer to
525 * the KeyHistory requires a lookup of mHistory under mLock. Once the shared
526 * pointer to KeyHistory is obtained, the mLock for mHistory can be released.
527 *
528 * Once the shared pointer to the key's KeyHistory is obtained, the KeyHistory
529 * can be locked for read and modification through the method getLockForKey().
530 *
531 * Instead of having a mutex per KeyHistory, we use a hash striped lock
532 * which assigns a mutex based on the hash of the key string.
533 *
534 * Once the last shared pointer reference to KeyHistory is released, it is
535 * destroyed. This is done through the garbage collection method.
536 *
537 * This two level locking allows multiple threads to access the TimeMachine
538 * in parallel.
539 */
540
541 mutable std::mutex mLock; // Lock for mHistory
542 History mHistory; // GUARDED_BY mLock
543
544 // KEY_LOCKS is the number of mutexes for keys.
545 // It need not be a power of 2, but faster that way.
546 static inline constexpr size_t KEY_LOCKS = 256;
547 mutable std::mutex mKeyLocks[KEY_LOCKS]; // Hash-striped lock for KeyHistory based on key.
548};
549
550} // namespace android::mediametrics