Andy Hung | 06f3aba | 2019-12-03 16:36:42 -0800 | [diff] [blame] | 1 | /* |
| 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 | |
| 26 | #include <media/MediaAnalyticsItem.h> |
| 27 | #include <utils/Timers.h> |
| 28 | |
| 29 | namespace android::mediametrics { |
| 30 | |
| 31 | // define a way of printing the monostate |
| 32 | inline std::ostream & operator<< (std::ostream& s, |
| 33 | std::monostate const& v __unused) { |
| 34 | s << "none_item"; |
| 35 | return s; |
| 36 | } |
| 37 | |
| 38 | // define a way of printing a variant |
| 39 | // see https://en.cppreference.com/w/cpp/utility/variant/visit |
| 40 | template <typename T0, typename ... Ts> |
| 41 | std::ostream & operator<< (std::ostream& s, |
| 42 | std::variant<T0, Ts...> const& v) { |
| 43 | std::visit([&s](auto && arg){ s << std::forward<decltype(arg)>(arg); }, v); |
| 44 | return s; |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * The TimeMachine is used to record timing changes of MediaAnalyticItem |
| 49 | * properties. |
| 50 | * |
| 51 | * Any URL that ends with '!' will have a time sequence that keeps duplicates. |
| 52 | * |
| 53 | * The TimeMachine is NOT thread safe. |
| 54 | */ |
| 55 | class TimeMachine { |
| 56 | |
| 57 | using Elem = std::variant<std::monostate, int32_t, int64_t, double, std::string>; |
| 58 | using PropertyHistory = std::multimap<int64_t /* time */, Elem>; |
| 59 | |
| 60 | // KeyHistory contains no lock. |
| 61 | // Access is through the TimeMachine, and a hash-striped lock is used |
| 62 | // before calling into KeyHistory. |
| 63 | class KeyHistory { |
| 64 | public: |
| 65 | template <typename T> |
| 66 | KeyHistory(T key, pid_t pid, uid_t uid, int64_t time) |
| 67 | : mKey(key) |
| 68 | , mPid(pid) |
| 69 | , mUid(uid) |
| 70 | , mCreationTime(time) |
| 71 | , mLastModificationTime(time) |
| 72 | { |
| 73 | putValue("_pid", (int32_t)pid, time); |
| 74 | putValue("_uid", (int32_t)uid, time); |
| 75 | } |
| 76 | |
| 77 | status_t checkPermission(uid_t uidCheck) const { |
| 78 | return uidCheck != (uid_t)-1 && uidCheck != mUid ? PERMISSION_DENIED : NO_ERROR; |
| 79 | } |
| 80 | |
| 81 | template <typename T> |
| 82 | status_t getValue(const std::string &property, T* value, int64_t time = 0) const { |
| 83 | if (time == 0) time = systemTime(SYSTEM_TIME_BOOTTIME); |
| 84 | const auto tsptr = mPropertyMap.find(property); |
| 85 | if (tsptr == mPropertyMap.end()) return BAD_VALUE; |
| 86 | const auto& timeSequence = tsptr->second; |
| 87 | auto eptr = timeSequence.upper_bound(time); |
| 88 | if (eptr == timeSequence.begin()) return BAD_VALUE; |
| 89 | --eptr; |
| 90 | if (eptr == timeSequence.end()) return BAD_VALUE; |
| 91 | const T* vptr = std::get_if<T>(&eptr->second); |
| 92 | if (vptr == nullptr) return BAD_VALUE; |
| 93 | *value = *vptr; |
| 94 | return NO_ERROR; |
| 95 | } |
| 96 | |
| 97 | template <typename T> |
| 98 | status_t getValue(const std::string &property, T defaultValue, int64_t time = 0) const { |
| 99 | T value; |
| 100 | return getValue(property, &value, time) != NO_ERROR ? defaultValue : value; |
| 101 | } |
| 102 | |
| 103 | void putProp( |
| 104 | const std::string &name, const MediaAnalyticsItem::Prop &prop, int64_t time = 0) { |
| 105 | prop.visit([&](auto value) { putValue(name, value, time); }); |
| 106 | } |
| 107 | |
| 108 | template <typename T> |
| 109 | void putValue(const std::string &property, |
| 110 | T&& e, int64_t time = 0) { |
| 111 | if (time == 0) time = systemTime(SYSTEM_TIME_BOOTTIME); |
| 112 | mLastModificationTime = time; |
| 113 | auto& timeSequence = mPropertyMap[property]; |
| 114 | Elem el{std::forward<T>(e)}; |
| 115 | if (timeSequence.empty() // no elements |
| 116 | || property.back() == '!' // keep duplicates TODO: remove? |
| 117 | || timeSequence.rbegin()->second != el) { // value changed |
| 118 | timeSequence.emplace(time, std::move(el)); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // Explicitly ignore rate properties - we don't expose them for now. |
| 123 | void putValue( |
| 124 | const std::string &property __unused, |
| 125 | std::pair<int64_t, int64_t>& e __unused, |
| 126 | int64_t time __unused) { |
| 127 | } |
| 128 | |
| 129 | std::pair<std::string, int32_t> dump(int32_t lines, int64_t time) const { |
| 130 | std::stringstream ss; |
| 131 | int32_t ll = lines; |
| 132 | for (auto& tsPair : mPropertyMap) { |
| 133 | if (ll <= 0) break; |
| 134 | ss << dump(mKey, tsPair, time); |
| 135 | --ll; |
| 136 | } |
| 137 | return { ss.str(), lines - ll }; |
| 138 | } |
| 139 | |
| 140 | int64_t getLastModificationTime() const { return mLastModificationTime; } |
| 141 | |
| 142 | private: |
| 143 | static std::string dump( |
| 144 | const std::string &key, |
| 145 | const std::pair<std::string /* prop */, PropertyHistory>& tsPair, |
| 146 | int64_t time) { |
| 147 | const auto timeSequence = tsPair.second; |
| 148 | auto eptr = timeSequence.lower_bound(time); |
| 149 | if (eptr == timeSequence.end()) { |
| 150 | return tsPair.first + "={};\n"; |
| 151 | } |
| 152 | std::stringstream ss; |
| 153 | ss << key << "." << tsPair.first << "={"; |
| 154 | do { |
| 155 | ss << eptr->first << ":" << eptr->second << ","; |
| 156 | } while (++eptr != timeSequence.end()); |
| 157 | ss << "};\n"; |
| 158 | return ss.str(); |
| 159 | } |
| 160 | |
| 161 | const std::string mKey; |
| 162 | const pid_t mPid __unused; |
| 163 | const uid_t mUid; |
| 164 | const int64_t mCreationTime __unused; |
| 165 | |
| 166 | int64_t mLastModificationTime; |
| 167 | std::map<std::string /* property */, PropertyHistory> mPropertyMap; |
| 168 | }; |
| 169 | |
| 170 | using History = std::map<std::string /* key */, std::shared_ptr<KeyHistory>>; |
| 171 | |
| 172 | static inline constexpr size_t kKeyLowWaterMark = 500; |
| 173 | static inline constexpr size_t kKeyHighWaterMark = 1000; |
| 174 | |
| 175 | // Estimated max data space usage is 3KB * kKeyHighWaterMark. |
| 176 | |
| 177 | public: |
| 178 | |
| 179 | TimeMachine() = default; |
| 180 | TimeMachine(size_t keyLowWaterMark, size_t keyHighWaterMark) |
| 181 | : mKeyLowWaterMark(keyLowWaterMark) |
| 182 | , mKeyHighWaterMark(keyHighWaterMark) { |
| 183 | LOG_ALWAYS_FATAL_IF(keyHighWaterMark <= keyLowWaterMark, |
| 184 | "%s: required that keyHighWaterMark:%zu > keyLowWaterMark:%zu", |
| 185 | __func__, keyHighWaterMark, keyLowWaterMark); |
| 186 | } |
| 187 | |
| 188 | /** |
| 189 | * Put all the properties from an item into the Time Machine log. |
| 190 | */ |
| 191 | status_t put(const std::shared_ptr<const MediaAnalyticsItem>& item, bool isTrusted = false) { |
| 192 | const int64_t time = item->getTimestamp(); |
| 193 | const std::string &key = item->getKey(); |
| 194 | |
| 195 | std::shared_ptr<KeyHistory> keyHistory; |
| 196 | { |
| 197 | std::vector<std::any> garbage; |
| 198 | std::lock_guard lock(mLock); |
| 199 | |
| 200 | auto it = mHistory.find(key); |
| 201 | if (it == mHistory.end()) { |
| 202 | if (!isTrusted) return PERMISSION_DENIED; |
| 203 | |
| 204 | (void)gc_l(garbage); |
| 205 | |
| 206 | // no keylock needed here as we are sole owner |
| 207 | // until placed on mHistory. |
| 208 | keyHistory = std::make_shared<KeyHistory>( |
| 209 | key, item->getPid(), item->getUid(), time); |
| 210 | mHistory[key] = keyHistory; |
| 211 | } else { |
| 212 | keyHistory = it->second; |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | // deferred contains remote properties (for other keys) to do later. |
| 217 | std::vector<const MediaAnalyticsItem::Prop *> deferred; |
| 218 | { |
| 219 | // handle local properties |
| 220 | std::lock_guard lock(getLockForKey(key)); |
| 221 | if (!isTrusted) { |
| 222 | status_t status = keyHistory->checkPermission(item->getUid()); |
| 223 | if (status != NO_ERROR) return status; |
| 224 | } |
| 225 | |
| 226 | for (const auto &prop : *item) { |
| 227 | const std::string &name = prop.getName(); |
| 228 | if (name.size() == 0 || name[0] == '_') continue; |
| 229 | |
| 230 | // Cross key settings are with [key]property |
| 231 | if (name[0] == '[') { |
| 232 | if (!isTrusted) continue; |
| 233 | deferred.push_back(&prop); |
| 234 | } else { |
| 235 | keyHistory->putProp(name, prop, time); |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | // handle remote properties, if any |
| 241 | for (const auto propptr : deferred) { |
| 242 | const auto &prop = *propptr; |
| 243 | const std::string &name = prop.getName(); |
| 244 | size_t end = name.find_first_of(']'); // TODO: handle nested [] or escape? |
| 245 | if (end == 0) continue; |
| 246 | std::string remoteKey = name.substr(1, end - 1); |
| 247 | std::string remoteName = name.substr(end + 1); |
| 248 | if (remoteKey.size() == 0 || remoteName.size() == 0) continue; |
| 249 | std::shared_ptr<KeyHistory> remoteKeyHistory; |
| 250 | { |
| 251 | std::lock_guard lock(mLock); |
| 252 | auto it = mHistory.find(remoteKey); |
| 253 | if (it == mHistory.end()) continue; |
| 254 | remoteKeyHistory = it->second; |
| 255 | } |
| 256 | std::lock_guard(getLockForKey(remoteKey)); |
| 257 | remoteKeyHistory->putProp(remoteName, prop, time); |
| 258 | } |
| 259 | return NO_ERROR; |
| 260 | } |
| 261 | |
| 262 | template <typename T> |
| 263 | status_t get(const std::string &key, const std::string &property, |
| 264 | T* value, int32_t uidCheck = -1, int64_t time = 0) const { |
| 265 | std::shared_ptr<KeyHistory> keyHistory; |
| 266 | { |
| 267 | std::lock_guard lock(mLock); |
| 268 | const auto it = mHistory.find(key); |
| 269 | if (it == mHistory.end()) return BAD_VALUE; |
| 270 | keyHistory = it->second; |
| 271 | } |
| 272 | std::lock_guard lock(getLockForKey(key)); |
| 273 | return keyHistory->checkPermission(uidCheck) |
| 274 | ?: keyHistory->getValue(property, value, time); |
| 275 | } |
| 276 | |
| 277 | /** |
| 278 | * Individual property put. |
| 279 | * |
| 280 | * Put takes in a time (if none is provided then BOOTTIME is used). |
| 281 | */ |
| 282 | template <typename T> |
| 283 | status_t put(const std::string &url, T &&e, int64_t time = 0) { |
| 284 | std::string key; |
| 285 | std::string prop; |
| 286 | std::shared_ptr<KeyHistory> keyHistory = |
| 287 | getKeyHistoryFromUrl(url, &key, &prop); |
| 288 | if (keyHistory == nullptr) return BAD_VALUE; |
| 289 | if (time == 0) time = systemTime(SYSTEM_TIME_BOOTTIME); |
| 290 | std::lock_guard lock(getLockForKey(key)); |
| 291 | keyHistory->putValue(prop, std::forward<T>(e), time); |
| 292 | return NO_ERROR; |
| 293 | } |
| 294 | |
| 295 | /** |
| 296 | * Individual property get |
| 297 | */ |
| 298 | template <typename T> |
| 299 | status_t get(const std::string &url, T* value, int32_t uidCheck, int64_t time = 0) const { |
| 300 | std::string key; |
| 301 | std::string prop; |
| 302 | std::shared_ptr<KeyHistory> keyHistory = |
| 303 | getKeyHistoryFromUrl(url, &key, &prop); |
| 304 | if (keyHistory == nullptr) return BAD_VALUE; |
| 305 | |
| 306 | std::lock_guard lock(getLockForKey(key)); |
| 307 | return keyHistory->checkPermission(uidCheck) |
| 308 | ?: keyHistory->getValue(prop, value, time); |
| 309 | } |
| 310 | |
| 311 | /** |
| 312 | * Individual property get with default |
| 313 | */ |
| 314 | template <typename T> |
| 315 | T get(const std::string &url, const T &defaultValue, int32_t uidCheck, |
| 316 | int64_t time = 0) const { |
| 317 | T value; |
| 318 | return get(url, &value, uidCheck, time) == NO_ERROR |
| 319 | ? value : defaultValue; |
| 320 | } |
| 321 | |
| 322 | /** |
| 323 | * Returns number of keys in the Time Machine. |
| 324 | */ |
| 325 | size_t size() const { |
| 326 | std::lock_guard lock(mLock); |
| 327 | return mHistory.size(); |
| 328 | } |
| 329 | |
| 330 | /** |
| 331 | * Clears all properties from the Time Machine. |
| 332 | */ |
| 333 | void clear() { |
| 334 | std::lock_guard lock(mLock); |
| 335 | mHistory.clear(); |
| 336 | } |
| 337 | |
| 338 | /** |
| 339 | * Returns a pair consisting of the TimeMachine state as a string |
| 340 | * and the number of lines in the string. |
| 341 | * |
| 342 | * The number of lines in the returned pair is used as an optimization |
| 343 | * for subsequent line limiting. |
| 344 | * |
| 345 | * \param lines the maximum number of lines in the string returned. |
| 346 | * \param key selects only that key. |
| 347 | * \param time to start the dump from. |
| 348 | */ |
| 349 | std::pair<std::string, int32_t> dump( |
| 350 | int32_t lines = INT32_MAX, const std::string &key = {}, int64_t time = 0) const { |
| 351 | std::lock_guard lock(mLock); |
| 352 | if (!key.empty()) { // use std::regex |
| 353 | const auto it = mHistory.find(key); |
| 354 | if (it == mHistory.end()) return {}; |
| 355 | std::lock_guard lock(getLockForKey(it->first)); |
| 356 | return it->second->dump(lines, time); |
| 357 | } |
| 358 | |
| 359 | std::stringstream ss; |
| 360 | int32_t ll = lines; |
| 361 | for (const auto &keyPair : mHistory) { |
| 362 | std::lock_guard lock(getLockForKey(keyPair.first)); |
| 363 | if (lines <= 0) break; |
| 364 | auto [s, l] = keyPair.second->dump(ll, time); |
| 365 | ss << s; |
| 366 | ll -= l; |
| 367 | } |
| 368 | return { ss.str(), lines - ll }; |
| 369 | } |
| 370 | |
| 371 | private: |
| 372 | |
| 373 | // Obtains the lock for a KeyHistory. |
| 374 | std::mutex &getLockForKey(const std::string &key) const { |
| 375 | return mKeyLocks[std::hash<std::string>{}(key) % std::size(mKeyLocks)]; |
| 376 | } |
| 377 | |
| 378 | // Finds a KeyHistory from a URL. Returns nullptr if not found. |
| 379 | std::shared_ptr<KeyHistory> getKeyHistoryFromUrl( |
| 380 | std::string url, std::string* key, std::string *prop) const { |
| 381 | std::lock_guard lock(mLock); |
| 382 | |
| 383 | auto it = mHistory.upper_bound(url); |
| 384 | if (it == mHistory.begin()) { |
| 385 | return nullptr; |
| 386 | } |
| 387 | --it; // go to the actual key, if it exists. |
| 388 | |
| 389 | const std::string& itKey = it->first; |
| 390 | if (strncmp(itKey.c_str(), url.c_str(), itKey.size())) { |
| 391 | return nullptr; |
| 392 | } |
| 393 | if (key) *key = itKey; |
| 394 | if (prop) *prop = url.substr(itKey.size() + 1); |
| 395 | return it->second; |
| 396 | } |
| 397 | |
| 398 | // GUARDED_BY mLock |
| 399 | /** |
| 400 | * Garbage collects if the TimeMachine size exceeds the high water mark. |
| 401 | * |
| 402 | * \param garbage a type-erased vector of elements to be destroyed |
| 403 | * outside of lock. Move large items to be destroyed here. |
| 404 | * |
| 405 | * \return true if garbage collection was done. |
| 406 | */ |
| 407 | bool gc_l(std::vector<std::any>& garbage) { |
| 408 | // TODO: something better than this for garbage collection. |
| 409 | if (mHistory.size() < mKeyHighWaterMark) return false; |
| 410 | |
| 411 | ALOGD("%s: garbage collection", __func__); |
| 412 | |
| 413 | // erase everything explicitly expired. |
| 414 | std::multimap<int64_t, std::string> accessList; |
| 415 | // use a stale vector with precise type to avoid type erasure overhead in garbage |
| 416 | std::vector<std::shared_ptr<KeyHistory>> stale; |
| 417 | |
| 418 | for (auto it = mHistory.begin(); it != mHistory.end();) { |
| 419 | const std::string& key = it->first; |
| 420 | std::shared_ptr<KeyHistory> &keyHist = it->second; |
| 421 | |
| 422 | std::lock_guard lock(getLockForKey(it->first)); |
| 423 | int64_t expireTime = keyHist->getValue("_expire", -1 /* default */); |
| 424 | if (expireTime != -1) { |
| 425 | stale.emplace_back(std::move(it->second)); |
| 426 | it = mHistory.erase(it); |
| 427 | } else { |
| 428 | accessList.emplace(keyHist->getLastModificationTime(), key); |
| 429 | ++it; |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | if (mHistory.size() > mKeyLowWaterMark) { |
| 434 | const size_t toDelete = mHistory.size() - mKeyLowWaterMark; |
| 435 | auto it = accessList.begin(); |
| 436 | for (size_t i = 0; i < toDelete; ++i) { |
| 437 | auto it2 = mHistory.find(it->second); |
| 438 | stale.emplace_back(std::move(it2->second)); |
| 439 | mHistory.erase(it2); |
| 440 | ++it; |
| 441 | } |
| 442 | } |
| 443 | garbage.emplace_back(std::move(accessList)); |
| 444 | garbage.emplace_back(std::move(stale)); |
| 445 | |
| 446 | ALOGD("%s(%zu, %zu): key size:%zu", |
| 447 | __func__, mKeyLowWaterMark, mKeyHighWaterMark, |
| 448 | mHistory.size()); |
| 449 | return true; |
| 450 | } |
| 451 | |
| 452 | const size_t mKeyLowWaterMark = kKeyLowWaterMark; |
| 453 | const size_t mKeyHighWaterMark = kKeyHighWaterMark; |
| 454 | |
| 455 | /** |
| 456 | * Locking Strategy |
| 457 | * |
| 458 | * Each key in the History has a KeyHistory. To get a shared pointer to |
| 459 | * the KeyHistory requires a lookup of mHistory under mLock. Once the shared |
| 460 | * pointer to KeyHistory is obtained, the mLock for mHistory can be released. |
| 461 | * |
| 462 | * Once the shared pointer to the key's KeyHistory is obtained, the KeyHistory |
| 463 | * can be locked for read and modification through the method getLockForKey(). |
| 464 | * |
| 465 | * Instead of having a mutex per KeyHistory, we use a hash striped lock |
| 466 | * which assigns a mutex based on the hash of the key string. |
| 467 | * |
| 468 | * Once the last shared pointer reference to KeyHistory is released, it is |
| 469 | * destroyed. This is done through the garbage collection method. |
| 470 | * |
| 471 | * This two level locking allows multiple threads to access the TimeMachine |
| 472 | * in parallel. |
| 473 | */ |
| 474 | |
| 475 | mutable std::mutex mLock; // Lock for mHistory |
| 476 | History mHistory; // GUARDED_BY mLock |
| 477 | |
| 478 | // KEY_LOCKS is the number of mutexes for keys. |
| 479 | // It need not be a power of 2, but faster that way. |
| 480 | static inline constexpr size_t KEY_LOCKS = 256; |
| 481 | mutable std::mutex mKeyLocks[KEY_LOCKS]; // Hash-striped lock for KeyHistory based on key. |
| 482 | }; |
| 483 | |
| 484 | } // namespace android::mediametrics |