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