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