1 /*
2  * Copyright (C) 2017 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 #define DEBUG false  // STOPSHIP if true
18 #include "Log.h"
19 
20 #include "EventMetricProducer.h"
21 #include "stats_util.h"
22 #include "stats_log_util.h"
23 
24 #include <limits.h>
25 #include <stdlib.h>
26 
27 using android::util::FIELD_COUNT_REPEATED;
28 using android::util::FIELD_TYPE_BOOL;
29 using android::util::FIELD_TYPE_FLOAT;
30 using android::util::FIELD_TYPE_INT32;
31 using android::util::FIELD_TYPE_INT64;
32 using android::util::FIELD_TYPE_STRING;
33 using android::util::FIELD_TYPE_MESSAGE;
34 using android::util::ProtoOutputStream;
35 using std::map;
36 using std::string;
37 using std::unordered_map;
38 using std::vector;
39 using std::shared_ptr;
40 
41 namespace android {
42 namespace os {
43 namespace statsd {
44 
45 // for StatsLogReport
46 const int FIELD_ID_ID = 1;
47 const int FIELD_ID_EVENT_METRICS = 4;
48 const int FIELD_ID_IS_ACTIVE = 14;
49 // for EventMetricDataWrapper
50 const int FIELD_ID_DATA = 1;
51 // for EventMetricData
52 const int FIELD_ID_ELAPSED_TIMESTAMP_NANOS = 1;
53 const int FIELD_ID_ATOMS = 2;
54 
EventMetricProducer(const ConfigKey & key,const EventMetric & metric,const int conditionIndex,const vector<ConditionState> & initialConditionCache,const sp<ConditionWizard> & wizard,const int64_t startTimeNs,const unordered_map<int,shared_ptr<Activation>> & eventActivationMap,const unordered_map<int,vector<shared_ptr<Activation>>> & eventDeactivationMap,const vector<int> & slicedStateAtoms,const unordered_map<int,unordered_map<int,int64_t>> & stateGroupMap)55 EventMetricProducer::EventMetricProducer(
56         const ConfigKey& key, const EventMetric& metric, const int conditionIndex,
57         const vector<ConditionState>& initialConditionCache, const sp<ConditionWizard>& wizard,
58         const int64_t startTimeNs,
59         const unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
60         const unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap,
61         const vector<int>& slicedStateAtoms,
62         const unordered_map<int, unordered_map<int, int64_t>>& stateGroupMap)
63     : MetricProducer(metric.id(), key, startTimeNs, conditionIndex, initialConditionCache, wizard,
64                      eventActivationMap, eventDeactivationMap, slicedStateAtoms, stateGroupMap) {
65     if (metric.links().size() > 0) {
66         for (const auto& link : metric.links()) {
67             Metric2Condition mc;
68             mc.conditionId = link.condition();
69             translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
70             translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
71             mMetric2ConditionLinks.push_back(mc);
72         }
73         mConditionSliced = true;
74     }
75     mProto = std::make_unique<ProtoOutputStream>();
76     VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
77          (long long)mBucketSizeNs, (long long)mTimeBaseNs);
78 }
79 
~EventMetricProducer()80 EventMetricProducer::~EventMetricProducer() {
81     VLOG("~EventMetricProducer() called");
82 }
83 
dropDataLocked(const int64_t dropTimeNs)84 void EventMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
85     mProto->clear();
86     StatsdStats::getInstance().noteBucketDropped(mMetricId);
87 }
88 
onSlicedConditionMayChangeLocked(bool overallCondition,const int64_t eventTime)89 void EventMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
90                                                            const int64_t eventTime) {
91 }
92 
serializeProtoLocked(ProtoOutputStream & protoOutput)93 std::unique_ptr<std::vector<uint8_t>> serializeProtoLocked(ProtoOutputStream& protoOutput) {
94     size_t bufferSize = protoOutput.size();
95 
96     std::unique_ptr<std::vector<uint8_t>> buffer(new std::vector<uint8_t>(bufferSize));
97 
98     size_t pos = 0;
99     sp<android::util::ProtoReader> reader = protoOutput.data();
100     while (reader->readBuffer() != NULL) {
101         size_t toRead = reader->currentToRead();
102         std::memcpy(&((*buffer)[pos]), reader->readBuffer(), toRead);
103         pos += toRead;
104         reader->move(toRead);
105     }
106 
107     return buffer;
108 }
109 
clearPastBucketsLocked(const int64_t dumpTimeNs)110 void EventMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
111     mProto->clear();
112 }
113 
onDumpReportLocked(const int64_t dumpTimeNs,const bool include_current_partial_bucket,const bool erase_data,const DumpLatency dumpLatency,std::set<string> * str_set,ProtoOutputStream * protoOutput)114 void EventMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
115                                              const bool include_current_partial_bucket,
116                                              const bool erase_data,
117                                              const DumpLatency dumpLatency,
118                                              std::set<string> *str_set,
119                                              ProtoOutputStream* protoOutput) {
120     protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
121     protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_IS_ACTIVE, isActiveLocked());
122     if (mProto->size() <= 0) {
123         return;
124     }
125 
126     size_t bufferSize = mProto->size();
127     VLOG("metric %lld dump report now... proto size: %zu ",
128         (long long)mMetricId, bufferSize);
129     std::unique_ptr<std::vector<uint8_t>> buffer = serializeProtoLocked(*mProto);
130 
131     protoOutput->write(FIELD_TYPE_MESSAGE | FIELD_ID_EVENT_METRICS,
132                        reinterpret_cast<char*>(buffer.get()->data()), buffer.get()->size());
133 
134     if (erase_data) {
135         mProto->clear();
136     }
137 }
138 
onConditionChangedLocked(const bool conditionMet,const int64_t eventTime)139 void EventMetricProducer::onConditionChangedLocked(const bool conditionMet,
140                                                    const int64_t eventTime) {
141     VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
142     mCondition = conditionMet ? ConditionState::kTrue : ConditionState::kFalse;
143 }
144 
onMatchedLogEventInternalLocked(const size_t matcherIndex,const MetricDimensionKey & eventKey,const ConditionKey & conditionKey,bool condition,const LogEvent & event,const map<int,HashableDimensionKey> & statePrimaryKeys)145 void EventMetricProducer::onMatchedLogEventInternalLocked(
146         const size_t matcherIndex, const MetricDimensionKey& eventKey,
147         const ConditionKey& conditionKey, bool condition, const LogEvent& event,
148         const map<int, HashableDimensionKey>& statePrimaryKeys) {
149     if (!condition) {
150         return;
151     }
152 
153     uint64_t wrapperToken =
154             mProto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
155     const int64_t elapsedTimeNs = truncateTimestampIfNecessary(event);
156     mProto->write(FIELD_TYPE_INT64 | FIELD_ID_ELAPSED_TIMESTAMP_NANOS, (long long) elapsedTimeNs);
157 
158     uint64_t eventToken = mProto->start(FIELD_TYPE_MESSAGE | FIELD_ID_ATOMS);
159     event.ToProto(*mProto);
160     mProto->end(eventToken);
161     mProto->end(wrapperToken);
162 }
163 
byteSizeLocked() const164 size_t EventMetricProducer::byteSizeLocked() const {
165     return mProto->bytesWritten();
166 }
167 
168 }  // namespace statsd
169 }  // namespace os
170 }  // namespace android
171