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