blob: 0440e5b380313cd5f4ac911569fb9b2e4913bfb1 [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 *
59 * Any URL that ends with '!' will have a time sequence that keeps duplicates.
60 *
61 * The TimeMachine is NOT thread safe.
62 */
Andy Hunga8f1c6e2020-01-02 18:25:41 -080063class TimeMachine final { // made final as we have copy constructor instead of dup() override.
Andy Hunge8989ae2020-01-03 12:20:43 -080064public:
65 using Elem = Item::Prop::Elem; // use the Item property element.
Andy Hung06f3aba2019-12-03 16:36:42 -080066 using PropertyHistory = std::multimap<int64_t /* time */, Elem>;
67
Andy Hunge8989ae2020-01-03 12:20:43 -080068private:
69
Andy Hung06f3aba2019-12-03 16:36:42 -080070 // KeyHistory contains no lock.
71 // Access is through the TimeMachine, and a hash-striped lock is used
72 // before calling into KeyHistory.
73 class KeyHistory {
74 public:
75 template <typename T>
76 KeyHistory(T key, pid_t pid, uid_t uid, int64_t time)
77 : mKey(key)
78 , mPid(pid)
79 , mUid(uid)
80 , mCreationTime(time)
81 , mLastModificationTime(time)
82 {
Andy Hung611268d2019-12-19 13:54:02 -080083 putValue(BUNDLE_PID, (int32_t)pid, time);
84 putValue(BUNDLE_UID, (int32_t)uid, time);
Andy Hung06f3aba2019-12-03 16:36:42 -080085 }
86
Andy Hunga8f1c6e2020-01-02 18:25:41 -080087 KeyHistory(const KeyHistory &other) = default;
88
Andy Hung06f3aba2019-12-03 16:36:42 -080089 status_t checkPermission(uid_t uidCheck) const {
90 return uidCheck != (uid_t)-1 && uidCheck != mUid ? PERMISSION_DENIED : NO_ERROR;
91 }
92
93 template <typename T>
94 status_t getValue(const std::string &property, T* value, int64_t time = 0) const {
95 if (time == 0) time = systemTime(SYSTEM_TIME_BOOTTIME);
96 const auto tsptr = mPropertyMap.find(property);
97 if (tsptr == mPropertyMap.end()) return BAD_VALUE;
98 const auto& timeSequence = tsptr->second;
99 auto eptr = timeSequence.upper_bound(time);
100 if (eptr == timeSequence.begin()) return BAD_VALUE;
101 --eptr;
102 if (eptr == timeSequence.end()) return BAD_VALUE;
103 const T* vptr = std::get_if<T>(&eptr->second);
104 if (vptr == nullptr) return BAD_VALUE;
105 *value = *vptr;
106 return NO_ERROR;
107 }
108
109 template <typename T>
110 status_t getValue(const std::string &property, T defaultValue, int64_t time = 0) const {
111 T value;
112 return getValue(property, &value, time) != NO_ERROR ? defaultValue : value;
113 }
114
115 void putProp(
Ray Essickf27e9872019-12-07 06:28:46 -0800116 const std::string &name, const mediametrics::Item::Prop &prop, int64_t time = 0) {
Andy Hunge8989ae2020-01-03 12:20:43 -0800117 //alternatively: prop.visit([&](auto value) { putValue(name, value, time); });
118 putValue(name, prop.get(), time);
Andy Hung06f3aba2019-12-03 16:36:42 -0800119 }
120
121 template <typename T>
122 void putValue(const std::string &property,
123 T&& e, int64_t time = 0) {
124 if (time == 0) time = systemTime(SYSTEM_TIME_BOOTTIME);
125 mLastModificationTime = time;
126 auto& timeSequence = mPropertyMap[property];
127 Elem el{std::forward<T>(e)};
128 if (timeSequence.empty() // no elements
129 || property.back() == '!' // keep duplicates TODO: remove?
130 || timeSequence.rbegin()->second != el) { // value changed
131 timeSequence.emplace(time, std::move(el));
132 }
133 }
134
Andy Hung06f3aba2019-12-03 16:36:42 -0800135 std::pair<std::string, int32_t> dump(int32_t lines, int64_t time) const {
136 std::stringstream ss;
137 int32_t ll = lines;
138 for (auto& tsPair : mPropertyMap) {
139 if (ll <= 0) break;
140 ss << dump(mKey, tsPair, time);
141 --ll;
142 }
143 return { ss.str(), lines - ll };
144 }
145
146 int64_t getLastModificationTime() const { return mLastModificationTime; }
147
148 private:
149 static std::string dump(
150 const std::string &key,
151 const std::pair<std::string /* prop */, PropertyHistory>& tsPair,
152 int64_t time) {
153 const auto timeSequence = tsPair.second;
154 auto eptr = timeSequence.lower_bound(time);
155 if (eptr == timeSequence.end()) {
156 return tsPair.first + "={};\n";
157 }
158 std::stringstream ss;
159 ss << key << "." << tsPair.first << "={";
Andy Hung3b4c1f02020-01-23 18:58:32 -0800160
161 time_string_t last_timestring{}; // last timestring used.
162 while (true) {
163 const time_string_t timestring = mediametrics::timeStringFromNs(eptr->first);
164 // find common prefix offset.
165 const size_t offset = commonTimePrefixPosition(timestring.time,
166 last_timestring.time);
167 last_timestring = timestring;
168 ss << "(" << (offset == 0 ? "" : "~") << &timestring.time[offset]
169 << ") " << eptr->second;
170 if (++eptr == timeSequence.end()) {
Andy Hung3b4c1f02020-01-23 18:58:32 -0800171 break;
172 }
173 ss << ", ";
174 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800175 ss << "};\n";
176 return ss.str();
177 }
178
179 const std::string mKey;
180 const pid_t mPid __unused;
181 const uid_t mUid;
182 const int64_t mCreationTime __unused;
183
184 int64_t mLastModificationTime;
185 std::map<std::string /* property */, PropertyHistory> mPropertyMap;
186 };
187
188 using History = std::map<std::string /* key */, std::shared_ptr<KeyHistory>>;
189
190 static inline constexpr size_t kKeyLowWaterMark = 500;
191 static inline constexpr size_t kKeyHighWaterMark = 1000;
192
193 // Estimated max data space usage is 3KB * kKeyHighWaterMark.
194
195public:
196
197 TimeMachine() = default;
198 TimeMachine(size_t keyLowWaterMark, size_t keyHighWaterMark)
199 : mKeyLowWaterMark(keyLowWaterMark)
200 , mKeyHighWaterMark(keyHighWaterMark) {
201 LOG_ALWAYS_FATAL_IF(keyHighWaterMark <= keyLowWaterMark,
202 "%s: required that keyHighWaterMark:%zu > keyLowWaterMark:%zu",
203 __func__, keyHighWaterMark, keyLowWaterMark);
204 }
205
Andy Hunga8f1c6e2020-01-02 18:25:41 -0800206 // The TimeMachine copy constructor/assignment uses a deep copy,
207 // though the snapshot is not instantaneous nor isochronous.
208 //
209 // If there are concurrent operations ongoing in the other TimeMachine
210 // then there may be some history more recent than others (a time shear).
211 // This is expected to be a benign addition in history as small number of
212 // future elements are incorporated.
213 TimeMachine(const TimeMachine& other) {
214 *this = other;
215 }
216 TimeMachine& operator=(const TimeMachine& other) {
217 std::lock_guard lock(mLock);
218 mHistory.clear();
219
220 {
221 std::lock_guard lock2(other.mLock);
222 mHistory = other.mHistory;
223 }
224
225 // Now that we safely have our own shared pointers, let's dup them
226 // to ensure they are decoupled. We do this by acquiring the other lock.
227 for (const auto &[lkey, lhist] : mHistory) {
228 std::lock_guard lock2(other.getLockForKey(lkey));
229 mHistory[lkey] = std::make_shared<KeyHistory>(*lhist);
230 }
231 return *this;
232 }
233
Andy Hung06f3aba2019-12-03 16:36:42 -0800234 /**
235 * Put all the properties from an item into the Time Machine log.
236 */
Ray Essickf27e9872019-12-07 06:28:46 -0800237 status_t put(const std::shared_ptr<const mediametrics::Item>& item, bool isTrusted = false) {
Andy Hung06f3aba2019-12-03 16:36:42 -0800238 const int64_t time = item->getTimestamp();
239 const std::string &key = item->getKey();
240
241 std::shared_ptr<KeyHistory> keyHistory;
242 {
243 std::vector<std::any> garbage;
244 std::lock_guard lock(mLock);
245
246 auto it = mHistory.find(key);
247 if (it == mHistory.end()) {
248 if (!isTrusted) return PERMISSION_DENIED;
249
250 (void)gc_l(garbage);
251
252 // no keylock needed here as we are sole owner
253 // until placed on mHistory.
254 keyHistory = std::make_shared<KeyHistory>(
255 key, item->getPid(), item->getUid(), time);
256 mHistory[key] = keyHistory;
257 } else {
258 keyHistory = it->second;
259 }
260 }
261
262 // deferred contains remote properties (for other keys) to do later.
Ray Essickf27e9872019-12-07 06:28:46 -0800263 std::vector<const mediametrics::Item::Prop *> deferred;
Andy Hung06f3aba2019-12-03 16:36:42 -0800264 {
265 // handle local properties
266 std::lock_guard lock(getLockForKey(key));
267 if (!isTrusted) {
268 status_t status = keyHistory->checkPermission(item->getUid());
269 if (status != NO_ERROR) return status;
270 }
271
272 for (const auto &prop : *item) {
273 const std::string &name = prop.getName();
274 if (name.size() == 0 || name[0] == '_') continue;
275
276 // Cross key settings are with [key]property
277 if (name[0] == '[') {
278 if (!isTrusted) continue;
279 deferred.push_back(&prop);
280 } else {
281 keyHistory->putProp(name, prop, time);
282 }
283 }
284 }
285
286 // handle remote properties, if any
287 for (const auto propptr : deferred) {
288 const auto &prop = *propptr;
289 const std::string &name = prop.getName();
290 size_t end = name.find_first_of(']'); // TODO: handle nested [] or escape?
291 if (end == 0) continue;
292 std::string remoteKey = name.substr(1, end - 1);
293 std::string remoteName = name.substr(end + 1);
294 if (remoteKey.size() == 0 || remoteName.size() == 0) continue;
295 std::shared_ptr<KeyHistory> remoteKeyHistory;
296 {
297 std::lock_guard lock(mLock);
298 auto it = mHistory.find(remoteKey);
299 if (it == mHistory.end()) continue;
300 remoteKeyHistory = it->second;
301 }
302 std::lock_guard(getLockForKey(remoteKey));
303 remoteKeyHistory->putProp(remoteName, prop, time);
304 }
305 return NO_ERROR;
306 }
307
308 template <typename T>
309 status_t get(const std::string &key, const std::string &property,
310 T* value, int32_t uidCheck = -1, int64_t time = 0) const {
311 std::shared_ptr<KeyHistory> keyHistory;
312 {
313 std::lock_guard lock(mLock);
314 const auto it = mHistory.find(key);
315 if (it == mHistory.end()) return BAD_VALUE;
316 keyHistory = it->second;
317 }
318 std::lock_guard lock(getLockForKey(key));
319 return keyHistory->checkPermission(uidCheck)
320 ?: keyHistory->getValue(property, value, time);
321 }
322
323 /**
324 * Individual property put.
325 *
326 * Put takes in a time (if none is provided then BOOTTIME is used).
327 */
328 template <typename T>
329 status_t put(const std::string &url, T &&e, int64_t time = 0) {
330 std::string key;
331 std::string prop;
332 std::shared_ptr<KeyHistory> keyHistory =
333 getKeyHistoryFromUrl(url, &key, &prop);
334 if (keyHistory == nullptr) return BAD_VALUE;
335 if (time == 0) time = systemTime(SYSTEM_TIME_BOOTTIME);
336 std::lock_guard lock(getLockForKey(key));
337 keyHistory->putValue(prop, std::forward<T>(e), time);
338 return NO_ERROR;
339 }
340
341 /**
342 * Individual property get
343 */
344 template <typename T>
345 status_t get(const std::string &url, T* value, int32_t uidCheck, int64_t time = 0) const {
346 std::string key;
347 std::string prop;
348 std::shared_ptr<KeyHistory> keyHistory =
349 getKeyHistoryFromUrl(url, &key, &prop);
350 if (keyHistory == nullptr) return BAD_VALUE;
351
352 std::lock_guard lock(getLockForKey(key));
353 return keyHistory->checkPermission(uidCheck)
354 ?: keyHistory->getValue(prop, value, time);
355 }
356
357 /**
358 * Individual property get with default
359 */
360 template <typename T>
361 T get(const std::string &url, const T &defaultValue, int32_t uidCheck,
362 int64_t time = 0) const {
363 T value;
364 return get(url, &value, uidCheck, time) == NO_ERROR
365 ? value : defaultValue;
366 }
367
368 /**
369 * Returns number of keys in the Time Machine.
370 */
371 size_t size() const {
372 std::lock_guard lock(mLock);
373 return mHistory.size();
374 }
375
376 /**
377 * Clears all properties from the Time Machine.
378 */
379 void clear() {
380 std::lock_guard lock(mLock);
381 mHistory.clear();
382 }
383
384 /**
385 * Returns a pair consisting of the TimeMachine state as a string
386 * and the number of lines in the string.
387 *
388 * The number of lines in the returned pair is used as an optimization
389 * for subsequent line limiting.
390 *
391 * \param lines the maximum number of lines in the string returned.
392 * \param key selects only that key.
393 * \param time to start the dump from.
394 */
395 std::pair<std::string, int32_t> dump(
396 int32_t lines = INT32_MAX, const std::string &key = {}, int64_t time = 0) const {
397 std::lock_guard lock(mLock);
398 if (!key.empty()) { // use std::regex
399 const auto it = mHistory.find(key);
400 if (it == mHistory.end()) return {};
401 std::lock_guard lock(getLockForKey(it->first));
402 return it->second->dump(lines, time);
403 }
404
405 std::stringstream ss;
406 int32_t ll = lines;
Andy Hunge8989ae2020-01-03 12:20:43 -0800407 for (const auto &[lkey, lhist] : mHistory) {
408 std::lock_guard lock(getLockForKey(lkey));
Andy Hung06f3aba2019-12-03 16:36:42 -0800409 if (lines <= 0) break;
Andy Hunge8989ae2020-01-03 12:20:43 -0800410 auto [s, l] = lhist->dump(ll, time);
Andy Hung06f3aba2019-12-03 16:36:42 -0800411 ss << s;
412 ll -= l;
413 }
414 return { ss.str(), lines - ll };
415 }
416
417private:
418
419 // Obtains the lock for a KeyHistory.
420 std::mutex &getLockForKey(const std::string &key) const {
421 return mKeyLocks[std::hash<std::string>{}(key) % std::size(mKeyLocks)];
422 }
423
424 // Finds a KeyHistory from a URL. Returns nullptr if not found.
425 std::shared_ptr<KeyHistory> getKeyHistoryFromUrl(
426 std::string url, std::string* key, std::string *prop) const {
427 std::lock_guard lock(mLock);
428
429 auto it = mHistory.upper_bound(url);
430 if (it == mHistory.begin()) {
431 return nullptr;
432 }
433 --it; // go to the actual key, if it exists.
434
435 const std::string& itKey = it->first;
436 if (strncmp(itKey.c_str(), url.c_str(), itKey.size())) {
437 return nullptr;
438 }
439 if (key) *key = itKey;
440 if (prop) *prop = url.substr(itKey.size() + 1);
441 return it->second;
442 }
443
444 // GUARDED_BY mLock
445 /**
446 * Garbage collects if the TimeMachine size exceeds the high water mark.
447 *
448 * \param garbage a type-erased vector of elements to be destroyed
449 * outside of lock. Move large items to be destroyed here.
450 *
451 * \return true if garbage collection was done.
452 */
453 bool gc_l(std::vector<std::any>& garbage) {
454 // TODO: something better than this for garbage collection.
455 if (mHistory.size() < mKeyHighWaterMark) return false;
456
457 ALOGD("%s: garbage collection", __func__);
458
459 // erase everything explicitly expired.
460 std::multimap<int64_t, std::string> accessList;
461 // use a stale vector with precise type to avoid type erasure overhead in garbage
462 std::vector<std::shared_ptr<KeyHistory>> stale;
463
464 for (auto it = mHistory.begin(); it != mHistory.end();) {
465 const std::string& key = it->first;
466 std::shared_ptr<KeyHistory> &keyHist = it->second;
467
468 std::lock_guard lock(getLockForKey(it->first));
469 int64_t expireTime = keyHist->getValue("_expire", -1 /* default */);
470 if (expireTime != -1) {
471 stale.emplace_back(std::move(it->second));
472 it = mHistory.erase(it);
473 } else {
474 accessList.emplace(keyHist->getLastModificationTime(), key);
475 ++it;
476 }
477 }
478
479 if (mHistory.size() > mKeyLowWaterMark) {
480 const size_t toDelete = mHistory.size() - mKeyLowWaterMark;
481 auto it = accessList.begin();
482 for (size_t i = 0; i < toDelete; ++i) {
483 auto it2 = mHistory.find(it->second);
484 stale.emplace_back(std::move(it2->second));
485 mHistory.erase(it2);
486 ++it;
487 }
488 }
489 garbage.emplace_back(std::move(accessList));
490 garbage.emplace_back(std::move(stale));
491
492 ALOGD("%s(%zu, %zu): key size:%zu",
493 __func__, mKeyLowWaterMark, mKeyHighWaterMark,
494 mHistory.size());
495 return true;
496 }
497
498 const size_t mKeyLowWaterMark = kKeyLowWaterMark;
499 const size_t mKeyHighWaterMark = kKeyHighWaterMark;
500
501 /**
502 * Locking Strategy
503 *
504 * Each key in the History has a KeyHistory. To get a shared pointer to
505 * the KeyHistory requires a lookup of mHistory under mLock. Once the shared
506 * pointer to KeyHistory is obtained, the mLock for mHistory can be released.
507 *
508 * Once the shared pointer to the key's KeyHistory is obtained, the KeyHistory
509 * can be locked for read and modification through the method getLockForKey().
510 *
511 * Instead of having a mutex per KeyHistory, we use a hash striped lock
512 * which assigns a mutex based on the hash of the key string.
513 *
514 * Once the last shared pointer reference to KeyHistory is released, it is
515 * destroyed. This is done through the garbage collection method.
516 *
517 * This two level locking allows multiple threads to access the TimeMachine
518 * in parallel.
519 */
520
521 mutable std::mutex mLock; // Lock for mHistory
522 History mHistory; // GUARDED_BY mLock
523
524 // KEY_LOCKS is the number of mutexes for keys.
525 // It need not be a power of 2, but faster that way.
526 static inline constexpr size_t KEY_LOCKS = 256;
527 mutable std::mutex mKeyLocks[KEY_LOCKS]; // Hash-striped lock for KeyHistory based on key.
528};
529
530} // namespace android::mediametrics