• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2011 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 <fcntl.h>
20 #include <signal.h>
21 #include <stdlib.h>
22 #include <sys/mount.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 
26 #include <cmath>
27 
28 #include <base/files/file_path.h>
29 #include <base/files/file_util.h>
30 #include <base/logging.h>
31 #include <base/strings/string_split.h>
32 #include <base/strings/string_util.h>
33 
34 #include "update_engine/common/action_processor.h"
35 #include "update_engine/common/boot_control_interface.h"
36 #include "update_engine/common/platform_constants.h"
37 #include "update_engine/common/subprocess.h"
38 #include "update_engine/common/utils.h"
39 
40 namespace {
41 
42 // The file descriptor number from the postinstall program's perspective where
43 // it can report status updates. This can be any number greater than 2 (stderr),
44 // but must be kept in sync with the "bin/postinst_progress" defined in the
45 // sample_images.sh file.
46 const int kPostinstallStatusFd = 3;
47 
48 }  // namespace
49 
50 namespace chromeos_update_engine {
51 
52 using brillo::MessageLoop;
53 using std::string;
54 using std::vector;
55 
PerformAction()56 void PostinstallRunnerAction::PerformAction() {
57   CHECK(HasInputObject());
58   install_plan_ = GetInputObject();
59 
60   // Currently we're always powerwashing when rolling back.
61   if (install_plan_.powerwash_required || install_plan_.is_rollback) {
62     if (hardware_->SchedulePowerwash(install_plan_.is_rollback)) {
63       powerwash_scheduled_ = true;
64     } else {
65       return CompletePostinstall(ErrorCode::kPostinstallPowerwashError);
66     }
67   }
68 
69   // Initialize all the partition weights.
70   partition_weight_.resize(install_plan_.partitions.size());
71   total_weight_ = 0;
72   for (size_t i = 0; i < install_plan_.partitions.size(); ++i) {
73     // TODO(deymo): This code sets the weight to all the postinstall commands,
74     // but we could remember how long they took in the past and use those
75     // values.
76     partition_weight_[i] = install_plan_.partitions[i].run_postinstall;
77     total_weight_ += partition_weight_[i];
78   }
79   accumulated_weight_ = 0;
80   ReportProgress(0);
81 
82   PerformPartitionPostinstall();
83 }
84 
PerformPartitionPostinstall()85 void PostinstallRunnerAction::PerformPartitionPostinstall() {
86   if (!install_plan_.run_post_install) {
87     LOG(INFO) << "Skipping post-install according to install plan.";
88     return CompletePostinstall(ErrorCode::kSuccess);
89   }
90 
91   if (install_plan_.download_url.empty()) {
92     LOG(INFO) << "Skipping post-install during rollback";
93     return CompletePostinstall(ErrorCode::kSuccess);
94   }
95 
96   // Skip all the partitions that don't have a post-install step.
97   while (current_partition_ < install_plan_.partitions.size() &&
98          !install_plan_.partitions[current_partition_].run_postinstall) {
99     VLOG(1) << "Skipping post-install on partition "
100             << install_plan_.partitions[current_partition_].name;
101     current_partition_++;
102   }
103   if (current_partition_ == install_plan_.partitions.size())
104     return CompletePostinstall(ErrorCode::kSuccess);
105 
106   const InstallPlan::Partition& partition =
107       install_plan_.partitions[current_partition_];
108 
109   const string mountable_device =
110       utils::MakePartitionNameForMount(partition.target_path);
111   if (mountable_device.empty()) {
112     LOG(ERROR) << "Cannot make mountable device from " << partition.target_path;
113     return CompletePostinstall(ErrorCode::kPostinstallRunnerError);
114   }
115 
116   // Perform post-install for the current_partition_ partition. At this point we
117   // need to call CompletePartitionPostinstall to complete the operation and
118   // cleanup.
119 #ifdef __ANDROID__
120   fs_mount_dir_ = "/postinstall";
121 #else   // __ANDROID__
122   base::FilePath temp_dir;
123   TEST_AND_RETURN(base::CreateNewTempDirectory("au_postint_mount", &temp_dir));
124   fs_mount_dir_ = temp_dir.value();
125 #endif  // __ANDROID__
126 
127   // Double check that the fs_mount_dir is not busy with a previous mounted
128   // filesystem from a previous crashed postinstall step.
129   if (utils::IsMountpoint(fs_mount_dir_)) {
130     LOG(INFO) << "Found previously mounted filesystem at " << fs_mount_dir_;
131     utils::UnmountFilesystem(fs_mount_dir_);
132   }
133 
134   base::FilePath postinstall_path(partition.postinstall_path);
135   if (postinstall_path.IsAbsolute()) {
136     LOG(ERROR) << "Invalid absolute path passed to postinstall, use a relative"
137                   "path instead: "
138                << partition.postinstall_path;
139     return CompletePostinstall(ErrorCode::kPostinstallRunnerError);
140   }
141 
142   string abs_path =
143       base::FilePath(fs_mount_dir_).Append(postinstall_path).value();
144   if (!base::StartsWith(
145           abs_path, fs_mount_dir_, base::CompareCase::SENSITIVE)) {
146     LOG(ERROR) << "Invalid relative postinstall path: "
147                << partition.postinstall_path;
148     return CompletePostinstall(ErrorCode::kPostinstallRunnerError);
149   }
150 
151 #ifdef __ANDROID__
152   // In Chromium OS, the postinstall step is allowed to write to the block
153   // device on the target image, so we don't mark it as read-only and should
154   // be read-write since we just wrote to it during the update.
155 
156   // Mark the block device as read-only before mounting for post-install.
157   if (!utils::SetBlockDeviceReadOnly(mountable_device, true)) {
158     return CompletePartitionPostinstall(
159         1, "Error marking the device " + mountable_device + " read only.");
160   }
161 #endif  // __ANDROID__
162 
163   if (!utils::MountFilesystem(mountable_device,
164                               fs_mount_dir_,
165                               MS_RDONLY,
166                               partition.filesystem_type,
167                               constants::kPostinstallMountOptions)) {
168     return CompletePartitionPostinstall(
169         1, "Error mounting the device " + mountable_device);
170   }
171 
172   LOG(INFO) << "Performing postinst (" << partition.postinstall_path << " at "
173             << abs_path << ") installed on device " << partition.target_path
174             << " and mountable device " << mountable_device;
175 
176   // Logs the file format of the postinstall script we are about to run. This
177   // will help debug when the postinstall script doesn't match the architecture
178   // of our build.
179   LOG(INFO) << "Format file for new " << partition.postinstall_path
180             << " is: " << utils::GetFileFormat(abs_path);
181 
182   // Runs the postinstall script asynchronously to free up the main loop while
183   // it's running.
184   vector<string> command = {abs_path};
185 #ifdef __ANDROID__
186   // In Brillo and Android, we pass the slot number and status fd.
187   command.push_back(std::to_string(install_plan_.target_slot));
188   command.push_back(std::to_string(kPostinstallStatusFd));
189 #else
190   // Chrome OS postinstall expects the target rootfs as the first parameter.
191   command.push_back(partition.target_path);
192 #endif  // __ANDROID__
193 
194   current_command_ = Subprocess::Get().ExecFlags(
195       command,
196       Subprocess::kRedirectStderrToStdout,
197       {kPostinstallStatusFd},
198       base::Bind(&PostinstallRunnerAction::CompletePartitionPostinstall,
199                  base::Unretained(this)));
200   // Subprocess::Exec should never return a negative process id.
201   CHECK_GE(current_command_, 0);
202 
203   if (!current_command_) {
204     CompletePartitionPostinstall(1, "Postinstall didn't launch");
205     return;
206   }
207 
208   // Monitor the status file descriptor.
209   progress_fd_ =
210       Subprocess::Get().GetPipeFd(current_command_, kPostinstallStatusFd);
211   int fd_flags = fcntl(progress_fd_, F_GETFL, 0) | O_NONBLOCK;
212   if (HANDLE_EINTR(fcntl(progress_fd_, F_SETFL, fd_flags)) < 0) {
213     PLOG(ERROR) << "Unable to set non-blocking I/O mode on fd " << progress_fd_;
214   }
215 
216   progress_task_ = MessageLoop::current()->WatchFileDescriptor(
217       FROM_HERE,
218       progress_fd_,
219       MessageLoop::WatchMode::kWatchRead,
220       true,
221       base::Bind(&PostinstallRunnerAction::OnProgressFdReady,
222                  base::Unretained(this)));
223 }
224 
OnProgressFdReady()225 void PostinstallRunnerAction::OnProgressFdReady() {
226   char buf[1024];
227   size_t bytes_read;
228   do {
229     bytes_read = 0;
230     bool eof;
231     bool ok =
232         utils::ReadAll(progress_fd_, buf, arraysize(buf), &bytes_read, &eof);
233     progress_buffer_.append(buf, bytes_read);
234     // Process every line.
235     vector<string> lines = base::SplitString(
236         progress_buffer_, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
237     if (!lines.empty()) {
238       progress_buffer_ = lines.back();
239       lines.pop_back();
240       for (const auto& line : lines) {
241         ProcessProgressLine(line);
242       }
243     }
244     if (!ok || eof) {
245       // There was either an error or an EOF condition, so we are done watching
246       // the file descriptor.
247       MessageLoop::current()->CancelTask(progress_task_);
248       progress_task_ = MessageLoop::kTaskIdNull;
249       return;
250     }
251   } while (bytes_read);
252 }
253 
ProcessProgressLine(const string & line)254 bool PostinstallRunnerAction::ProcessProgressLine(const string& line) {
255   double frac = 0;
256   if (sscanf(line.c_str(), "global_progress %lf", &frac) == 1 &&
257       !std::isnan(frac)) {
258     ReportProgress(frac);
259     return true;
260   }
261 
262   return false;
263 }
264 
ReportProgress(double frac)265 void PostinstallRunnerAction::ReportProgress(double frac) {
266   if (!delegate_)
267     return;
268   if (current_partition_ >= partition_weight_.size() || total_weight_ == 0) {
269     delegate_->ProgressUpdate(1.);
270     return;
271   }
272   if (!std::isfinite(frac) || frac < 0)
273     frac = 0;
274   if (frac > 1)
275     frac = 1;
276   double postinst_action_progress =
277       (accumulated_weight_ + partition_weight_[current_partition_] * frac) /
278       total_weight_;
279   delegate_->ProgressUpdate(postinst_action_progress);
280 }
281 
Cleanup()282 void PostinstallRunnerAction::Cleanup() {
283   utils::UnmountFilesystem(fs_mount_dir_);
284 #ifndef __ANDROID__
285   if (!base::DeleteFile(base::FilePath(fs_mount_dir_), false)) {
286     PLOG(WARNING) << "Not removing temporary mountpoint " << fs_mount_dir_;
287   }
288 #endif  // !__ANDROID__
289   fs_mount_dir_.clear();
290 
291   progress_fd_ = -1;
292   if (progress_task_ != MessageLoop::kTaskIdNull) {
293     MessageLoop::current()->CancelTask(progress_task_);
294     progress_task_ = MessageLoop::kTaskIdNull;
295   }
296   progress_buffer_.clear();
297 }
298 
CompletePartitionPostinstall(int return_code,const string & output)299 void PostinstallRunnerAction::CompletePartitionPostinstall(
300     int return_code, const string& output) {
301   current_command_ = 0;
302   Cleanup();
303 
304   if (return_code != 0) {
305     LOG(ERROR) << "Postinst command failed with code: " << return_code;
306     ErrorCode error_code = ErrorCode::kPostinstallRunnerError;
307 
308     if (return_code == 3) {
309       // This special return code means that we tried to update firmware,
310       // but couldn't because we booted from FW B, and we need to reboot
311       // to get back to FW A.
312       error_code = ErrorCode::kPostinstallBootedFromFirmwareB;
313     }
314 
315     if (return_code == 4) {
316       // This special return code means that we tried to update firmware,
317       // but couldn't because we booted from FW B, and we need to reboot
318       // to get back to FW A.
319       error_code = ErrorCode::kPostinstallFirmwareRONotUpdatable;
320     }
321 
322     // If postinstall script for this partition is optional we can ignore the
323     // result.
324     if (install_plan_.partitions[current_partition_].postinstall_optional) {
325       LOG(INFO) << "Ignoring postinstall failure since it is optional";
326     } else {
327       return CompletePostinstall(error_code);
328     }
329   }
330   accumulated_weight_ += partition_weight_[current_partition_];
331   current_partition_++;
332   ReportProgress(0);
333 
334   PerformPartitionPostinstall();
335 }
336 
CompletePostinstall(ErrorCode error_code)337 void PostinstallRunnerAction::CompletePostinstall(ErrorCode error_code) {
338   // We only attempt to mark the new slot as active if all the postinstall
339   // steps succeeded.
340   if (error_code == ErrorCode::kSuccess) {
341     if (install_plan_.switch_slot_on_reboot) {
342       if (!boot_control_->SetActiveBootSlot(install_plan_.target_slot)) {
343         error_code = ErrorCode::kPostinstallRunnerError;
344       }
345     } else {
346       error_code = ErrorCode::kUpdatedButNotActive;
347     }
348   }
349 
350   ScopedActionCompleter completer(processor_, this);
351   completer.set_code(error_code);
352 
353   if (error_code != ErrorCode::kSuccess &&
354       error_code != ErrorCode::kUpdatedButNotActive) {
355     LOG(ERROR) << "Postinstall action failed.";
356 
357     // Undo any changes done to trigger Powerwash.
358     if (powerwash_scheduled_)
359       hardware_->CancelPowerwash();
360 
361     return;
362   }
363 
364   LOG(INFO) << "All post-install commands succeeded";
365   if (HasOutputPipe()) {
366     SetOutputObject(install_plan_);
367   }
368 }
369 
SuspendAction()370 void PostinstallRunnerAction::SuspendAction() {
371   if (!current_command_)
372     return;
373   if (kill(current_command_, SIGSTOP) != 0) {
374     PLOG(ERROR) << "Couldn't pause child process " << current_command_;
375   } else {
376     is_current_command_suspended_ = true;
377   }
378 }
379 
ResumeAction()380 void PostinstallRunnerAction::ResumeAction() {
381   if (!current_command_)
382     return;
383   if (kill(current_command_, SIGCONT) != 0) {
384     PLOG(ERROR) << "Couldn't resume child process " << current_command_;
385   } else {
386     is_current_command_suspended_ = false;
387   }
388 }
389 
TerminateProcessing()390 void PostinstallRunnerAction::TerminateProcessing() {
391   if (!current_command_)
392     return;
393   // Calling KillExec() will discard the callback we registered and therefore
394   // the unretained reference to this object.
395   Subprocess::Get().KillExec(current_command_);
396 
397   // If the command has been suspended, resume it after KillExec() so that the
398   // process can process the SIGTERM sent by KillExec().
399   if (is_current_command_suspended_) {
400     ResumeAction();
401   }
402 
403   current_command_ = 0;
404   Cleanup();
405 }
406 
407 }  // namespace chromeos_update_engine
408