jeremy | 76a2676 | 2014-11-17 12:09:33 | [diff] [blame] | 1 | // Copyright 2014 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "content/browser/power_usage_monitor_impl.h" |
| 6 | |
avi | b734894 | 2015-12-25 20:57:10 | [diff] [blame] | 7 | #include <stddef.h> |
dcheng | 36b6aec9 | 2015-12-26 06:16:36 | [diff] [blame] | 8 | #include <utility> |
avi | b734894 | 2015-12-25 20:57:10 | [diff] [blame] | 9 | |
jeremy | 76a2676 | 2014-11-17 12:09:33 | [diff] [blame] | 10 | #include "base/bind.h" |
| 11 | #include "base/lazy_instance.h" |
| 12 | #include "base/logging.h" |
| 13 | #include "base/macros.h" |
| 14 | #include "base/metrics/histogram.h" |
| 15 | #include "base/strings/stringprintf.h" |
| 16 | #include "base/sys_info.h" |
| 17 | #include "content/public/browser/browser_thread.h" |
| 18 | #include "content/public/browser/notification_service.h" |
| 19 | #include "content/public/browser/notification_source.h" |
| 20 | #include "content/public/browser/notification_types.h" |
| 21 | #include "content/public/browser/power_usage_monitor.h" |
| 22 | #include "content/public/browser/render_process_host.h" |
| 23 | |
| 24 | namespace content { |
| 25 | |
| 26 | namespace { |
| 27 | |
| 28 | // Wait this long after power on before enabling power usage monitoring. |
| 29 | const int kMinUptimeMinutes = 30; |
| 30 | |
| 31 | // Minimum discharge time after which we collect the discharge rate. |
| 32 | const int kMinDischargeMinutes = 30; |
| 33 | |
| 34 | class PowerUsageMonitorSystemInterface |
| 35 | : public PowerUsageMonitor::SystemInterface { |
| 36 | public: |
| 37 | explicit PowerUsageMonitorSystemInterface(PowerUsageMonitor* owner) |
| 38 | : power_usage_monitor_(owner), |
| 39 | weak_ptr_factory_(this) {} |
| 40 | ~PowerUsageMonitorSystemInterface() override {} |
| 41 | |
| 42 | void ScheduleHistogramReport(base::TimeDelta delay) override { |
| 43 | BrowserThread::PostDelayedTask( |
| 44 | BrowserThread::UI, |
| 45 | FROM_HERE, |
| 46 | base::Bind( |
| 47 | &PowerUsageMonitorSystemInterface::ReportBatteryLevelHistogram, |
| 48 | weak_ptr_factory_.GetWeakPtr(), |
| 49 | Now(), |
| 50 | delay), |
| 51 | delay); |
| 52 | } |
| 53 | |
| 54 | void CancelPendingHistogramReports() override { |
| 55 | weak_ptr_factory_.InvalidateWeakPtrs(); |
| 56 | } |
| 57 | |
| 58 | void RecordDischargePercentPerHour(int percent_per_hour) override { |
| 59 | UMA_HISTOGRAM_PERCENTAGE("Power.BatteryDischargePercentPerHour", |
| 60 | percent_per_hour); |
| 61 | } |
| 62 | |
| 63 | base::Time Now() override { return base::Time::Now(); } |
| 64 | |
| 65 | protected: |
| 66 | void ReportBatteryLevelHistogram(base::Time start_time, |
| 67 | base::TimeDelta discharge_time) { |
| 68 | // It's conceivable that the code to cancel pending histogram reports on |
| 69 | // system suspend, will only get called after the system has woken up. |
| 70 | // To mitigage this, check whether more time has passed than expected and |
| 71 | // abort histogram recording in this case. |
| 72 | |
| 73 | // Delayed tasks are subject to timer coalescing and can fire anywhere from |
| 74 | // delay -> delay * 1.5) . In most cases, the OS should fire the task |
| 75 | // at the next wakeup and not as late as it can. |
| 76 | // A threshold of 2 minutes is used, since that should be large enough to |
| 77 | // take the slop factor due to coalescing into account. |
| 78 | base::TimeDelta threshold = discharge_time + |
| 79 | base::TimeDelta::FromMinutes(2); |
| 80 | if ((Now() - start_time) > threshold) { |
| 81 | return; |
| 82 | } |
| 83 | |
| 84 | const std::string histogram_name = base::StringPrintf( |
| 85 | "Power.BatteryDischarge_%d", discharge_time.InMinutes()); |
| 86 | base::HistogramBase* histogram = |
| 87 | base::Histogram::FactoryGet(histogram_name, |
| 88 | 1, |
| 89 | 100, |
| 90 | 101, |
| 91 | base::Histogram::kUmaTargetedHistogramFlag); |
| 92 | double discharge_amount = power_usage_monitor_->discharge_amount(); |
| 93 | histogram->Add(discharge_amount * 100); |
| 94 | } |
| 95 | |
| 96 | private: |
| 97 | PowerUsageMonitor* power_usage_monitor_; // Not owned. |
| 98 | |
| 99 | // Used to cancel in progress delayed tasks. |
| 100 | base::WeakPtrFactory<PowerUsageMonitorSystemInterface> weak_ptr_factory_; |
| 101 | }; |
| 102 | |
| 103 | } // namespace |
| 104 | |
| 105 | void StartPowerUsageMonitor() { |
| 106 | static base::LazyInstance<PowerUsageMonitor>::Leaky monitor = |
| 107 | LAZY_INSTANCE_INITIALIZER; |
| 108 | monitor.Get().Start(); |
| 109 | } |
| 110 | |
| 111 | PowerUsageMonitor::PowerUsageMonitor() |
| 112 | : callback_(base::Bind(&PowerUsageMonitor::OnBatteryStatusUpdate, |
| 113 | base::Unretained(this))), |
| 114 | system_interface_(new PowerUsageMonitorSystemInterface(this)), |
| 115 | started_(false), |
| 116 | tracking_discharge_(false), |
| 117 | on_battery_power_(false), |
| 118 | initial_battery_level_(0), |
| 119 | current_battery_level_(0) { |
| 120 | } |
| 121 | |
| 122 | PowerUsageMonitor::~PowerUsageMonitor() { |
| 123 | if (started_) |
| 124 | base::PowerMonitor::Get()->RemoveObserver(this); |
| 125 | } |
| 126 | |
| 127 | void PowerUsageMonitor::Start() { |
| 128 | // Power monitoring may be delayed based on uptime, but renderer process |
| 129 | // lifetime tracking needs to start immediately so processes created before |
| 130 | // then are accounted for. |
| 131 | registrar_.Add(this, |
| 132 | NOTIFICATION_RENDERER_PROCESS_CREATED, |
| 133 | NotificationService::AllBrowserContextsAndSources()); |
| 134 | registrar_.Add(this, |
| 135 | NOTIFICATION_RENDERER_PROCESS_CLOSED, |
| 136 | NotificationService::AllBrowserContextsAndSources()); |
| 137 | subscription_ = |
| 138 | device::BatteryStatusService::GetInstance()->AddCallback(callback_); |
| 139 | |
| 140 | // Delay initialization until the system has been up for a while. |
| 141 | // This is to mitigate the effect of increased power draw during system start. |
sque | 0f78ba54 | 2015-11-05 00:01:03 | [diff] [blame] | 142 | base::TimeDelta uptime = base::SysInfo::Uptime(); |
jeremy | 76a2676 | 2014-11-17 12:09:33 | [diff] [blame] | 143 | base::TimeDelta min_uptime = base::TimeDelta::FromMinutes(kMinUptimeMinutes); |
| 144 | if (uptime < min_uptime) { |
| 145 | base::TimeDelta delay = min_uptime - uptime; |
| 146 | BrowserThread::PostDelayedTask( |
| 147 | BrowserThread::UI, |
| 148 | FROM_HERE, |
| 149 | base::Bind(&PowerUsageMonitor::StartInternal, base::Unretained(this)), |
| 150 | delay); |
| 151 | } else { |
| 152 | StartInternal(); |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | void PowerUsageMonitor::StartInternal() { |
| 157 | DCHECK(!started_); |
| 158 | started_ = true; |
| 159 | |
| 160 | // PowerMonitor is used to get suspend/resume notifications. |
| 161 | base::PowerMonitor::Get()->AddObserver(this); |
| 162 | } |
| 163 | |
| 164 | void PowerUsageMonitor::DischargeStarted(double battery_level) { |
| 165 | on_battery_power_ = true; |
| 166 | |
| 167 | // If all browser windows are closed, don't report power metrics since |
| 168 | // Chrome's power draw is likely not significant. |
| 169 | if (live_renderer_ids_.empty()) |
| 170 | return; |
| 171 | |
| 172 | // Cancel any in-progress ReportBatteryLevelHistogram() calls. |
| 173 | system_interface_->CancelPendingHistogramReports(); |
| 174 | |
| 175 | tracking_discharge_ = true; |
| 176 | start_discharge_time_ = system_interface_->Now(); |
| 177 | |
| 178 | initial_battery_level_ = battery_level; |
| 179 | current_battery_level_ = battery_level; |
| 180 | |
| 181 | const int kBatteryReportingIntervalMinutes[] = {5, 15, 30}; |
| 182 | for (auto reporting_interval : kBatteryReportingIntervalMinutes) { |
| 183 | base::TimeDelta delay = base::TimeDelta::FromMinutes(reporting_interval); |
| 184 | system_interface_->ScheduleHistogramReport(delay); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | void PowerUsageMonitor::WallPowerConnected(double battery_level) { |
| 189 | on_battery_power_ = false; |
| 190 | |
| 191 | if (tracking_discharge_) { |
| 192 | DCHECK(!start_discharge_time_.is_null()); |
| 193 | base::TimeDelta discharge_time = |
| 194 | system_interface_->Now() - start_discharge_time_; |
| 195 | |
| 196 | if (discharge_time.InMinutes() > kMinDischargeMinutes) { |
| 197 | // Record the rate at which the battery discharged over the entire period |
| 198 | // the system was on battery power. |
| 199 | double discharge_hours = discharge_time.InSecondsF() / 3600.0; |
| 200 | int percent_per_hour = |
| 201 | floor(((discharge_amount() / discharge_hours) * 100.0) + 0.5); |
| 202 | system_interface_->RecordDischargePercentPerHour(percent_per_hour); |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // Cancel any in-progress ReportBatteryLevelHistogram() calls. |
| 207 | system_interface_->CancelPendingHistogramReports(); |
| 208 | |
| 209 | initial_battery_level_ = 0; |
| 210 | current_battery_level_ = 0; |
| 211 | start_discharge_time_ = base::Time(); |
| 212 | tracking_discharge_ = false; |
| 213 | } |
| 214 | |
| 215 | void PowerUsageMonitor::OnBatteryStatusUpdate( |
| 216 | const device::BatteryStatus& status) { |
| 217 | bool now_on_battery_power = (status.charging == 0); |
| 218 | bool was_on_battery_power = on_battery_power_; |
| 219 | double battery_level = status.level; |
| 220 | |
| 221 | if (now_on_battery_power == was_on_battery_power) { |
| 222 | if (now_on_battery_power) |
| 223 | current_battery_level_ = battery_level; |
| 224 | return; |
| 225 | } else if (now_on_battery_power) { // Wall power disconnected. |
| 226 | DischargeStarted(battery_level); |
| 227 | } else { // Wall power connected. |
| 228 | WallPowerConnected(battery_level); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | void PowerUsageMonitor::OnRenderProcessNotification(int type, int rph_id) { |
| 233 | size_t previous_num_live_renderers = live_renderer_ids_.size(); |
| 234 | |
| 235 | if (type == NOTIFICATION_RENDERER_PROCESS_CREATED) { |
| 236 | live_renderer_ids_.insert(rph_id); |
| 237 | } else if (type == NOTIFICATION_RENDERER_PROCESS_CLOSED) { |
| 238 | live_renderer_ids_.erase(rph_id); |
| 239 | } else { |
| 240 | NOTREACHED() << "Unexpected notification type: " << type; |
| 241 | } |
| 242 | |
| 243 | if (live_renderer_ids_.empty() && previous_num_live_renderers != 0) { |
| 244 | // All render processes have died. |
| 245 | CancelPendingHistogramReporting(); |
| 246 | tracking_discharge_ = false; |
| 247 | } |
| 248 | |
| 249 | } |
| 250 | |
| 251 | void PowerUsageMonitor::SetSystemInterfaceForTest( |
dcheng | 5971627 | 2016-04-09 05:19:08 | [diff] [blame] | 252 | std::unique_ptr<SystemInterface> interface) { |
dcheng | 36b6aec9 | 2015-12-26 06:16:36 | [diff] [blame] | 253 | system_interface_ = std::move(interface); |
jeremy | 76a2676 | 2014-11-17 12:09:33 | [diff] [blame] | 254 | } |
| 255 | |
| 256 | void PowerUsageMonitor::OnPowerStateChange(bool on_battery_power) { |
| 257 | } |
| 258 | |
| 259 | void PowerUsageMonitor::OnResume() { |
| 260 | } |
| 261 | |
| 262 | void PowerUsageMonitor::OnSuspend() { |
| 263 | CancelPendingHistogramReporting(); |
| 264 | } |
| 265 | |
| 266 | void PowerUsageMonitor::Observe(int type, |
| 267 | const NotificationSource& source, |
| 268 | const NotificationDetails& details) { |
| 269 | RenderProcessHost* rph = Source<RenderProcessHost>(source).ptr(); |
| 270 | OnRenderProcessNotification(type, rph->GetID()); |
| 271 | } |
| 272 | |
| 273 | void PowerUsageMonitor::CancelPendingHistogramReporting() { |
| 274 | // Cancel any in-progress histogram reports and reporting of discharge UMA. |
| 275 | system_interface_->CancelPendingHistogramReports(); |
| 276 | } |
| 277 | |
| 278 | } // namespace content |