postinstall_runner_action.cc 13 KB

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