update_attempter.cc 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  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. #include "update_engine/update_attempter.h"
  17. #include <stdint.h>
  18. #include <algorithm>
  19. #include <memory>
  20. #include <string>
  21. #include <utility>
  22. #include <vector>
  23. #include <base/bind.h>
  24. #include <base/files/file_util.h>
  25. #include <base/logging.h>
  26. #include <base/rand_util.h>
  27. #include <base/strings/string_util.h>
  28. #include <base/strings/stringprintf.h>
  29. #include <base/time/time.h>
  30. #include <brillo/data_encoding.h>
  31. #include <brillo/errors/error_codes.h>
  32. #include <brillo/message_loops/message_loop.h>
  33. #include <policy/device_policy.h>
  34. #include <policy/libpolicy.h>
  35. #include <update_engine/dbus-constants.h>
  36. #include "update_engine/certificate_checker.h"
  37. #include "update_engine/common/boot_control_interface.h"
  38. #include "update_engine/common/clock_interface.h"
  39. #include "update_engine/common/constants.h"
  40. #include "update_engine/common/dlcservice_interface.h"
  41. #include "update_engine/common/hardware_interface.h"
  42. #include "update_engine/common/platform_constants.h"
  43. #include "update_engine/common/prefs_interface.h"
  44. #include "update_engine/common/subprocess.h"
  45. #include "update_engine/common/utils.h"
  46. #include "update_engine/libcurl_http_fetcher.h"
  47. #include "update_engine/metrics_reporter_interface.h"
  48. #include "update_engine/omaha_request_action.h"
  49. #include "update_engine/omaha_request_params.h"
  50. #include "update_engine/omaha_response_handler_action.h"
  51. #include "update_engine/p2p_manager.h"
  52. #include "update_engine/payload_consumer/download_action.h"
  53. #include "update_engine/payload_consumer/filesystem_verifier_action.h"
  54. #include "update_engine/payload_consumer/postinstall_runner_action.h"
  55. #include "update_engine/payload_state_interface.h"
  56. #include "update_engine/power_manager_interface.h"
  57. #include "update_engine/system_state.h"
  58. #include "update_engine/update_boot_flags_action.h"
  59. #include "update_engine/update_manager/policy.h"
  60. #include "update_engine/update_manager/policy_utils.h"
  61. #include "update_engine/update_manager/update_manager.h"
  62. #include "update_engine/update_status_utils.h"
  63. using base::Bind;
  64. using base::Callback;
  65. using base::Time;
  66. using base::TimeDelta;
  67. using base::TimeTicks;
  68. using brillo::MessageLoop;
  69. using chromeos_update_manager::CalculateStagingCase;
  70. using chromeos_update_manager::EvalStatus;
  71. using chromeos_update_manager::Policy;
  72. using chromeos_update_manager::StagingCase;
  73. using chromeos_update_manager::UpdateCheckParams;
  74. using std::string;
  75. using std::vector;
  76. using update_engine::UpdateAttemptFlags;
  77. using update_engine::UpdateEngineStatus;
  78. namespace chromeos_update_engine {
  79. const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
  80. namespace {
  81. const int kMaxConsecutiveObeyProxyRequests = 20;
  82. // Minimum threshold to broadcast an status update in progress and time.
  83. const double kBroadcastThresholdProgress = 0.01; // 1%
  84. const int kBroadcastThresholdSeconds = 10;
  85. // By default autest bypasses scattering. If we want to test scattering,
  86. // use kScheduledAUTestURLRequest. The URL used is same in both cases, but
  87. // different params are passed to CheckForUpdate().
  88. const char kAUTestURLRequest[] = "autest";
  89. const char kScheduledAUTestURLRequest[] = "autest-scheduled";
  90. } // namespace
  91. ErrorCode GetErrorCodeForAction(AbstractAction* action, ErrorCode code) {
  92. if (code != ErrorCode::kError)
  93. return code;
  94. const string type = action->Type();
  95. if (type == OmahaRequestAction::StaticType())
  96. return ErrorCode::kOmahaRequestError;
  97. if (type == OmahaResponseHandlerAction::StaticType())
  98. return ErrorCode::kOmahaResponseHandlerError;
  99. if (type == FilesystemVerifierAction::StaticType())
  100. return ErrorCode::kFilesystemVerifierError;
  101. if (type == PostinstallRunnerAction::StaticType())
  102. return ErrorCode::kPostinstallRunnerError;
  103. return code;
  104. }
  105. UpdateAttempter::UpdateAttempter(SystemState* system_state,
  106. CertificateChecker* cert_checker)
  107. : processor_(new ActionProcessor()),
  108. system_state_(system_state),
  109. cert_checker_(cert_checker),
  110. is_install_(false) {}
  111. UpdateAttempter::~UpdateAttempter() {
  112. // CertificateChecker might not be initialized in unittests.
  113. if (cert_checker_)
  114. cert_checker_->SetObserver(nullptr);
  115. // Release ourselves as the ActionProcessor's delegate to prevent
  116. // re-scheduling the updates due to the processing stopped.
  117. processor_->set_delegate(nullptr);
  118. }
  119. void UpdateAttempter::Init() {
  120. // Pulling from the SystemState can only be done after construction, since
  121. // this is an aggregate of various objects (such as the UpdateAttempter),
  122. // which requires them all to be constructed prior to it being used.
  123. prefs_ = system_state_->prefs();
  124. omaha_request_params_ = system_state_->request_params();
  125. if (cert_checker_)
  126. cert_checker_->SetObserver(this);
  127. // In case of update_engine restart without a reboot we need to restore the
  128. // reboot needed state.
  129. if (GetBootTimeAtUpdate(nullptr))
  130. status_ = UpdateStatus::UPDATED_NEED_REBOOT;
  131. else
  132. status_ = UpdateStatus::IDLE;
  133. }
  134. bool UpdateAttempter::ScheduleUpdates() {
  135. if (IsUpdateRunningOrScheduled())
  136. return false;
  137. chromeos_update_manager::UpdateManager* const update_manager =
  138. system_state_->update_manager();
  139. CHECK(update_manager);
  140. Callback<void(EvalStatus, const UpdateCheckParams&)> callback =
  141. Bind(&UpdateAttempter::OnUpdateScheduled, base::Unretained(this));
  142. // We limit the async policy request to a reasonably short time, to avoid a
  143. // starvation due to a transient bug.
  144. update_manager->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed);
  145. waiting_for_scheduled_check_ = true;
  146. return true;
  147. }
  148. void UpdateAttempter::CertificateChecked(ServerToCheck server_to_check,
  149. CertificateCheckResult result) {
  150. system_state_->metrics_reporter()->ReportCertificateCheckMetrics(
  151. server_to_check, result);
  152. }
  153. bool UpdateAttempter::CheckAndReportDailyMetrics() {
  154. int64_t stored_value;
  155. Time now = system_state_->clock()->GetWallclockTime();
  156. if (system_state_->prefs()->Exists(kPrefsDailyMetricsLastReportedAt) &&
  157. system_state_->prefs()->GetInt64(kPrefsDailyMetricsLastReportedAt,
  158. &stored_value)) {
  159. Time last_reported_at = Time::FromInternalValue(stored_value);
  160. TimeDelta time_reported_since = now - last_reported_at;
  161. if (time_reported_since.InSeconds() < 0) {
  162. LOG(WARNING) << "Last reported daily metrics "
  163. << utils::FormatTimeDelta(time_reported_since) << " ago "
  164. << "which is negative. Either the system clock is wrong or "
  165. << "the kPrefsDailyMetricsLastReportedAt state variable "
  166. << "is wrong.";
  167. // In this case, report daily metrics to reset.
  168. } else {
  169. if (time_reported_since.InSeconds() < 24 * 60 * 60) {
  170. LOG(INFO) << "Last reported daily metrics "
  171. << utils::FormatTimeDelta(time_reported_since) << " ago.";
  172. return false;
  173. }
  174. LOG(INFO) << "Last reported daily metrics "
  175. << utils::FormatTimeDelta(time_reported_since) << " ago, "
  176. << "which is more than 24 hours ago.";
  177. }
  178. }
  179. LOG(INFO) << "Reporting daily metrics.";
  180. system_state_->prefs()->SetInt64(kPrefsDailyMetricsLastReportedAt,
  181. now.ToInternalValue());
  182. ReportOSAge();
  183. return true;
  184. }
  185. void UpdateAttempter::ReportOSAge() {
  186. struct stat sb;
  187. if (system_state_ == nullptr)
  188. return;
  189. if (stat("/etc/lsb-release", &sb) != 0) {
  190. PLOG(ERROR) << "Error getting file status for /etc/lsb-release "
  191. << "(Note: this may happen in some unit tests)";
  192. return;
  193. }
  194. Time lsb_release_timestamp = Time::FromTimeSpec(sb.st_ctim);
  195. Time now = system_state_->clock()->GetWallclockTime();
  196. TimeDelta age = now - lsb_release_timestamp;
  197. if (age.InSeconds() < 0) {
  198. LOG(ERROR) << "The OS age (" << utils::FormatTimeDelta(age)
  199. << ") is negative. Maybe the clock is wrong? "
  200. << "(Note: this may happen in some unit tests.)";
  201. return;
  202. }
  203. system_state_->metrics_reporter()->ReportDailyMetrics(age);
  204. }
  205. void UpdateAttempter::Update(const string& app_version,
  206. const string& omaha_url,
  207. const string& target_channel,
  208. const string& target_version_prefix,
  209. bool rollback_allowed,
  210. bool obey_proxies,
  211. bool interactive) {
  212. // This is normally called frequently enough so it's appropriate to use as a
  213. // hook for reporting daily metrics.
  214. // TODO(garnold) This should be hooked to a separate (reliable and consistent)
  215. // timeout event.
  216. CheckAndReportDailyMetrics();
  217. fake_update_success_ = false;
  218. if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
  219. // Although we have applied an update, we still want to ping Omaha
  220. // to ensure the number of active statistics is accurate.
  221. //
  222. // Also convey to the UpdateEngine.Check.Result metric that we're
  223. // not performing an update check because of this.
  224. LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
  225. << "reboot, we'll ping Omaha instead";
  226. system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
  227. system_state_,
  228. metrics::CheckResult::kRebootPending,
  229. metrics::CheckReaction::kUnset,
  230. metrics::DownloadErrorCode::kUnset);
  231. PingOmaha();
  232. return;
  233. }
  234. if (status_ != UpdateStatus::IDLE) {
  235. // Update in progress. Do nothing
  236. return;
  237. }
  238. if (!CalculateUpdateParams(app_version,
  239. omaha_url,
  240. target_channel,
  241. target_version_prefix,
  242. rollback_allowed,
  243. obey_proxies,
  244. interactive)) {
  245. return;
  246. }
  247. BuildUpdateActions(interactive);
  248. SetStatusAndNotify(UpdateStatus::CHECKING_FOR_UPDATE);
  249. // Update the last check time here; it may be re-updated when an Omaha
  250. // response is received, but this will prevent us from repeatedly scheduling
  251. // checks in the case where a response is not received.
  252. UpdateLastCheckedTime();
  253. ScheduleProcessingStart();
  254. }
  255. void UpdateAttempter::RefreshDevicePolicy() {
  256. // Lazy initialize the policy provider, or reload the latest policy data.
  257. if (!policy_provider_.get())
  258. policy_provider_.reset(new policy::PolicyProvider());
  259. policy_provider_->Reload();
  260. const policy::DevicePolicy* device_policy = nullptr;
  261. if (policy_provider_->device_policy_is_loaded())
  262. device_policy = &policy_provider_->GetDevicePolicy();
  263. if (device_policy)
  264. LOG(INFO) << "Device policies/settings present";
  265. else
  266. LOG(INFO) << "No device policies/settings present.";
  267. system_state_->set_device_policy(device_policy);
  268. system_state_->p2p_manager()->SetDevicePolicy(device_policy);
  269. }
  270. void UpdateAttempter::CalculateP2PParams(bool interactive) {
  271. bool use_p2p_for_downloading = false;
  272. bool use_p2p_for_sharing = false;
  273. // Never use p2p for downloading in interactive checks unless the developer
  274. // has opted in for it via a marker file.
  275. //
  276. // (Why would a developer want to opt in? If they are working on the
  277. // update_engine or p2p codebases so they can actually test their code.)
  278. if (system_state_ != nullptr) {
  279. if (!system_state_->p2p_manager()->IsP2PEnabled()) {
  280. LOG(INFO) << "p2p is not enabled - disallowing p2p for both"
  281. << " downloading and sharing.";
  282. } else {
  283. // Allow p2p for sharing, even in interactive checks.
  284. use_p2p_for_sharing = true;
  285. if (!interactive) {
  286. LOG(INFO) << "Non-interactive check - allowing p2p for downloading";
  287. use_p2p_for_downloading = true;
  288. } else {
  289. LOG(INFO) << "Forcibly disabling use of p2p for downloading "
  290. << "since this update attempt is interactive.";
  291. }
  292. }
  293. }
  294. PayloadStateInterface* const payload_state = system_state_->payload_state();
  295. payload_state->SetUsingP2PForDownloading(use_p2p_for_downloading);
  296. payload_state->SetUsingP2PForSharing(use_p2p_for_sharing);
  297. }
  298. bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
  299. const string& omaha_url,
  300. const string& target_channel,
  301. const string& target_version_prefix,
  302. bool rollback_allowed,
  303. bool obey_proxies,
  304. bool interactive) {
  305. http_response_code_ = 0;
  306. PayloadStateInterface* const payload_state = system_state_->payload_state();
  307. // Refresh the policy before computing all the update parameters.
  308. RefreshDevicePolicy();
  309. // Check whether we need to clear the rollback-happened preference after
  310. // policy is available again.
  311. UpdateRollbackHappened();
  312. // Update the target version prefix.
  313. omaha_request_params_->set_target_version_prefix(target_version_prefix);
  314. // Set whether rollback is allowed.
  315. omaha_request_params_->set_rollback_allowed(rollback_allowed);
  316. CalculateStagingParams(interactive);
  317. // If staging_wait_time_ wasn't set, staging is off, use scattering instead.
  318. if (staging_wait_time_.InSeconds() == 0) {
  319. CalculateScatteringParams(interactive);
  320. }
  321. CalculateP2PParams(interactive);
  322. if (payload_state->GetUsingP2PForDownloading() ||
  323. payload_state->GetUsingP2PForSharing()) {
  324. // OK, p2p is to be used - start it and perform housekeeping.
  325. if (!StartP2PAndPerformHousekeeping()) {
  326. // If this fails, disable p2p for this attempt
  327. LOG(INFO) << "Forcibly disabling use of p2p since starting p2p or "
  328. << "performing housekeeping failed.";
  329. payload_state->SetUsingP2PForDownloading(false);
  330. payload_state->SetUsingP2PForSharing(false);
  331. }
  332. }
  333. if (!omaha_request_params_->Init(app_version, omaha_url, interactive)) {
  334. LOG(ERROR) << "Unable to initialize Omaha request params.";
  335. return false;
  336. }
  337. // Set the target channel, if one was provided.
  338. if (target_channel.empty()) {
  339. LOG(INFO) << "No target channel mandated by policy.";
  340. } else {
  341. LOG(INFO) << "Setting target channel as mandated: " << target_channel;
  342. // Pass in false for powerwash_allowed until we add it to the policy
  343. // protobuf.
  344. string error_message;
  345. if (!omaha_request_params_->SetTargetChannel(
  346. target_channel, false, &error_message)) {
  347. LOG(ERROR) << "Setting the channel failed: " << error_message;
  348. }
  349. // Since this is the beginning of a new attempt, update the download
  350. // channel. The download channel won't be updated until the next attempt,
  351. // even if target channel changes meanwhile, so that how we'll know if we
  352. // should cancel the current download attempt if there's such a change in
  353. // target channel.
  354. omaha_request_params_->UpdateDownloadChannel();
  355. }
  356. // Set the DLC module ID list.
  357. omaha_request_params_->set_dlc_module_ids(dlc_module_ids_);
  358. omaha_request_params_->set_is_install(is_install_);
  359. LOG(INFO) << "target_version_prefix = "
  360. << omaha_request_params_->target_version_prefix()
  361. << ", rollback_allowed = "
  362. << omaha_request_params_->rollback_allowed()
  363. << ", scatter_factor_in_seconds = "
  364. << utils::FormatSecs(scatter_factor_.InSeconds());
  365. LOG(INFO) << "Wall Clock Based Wait Enabled = "
  366. << omaha_request_params_->wall_clock_based_wait_enabled()
  367. << ", Update Check Count Wait Enabled = "
  368. << omaha_request_params_->update_check_count_wait_enabled()
  369. << ", Waiting Period = "
  370. << utils::FormatSecs(
  371. omaha_request_params_->waiting_period().InSeconds());
  372. LOG(INFO) << "Use p2p For Downloading = "
  373. << payload_state->GetUsingP2PForDownloading()
  374. << ", Use p2p For Sharing = "
  375. << payload_state->GetUsingP2PForSharing();
  376. obeying_proxies_ = true;
  377. if (obey_proxies || proxy_manual_checks_ == 0) {
  378. LOG(INFO) << "forced to obey proxies";
  379. // If forced to obey proxies, every 20th request will not use proxies
  380. proxy_manual_checks_++;
  381. LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
  382. if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
  383. proxy_manual_checks_ = 0;
  384. obeying_proxies_ = false;
  385. }
  386. } else if (base::RandInt(0, 4) == 0) {
  387. obeying_proxies_ = false;
  388. }
  389. LOG_IF(INFO, !obeying_proxies_)
  390. << "To help ensure updates work, this update check we are ignoring the "
  391. << "proxy settings and using direct connections.";
  392. DisableDeltaUpdateIfNeeded();
  393. return true;
  394. }
  395. void UpdateAttempter::CalculateScatteringParams(bool interactive) {
  396. // Take a copy of the old scatter value before we update it, as
  397. // we need to update the waiting period if this value changes.
  398. TimeDelta old_scatter_factor = scatter_factor_;
  399. const policy::DevicePolicy* device_policy = system_state_->device_policy();
  400. if (device_policy) {
  401. int64_t new_scatter_factor_in_secs = 0;
  402. device_policy->GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
  403. if (new_scatter_factor_in_secs < 0) // sanitize input, just in case.
  404. new_scatter_factor_in_secs = 0;
  405. scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
  406. }
  407. bool is_scatter_enabled = false;
  408. if (scatter_factor_.InSeconds() == 0) {
  409. LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
  410. } else if (interactive) {
  411. LOG(INFO) << "Scattering disabled as this is an interactive update check";
  412. } else if (system_state_->hardware()->IsOOBEEnabled() &&
  413. !system_state_->hardware()->IsOOBEComplete(nullptr)) {
  414. LOG(INFO) << "Scattering disabled since OOBE is enabled but not complete "
  415. "yet";
  416. } else {
  417. is_scatter_enabled = true;
  418. LOG(INFO) << "Scattering is enabled";
  419. }
  420. if (is_scatter_enabled) {
  421. // This means the scattering policy is turned on.
  422. // Now check if we need to update the waiting period. The two cases
  423. // in which we'd need to update the waiting period are:
  424. // 1. First time in process or a scheduled check after a user-initiated one.
  425. // (omaha_request_params_->waiting_period will be zero in this case).
  426. // 2. Admin has changed the scattering policy value.
  427. // (new scattering value will be different from old one in this case).
  428. int64_t wait_period_in_secs = 0;
  429. if (omaha_request_params_->waiting_period().InSeconds() == 0) {
  430. // First case. Check if we have a suitable value to set for
  431. // the waiting period.
  432. if (prefs_->GetInt64(kPrefsWallClockScatteringWaitPeriod,
  433. &wait_period_in_secs) &&
  434. wait_period_in_secs > 0 &&
  435. wait_period_in_secs <= scatter_factor_.InSeconds()) {
  436. // This means:
  437. // 1. There's a persisted value for the waiting period available.
  438. // 2. And that persisted value is still valid.
  439. // So, in this case, we should reuse the persisted value instead of
  440. // generating a new random value to improve the chances of a good
  441. // distribution for scattering.
  442. omaha_request_params_->set_waiting_period(
  443. TimeDelta::FromSeconds(wait_period_in_secs));
  444. LOG(INFO) << "Using persisted wall-clock waiting period: "
  445. << utils::FormatSecs(
  446. omaha_request_params_->waiting_period().InSeconds());
  447. } else {
  448. // This means there's no persisted value for the waiting period
  449. // available or its value is invalid given the new scatter_factor value.
  450. // So, we should go ahead and regenerate a new value for the
  451. // waiting period.
  452. LOG(INFO) << "Persisted value not present or not valid ("
  453. << utils::FormatSecs(wait_period_in_secs)
  454. << ") for wall-clock waiting period.";
  455. GenerateNewWaitingPeriod();
  456. }
  457. } else if (scatter_factor_ != old_scatter_factor) {
  458. // This means there's already a waiting period value, but we detected
  459. // a change in the scattering policy value. So, we should regenerate the
  460. // waiting period to make sure it's within the bounds of the new scatter
  461. // factor value.
  462. GenerateNewWaitingPeriod();
  463. } else {
  464. // Neither the first time scattering is enabled nor the scattering value
  465. // changed. Nothing to do.
  466. LOG(INFO) << "Keeping current wall-clock waiting period: "
  467. << utils::FormatSecs(
  468. omaha_request_params_->waiting_period().InSeconds());
  469. }
  470. // The invariant at this point is that omaha_request_params_->waiting_period
  471. // is non-zero no matter which path we took above.
  472. LOG_IF(ERROR, omaha_request_params_->waiting_period().InSeconds() == 0)
  473. << "Waiting Period should NOT be zero at this point!!!";
  474. // Since scattering is enabled, wall clock based wait will always be
  475. // enabled.
  476. omaha_request_params_->set_wall_clock_based_wait_enabled(true);
  477. // If we don't have any issues in accessing the file system to update
  478. // the update check count value, we'll turn that on as well.
  479. bool decrement_succeeded = DecrementUpdateCheckCount();
  480. omaha_request_params_->set_update_check_count_wait_enabled(
  481. decrement_succeeded);
  482. } else {
  483. // This means the scattering feature is turned off or disabled for
  484. // this particular update check. Make sure to disable
  485. // all the knobs and artifacts so that we don't invoke any scattering
  486. // related code.
  487. omaha_request_params_->set_wall_clock_based_wait_enabled(false);
  488. omaha_request_params_->set_update_check_count_wait_enabled(false);
  489. omaha_request_params_->set_waiting_period(TimeDelta::FromSeconds(0));
  490. prefs_->Delete(kPrefsWallClockScatteringWaitPeriod);
  491. prefs_->Delete(kPrefsUpdateCheckCount);
  492. // Don't delete the UpdateFirstSeenAt file as we don't want manual checks
  493. // that result in no-updates (e.g. due to server side throttling) to
  494. // cause update starvation by having the client generate a new
  495. // UpdateFirstSeenAt for each scheduled check that follows a manual check.
  496. }
  497. }
  498. void UpdateAttempter::GenerateNewWaitingPeriod() {
  499. omaha_request_params_->set_waiting_period(
  500. TimeDelta::FromSeconds(base::RandInt(1, scatter_factor_.InSeconds())));
  501. LOG(INFO) << "Generated new wall-clock waiting period: "
  502. << utils::FormatSecs(
  503. omaha_request_params_->waiting_period().InSeconds());
  504. // Do a best-effort to persist this in all cases. Even if the persistence
  505. // fails, we'll still be able to scatter based on our in-memory value.
  506. // The persistence only helps in ensuring a good overall distribution
  507. // across multiple devices if they tend to reboot too often.
  508. system_state_->payload_state()->SetScatteringWaitPeriod(
  509. omaha_request_params_->waiting_period());
  510. }
  511. void UpdateAttempter::CalculateStagingParams(bool interactive) {
  512. bool oobe_complete = system_state_->hardware()->IsOOBEEnabled() &&
  513. system_state_->hardware()->IsOOBEComplete(nullptr);
  514. auto device_policy = system_state_->device_policy();
  515. StagingCase staging_case = StagingCase::kOff;
  516. if (device_policy && !interactive && oobe_complete) {
  517. staging_wait_time_ = omaha_request_params_->waiting_period();
  518. staging_case = CalculateStagingCase(
  519. device_policy, prefs_, &staging_wait_time_, &staging_schedule_);
  520. }
  521. switch (staging_case) {
  522. case StagingCase::kOff:
  523. // Staging is off, get rid of persisted value.
  524. prefs_->Delete(kPrefsWallClockStagingWaitPeriod);
  525. // Set |staging_wait_time_| to its default value so scattering can still
  526. // be turned on
  527. staging_wait_time_ = TimeDelta();
  528. break;
  529. // Let the cases fall through since they just add, and never remove, steps
  530. // to turning staging on.
  531. case StagingCase::kNoSavedValue:
  532. prefs_->SetInt64(kPrefsWallClockStagingWaitPeriod,
  533. staging_wait_time_.InDays());
  534. case StagingCase::kSetStagingFromPref:
  535. omaha_request_params_->set_waiting_period(staging_wait_time_);
  536. case StagingCase::kNoAction:
  537. // Staging is on, enable wallclock based wait so that its values get used.
  538. omaha_request_params_->set_wall_clock_based_wait_enabled(true);
  539. // Use UpdateCheckCount if possible to prevent devices updating all at
  540. // once.
  541. omaha_request_params_->set_update_check_count_wait_enabled(
  542. DecrementUpdateCheckCount());
  543. // Scattering should not be turned on if staging is on, delete the
  544. // existing scattering configuration.
  545. prefs_->Delete(kPrefsWallClockScatteringWaitPeriod);
  546. scatter_factor_ = TimeDelta();
  547. }
  548. }
  549. void UpdateAttempter::BuildUpdateActions(bool interactive) {
  550. CHECK(!processor_->IsRunning());
  551. processor_->set_delegate(this);
  552. // Actions:
  553. auto update_check_fetcher = std::make_unique<LibcurlHttpFetcher>(
  554. GetProxyResolver(), system_state_->hardware());
  555. update_check_fetcher->set_server_to_check(ServerToCheck::kUpdate);
  556. // Try harder to connect to the network, esp when not interactive.
  557. // See comment in libcurl_http_fetcher.cc.
  558. update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
  559. auto update_check_action = std::make_unique<OmahaRequestAction>(
  560. system_state_, nullptr, std::move(update_check_fetcher), false);
  561. auto response_handler_action =
  562. std::make_unique<OmahaResponseHandlerAction>(system_state_);
  563. auto update_boot_flags_action =
  564. std::make_unique<UpdateBootFlagsAction>(system_state_->boot_control());
  565. auto download_started_action = std::make_unique<OmahaRequestAction>(
  566. system_state_,
  567. new OmahaEvent(OmahaEvent::kTypeUpdateDownloadStarted),
  568. std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
  569. system_state_->hardware()),
  570. false);
  571. LibcurlHttpFetcher* download_fetcher =
  572. new LibcurlHttpFetcher(GetProxyResolver(), system_state_->hardware());
  573. download_fetcher->set_server_to_check(ServerToCheck::kDownload);
  574. if (interactive)
  575. download_fetcher->set_max_retry_count(kDownloadMaxRetryCountInteractive);
  576. auto download_action =
  577. std::make_unique<DownloadAction>(prefs_,
  578. system_state_->boot_control(),
  579. system_state_->hardware(),
  580. system_state_,
  581. download_fetcher, // passes ownership
  582. interactive);
  583. download_action->set_delegate(this);
  584. auto download_finished_action = std::make_unique<OmahaRequestAction>(
  585. system_state_,
  586. new OmahaEvent(OmahaEvent::kTypeUpdateDownloadFinished),
  587. std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
  588. system_state_->hardware()),
  589. false);
  590. auto filesystem_verifier_action =
  591. std::make_unique<FilesystemVerifierAction>();
  592. auto update_complete_action = std::make_unique<OmahaRequestAction>(
  593. system_state_,
  594. new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
  595. std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
  596. system_state_->hardware()),
  597. false);
  598. auto postinstall_runner_action = std::make_unique<PostinstallRunnerAction>(
  599. system_state_->boot_control(), system_state_->hardware());
  600. postinstall_runner_action->set_delegate(this);
  601. // Bond them together. We have to use the leaf-types when calling
  602. // BondActions().
  603. BondActions(update_check_action.get(), response_handler_action.get());
  604. BondActions(response_handler_action.get(), download_action.get());
  605. BondActions(download_action.get(), filesystem_verifier_action.get());
  606. BondActions(filesystem_verifier_action.get(),
  607. postinstall_runner_action.get());
  608. processor_->EnqueueAction(std::move(update_check_action));
  609. processor_->EnqueueAction(std::move(response_handler_action));
  610. processor_->EnqueueAction(std::move(update_boot_flags_action));
  611. processor_->EnqueueAction(std::move(download_started_action));
  612. processor_->EnqueueAction(std::move(download_action));
  613. processor_->EnqueueAction(std::move(download_finished_action));
  614. processor_->EnqueueAction(std::move(filesystem_verifier_action));
  615. processor_->EnqueueAction(std::move(postinstall_runner_action));
  616. processor_->EnqueueAction(std::move(update_complete_action));
  617. }
  618. bool UpdateAttempter::Rollback(bool powerwash) {
  619. is_install_ = false;
  620. if (!CanRollback()) {
  621. return false;
  622. }
  623. // Extra check for enterprise-enrolled devices since they don't support
  624. // powerwash.
  625. if (powerwash) {
  626. // Enterprise-enrolled devices have an empty owner in their device policy.
  627. string owner;
  628. RefreshDevicePolicy();
  629. const policy::DevicePolicy* device_policy = system_state_->device_policy();
  630. if (device_policy && (!device_policy->GetOwner(&owner) || owner.empty())) {
  631. LOG(ERROR) << "Enterprise device detected. "
  632. << "Cannot perform a powerwash for enterprise devices.";
  633. return false;
  634. }
  635. }
  636. processor_->set_delegate(this);
  637. // Initialize the default request params.
  638. if (!omaha_request_params_->Init("", "", true)) {
  639. LOG(ERROR) << "Unable to initialize Omaha request params.";
  640. return false;
  641. }
  642. LOG(INFO) << "Setting rollback options.";
  643. install_plan_.reset(new InstallPlan());
  644. install_plan_->target_slot = GetRollbackSlot();
  645. install_plan_->source_slot = system_state_->boot_control()->GetCurrentSlot();
  646. TEST_AND_RETURN_FALSE(
  647. install_plan_->LoadPartitionsFromSlots(system_state_->boot_control()));
  648. install_plan_->powerwash_required = powerwash;
  649. LOG(INFO) << "Using this install plan:";
  650. install_plan_->Dump();
  651. auto install_plan_action =
  652. std::make_unique<InstallPlanAction>(*install_plan_);
  653. auto postinstall_runner_action = std::make_unique<PostinstallRunnerAction>(
  654. system_state_->boot_control(), system_state_->hardware());
  655. postinstall_runner_action->set_delegate(this);
  656. BondActions(install_plan_action.get(), postinstall_runner_action.get());
  657. processor_->EnqueueAction(std::move(install_plan_action));
  658. processor_->EnqueueAction(std::move(postinstall_runner_action));
  659. // Update the payload state for Rollback.
  660. system_state_->payload_state()->Rollback();
  661. SetStatusAndNotify(UpdateStatus::ATTEMPTING_ROLLBACK);
  662. ScheduleProcessingStart();
  663. return true;
  664. }
  665. bool UpdateAttempter::CanRollback() const {
  666. // We can only rollback if the update_engine isn't busy and we have a valid
  667. // rollback partition.
  668. return (status_ == UpdateStatus::IDLE &&
  669. GetRollbackSlot() != BootControlInterface::kInvalidSlot);
  670. }
  671. BootControlInterface::Slot UpdateAttempter::GetRollbackSlot() const {
  672. LOG(INFO) << "UpdateAttempter::GetRollbackSlot";
  673. const unsigned int num_slots = system_state_->boot_control()->GetNumSlots();
  674. const BootControlInterface::Slot current_slot =
  675. system_state_->boot_control()->GetCurrentSlot();
  676. LOG(INFO) << " Installed slots: " << num_slots;
  677. LOG(INFO) << " Booted from slot: "
  678. << BootControlInterface::SlotName(current_slot);
  679. if (current_slot == BootControlInterface::kInvalidSlot || num_slots < 2) {
  680. LOG(INFO) << "Device is not updateable.";
  681. return BootControlInterface::kInvalidSlot;
  682. }
  683. vector<BootControlInterface::Slot> bootable_slots;
  684. for (BootControlInterface::Slot slot = 0; slot < num_slots; slot++) {
  685. if (slot != current_slot &&
  686. system_state_->boot_control()->IsSlotBootable(slot)) {
  687. LOG(INFO) << "Found bootable slot "
  688. << BootControlInterface::SlotName(slot);
  689. return slot;
  690. }
  691. }
  692. LOG(INFO) << "No other bootable slot found.";
  693. return BootControlInterface::kInvalidSlot;
  694. }
  695. bool UpdateAttempter::CheckForUpdate(const string& app_version,
  696. const string& omaha_url,
  697. UpdateAttemptFlags flags) {
  698. dlc_module_ids_.clear();
  699. is_install_ = false;
  700. bool interactive = !(flags & UpdateAttemptFlags::kFlagNonInteractive);
  701. if (interactive && status_ != UpdateStatus::IDLE) {
  702. // An update check is either in-progress, or an update has completed and the
  703. // system is in UPDATED_NEED_REBOOT. Either way, don't do an interactive
  704. // update at this time
  705. LOG(INFO) << "Refusing to do an interactive update with an update already "
  706. "in progress";
  707. return false;
  708. }
  709. LOG(INFO) << "Forced update check requested.";
  710. forced_app_version_.clear();
  711. forced_omaha_url_.clear();
  712. // Certain conditions must be met to allow setting custom version and update
  713. // server URLs. However, kScheduledAUTestURLRequest and kAUTestURLRequest are
  714. // always allowed regardless of device state.
  715. if (IsAnyUpdateSourceAllowed()) {
  716. forced_app_version_ = app_version;
  717. forced_omaha_url_ = omaha_url;
  718. }
  719. if (omaha_url == kScheduledAUTestURLRequest) {
  720. forced_omaha_url_ = constants::kOmahaDefaultAUTestURL;
  721. // Pretend that it's not user-initiated even though it is,
  722. // so as to test scattering logic, etc. which get kicked off
  723. // only in scheduled update checks.
  724. interactive = false;
  725. } else if (omaha_url == kAUTestURLRequest) {
  726. forced_omaha_url_ = constants::kOmahaDefaultAUTestURL;
  727. }
  728. if (interactive) {
  729. // Use the passed-in update attempt flags for this update attempt instead
  730. // of the previously set ones.
  731. current_update_attempt_flags_ = flags;
  732. // Note: The caching for non-interactive update checks happens in
  733. // OnUpdateScheduled().
  734. }
  735. if (forced_update_pending_callback_.get()) {
  736. if (!system_state_->dlcservice()->GetInstalled(&dlc_module_ids_)) {
  737. dlc_module_ids_.clear();
  738. }
  739. // Make sure that a scheduling request is made prior to calling the forced
  740. // update pending callback.
  741. ScheduleUpdates();
  742. forced_update_pending_callback_->Run(true, interactive);
  743. }
  744. return true;
  745. }
  746. bool UpdateAttempter::CheckForInstall(const vector<string>& dlc_module_ids,
  747. const string& omaha_url) {
  748. dlc_module_ids_ = dlc_module_ids;
  749. is_install_ = true;
  750. forced_omaha_url_.clear();
  751. // Certain conditions must be met to allow setting custom version and update
  752. // server URLs. However, kScheduledAUTestURLRequest and kAUTestURLRequest are
  753. // always allowed regardless of device state.
  754. if (IsAnyUpdateSourceAllowed()) {
  755. forced_omaha_url_ = omaha_url;
  756. }
  757. if (omaha_url == kScheduledAUTestURLRequest) {
  758. forced_omaha_url_ = constants::kOmahaDefaultAUTestURL;
  759. } else if (omaha_url == kAUTestURLRequest) {
  760. forced_omaha_url_ = constants::kOmahaDefaultAUTestURL;
  761. }
  762. if (!ScheduleUpdates()) {
  763. if (forced_update_pending_callback_.get()) {
  764. // Make sure that a scheduling request is made prior to calling the forced
  765. // update pending callback.
  766. ScheduleUpdates();
  767. forced_update_pending_callback_->Run(true, true);
  768. return true;
  769. }
  770. return false;
  771. }
  772. return true;
  773. }
  774. bool UpdateAttempter::RebootIfNeeded() {
  775. #ifdef __ANDROID__
  776. if (status_ != UpdateStatus::UPDATED_NEED_REBOOT) {
  777. LOG(INFO) << "Reboot requested, but status is "
  778. << UpdateStatusToString(status_) << ", so not rebooting.";
  779. return false;
  780. }
  781. #endif // __ANDROID__
  782. if (system_state_->power_manager()->RequestReboot())
  783. return true;
  784. return RebootDirectly();
  785. }
  786. void UpdateAttempter::WriteUpdateCompletedMarker() {
  787. string boot_id;
  788. if (!utils::GetBootId(&boot_id))
  789. return;
  790. prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
  791. int64_t value = system_state_->clock()->GetBootTime().ToInternalValue();
  792. prefs_->SetInt64(kPrefsUpdateCompletedBootTime, value);
  793. }
  794. bool UpdateAttempter::RebootDirectly() {
  795. vector<string> command;
  796. command.push_back("/sbin/shutdown");
  797. command.push_back("-r");
  798. command.push_back("now");
  799. LOG(INFO) << "Running \"" << base::JoinString(command, " ") << "\"";
  800. int rc = 0;
  801. Subprocess::SynchronousExec(command, &rc, nullptr);
  802. return rc == 0;
  803. }
  804. void UpdateAttempter::OnUpdateScheduled(EvalStatus status,
  805. const UpdateCheckParams& params) {
  806. waiting_for_scheduled_check_ = false;
  807. if (status == EvalStatus::kSucceeded) {
  808. if (!params.updates_enabled) {
  809. LOG(WARNING) << "Updates permanently disabled.";
  810. // Signal disabled status, then switch right back to idle. This is
  811. // necessary for ensuring that observers waiting for a signal change will
  812. // actually notice one on subsequent calls. Note that we don't need to
  813. // re-schedule a check in this case as updates are permanently disabled;
  814. // further (forced) checks may still initiate a scheduling call.
  815. SetStatusAndNotify(UpdateStatus::DISABLED);
  816. SetStatusAndNotify(UpdateStatus::IDLE);
  817. return;
  818. }
  819. LOG(INFO) << "Running " << (params.interactive ? "interactive" : "periodic")
  820. << " update.";
  821. if (!params.interactive) {
  822. // Cache the update attempt flags that will be used by this update attempt
  823. // so that they can't be changed mid-way through.
  824. current_update_attempt_flags_ = update_attempt_flags_;
  825. }
  826. LOG(INFO) << "Update attempt flags in use = 0x" << std::hex
  827. << current_update_attempt_flags_;
  828. Update(forced_app_version_,
  829. forced_omaha_url_,
  830. params.target_channel,
  831. params.target_version_prefix,
  832. params.rollback_allowed,
  833. /*obey_proxies=*/false,
  834. params.interactive);
  835. // Always clear the forced app_version and omaha_url after an update attempt
  836. // so the next update uses the defaults.
  837. forced_app_version_.clear();
  838. forced_omaha_url_.clear();
  839. } else {
  840. LOG(WARNING)
  841. << "Update check scheduling failed (possibly timed out); retrying.";
  842. ScheduleUpdates();
  843. }
  844. // This check ensures that future update checks will be or are already
  845. // scheduled. The check should never fail. A check failure means that there's
  846. // a bug that will most likely prevent further automatic update checks. It
  847. // seems better to crash in such cases and restart the update_engine daemon
  848. // into, hopefully, a known good state.
  849. CHECK(IsUpdateRunningOrScheduled());
  850. }
  851. void UpdateAttempter::UpdateLastCheckedTime() {
  852. last_checked_time_ = system_state_->clock()->GetWallclockTime().ToTimeT();
  853. }
  854. void UpdateAttempter::UpdateRollbackHappened() {
  855. DCHECK(system_state_);
  856. DCHECK(system_state_->payload_state());
  857. DCHECK(policy_provider_);
  858. if (system_state_->payload_state()->GetRollbackHappened() &&
  859. (policy_provider_->device_policy_is_loaded() ||
  860. policy_provider_->IsConsumerDevice())) {
  861. // Rollback happened, but we already went through OOBE and policy is
  862. // present or it's a consumer device.
  863. system_state_->payload_state()->SetRollbackHappened(false);
  864. }
  865. }
  866. // Delegate methods:
  867. void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
  868. ErrorCode code) {
  869. LOG(INFO) << "Processing Done.";
  870. // Reset cpu shares back to normal.
  871. cpu_limiter_.StopLimiter();
  872. // reset the state that's only valid for a single update pass
  873. current_update_attempt_flags_ = UpdateAttemptFlags::kNone;
  874. if (forced_update_pending_callback_.get())
  875. // Clear prior interactive requests once the processor is done.
  876. forced_update_pending_callback_->Run(false, false);
  877. if (status_ == UpdateStatus::REPORTING_ERROR_EVENT) {
  878. LOG(INFO) << "Error event sent.";
  879. // Inform scheduler of new status;
  880. SetStatusAndNotify(UpdateStatus::IDLE);
  881. ScheduleUpdates();
  882. if (!fake_update_success_) {
  883. return;
  884. }
  885. LOG(INFO) << "Booted from FW B and tried to install new firmware, "
  886. "so requesting reboot from user.";
  887. }
  888. attempt_error_code_ = utils::GetBaseErrorCode(code);
  889. if (code == ErrorCode::kSuccess) {
  890. // For install operation, we do not mark update complete since we do not
  891. // need reboot.
  892. if (!is_install_)
  893. WriteUpdateCompletedMarker();
  894. ReportTimeToUpdateAppliedMetric();
  895. prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
  896. prefs_->SetString(kPrefsPreviousVersion,
  897. omaha_request_params_->app_version());
  898. DeltaPerformer::ResetUpdateProgress(prefs_, false);
  899. system_state_->payload_state()->UpdateSucceeded();
  900. // Since we're done with scattering fully at this point, this is the
  901. // safest point delete the state files, as we're sure that the status is
  902. // set to reboot (which means no more updates will be applied until reboot)
  903. // This deletion is required for correctness as we want the next update
  904. // check to re-create a new random number for the update check count.
  905. // Similarly, we also delete the wall-clock-wait period that was persisted
  906. // so that we start with a new random value for the next update check
  907. // after reboot so that the same device is not favored or punished in any
  908. // way.
  909. prefs_->Delete(kPrefsUpdateCheckCount);
  910. system_state_->payload_state()->SetScatteringWaitPeriod(TimeDelta());
  911. system_state_->payload_state()->SetStagingWaitPeriod(TimeDelta());
  912. prefs_->Delete(kPrefsUpdateFirstSeenAt);
  913. if (is_install_) {
  914. LOG(INFO) << "DLC successfully installed, no reboot needed.";
  915. SetStatusAndNotify(UpdateStatus::IDLE);
  916. ScheduleUpdates();
  917. return;
  918. }
  919. SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
  920. ScheduleUpdates();
  921. LOG(INFO) << "Update successfully applied, waiting to reboot.";
  922. // |install_plan_| is null during rollback operations, and the stats don't
  923. // make much sense then anyway.
  924. if (install_plan_) {
  925. // Generate an unique payload identifier.
  926. string target_version_uid;
  927. for (const auto& payload : install_plan_->payloads) {
  928. target_version_uid +=
  929. brillo::data_encoding::Base64Encode(payload.hash) + ":" +
  930. payload.metadata_signature + ":";
  931. }
  932. // If we just downloaded a rollback image, we should preserve this fact
  933. // over the following powerwash.
  934. if (install_plan_->is_rollback) {
  935. system_state_->payload_state()->SetRollbackHappened(true);
  936. system_state_->metrics_reporter()->ReportEnterpriseRollbackMetrics(
  937. /*success=*/true, install_plan_->version);
  938. }
  939. // Expect to reboot into the new version to send the proper metric during
  940. // next boot.
  941. system_state_->payload_state()->ExpectRebootInNewVersion(
  942. target_version_uid);
  943. } else {
  944. // If we just finished a rollback, then we expect to have no Omaha
  945. // response. Otherwise, it's an error.
  946. if (system_state_->payload_state()->GetRollbackVersion().empty()) {
  947. LOG(ERROR) << "Can't send metrics because there was no Omaha response";
  948. }
  949. }
  950. return;
  951. }
  952. if (ScheduleErrorEventAction()) {
  953. return;
  954. }
  955. LOG(INFO) << "No update.";
  956. SetStatusAndNotify(UpdateStatus::IDLE);
  957. ScheduleUpdates();
  958. }
  959. void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
  960. // Reset cpu shares back to normal.
  961. cpu_limiter_.StopLimiter();
  962. download_progress_ = 0.0;
  963. if (forced_update_pending_callback_.get())
  964. // Clear prior interactive requests once the processor is done.
  965. forced_update_pending_callback_->Run(false, false);
  966. SetStatusAndNotify(UpdateStatus::IDLE);
  967. ScheduleUpdates();
  968. error_event_.reset(nullptr);
  969. }
  970. // Called whenever an action has finished processing, either successfully
  971. // or otherwise.
  972. void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
  973. AbstractAction* action,
  974. ErrorCode code) {
  975. // Reset download progress regardless of whether or not the download
  976. // action succeeded. Also, get the response code from HTTP request
  977. // actions (update download as well as the initial update check
  978. // actions).
  979. const string type = action->Type();
  980. if (type == DownloadAction::StaticType()) {
  981. download_progress_ = 0.0;
  982. DownloadAction* download_action = static_cast<DownloadAction*>(action);
  983. http_response_code_ = download_action->GetHTTPResponseCode();
  984. } else if (type == OmahaRequestAction::StaticType()) {
  985. OmahaRequestAction* omaha_request_action =
  986. static_cast<OmahaRequestAction*>(action);
  987. // If the request is not an event, then it's the update-check.
  988. if (!omaha_request_action->IsEvent()) {
  989. http_response_code_ = omaha_request_action->GetHTTPResponseCode();
  990. // Record the number of consecutive failed update checks.
  991. if (http_response_code_ == kHttpResponseInternalServerError ||
  992. http_response_code_ == kHttpResponseServiceUnavailable) {
  993. consecutive_failed_update_checks_++;
  994. } else {
  995. consecutive_failed_update_checks_ = 0;
  996. }
  997. const OmahaResponse& omaha_response =
  998. omaha_request_action->GetOutputObject();
  999. // Store the server-dictated poll interval, if any.
  1000. server_dictated_poll_interval_ =
  1001. std::max(0, omaha_response.poll_interval);
  1002. // This update is ignored by omaha request action because update over
  1003. // cellular connection is not allowed. Needs to ask for user's permissions
  1004. // to update.
  1005. if (code == ErrorCode::kOmahaUpdateIgnoredOverCellular) {
  1006. new_version_ = omaha_response.version;
  1007. new_payload_size_ = 0;
  1008. for (const auto& package : omaha_response.packages) {
  1009. new_payload_size_ += package.size;
  1010. }
  1011. SetStatusAndNotify(UpdateStatus::NEED_PERMISSION_TO_UPDATE);
  1012. }
  1013. }
  1014. } else if (type == OmahaResponseHandlerAction::StaticType()) {
  1015. // Depending on the returned error code, note that an update is available.
  1016. if (code == ErrorCode::kOmahaUpdateDeferredPerPolicy ||
  1017. code == ErrorCode::kSuccess) {
  1018. // Note that the status will be updated to DOWNLOADING when some bytes
  1019. // get actually downloaded from the server and the BytesReceived
  1020. // callback is invoked. This avoids notifying the user that a download
  1021. // has started in cases when the server and the client are unable to
  1022. // initiate the download.
  1023. auto omaha_response_handler_action =
  1024. static_cast<OmahaResponseHandlerAction*>(action);
  1025. install_plan_.reset(
  1026. new InstallPlan(omaha_response_handler_action->install_plan()));
  1027. UpdateLastCheckedTime();
  1028. new_version_ = install_plan_->version;
  1029. new_system_version_ = install_plan_->system_version;
  1030. new_payload_size_ = 0;
  1031. for (const auto& payload : install_plan_->payloads)
  1032. new_payload_size_ += payload.size;
  1033. cpu_limiter_.StartLimiter();
  1034. SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
  1035. }
  1036. }
  1037. // General failure cases.
  1038. if (code != ErrorCode::kSuccess) {
  1039. // If the current state is at or past the download phase, count the failure
  1040. // in case a switch to full update becomes necessary. Ignore network
  1041. // transfer timeouts and failures.
  1042. if (code != ErrorCode::kDownloadTransferError) {
  1043. switch (status_) {
  1044. case UpdateStatus::IDLE:
  1045. case UpdateStatus::CHECKING_FOR_UPDATE:
  1046. case UpdateStatus::UPDATE_AVAILABLE:
  1047. case UpdateStatus::NEED_PERMISSION_TO_UPDATE:
  1048. break;
  1049. case UpdateStatus::DOWNLOADING:
  1050. case UpdateStatus::VERIFYING:
  1051. case UpdateStatus::FINALIZING:
  1052. case UpdateStatus::UPDATED_NEED_REBOOT:
  1053. case UpdateStatus::REPORTING_ERROR_EVENT:
  1054. case UpdateStatus::ATTEMPTING_ROLLBACK:
  1055. case UpdateStatus::DISABLED:
  1056. MarkDeltaUpdateFailure();
  1057. break;
  1058. }
  1059. }
  1060. if (code != ErrorCode::kNoUpdate) {
  1061. // On failure, schedule an error event to be sent to Omaha.
  1062. CreatePendingErrorEvent(action, code);
  1063. }
  1064. return;
  1065. }
  1066. // Find out which action completed (successfully).
  1067. if (type == DownloadAction::StaticType()) {
  1068. SetStatusAndNotify(UpdateStatus::FINALIZING);
  1069. } else if (type == FilesystemVerifierAction::StaticType()) {
  1070. // Log the system properties before the postinst and after the file system
  1071. // is verified. It used to be done in the postinst itself. But postinst
  1072. // cannot do this anymore. On the other hand, these logs are frequently
  1073. // looked at and it is preferable not to scatter them in random location in
  1074. // the log and rather log it right before the postinst. The reason not do
  1075. // this in the |PostinstallRunnerAction| is to prevent dependency from
  1076. // libpayload_consumer to libupdate_engine.
  1077. LogImageProperties();
  1078. }
  1079. }
  1080. void UpdateAttempter::BytesReceived(uint64_t bytes_progressed,
  1081. uint64_t bytes_received,
  1082. uint64_t total) {
  1083. // The PayloadState keeps track of how many bytes were actually downloaded
  1084. // from a given URL for the URL skipping logic.
  1085. system_state_->payload_state()->DownloadProgress(bytes_progressed);
  1086. double progress = 0;
  1087. if (total)
  1088. progress = static_cast<double>(bytes_received) / static_cast<double>(total);
  1089. if (status_ != UpdateStatus::DOWNLOADING || bytes_received == total) {
  1090. download_progress_ = progress;
  1091. SetStatusAndNotify(UpdateStatus::DOWNLOADING);
  1092. } else {
  1093. ProgressUpdate(progress);
  1094. }
  1095. }
  1096. void UpdateAttempter::DownloadComplete() {
  1097. system_state_->payload_state()->DownloadComplete();
  1098. }
  1099. void UpdateAttempter::ProgressUpdate(double progress) {
  1100. // Self throttle based on progress. Also send notifications if progress is
  1101. // too slow.
  1102. if (progress == 1.0 ||
  1103. progress - download_progress_ >= kBroadcastThresholdProgress ||
  1104. TimeTicks::Now() - last_notify_time_ >=
  1105. TimeDelta::FromSeconds(kBroadcastThresholdSeconds)) {
  1106. download_progress_ = progress;
  1107. BroadcastStatus();
  1108. }
  1109. }
  1110. bool UpdateAttempter::ResetStatus() {
  1111. LOG(INFO) << "Attempting to reset state from "
  1112. << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
  1113. switch (status_) {
  1114. case UpdateStatus::IDLE:
  1115. // no-op.
  1116. return true;
  1117. case UpdateStatus::UPDATED_NEED_REBOOT: {
  1118. bool ret_value = true;
  1119. status_ = UpdateStatus::IDLE;
  1120. // Remove the reboot marker so that if the machine is rebooted
  1121. // after resetting to idle state, it doesn't go back to
  1122. // UpdateStatus::UPDATED_NEED_REBOOT state.
  1123. ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId) && ret_value;
  1124. ret_value = prefs_->Delete(kPrefsUpdateCompletedBootTime) && ret_value;
  1125. // Update the boot flags so the current slot has higher priority.
  1126. BootControlInterface* boot_control = system_state_->boot_control();
  1127. if (!boot_control->SetActiveBootSlot(boot_control->GetCurrentSlot()))
  1128. ret_value = false;
  1129. // Mark the current slot as successful again, since marking it as active
  1130. // may reset the successful bit. We ignore the result of whether marking
  1131. // the current slot as successful worked.
  1132. if (!boot_control->MarkBootSuccessfulAsync(Bind([](bool successful) {})))
  1133. ret_value = false;
  1134. // Notify the PayloadState that the successful payload was canceled.
  1135. system_state_->payload_state()->ResetUpdateStatus();
  1136. // The previous version is used to report back to omaha after reboot that
  1137. // we actually rebooted into the new version from this "prev-version". We
  1138. // need to clear out this value now to prevent it being sent on the next
  1139. // updatecheck request.
  1140. ret_value = prefs_->SetString(kPrefsPreviousVersion, "") && ret_value;
  1141. LOG(INFO) << "Reset status " << (ret_value ? "successful" : "failed");
  1142. return ret_value;
  1143. }
  1144. default:
  1145. LOG(ERROR) << "Reset not allowed in this state.";
  1146. return false;
  1147. }
  1148. }
  1149. bool UpdateAttempter::GetStatus(UpdateEngineStatus* out_status) {
  1150. out_status->last_checked_time = last_checked_time_;
  1151. out_status->status = status_;
  1152. out_status->current_version = omaha_request_params_->app_version();
  1153. out_status->current_system_version = omaha_request_params_->system_version();
  1154. out_status->progress = download_progress_;
  1155. out_status->new_size_bytes = new_payload_size_;
  1156. out_status->new_version = new_version_;
  1157. out_status->new_system_version = new_system_version_;
  1158. return true;
  1159. }
  1160. void UpdateAttempter::BroadcastStatus() {
  1161. UpdateEngineStatus broadcast_status;
  1162. // Use common method for generating the current status.
  1163. GetStatus(&broadcast_status);
  1164. for (const auto& observer : service_observers_) {
  1165. observer->SendStatusUpdate(broadcast_status);
  1166. }
  1167. last_notify_time_ = TimeTicks::Now();
  1168. }
  1169. uint32_t UpdateAttempter::GetErrorCodeFlags() {
  1170. uint32_t flags = 0;
  1171. if (!system_state_->hardware()->IsNormalBootMode())
  1172. flags |= static_cast<uint32_t>(ErrorCode::kDevModeFlag);
  1173. if (install_plan_ && install_plan_->is_resume)
  1174. flags |= static_cast<uint32_t>(ErrorCode::kResumedFlag);
  1175. if (!system_state_->hardware()->IsOfficialBuild())
  1176. flags |= static_cast<uint32_t>(ErrorCode::kTestImageFlag);
  1177. if (!omaha_request_params_->IsUpdateUrlOfficial()) {
  1178. flags |= static_cast<uint32_t>(ErrorCode::kTestOmahaUrlFlag);
  1179. }
  1180. return flags;
  1181. }
  1182. bool UpdateAttempter::ShouldCancel(ErrorCode* cancel_reason) {
  1183. // Check if the channel we're attempting to update to is the same as the
  1184. // target channel currently chosen by the user.
  1185. OmahaRequestParams* params = system_state_->request_params();
  1186. if (params->download_channel() != params->target_channel()) {
  1187. LOG(ERROR) << "Aborting download as target channel: "
  1188. << params->target_channel()
  1189. << " is different from the download channel: "
  1190. << params->download_channel();
  1191. *cancel_reason = ErrorCode::kUpdateCanceledByChannelChange;
  1192. return true;
  1193. }
  1194. return false;
  1195. }
  1196. void UpdateAttempter::SetStatusAndNotify(UpdateStatus status) {
  1197. status_ = status;
  1198. BroadcastStatus();
  1199. }
  1200. void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
  1201. ErrorCode code) {
  1202. if (error_event_.get() || status_ == UpdateStatus::REPORTING_ERROR_EVENT) {
  1203. // This shouldn't really happen.
  1204. LOG(WARNING) << "There's already an existing pending error event.";
  1205. return;
  1206. }
  1207. // Classify the code to generate the appropriate result so that
  1208. // the Borgmon charts show up the results correctly.
  1209. // Do this before calling GetErrorCodeForAction which could potentially
  1210. // augment the bit representation of code and thus cause no matches for
  1211. // the switch cases below.
  1212. OmahaEvent::Result event_result;
  1213. switch (code) {
  1214. case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
  1215. case ErrorCode::kOmahaUpdateDeferredPerPolicy:
  1216. case ErrorCode::kOmahaUpdateDeferredForBackoff:
  1217. event_result = OmahaEvent::kResultUpdateDeferred;
  1218. break;
  1219. default:
  1220. event_result = OmahaEvent::kResultError;
  1221. break;
  1222. }
  1223. code = GetErrorCodeForAction(action, code);
  1224. fake_update_success_ = code == ErrorCode::kPostinstallBootedFromFirmwareB;
  1225. // Compute the final error code with all the bit flags to be sent to Omaha.
  1226. code =
  1227. static_cast<ErrorCode>(static_cast<uint32_t>(code) | GetErrorCodeFlags());
  1228. error_event_.reset(
  1229. new OmahaEvent(OmahaEvent::kTypeUpdateComplete, event_result, code));
  1230. }
  1231. bool UpdateAttempter::ScheduleErrorEventAction() {
  1232. if (error_event_.get() == nullptr)
  1233. return false;
  1234. LOG(ERROR) << "Update failed.";
  1235. system_state_->payload_state()->UpdateFailed(error_event_->error_code);
  1236. // Send metrics if it was a rollback.
  1237. if (install_plan_ && install_plan_->is_rollback) {
  1238. system_state_->metrics_reporter()->ReportEnterpriseRollbackMetrics(
  1239. /*success=*/false, install_plan_->version);
  1240. }
  1241. // Send it to Omaha.
  1242. LOG(INFO) << "Reporting the error event";
  1243. auto error_event_action = std::make_unique<OmahaRequestAction>(
  1244. system_state_,
  1245. error_event_.release(), // Pass ownership.
  1246. std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
  1247. system_state_->hardware()),
  1248. false);
  1249. processor_->EnqueueAction(std::move(error_event_action));
  1250. SetStatusAndNotify(UpdateStatus::REPORTING_ERROR_EVENT);
  1251. processor_->StartProcessing();
  1252. return true;
  1253. }
  1254. void UpdateAttempter::ScheduleProcessingStart() {
  1255. LOG(INFO) << "Scheduling an action processor start.";
  1256. MessageLoop::current()->PostTask(
  1257. FROM_HERE,
  1258. Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
  1259. base::Unretained(processor_.get())));
  1260. }
  1261. void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
  1262. int64_t delta_failures;
  1263. if (omaha_request_params_->delta_okay() &&
  1264. prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
  1265. delta_failures >= kMaxDeltaUpdateFailures) {
  1266. LOG(WARNING) << "Too many delta update failures, forcing full update.";
  1267. omaha_request_params_->set_delta_okay(false);
  1268. }
  1269. }
  1270. void UpdateAttempter::MarkDeltaUpdateFailure() {
  1271. // Don't try to resume a failed delta update.
  1272. DeltaPerformer::ResetUpdateProgress(prefs_, false);
  1273. int64_t delta_failures;
  1274. if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
  1275. delta_failures < 0) {
  1276. delta_failures = 0;
  1277. }
  1278. prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
  1279. }
  1280. void UpdateAttempter::PingOmaha() {
  1281. if (!processor_->IsRunning()) {
  1282. auto ping_action = std::make_unique<OmahaRequestAction>(
  1283. system_state_,
  1284. nullptr,
  1285. std::make_unique<LibcurlHttpFetcher>(GetProxyResolver(),
  1286. system_state_->hardware()),
  1287. true);
  1288. processor_->set_delegate(nullptr);
  1289. processor_->EnqueueAction(std::move(ping_action));
  1290. // Call StartProcessing() synchronously here to avoid any race conditions
  1291. // caused by multiple outstanding ping Omaha requests. If we call
  1292. // StartProcessing() asynchronously, the device can be suspended before we
  1293. // get a chance to callback to StartProcessing(). When the device resumes
  1294. // (assuming the device sleeps longer than the next update check period),
  1295. // StartProcessing() is called back and at the same time, the next update
  1296. // check is fired which eventually invokes StartProcessing(). A crash
  1297. // can occur because StartProcessing() checks to make sure that the
  1298. // processor is idle which it isn't due to the two concurrent ping Omaha
  1299. // requests.
  1300. processor_->StartProcessing();
  1301. } else {
  1302. LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
  1303. }
  1304. // Update the last check time here; it may be re-updated when an Omaha
  1305. // response is received, but this will prevent us from repeatedly scheduling
  1306. // checks in the case where a response is not received.
  1307. UpdateLastCheckedTime();
  1308. // Update the status which will schedule the next update check
  1309. SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
  1310. ScheduleUpdates();
  1311. }
  1312. bool UpdateAttempter::DecrementUpdateCheckCount() {
  1313. int64_t update_check_count_value;
  1314. if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
  1315. // This file does not exist. This means we haven't started our update
  1316. // check count down yet, so nothing more to do. This file will be created
  1317. // later when we first satisfy the wall-clock-based-wait period.
  1318. LOG(INFO) << "No existing update check count. That's normal.";
  1319. return true;
  1320. }
  1321. if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
  1322. // Only if we're able to read a proper integer value, then go ahead
  1323. // and decrement and write back the result in the same file, if needed.
  1324. LOG(INFO) << "Update check count = " << update_check_count_value;
  1325. if (update_check_count_value == 0) {
  1326. // It could be 0, if, for some reason, the file didn't get deleted
  1327. // when we set our status to waiting for reboot. so we just leave it
  1328. // as is so that we can prevent another update_check wait for this client.
  1329. LOG(INFO) << "Not decrementing update check count as it's already 0.";
  1330. return true;
  1331. }
  1332. if (update_check_count_value > 0)
  1333. update_check_count_value--;
  1334. else
  1335. update_check_count_value = 0;
  1336. // Write out the new value of update_check_count_value.
  1337. if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
  1338. // We successfully wrote out the new value, so enable the
  1339. // update check based wait.
  1340. LOG(INFO) << "New update check count = " << update_check_count_value;
  1341. return true;
  1342. }
  1343. }
  1344. LOG(INFO) << "Deleting update check count state due to read/write errors.";
  1345. // We cannot read/write to the file, so disable the update check based wait
  1346. // so that we don't get stuck in this OS version by any chance (which could
  1347. // happen if there's some bug that causes to read/write incorrectly).
  1348. // Also attempt to delete the file to do our best effort to cleanup.
  1349. prefs_->Delete(kPrefsUpdateCheckCount);
  1350. return false;
  1351. }
  1352. void UpdateAttempter::UpdateEngineStarted() {
  1353. // If we just booted into a new update, keep the previous OS version
  1354. // in case we rebooted because of a crash of the old version, so we
  1355. // can do a proper crash report with correct information.
  1356. // This must be done before calling
  1357. // system_state_->payload_state()->UpdateEngineStarted() since it will
  1358. // delete SystemUpdated marker file.
  1359. if (system_state_->system_rebooted() &&
  1360. prefs_->Exists(kPrefsSystemUpdatedMarker)) {
  1361. if (!prefs_->GetString(kPrefsPreviousVersion, &prev_version_)) {
  1362. // If we fail to get the version string, make sure it stays empty.
  1363. prev_version_.clear();
  1364. }
  1365. }
  1366. system_state_->payload_state()->UpdateEngineStarted();
  1367. StartP2PAtStartup();
  1368. }
  1369. bool UpdateAttempter::StartP2PAtStartup() {
  1370. if (system_state_ == nullptr ||
  1371. !system_state_->p2p_manager()->IsP2PEnabled()) {
  1372. LOG(INFO) << "Not starting p2p at startup since it's not enabled.";
  1373. return false;
  1374. }
  1375. if (system_state_->p2p_manager()->CountSharedFiles() < 1) {
  1376. LOG(INFO) << "Not starting p2p at startup since our application "
  1377. << "is not sharing any files.";
  1378. return false;
  1379. }
  1380. return StartP2PAndPerformHousekeeping();
  1381. }
  1382. bool UpdateAttempter::StartP2PAndPerformHousekeeping() {
  1383. if (system_state_ == nullptr)
  1384. return false;
  1385. if (!system_state_->p2p_manager()->IsP2PEnabled()) {
  1386. LOG(INFO) << "Not starting p2p since it's not enabled.";
  1387. return false;
  1388. }
  1389. LOG(INFO) << "Ensuring that p2p is running.";
  1390. if (!system_state_->p2p_manager()->EnsureP2PRunning()) {
  1391. LOG(ERROR) << "Error starting p2p.";
  1392. return false;
  1393. }
  1394. LOG(INFO) << "Performing p2p housekeeping.";
  1395. if (!system_state_->p2p_manager()->PerformHousekeeping()) {
  1396. LOG(ERROR) << "Error performing housekeeping for p2p.";
  1397. return false;
  1398. }
  1399. LOG(INFO) << "Done performing p2p housekeeping.";
  1400. return true;
  1401. }
  1402. bool UpdateAttempter::GetBootTimeAtUpdate(Time* out_boot_time) {
  1403. // In case of an update_engine restart without a reboot, we stored the boot_id
  1404. // when the update was completed by setting a pref, so we can check whether
  1405. // the last update was on this boot or a previous one.
  1406. string boot_id;
  1407. TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
  1408. string update_completed_on_boot_id;
  1409. if (!prefs_->Exists(kPrefsUpdateCompletedOnBootId) ||
  1410. !prefs_->GetString(kPrefsUpdateCompletedOnBootId,
  1411. &update_completed_on_boot_id) ||
  1412. update_completed_on_boot_id != boot_id)
  1413. return false;
  1414. // Short-circuit avoiding the read in case out_boot_time is nullptr.
  1415. if (out_boot_time) {
  1416. int64_t boot_time = 0;
  1417. // Since the kPrefsUpdateCompletedOnBootId was correctly set, this pref
  1418. // should not fail.
  1419. TEST_AND_RETURN_FALSE(
  1420. prefs_->GetInt64(kPrefsUpdateCompletedBootTime, &boot_time));
  1421. *out_boot_time = Time::FromInternalValue(boot_time);
  1422. }
  1423. return true;
  1424. }
  1425. bool UpdateAttempter::IsUpdateRunningOrScheduled() {
  1426. return ((status_ != UpdateStatus::IDLE &&
  1427. status_ != UpdateStatus::UPDATED_NEED_REBOOT) ||
  1428. waiting_for_scheduled_check_);
  1429. }
  1430. bool UpdateAttempter::IsAnyUpdateSourceAllowed() const {
  1431. // We allow updates from any source if either of these are true:
  1432. // * The device is running an unofficial (dev/test) image.
  1433. // * The debugd dev features are accessible (i.e. in devmode with no owner).
  1434. // This protects users running a base image, while still allowing a specific
  1435. // window (gated by the debug dev features) where `cros flash` is usable.
  1436. if (!system_state_->hardware()->IsOfficialBuild()) {
  1437. LOG(INFO) << "Non-official build; allowing any update source.";
  1438. return true;
  1439. }
  1440. if (system_state_->hardware()->AreDevFeaturesEnabled()) {
  1441. LOG(INFO) << "Developer features enabled; allowing custom update sources.";
  1442. return true;
  1443. }
  1444. LOG(INFO)
  1445. << "Developer features disabled; disallowing custom update sources.";
  1446. return false;
  1447. }
  1448. void UpdateAttempter::ReportTimeToUpdateAppliedMetric() {
  1449. const policy::DevicePolicy* device_policy = system_state_->device_policy();
  1450. if (device_policy && device_policy->IsEnterpriseEnrolled()) {
  1451. vector<policy::DevicePolicy::WeeklyTimeInterval> parsed_intervals;
  1452. bool has_time_restrictions =
  1453. device_policy->GetDisallowedTimeIntervals(&parsed_intervals);
  1454. int64_t update_first_seen_at_int;
  1455. if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
  1456. if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
  1457. &update_first_seen_at_int)) {
  1458. TimeDelta update_delay =
  1459. system_state_->clock()->GetWallclockTime() -
  1460. Time::FromInternalValue(update_first_seen_at_int);
  1461. system_state_->metrics_reporter()
  1462. ->ReportEnterpriseUpdateSeenToDownloadDays(has_time_restrictions,
  1463. update_delay.InDays());
  1464. }
  1465. }
  1466. }
  1467. }
  1468. } // namespace chromeos_update_engine