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