1 //
2 // Copyright (C) 2012 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 "update_engine/payload_consumer/postinstall_runner_action.h"
18
19 #include <sys/stat.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22
23 #include <memory>
24 #include <string>
25 #include <utility>
26
27 #include <base/bind.h>
28 #include <base/files/file_util.h>
29 #include <base/message_loop/message_loop.h>
30 #include <base/strings/string_util.h>
31 #include <base/strings/stringprintf.h>
32 #include <brillo/message_loops/base_message_loop.h>
33 #include <brillo/message_loops/message_loop_utils.h>
34 #include <gmock/gmock.h>
35 #include <gtest/gtest.h>
36
37 #include "update_engine/common/constants.h"
38 #include "update_engine/common/fake_boot_control.h"
39 #include "update_engine/common/fake_hardware.h"
40 #include "update_engine/common/subprocess.h"
41 #include "update_engine/common/test_utils.h"
42 #include "update_engine/common/utils.h"
43 #include "update_engine/mock_payload_state.h"
44
45 using brillo::MessageLoop;
46 using chromeos_update_engine::test_utils::ScopedLoopbackDeviceBinder;
47 using std::string;
48
49 namespace chromeos_update_engine {
50
51 class PostinstActionProcessorDelegate : public ActionProcessorDelegate {
52 public:
53 PostinstActionProcessorDelegate() = default;
ProcessingDone(const ActionProcessor * processor,ErrorCode code)54 void ProcessingDone(const ActionProcessor* processor,
55 ErrorCode code) override {
56 MessageLoop::current()->BreakLoop();
57 processing_done_called_ = true;
58 }
ProcessingStopped(const ActionProcessor * processor)59 void ProcessingStopped(const ActionProcessor* processor) override {
60 MessageLoop::current()->BreakLoop();
61 processing_stopped_called_ = true;
62 }
63
ActionCompleted(ActionProcessor * processor,AbstractAction * action,ErrorCode code)64 void ActionCompleted(ActionProcessor* processor,
65 AbstractAction* action,
66 ErrorCode code) override {
67 if (action->Type() == PostinstallRunnerAction::StaticType()) {
68 code_ = code;
69 code_set_ = true;
70 }
71 }
72
73 ErrorCode code_{ErrorCode::kError};
74 bool code_set_{false};
75 bool processing_done_called_{false};
76 bool processing_stopped_called_{false};
77 };
78
79 class MockPostinstallRunnerActionDelegate
80 : public PostinstallRunnerAction::DelegateInterface {
81 public:
82 MOCK_METHOD1(ProgressUpdate, void(double progress));
83 };
84
85 class PostinstallRunnerActionTest : public ::testing::Test {
86 protected:
SetUp()87 void SetUp() override {
88 loop_.SetAsCurrent();
89 async_signal_handler_.Init();
90 subprocess_.Init(&async_signal_handler_);
91 // These tests use the postinstall files generated by "generate_images.sh"
92 // stored in the "disk_ext2_unittest.img" image.
93 postinstall_image_ =
94 test_utils::GetBuildArtifactsPath("gen/disk_ext2_unittest.img");
95 }
96
97 // Setup an action processor and run the PostinstallRunnerAction with a single
98 // partition |device_path|, running the |postinstall_program| command from
99 // there.
100 void RunPostinstallAction(const string& device_path,
101 const string& postinstall_program,
102 bool powerwash_required,
103 bool is_rollback);
104
105 public:
ResumeRunningAction()106 void ResumeRunningAction() {
107 ASSERT_NE(nullptr, postinstall_action_);
108 postinstall_action_->ResumeAction();
109 }
110
SuspendRunningAction()111 void SuspendRunningAction() {
112 if (!postinstall_action_ || !postinstall_action_->current_command_ ||
113 test_utils::Readlink(base::StringPrintf(
114 "/proc/%d/fd/0", postinstall_action_->current_command_)) !=
115 "/dev/zero") {
116 // We need to wait for the postinstall command to start and flag that it
117 // is ready by redirecting its input to /dev/zero.
118 loop_.PostDelayedTask(
119 FROM_HERE,
120 base::Bind(&PostinstallRunnerActionTest::SuspendRunningAction,
121 base::Unretained(this)),
122 base::TimeDelta::FromMilliseconds(100));
123 } else {
124 postinstall_action_->SuspendAction();
125 // Schedule to be resumed in a little bit.
126 loop_.PostDelayedTask(
127 FROM_HERE,
128 base::Bind(&PostinstallRunnerActionTest::ResumeRunningAction,
129 base::Unretained(this)),
130 base::TimeDelta::FromMilliseconds(100));
131 }
132 }
133
CancelWhenStarted()134 void CancelWhenStarted() {
135 if (!postinstall_action_ || !postinstall_action_->current_command_) {
136 // Wait for the postinstall command to run.
137 loop_.PostDelayedTask(
138 FROM_HERE,
139 base::Bind(&PostinstallRunnerActionTest::CancelWhenStarted,
140 base::Unretained(this)),
141 base::TimeDelta::FromMilliseconds(10));
142 } else {
143 CHECK(processor_);
144 processor_->StopProcessing();
145 }
146 }
147
148 protected:
149 base::MessageLoopForIO base_loop_;
150 brillo::BaseMessageLoop loop_{&base_loop_};
151 brillo::AsynchronousSignalHandler async_signal_handler_;
152 Subprocess subprocess_;
153
154 // The path to the postinstall sample image.
155 string postinstall_image_;
156
157 FakeBootControl fake_boot_control_;
158 FakeHardware fake_hardware_;
159 PostinstActionProcessorDelegate processor_delegate_;
160
161 // The PostinstallRunnerAction delegate receiving the progress updates.
162 PostinstallRunnerAction::DelegateInterface* setup_action_delegate_{nullptr};
163
164 // A pointer to the posinstall_runner action and the processor.
165 PostinstallRunnerAction* postinstall_action_{nullptr};
166 ActionProcessor* processor_{nullptr};
167 };
168
RunPostinstallAction(const string & device_path,const string & postinstall_program,bool powerwash_required,bool is_rollback)169 void PostinstallRunnerActionTest::RunPostinstallAction(
170 const string& device_path,
171 const string& postinstall_program,
172 bool powerwash_required,
173 bool is_rollback) {
174 ActionProcessor processor;
175 processor_ = &processor;
176 auto feeder_action = std::make_unique<ObjectFeederAction<InstallPlan>>();
177 InstallPlan::Partition part;
178 part.name = "part";
179 part.target_path = device_path;
180 part.run_postinstall = true;
181 part.postinstall_path = postinstall_program;
182 InstallPlan install_plan;
183 install_plan.partitions = {part};
184 install_plan.download_url = "http://127.0.0.1:8080/update";
185 install_plan.powerwash_required = powerwash_required;
186 install_plan.is_rollback = is_rollback;
187 feeder_action->set_obj(install_plan);
188 auto runner_action = std::make_unique<PostinstallRunnerAction>(
189 &fake_boot_control_, &fake_hardware_);
190 postinstall_action_ = runner_action.get();
191 runner_action->set_delegate(setup_action_delegate_);
192 BondActions(feeder_action.get(), runner_action.get());
193 auto collector_action =
194 std::make_unique<ObjectCollectorAction<InstallPlan>>();
195 BondActions(runner_action.get(), collector_action.get());
196 processor.EnqueueAction(std::move(feeder_action));
197 processor.EnqueueAction(std::move(runner_action));
198 processor.EnqueueAction(std::move(collector_action));
199 processor.set_delegate(&processor_delegate_);
200
201 loop_.PostTask(
202 FROM_HERE,
203 base::Bind(
204 [](ActionProcessor* processor) { processor->StartProcessing(); },
205 base::Unretained(&processor)));
206 loop_.Run();
207 ASSERT_FALSE(processor.IsRunning());
208 postinstall_action_ = nullptr;
209 processor_ = nullptr;
210 EXPECT_TRUE(processor_delegate_.processing_stopped_called_ ||
211 processor_delegate_.processing_done_called_);
212 if (processor_delegate_.processing_done_called_) {
213 // Sanity check that the code was set when the processor finishes.
214 EXPECT_TRUE(processor_delegate_.code_set_);
215 }
216 }
217
TEST_F(PostinstallRunnerActionTest,ProcessProgressLineTest)218 TEST_F(PostinstallRunnerActionTest, ProcessProgressLineTest) {
219 PostinstallRunnerAction action(&fake_boot_control_, &fake_hardware_);
220 testing::StrictMock<MockPostinstallRunnerActionDelegate> mock_delegate_;
221 action.set_delegate(&mock_delegate_);
222
223 action.current_partition_ = 1;
224 action.partition_weight_ = {1, 2, 5};
225 action.accumulated_weight_ = 1;
226 action.total_weight_ = 8;
227
228 // 50% of the second action is 2/8 = 0.25 of the total.
229 EXPECT_CALL(mock_delegate_, ProgressUpdate(0.25));
230 action.ProcessProgressLine("global_progress 0.5");
231 testing::Mock::VerifyAndClearExpectations(&mock_delegate_);
232
233 // 1.5 should be read as 100%, to catch rounding error cases like 1.000001.
234 // 100% of the second is 3/8 of the total.
235 EXPECT_CALL(mock_delegate_, ProgressUpdate(0.375));
236 action.ProcessProgressLine("global_progress 1.5");
237 testing::Mock::VerifyAndClearExpectations(&mock_delegate_);
238
239 // None of these should trigger a progress update.
240 action.ProcessProgressLine("foo_bar");
241 action.ProcessProgressLine("global_progress");
242 action.ProcessProgressLine("global_progress ");
243 action.ProcessProgressLine("global_progress NaN");
244 action.ProcessProgressLine("global_progress Exception in ... :)");
245 }
246
247 // Test that postinstall succeeds in the simple case of running the default
248 // /postinst command which only exits 0.
TEST_F(PostinstallRunnerActionTest,RunAsRootSimpleTest)249 TEST_F(PostinstallRunnerActionTest, RunAsRootSimpleTest) {
250 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
251
252 RunPostinstallAction(loop.dev(), kPostinstallDefaultScript, false, false);
253 EXPECT_EQ(ErrorCode::kSuccess, processor_delegate_.code_);
254 EXPECT_TRUE(processor_delegate_.processing_done_called_);
255
256 // Since powerwash_required was false, this should not trigger a powerwash.
257 EXPECT_FALSE(fake_hardware_.IsPowerwashScheduled());
258 EXPECT_FALSE(fake_hardware_.GetIsRollbackPowerwashScheduled());
259 }
260
TEST_F(PostinstallRunnerActionTest,RunAsRootRunSymlinkFileTest)261 TEST_F(PostinstallRunnerActionTest, RunAsRootRunSymlinkFileTest) {
262 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
263 RunPostinstallAction(loop.dev(), "bin/postinst_link", false, false);
264 EXPECT_EQ(ErrorCode::kSuccess, processor_delegate_.code_);
265 }
266
TEST_F(PostinstallRunnerActionTest,RunAsRootPowerwashRequiredTest)267 TEST_F(PostinstallRunnerActionTest, RunAsRootPowerwashRequiredTest) {
268 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
269 // Run a simple postinstall program but requiring a powerwash.
270 RunPostinstallAction(loop.dev(),
271 "bin/postinst_example",
272 /*powerwash_required=*/true,
273 false);
274 EXPECT_EQ(ErrorCode::kSuccess, processor_delegate_.code_);
275
276 // Check that powerwash was scheduled.
277 EXPECT_TRUE(fake_hardware_.IsPowerwashScheduled());
278 EXPECT_FALSE(fake_hardware_.GetIsRollbackPowerwashScheduled());
279 }
280
TEST_F(PostinstallRunnerActionTest,RunAsRootRollbackTest)281 TEST_F(PostinstallRunnerActionTest, RunAsRootRollbackTest) {
282 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
283
284 // Run a simple postinstall program, rollback happened.
285 RunPostinstallAction(loop.dev(),
286 "bin/postinst_example",
287 false,
288 /*is_rollback=*/true);
289 EXPECT_EQ(ErrorCode::kSuccess, processor_delegate_.code_);
290
291 // Check that powerwash was scheduled and that it's a rollback powerwash.
292 EXPECT_TRUE(fake_hardware_.IsPowerwashScheduled());
293 EXPECT_TRUE(fake_hardware_.GetIsRollbackPowerwashScheduled());
294 }
295
296 // Runs postinstall from a partition file that doesn't mount, so it should
297 // fail.
TEST_F(PostinstallRunnerActionTest,RunAsRootCantMountTest)298 TEST_F(PostinstallRunnerActionTest, RunAsRootCantMountTest) {
299 RunPostinstallAction("/dev/null", kPostinstallDefaultScript, false, false);
300 EXPECT_EQ(ErrorCode::kPostinstallRunnerError, processor_delegate_.code_);
301
302 // In case of failure, Postinstall should not signal a powerwash even if it
303 // was requested.
304 EXPECT_FALSE(fake_hardware_.IsPowerwashScheduled());
305 EXPECT_FALSE(fake_hardware_.GetIsRollbackPowerwashScheduled());
306 }
307
308 // Check that the failures from the postinstall script cause the action to
309 // fail.
TEST_F(PostinstallRunnerActionTest,RunAsRootErrScriptTest)310 TEST_F(PostinstallRunnerActionTest, RunAsRootErrScriptTest) {
311 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
312 RunPostinstallAction(loop.dev(), "bin/postinst_fail1", false, false);
313 EXPECT_EQ(ErrorCode::kPostinstallRunnerError, processor_delegate_.code_);
314 }
315
316 // The exit code 3 and 4 are a specials cases that would be reported back to
317 // UMA with a different error code. Test those cases are properly detected.
TEST_F(PostinstallRunnerActionTest,RunAsRootFirmwareBErrScriptTest)318 TEST_F(PostinstallRunnerActionTest, RunAsRootFirmwareBErrScriptTest) {
319 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
320 RunPostinstallAction(loop.dev(), "bin/postinst_fail3", false, false);
321 EXPECT_EQ(ErrorCode::kPostinstallBootedFromFirmwareB,
322 processor_delegate_.code_);
323 }
324
325 // Check that you can't specify an absolute path.
TEST_F(PostinstallRunnerActionTest,RunAsRootAbsolutePathNotAllowedTest)326 TEST_F(PostinstallRunnerActionTest, RunAsRootAbsolutePathNotAllowedTest) {
327 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
328 RunPostinstallAction(loop.dev(), "/etc/../bin/sh", false, false);
329 EXPECT_EQ(ErrorCode::kPostinstallRunnerError, processor_delegate_.code_);
330 }
331
332 #ifdef __ANDROID__
333 // Check that the postinstall file is relabeled to the postinstall label.
334 // SElinux labels are only set on Android.
TEST_F(PostinstallRunnerActionTest,RunAsRootCheckFileContextsTest)335 TEST_F(PostinstallRunnerActionTest, RunAsRootCheckFileContextsTest) {
336 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
337 RunPostinstallAction(loop.dev(), "bin/self_check_context", false, false);
338 EXPECT_EQ(ErrorCode::kSuccess, processor_delegate_.code_);
339 }
340 #endif // __ANDROID__
341
342 // Check that you can suspend/resume postinstall actions.
TEST_F(PostinstallRunnerActionTest,RunAsRootSuspendResumeActionTest)343 TEST_F(PostinstallRunnerActionTest, RunAsRootSuspendResumeActionTest) {
344 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
345
346 // We need to wait for the child to run and setup its signal handler.
347 loop_.PostTask(FROM_HERE,
348 base::Bind(&PostinstallRunnerActionTest::SuspendRunningAction,
349 base::Unretained(this)));
350 RunPostinstallAction(loop.dev(), "bin/postinst_suspend", false, false);
351 // postinst_suspend returns 0 only if it was suspended at some point.
352 EXPECT_EQ(ErrorCode::kSuccess, processor_delegate_.code_);
353 EXPECT_TRUE(processor_delegate_.processing_done_called_);
354 }
355
356 // Test that we can cancel a postinstall action while it is running.
TEST_F(PostinstallRunnerActionTest,RunAsRootCancelPostinstallActionTest)357 TEST_F(PostinstallRunnerActionTest, RunAsRootCancelPostinstallActionTest) {
358 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
359
360 // Wait for the action to start and then cancel it.
361 CancelWhenStarted();
362 RunPostinstallAction(loop.dev(), "bin/postinst_suspend", false, false);
363 // When canceling the action, the action never finished and therefore we had
364 // a ProcessingStopped call instead.
365 EXPECT_FALSE(processor_delegate_.code_set_);
366 EXPECT_TRUE(processor_delegate_.processing_stopped_called_);
367 }
368
369 // Test that we parse and process the progress reports from the progress
370 // file descriptor.
TEST_F(PostinstallRunnerActionTest,RunAsRootProgressUpdatesTest)371 TEST_F(PostinstallRunnerActionTest, RunAsRootProgressUpdatesTest) {
372 testing::StrictMock<MockPostinstallRunnerActionDelegate> mock_delegate_;
373 testing::InSequence s;
374 EXPECT_CALL(mock_delegate_, ProgressUpdate(0));
375
376 // The postinst_progress program will call with 0.25, 0.5 and 1.
377 EXPECT_CALL(mock_delegate_, ProgressUpdate(0.25));
378 EXPECT_CALL(mock_delegate_, ProgressUpdate(0.5));
379 EXPECT_CALL(mock_delegate_, ProgressUpdate(1.));
380
381 EXPECT_CALL(mock_delegate_, ProgressUpdate(1.));
382
383 ScopedLoopbackDeviceBinder loop(postinstall_image_, false, nullptr);
384 setup_action_delegate_ = &mock_delegate_;
385 RunPostinstallAction(loop.dev(), "bin/postinst_progress", false, false);
386 EXPECT_EQ(ErrorCode::kSuccess, processor_delegate_.code_);
387 }
388
389 } // namespace chromeos_update_engine
390