1 /*
2  * Copyright (C) 2023 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 #include <stats_event.h>
18 #include <stats_socket_loss_reporter.h>
19 #include <unistd.h>
20 
21 #include <vector>
22 
23 #include "stats_statsdsocketlog.h"
24 #include "utils.h"
25 
StatsSocketLossReporter()26 StatsSocketLossReporter::StatsSocketLossReporter() : mUid(getuid()) {
27 }
28 
~StatsSocketLossReporter()29 StatsSocketLossReporter::~StatsSocketLossReporter() {
30     // try to dump loss stats since there might be pending data which have been not sent earlier
31     // due to:
32     // - cool down timer was active
33     // - no input atoms to trigger loss info dump after cooldown timer expired
34     dumpAtomsLossStats(true);
35 }
36 
getInstance()37 StatsSocketLossReporter& StatsSocketLossReporter::getInstance() {
38     static StatsSocketLossReporter instance;
39     return instance;
40 }
41 
noteDrop(int32_t error,int32_t atomId)42 void StatsSocketLossReporter::noteDrop(int32_t error, int32_t atomId) {
43     using namespace android::os::statsdsocket;
44 
45     const int64_t currentRealtimeTsNanos = get_elapsed_realtime_ns();
46 
47     // The intention is to skip self counting, however the timestamps still need to be updated
48     // to know when was last failed attempt to log atom.
49     // This is required for more accurate cool down timer work
50     if (mFirstTsNanos == 0) {
51         mFirstTsNanos.store(currentRealtimeTsNanos, std::memory_order_relaxed);
52     }
53     mLastTsNanos.store(currentRealtimeTsNanos, std::memory_order_relaxed);
54 
55     if (atomId == STATS_SOCKET_LOSS_REPORTED) {
56         // avoid self counting due to write to socket might fail during dumpAtomsLossStats()
57         // also due to mutex is not re-entrant and is already locked by dumpAtomsLossStats() API,
58         // return to avoid deadlock
59         // alternative is to consider std::recursive_mutex
60         return;
61     }
62 
63     std::unique_lock<std::mutex> lock(mMutex);
64 
65     // using unordered_map is more CPU efficient vs vectors, however will require some
66     // postprocessing before writing into the socket
67     const LossInfoKey key = std::make_pair(error, atomId);
68     auto counterIt = mLossInfo.find(key);
69     if (counterIt != mLossInfo.end()) {
70         ++counterIt->second;
71     } else if (mLossInfo.size() < kMaxAtomTagsCount) {
72         mLossInfo[key] = 1;
73     } else {
74         mOverflowCounter++;
75     }
76 }
77 
dumpAtomsLossStats(bool forceDump)78 void StatsSocketLossReporter::dumpAtomsLossStats(bool forceDump) {
79     using namespace android::os::statsdsocket;
80 
81     const int64_t currentRealtimeTsNanos = get_elapsed_realtime_ns();
82 
83     if (!forceDump && isCooldownTimerActive(currentRealtimeTsNanos)) {
84         // To avoid socket flooding with more STATS_SOCKET_LOSS_REPORTED atoms,
85         // which have high probability of write failures, the cooldown timer approach is applied:
86         // - start cooldown timer for 10us for every failed dump
87         // - before writing STATS_SOCKET_LOSS_REPORTED do check the timestamp to keep some delay
88         return;
89     }
90 
91     // intention to hold mutex here during the stats_write() to avoid data copy overhead
92     std::unique_lock<std::mutex> lock(mMutex);
93     if (mLossInfo.size() == 0) {
94         return;
95     }
96 
97     // populate temp vectors to be written into the socket
98     std::vector<int> errors(mLossInfo.size());
99     std::vector<int> tags(mLossInfo.size());
100     std::vector<int> counts(mLossInfo.size());
101 
102     auto lossInfoIt = mLossInfo.begin();
103     for (size_t i = 0; i < mLossInfo.size(); i++, lossInfoIt++) {
104         const LossInfoKey& key = lossInfoIt->first;
105         errors[i] = key.first;
106         tags[i] = key.second;
107         counts[i] = lossInfoIt->second;
108     }
109 
110     // below call might lead to socket loss event - intention is to avoid self counting
111     const int ret = stats_write(STATS_SOCKET_LOSS_REPORTED, mUid, mFirstTsNanos, mLastTsNanos,
112                                 mOverflowCounter, errors, tags, counts);
113     if (ret > 0) {
114         // Otherwise, in case of failure we preserve all socket loss information between dumps.
115         // When above write failed - the socket loss stats are not discarded
116         // and would be re-send during next attempt.
117         mOverflowCounter = 0;
118         mLossInfo.clear();
119 
120         mFirstTsNanos.store(0, std::memory_order_relaxed);
121         mLastTsNanos.store(0, std::memory_order_relaxed);
122     }
123     // since the delay before next attempt is significantly larger than this API call
124     // duration it is ok to have correctness of timestamp in a range of 10us
125     startCooldownTimer(currentRealtimeTsNanos);
126 }
127 
startCooldownTimer(int64_t elapsedRealtimeNanos)128 void StatsSocketLossReporter::startCooldownTimer(int64_t elapsedRealtimeNanos) {
129     mCooldownTimerFinishAtNanos = elapsedRealtimeNanos + kCoolDownTimerDurationNanos;
130 }
131 
isCooldownTimerActive(int64_t elapsedRealtimeNanos) const132 bool StatsSocketLossReporter::isCooldownTimerActive(int64_t elapsedRealtimeNanos) const {
133     return mCooldownTimerFinishAtNanos > elapsedRealtimeNanos;
134 }
135