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