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