1 // Copyright (C) 2018 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/shell/ShellSubscriber.h"
16 
17 #include <gtest/gtest.h>
18 #include <stdio.h>
19 #include <unistd.h>
20 
21 #include <vector>
22 
23 #include "frameworks/base/cmds/statsd/src/atoms.pb.h"
24 #include "frameworks/base/cmds/statsd/src/shell/shell_config.pb.h"
25 #include "frameworks/base/cmds/statsd/src/shell/shell_data.pb.h"
26 #include "stats_event.h"
27 #include "tests/metrics/metrics_test_helper.h"
28 #include "tests/statsd_test_util.h"
29 
30 using namespace android::os::statsd;
31 using android::sp;
32 using std::vector;
33 using testing::_;
34 using testing::Invoke;
35 using testing::NaggyMock;
36 using testing::StrictMock;
37 
38 #ifdef __ANDROID__
39 
runShellTest(ShellSubscription config,sp<MockUidMap> uidMap,sp<MockStatsPullerManager> pullerManager,const vector<std::shared_ptr<LogEvent>> & pushedEvents,const ShellData & expectedData)40 void runShellTest(ShellSubscription config, sp<MockUidMap> uidMap,
41                   sp<MockStatsPullerManager> pullerManager,
42                   const vector<std::shared_ptr<LogEvent>>& pushedEvents,
43                   const ShellData& expectedData) {
44     // set up 2 pipes for read/write config and data
45     int fds_config[2];
46     ASSERT_EQ(0, pipe(fds_config));
47 
48     int fds_data[2];
49     ASSERT_EQ(0, pipe(fds_data));
50 
51     size_t bufferSize = config.ByteSize();
52     // write the config to pipe, first write size of the config
53     write(fds_config[1], &bufferSize, sizeof(bufferSize));
54     // then write config itself
55     vector<uint8_t> buffer(bufferSize);
56     config.SerializeToArray(&buffer[0], bufferSize);
57     write(fds_config[1], buffer.data(), bufferSize);
58     close(fds_config[1]);
59 
60     sp<ShellSubscriber> shellClient = new ShellSubscriber(uidMap, pullerManager);
61 
62     // mimic a binder thread that a shell subscriber runs on. it would block.
63     std::thread reader([&shellClient, &fds_config, &fds_data] {
64         shellClient->startNewSubscription(fds_config[0], fds_data[1], /*timeoutSec=*/-1);
65     });
66     reader.detach();
67 
68     // let the shell subscriber to receive the config from pipe.
69     std::this_thread::sleep_for(100ms);
70 
71     if (pushedEvents.size() > 0) {
72         // send a log event that matches the config.
73         std::thread log_reader([&shellClient, &pushedEvents] {
74             for (const auto& event : pushedEvents) {
75                 shellClient->onLogEvent(*event);
76             }
77         });
78 
79         log_reader.detach();
80 
81         if (log_reader.joinable()) {
82             log_reader.join();
83         }
84     }
85 
86     // wait for the data to be written.
87     std::this_thread::sleep_for(100ms);
88 
89     // Because we might receive heartbeats from statsd, consisting of data sizes
90     // of 0, encapsulate reads within a while loop.
91     bool readAtom = false;
92     while (!readAtom) {
93         // Read the atom size.
94         size_t dataSize = 0;
95         read(fds_data[0], &dataSize, sizeof(dataSize));
96         if (dataSize == 0) continue;
97         EXPECT_EQ(expectedData.ByteSize(), int(dataSize));
98 
99         // Read that much data in proto binary format.
100         vector<uint8_t> dataBuffer(dataSize);
101         EXPECT_EQ((int)dataSize, read(fds_data[0], dataBuffer.data(), dataSize));
102 
103         // Make sure the received bytes can be parsed to an atom.
104         ShellData receivedAtom;
105         EXPECT_TRUE(receivedAtom.ParseFromArray(dataBuffer.data(), dataSize) != 0);
106 
107         // Serialize the expected atom to byte array and compare to make sure
108         // they are the same.
109         vector<uint8_t> expectedAtomBuffer(expectedData.ByteSize());
110         expectedData.SerializeToArray(expectedAtomBuffer.data(), expectedData.ByteSize());
111         EXPECT_EQ(expectedAtomBuffer, dataBuffer);
112 
113         readAtom = true;
114     }
115 
116     close(fds_data[0]);
117     if (reader.joinable()) {
118         reader.join();
119     }
120 }
121 
TEST(ShellSubscriberTest,testPushedSubscription)122 TEST(ShellSubscriberTest, testPushedSubscription) {
123     sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
124 
125     sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>();
126     vector<std::shared_ptr<LogEvent>> pushedList;
127 
128     // Create the LogEvent from an AStatsEvent
129     std::unique_ptr<LogEvent> logEvent = CreateScreenStateChangedEvent(
130             1000 /*timestamp*/, ::android::view::DisplayStateEnum::DISPLAY_STATE_ON);
131     pushedList.push_back(std::move(logEvent));
132 
133     // create a simple config to get screen events
134     ShellSubscription config;
135     config.add_pushed()->set_atom_id(29);
136 
137     // this is the expected screen event atom.
138     ShellData shellData;
139     shellData.add_atom()->mutable_screen_state_changed()->set_state(
140             ::android::view::DisplayStateEnum::DISPLAY_STATE_ON);
141 
142     runShellTest(config, uidMap, pullerManager, pushedList, shellData);
143 }
144 
145 namespace {
146 
147 int kUid1 = 1000;
148 int kUid2 = 2000;
149 
150 int kCpuTime1 = 100;
151 int kCpuTime2 = 200;
152 
getExpectedShellData()153 ShellData getExpectedShellData() {
154     ShellData shellData;
155     auto* atom1 = shellData.add_atom()->mutable_cpu_active_time();
156     atom1->set_uid(kUid1);
157     atom1->set_time_millis(kCpuTime1);
158 
159     auto* atom2 = shellData.add_atom()->mutable_cpu_active_time();
160     atom2->set_uid(kUid2);
161     atom2->set_time_millis(kCpuTime2);
162 
163     return shellData;
164 }
165 
getPulledConfig()166 ShellSubscription getPulledConfig() {
167     ShellSubscription config;
168     auto* pull_config = config.add_pulled();
169     pull_config->mutable_matcher()->set_atom_id(10016);
170     pull_config->set_freq_millis(2000);
171     return config;
172 }
173 
makeCpuActiveTimeAtom(int32_t uid,int64_t timeMillis)174 shared_ptr<LogEvent> makeCpuActiveTimeAtom(int32_t uid, int64_t timeMillis) {
175     AStatsEvent* statsEvent = AStatsEvent_obtain();
176     AStatsEvent_setAtomId(statsEvent, 10016);
177     AStatsEvent_overwriteTimestamp(statsEvent, 1111L);
178     AStatsEvent_writeInt32(statsEvent, uid);
179     AStatsEvent_writeInt64(statsEvent, timeMillis);
180 
181     std::shared_ptr<LogEvent> logEvent = std::make_shared<LogEvent>(/*uid=*/0, /*pid=*/0);
182     parseStatsEventToLogEvent(statsEvent, logEvent.get());
183     return logEvent;
184 }
185 
186 }  // namespace
187 
TEST(ShellSubscriberTest,testPulledSubscription)188 TEST(ShellSubscriberTest, testPulledSubscription) {
189     sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
190 
191     sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>();
192     const vector<int32_t> uids = {AID_SYSTEM};
193     EXPECT_CALL(*pullerManager, Pull(10016, uids, _, _, _))
194             .WillRepeatedly(Invoke([](int tagId, const vector<int32_t>&, const int64_t,
195                                       vector<std::shared_ptr<LogEvent>>* data, bool) {
196                 data->clear();
197                 data->push_back(makeCpuActiveTimeAtom(/*uid=*/kUid1, /*timeMillis=*/kCpuTime1));
198                 data->push_back(makeCpuActiveTimeAtom(/*uid=*/kUid2, /*timeMillis=*/kCpuTime2));
199                 return true;
200             }));
201     runShellTest(getPulledConfig(), uidMap, pullerManager, vector<std::shared_ptr<LogEvent>>(),
202                  getExpectedShellData());
203 }
204 
205 #else
206 GTEST_LOG_(INFO) << "This test does nothing.\n";
207 #endif
208