1 // Copyright (c) 2012 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.
5 #include "chrome/browser/chromeos/policy/device_status_collector.h"
11 #include <sys/statvfs.h>
13 #include "base/bind.h"
14 #include "base/bind_helpers.h"
15 #include "base/files/file_enumerator.h"
16 #include "base/files/file_util.h"
17 #include "base/format_macros.h"
18 #include "base/location.h"
19 #include "base/logging.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/posix/eintr_wrapper.h"
22 #include "base/prefs/pref_registry_simple.h"
23 #include "base/prefs/pref_service.h"
24 #include "base/prefs/scoped_user_pref_update.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/sys_info.h"
28 #include "base/task_runner_util.h"
29 #include "base/values.h"
30 #include "chrome/browser/browser_process.h"
31 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
32 #include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
33 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
34 #include "chrome/browser/chromeos/policy/device_local_account.h"
35 #include "chrome/browser/chromeos/profiles/profile_helper.h"
36 #include "chrome/browser/chromeos/settings/cros_settings.h"
37 #include "chrome/common/pref_names.h"
38 #include "chromeos/disks/disk_mount_manager.h"
39 #include "chromeos/network/device_state.h"
40 #include "chromeos/network/network_handler.h"
41 #include "chromeos/network/network_state.h"
42 #include "chromeos/network/network_state_handler.h"
43 #include "chromeos/settings/cros_settings_names.h"
44 #include "chromeos/system/statistics_provider.h"
45 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
46 #include "components/user_manager/user.h"
47 #include "components/user_manager/user_manager.h"
48 #include "components/user_manager/user_type.h"
49 #include "components/version_info/version_info.h"
50 #include "content/public/browser/browser_thread.h"
51 #include "extensions/browser/extension_registry.h"
52 #include "extensions/common/extension.h"
53 #include "policy/proto/device_management_backend.pb.h"
54 #include "storage/browser/fileapi/external_mount_points.h"
55 #include "third_party/cros_system_api/dbus/service_constants.h"
58 using base::TimeDelta
;
60 namespace em
= enterprise_management
;
63 // How many seconds of inactivity triggers the idle state.
64 const int kIdleStateThresholdSeconds
= 300;
66 // How many days in the past to store active periods for.
67 const unsigned int kMaxStoredPastActivityDays
= 30;
69 // How many days in the future to store active periods for.
70 const unsigned int kMaxStoredFutureActivityDays
= 2;
72 // How often, in seconds, to update the device location.
73 const unsigned int kGeolocationPollIntervalSeconds
= 30 * 60;
75 // How often, in seconds, to sample the hardware state.
76 static const unsigned int kHardwareStatusSampleIntervalSeconds
= 120;
78 // Keys for the geolocation status dictionary in local state.
79 const char kLatitude
[] = "latitude";
80 const char kLongitude
[] = "longitude";
81 const char kAltitude
[] = "altitude";
82 const char kAccuracy
[] = "accuracy";
83 const char kAltitudeAccuracy
[] = "altitude_accuracy";
84 const char kHeading
[] = "heading";
85 const char kSpeed
[] = "speed";
86 const char kTimestamp
[] = "timestamp";
88 // The location we read our CPU statistics from.
89 const char kProcStat
[] = "/proc/stat";
91 // The location we read our CPU temperature and channel label from.
92 const char kHwmonDir
[] = "/sys/class/hwmon/";
93 const char kDeviceDir
[] = "device";
94 const char kHwmonDirectoryPattern
[] = "hwmon*";
95 const char kCPUTempFilePattern
[] = "temp*_input";
97 // Determine the day key (milliseconds since epoch for corresponding day in UTC)
98 // for a given |timestamp|.
99 int64
TimestampToDayKey(Time timestamp
) {
100 Time::Exploded exploded
;
101 timestamp
.LocalMidnight().LocalExplode(&exploded
);
102 return (Time::FromUTCExploded(exploded
) - Time::UnixEpoch()).InMilliseconds();
105 // Helper function (invoked via blocking pool) to fetch information about
107 std::vector
<em::VolumeInfo
> GetVolumeInfo(
108 const std::vector
<std::string
>& mount_points
) {
109 std::vector
<em::VolumeInfo
> result
;
110 for (const std::string
& mount_point
: mount_points
) {
111 struct statvfs stat
= {}; // Zero-clear
112 if (HANDLE_EINTR(statvfs(mount_point
.c_str(), &stat
)) == 0) {
114 info
.set_volume_id(mount_point
);
115 info
.set_storage_total(static_cast<int64_t>(stat
.f_blocks
) *
117 info
.set_storage_free(static_cast<uint64_t>(stat
.f_bavail
) *
119 result
.push_back(info
);
121 LOG(ERROR
) << "Unable to get volume status for " << mount_point
;
127 // Reads the first CPU line from /proc/stat. Returns an empty string if
128 // the cpu data could not be read.
129 // The format of this line from /proc/stat is:
131 // cpu user_time nice_time system_time idle_time
133 // where user_time, nice_time, system_time, and idle_time are all integer
134 // values measured in jiffies from system startup.
135 std::string
ReadCPUStatistics() {
136 std::string contents
;
137 if (base::ReadFileToString(base::FilePath(kProcStat
), &contents
)) {
138 size_t eol
= contents
.find("\n");
139 if (eol
!= std::string::npos
) {
140 std::string line
= contents
.substr(0, eol
);
141 if (line
.compare(0, 4, "cpu ") == 0)
144 // First line should always start with "cpu ".
145 NOTREACHED() << "Could not parse /proc/stat contents: " << contents
;
147 LOG(WARNING
) << "Unable to read CPU statistics from " << kProcStat
;
148 return std::string();
151 // Reads the CPU temperature info from
152 // /sys/class/hwmon/hwmon*/device/temp*_input and
153 // /sys/class/hwmon/hwmon*/device/temp*_label files.
155 // temp*_input contains CPU temperature in millidegree Celsius
156 // temp*_label contains appropriate temperature channel label.
157 std::vector
<em::CPUTempInfo
> ReadCPUTempInfo() {
158 std::vector
<em::CPUTempInfo
> contents
;
159 // Get directories /sys/class/hwmon/hwmon*
160 base::FileEnumerator
hwmon_enumerator(base::FilePath(kHwmonDir
), false,
161 base::FileEnumerator::DIRECTORIES
,
162 kHwmonDirectoryPattern
);
164 for (base::FilePath hwmon_path
= hwmon_enumerator
.Next(); !hwmon_path
.empty();
165 hwmon_path
= hwmon_enumerator
.Next()) {
166 // Get files /sys/class/hwmon/hwmon*/device/temp*_input
167 const base::FilePath hwmon_device_dir
= hwmon_path
.Append(kDeviceDir
);
168 base::FileEnumerator
enumerator(hwmon_device_dir
, false,
169 base::FileEnumerator::FILES
,
170 kCPUTempFilePattern
);
171 for (base::FilePath temperature_path
= enumerator
.Next();
172 !temperature_path
.empty(); temperature_path
= enumerator
.Next()) {
173 // Get appropriate temp*_label file.
174 std::string label_path
= temperature_path
.MaybeAsASCII();
175 if (label_path
.empty()) {
176 LOG(WARNING
) << "Unable to parse a path to temp*_input file as ASCII";
179 base::ReplaceSubstringsAfterOffset(&label_path
, 0, "input", "label");
183 if (!base::PathExists(base::FilePath(label_path
)) ||
184 !base::ReadFileToString(base::FilePath(label_path
), &label
)) {
185 label
= std::string();
188 // Read temperature in millidegree Celsius.
189 std::string temperature_string
;
190 int32 temperature
= 0;
191 if (base::ReadFileToString(temperature_path
, &temperature_string
) &&
192 sscanf(temperature_string
.c_str(), "%d", &temperature
) == 1) {
193 // CPU temp in millidegree Celsius to Celsius
196 em::CPUTempInfo info
;
197 info
.set_cpu_label(label
);
198 info
.set_cpu_temp(temperature
);
199 contents
.push_back(info
);
201 LOG(WARNING
) << "Unable to read CPU temp from "
202 << temperature_path
.MaybeAsASCII();
209 // Returns the DeviceLocalAccount associated with the current kiosk session.
210 // Returns null if there is no active kiosk session, or if that kiosk
211 // session has been removed from policy since the session started, in which
212 // case we won't report its status).
213 scoped_ptr
<policy::DeviceLocalAccount
>
214 GetCurrentKioskDeviceLocalAccount(chromeos::CrosSettings
* settings
) {
215 if (!user_manager::UserManager::Get()->IsLoggedInAsKioskApp())
216 return scoped_ptr
<policy::DeviceLocalAccount
>();
217 const user_manager::User
* const user
=
218 user_manager::UserManager::Get()->GetActiveUser();
219 const std::string user_id
= user
->GetUserID();
220 const std::vector
<policy::DeviceLocalAccount
> accounts
=
221 policy::GetDeviceLocalAccounts(settings
);
223 for (const auto& device_local_account
: accounts
) {
224 if (device_local_account
.user_id
== user_id
) {
225 return make_scoped_ptr(
226 new policy::DeviceLocalAccount(device_local_account
)).Pass();
229 LOG(WARNING
) << "Kiosk app not found in list of device-local accounts";
230 return scoped_ptr
<policy::DeviceLocalAccount
>();
237 DeviceStatusCollector::DeviceStatusCollector(
238 PrefService
* local_state
,
239 chromeos::system::StatisticsProvider
* provider
,
240 const LocationUpdateRequester
& location_update_requester
,
241 const VolumeInfoFetcher
& volume_info_fetcher
,
242 const CPUStatisticsFetcher
& cpu_statistics_fetcher
,
243 const CPUTempFetcher
& cpu_temp_fetcher
)
244 : max_stored_past_activity_days_(kMaxStoredPastActivityDays
),
245 max_stored_future_activity_days_(kMaxStoredFutureActivityDays
),
246 local_state_(local_state
),
247 last_idle_check_(Time()),
248 last_reported_day_(0),
249 duration_for_last_reported_day_(0),
250 geolocation_update_in_progress_(false),
251 volume_info_fetcher_(volume_info_fetcher
),
252 cpu_statistics_fetcher_(cpu_statistics_fetcher
),
253 cpu_temp_fetcher_(cpu_temp_fetcher
),
254 statistics_provider_(provider
),
257 location_update_requester_(location_update_requester
),
258 report_version_info_(false),
259 report_activity_times_(false),
260 report_boot_mode_(false),
261 report_location_(false),
262 report_network_interfaces_(false),
263 report_users_(false),
264 report_hardware_status_(false),
265 report_session_status_(false),
266 weak_factory_(this) {
267 if (volume_info_fetcher_
.is_null())
268 volume_info_fetcher_
= base::Bind(&GetVolumeInfo
);
270 if (cpu_statistics_fetcher_
.is_null())
271 cpu_statistics_fetcher_
= base::Bind(&ReadCPUStatistics
);
273 if (cpu_temp_fetcher_
.is_null())
274 cpu_temp_fetcher_
= base::Bind(&ReadCPUTempInfo
);
276 idle_poll_timer_
.Start(FROM_HERE
,
277 TimeDelta::FromSeconds(kIdlePollIntervalSeconds
),
278 this, &DeviceStatusCollector::CheckIdleState
);
279 hardware_status_sampling_timer_
.Start(
281 TimeDelta::FromSeconds(kHardwareStatusSampleIntervalSeconds
),
282 this, &DeviceStatusCollector::SampleHardwareStatus
);
284 cros_settings_
= chromeos::CrosSettings::Get();
287 // Watch for changes to the individual policies that control what the status
289 base::Closure callback
=
290 base::Bind(&DeviceStatusCollector::UpdateReportingSettings
,
291 base::Unretained(this));
292 version_info_subscription_
= cros_settings_
->AddSettingsObserver(
293 chromeos::kReportDeviceVersionInfo
, callback
);
294 activity_times_subscription_
= cros_settings_
->AddSettingsObserver(
295 chromeos::kReportDeviceActivityTimes
, callback
);
296 boot_mode_subscription_
= cros_settings_
->AddSettingsObserver(
297 chromeos::kReportDeviceBootMode
, callback
);
298 location_subscription_
= cros_settings_
->AddSettingsObserver(
299 chromeos::kReportDeviceLocation
, callback
);
300 network_interfaces_subscription_
= cros_settings_
->AddSettingsObserver(
301 chromeos::kReportDeviceNetworkInterfaces
, callback
);
302 users_subscription_
= cros_settings_
->AddSettingsObserver(
303 chromeos::kReportDeviceUsers
, callback
);
304 hardware_status_subscription_
= cros_settings_
->AddSettingsObserver(
305 chromeos::kReportDeviceHardwareStatus
, callback
);
306 session_status_subscription_
= cros_settings_
->AddSettingsObserver(
307 chromeos::kReportDeviceSessionStatus
, callback
);
309 // The last known location is persisted in local state. This makes location
310 // information available immediately upon startup and avoids the need to
311 // reacquire the location on every user session change or browser crash.
312 content::Geoposition position
;
313 std::string timestamp_str
;
315 const base::DictionaryValue
* location
=
316 local_state_
->GetDictionary(prefs::kDeviceLocation
);
317 if (location
->GetDouble(kLatitude
, &position
.latitude
) &&
318 location
->GetDouble(kLongitude
, &position
.longitude
) &&
319 location
->GetDouble(kAltitude
, &position
.altitude
) &&
320 location
->GetDouble(kAccuracy
, &position
.accuracy
) &&
321 location
->GetDouble(kAltitudeAccuracy
, &position
.altitude_accuracy
) &&
322 location
->GetDouble(kHeading
, &position
.heading
) &&
323 location
->GetDouble(kSpeed
, &position
.speed
) &&
324 location
->GetString(kTimestamp
, ×tamp_str
) &&
325 base::StringToInt64(timestamp_str
, ×tamp
)) {
326 position
.timestamp
= Time::FromInternalValue(timestamp
);
327 position_
= position
;
330 // Fetch the current values of the policies.
331 UpdateReportingSettings();
333 // Get the the OS and firmware version info.
334 base::PostTaskAndReplyWithResult(
335 content::BrowserThread::GetBlockingPool(),
337 base::Bind(&chromeos::version_loader::GetVersion
,
338 chromeos::version_loader::VERSION_FULL
),
339 base::Bind(&DeviceStatusCollector::OnOSVersion
,
340 weak_factory_
.GetWeakPtr()));
341 base::PostTaskAndReplyWithResult(
342 content::BrowserThread::GetBlockingPool(),
344 base::Bind(&chromeos::version_loader::GetFirmware
),
345 base::Bind(&DeviceStatusCollector::OnOSFirmware
,
346 weak_factory_
.GetWeakPtr()));
349 DeviceStatusCollector::~DeviceStatusCollector() {
353 void DeviceStatusCollector::RegisterPrefs(PrefRegistrySimple
* registry
) {
354 registry
->RegisterDictionaryPref(prefs::kDeviceActivityTimes
,
355 new base::DictionaryValue
);
356 registry
->RegisterDictionaryPref(prefs::kDeviceLocation
,
357 new base::DictionaryValue
);
360 void DeviceStatusCollector::CheckIdleState() {
361 CalculateIdleState(kIdleStateThresholdSeconds
,
362 base::Bind(&DeviceStatusCollector::IdleStateCallback
,
363 base::Unretained(this)));
366 void DeviceStatusCollector::UpdateReportingSettings() {
367 // Attempt to fetch the current value of the reporting settings.
368 // If trusted values are not available, register this function to be called
369 // back when they are available.
370 if (chromeos::CrosSettingsProvider::TRUSTED
!=
371 cros_settings_
->PrepareTrustedValues(
372 base::Bind(&DeviceStatusCollector::UpdateReportingSettings
,
373 weak_factory_
.GetWeakPtr()))) {
377 // All reporting settings default to 'enabled'.
378 if (!cros_settings_
->GetBoolean(
379 chromeos::kReportDeviceVersionInfo
, &report_version_info_
)) {
380 report_version_info_
= true;
382 if (!cros_settings_
->GetBoolean(
383 chromeos::kReportDeviceActivityTimes
, &report_activity_times_
)) {
384 report_activity_times_
= true;
386 if (!cros_settings_
->GetBoolean(
387 chromeos::kReportDeviceBootMode
, &report_boot_mode_
)) {
388 report_boot_mode_
= true;
390 if (!cros_settings_
->GetBoolean(
391 chromeos::kReportDeviceNetworkInterfaces
,
392 &report_network_interfaces_
)) {
393 report_network_interfaces_
= true;
395 if (!cros_settings_
->GetBoolean(
396 chromeos::kReportDeviceUsers
, &report_users_
)) {
397 report_users_
= true;
400 const bool already_reporting_hardware_status
= report_hardware_status_
;
401 if (!cros_settings_
->GetBoolean(
402 chromeos::kReportDeviceHardwareStatus
, &report_hardware_status_
)) {
403 report_hardware_status_
= true;
406 if (!cros_settings_
->GetBoolean(
407 chromeos::kReportDeviceSessionStatus
, &report_session_status_
)) {
408 report_session_status_
= true;
411 // Device location reporting is disabled by default because it is
413 if (!cros_settings_
->GetBoolean(
414 chromeos::kReportDeviceLocation
, &report_location_
)) {
415 report_location_
= false;
418 if (report_location_
) {
419 ScheduleGeolocationUpdateRequest();
421 geolocation_update_timer_
.Stop();
422 position_
= content::Geoposition();
423 local_state_
->ClearPref(prefs::kDeviceLocation
);
426 if (!report_hardware_status_
) {
427 ClearCachedHardwareStatus();
428 } else if (!already_reporting_hardware_status
) {
429 // Turning on hardware status reporting - fetch an initial sample
430 // immediately instead of waiting for the sampling timer to fire.
431 SampleHardwareStatus();
435 Time
DeviceStatusCollector::GetCurrentTime() {
439 // Remove all out-of-range activity times from the local store.
440 void DeviceStatusCollector::PruneStoredActivityPeriods(Time base_time
) {
442 base_time
- TimeDelta::FromDays(max_stored_past_activity_days_
);
444 base_time
+ TimeDelta::FromDays(max_stored_future_activity_days_
);
445 TrimStoredActivityPeriods(TimestampToDayKey(min_time
), 0,
446 TimestampToDayKey(max_time
));
449 void DeviceStatusCollector::TrimStoredActivityPeriods(int64 min_day_key
,
450 int min_day_trim_duration
,
452 const base::DictionaryValue
* activity_times
=
453 local_state_
->GetDictionary(prefs::kDeviceActivityTimes
);
455 scoped_ptr
<base::DictionaryValue
> copy(activity_times
->DeepCopy());
456 for (base::DictionaryValue::Iterator
it(*activity_times
); !it
.IsAtEnd();
459 if (base::StringToInt64(it
.key(), ×tamp
)) {
460 // Remove data that is too old, or too far in the future.
461 if (timestamp
>= min_day_key
&& timestamp
< max_day_key
) {
462 if (timestamp
== min_day_key
) {
463 int new_activity_duration
= 0;
464 if (it
.value().GetAsInteger(&new_activity_duration
)) {
465 new_activity_duration
=
466 std::max(new_activity_duration
- min_day_trim_duration
, 0);
468 copy
->SetInteger(it
.key(), new_activity_duration
);
473 // The entry is out of range or couldn't be parsed. Remove it.
474 copy
->Remove(it
.key(), NULL
);
476 local_state_
->Set(prefs::kDeviceActivityTimes
, *copy
);
479 void DeviceStatusCollector::AddActivePeriod(Time start
, Time end
) {
482 // Maintain the list of active periods in a local_state pref.
483 DictionaryPrefUpdate
update(local_state_
, prefs::kDeviceActivityTimes
);
484 base::DictionaryValue
* activity_times
= update
.Get();
486 // Assign the period to day buckets in local time.
487 Time midnight
= start
.LocalMidnight();
488 while (midnight
< end
) {
489 midnight
+= TimeDelta::FromDays(1);
490 int64 activity
= (std::min(end
, midnight
) - start
).InMilliseconds();
491 std::string day_key
= base::Int64ToString(TimestampToDayKey(start
));
492 int previous_activity
= 0;
493 activity_times
->GetInteger(day_key
, &previous_activity
);
494 activity_times
->SetInteger(day_key
, previous_activity
+ activity
);
499 void DeviceStatusCollector::ClearCachedHardwareStatus() {
500 volume_info_
.clear();
501 resource_usage_
.clear();
502 last_cpu_active_
= 0;
506 void DeviceStatusCollector::IdleStateCallback(ui::IdleState state
) {
507 // Do nothing if device activity reporting is disabled.
508 if (!report_activity_times_
)
511 Time now
= GetCurrentTime();
513 if (state
== ui::IDLE_STATE_ACTIVE
) {
514 // If it's been too long since the last report, or if the activity is
515 // negative (which can happen when the clock changes), assume a single
516 // interval of activity.
517 int active_seconds
= (now
- last_idle_check_
).InSeconds();
518 if (active_seconds
< 0 ||
519 active_seconds
>= static_cast<int>((2 * kIdlePollIntervalSeconds
))) {
520 AddActivePeriod(now
- TimeDelta::FromSeconds(kIdlePollIntervalSeconds
),
523 AddActivePeriod(last_idle_check_
, now
);
526 PruneStoredActivityPeriods(now
);
528 last_idle_check_
= now
;
531 scoped_ptr
<DeviceLocalAccount
>
532 DeviceStatusCollector::GetAutoLaunchedKioskSessionInfo() {
533 scoped_ptr
<DeviceLocalAccount
> account
=
534 GetCurrentKioskDeviceLocalAccount(cros_settings_
);
536 chromeos::KioskAppManager::App current_app
;
537 if (chromeos::KioskAppManager::Get()->GetApp(account
->kiosk_app_id
,
539 current_app
.was_auto_launched_with_zero_delay
) {
540 return account
.Pass();
543 // No auto-launched kiosk session active.
544 return scoped_ptr
<DeviceLocalAccount
>();
547 void DeviceStatusCollector::SampleHardwareStatus() {
548 // If hardware reporting has been disabled, do nothing here.
549 if (!report_hardware_status_
)
552 // Create list of mounted disk volumes to query status.
553 std::vector
<storage::MountPoints::MountPointInfo
> external_mount_points
;
554 storage::ExternalMountPoints::GetSystemInstance()->AddMountPointInfosTo(
555 &external_mount_points
);
557 std::vector
<std::string
> mount_points
;
558 for (const auto& info
: external_mount_points
)
559 mount_points
.push_back(info
.path
.value());
561 for (const auto& mount_info
:
562 chromeos::disks::DiskMountManager::GetInstance()->mount_points()) {
563 // Extract a list of mount points to populate.
564 mount_points
.push_back(mount_info
.first
);
567 // Call out to the blocking pool to measure disk, CPU usage and CPU temp.
568 base::PostTaskAndReplyWithResult(
569 content::BrowserThread::GetBlockingPool(),
571 base::Bind(volume_info_fetcher_
, mount_points
),
572 base::Bind(&DeviceStatusCollector::ReceiveVolumeInfo
,
573 weak_factory_
.GetWeakPtr()));
575 base::PostTaskAndReplyWithResult(
576 content::BrowserThread::GetBlockingPool(), FROM_HERE
,
577 cpu_statistics_fetcher_
,
578 base::Bind(&DeviceStatusCollector::ReceiveCPUStatistics
,
579 weak_factory_
.GetWeakPtr()));
581 base::PostTaskAndReplyWithResult(
582 content::BrowserThread::GetBlockingPool(), FROM_HERE
, cpu_temp_fetcher_
,
583 base::Bind(&DeviceStatusCollector::StoreCPUTempInfo
,
584 weak_factory_
.GetWeakPtr()));
587 void DeviceStatusCollector::ReceiveCPUStatistics(const std::string
& stats
) {
588 int cpu_usage_percent
= 0;
590 DLOG(WARNING
) << "Unable to read CPU statistics";
592 // Parse the data from /proc/stat, whose format is defined at
593 // https://www.kernel.org/doc/Documentation/filesystems/proc.txt.
595 // The CPU usage values in /proc/stat are measured in the imprecise unit
596 // "jiffies", but we just care about the relative magnitude of "active" vs
597 // "idle" so the exact value of a jiffy is irrelevant.
599 // An example value for this line:
601 // cpu 123 456 789 012 345 678
603 // We only care about the first four numbers: user_time, nice_time,
604 // sys_time, and idle_time.
605 uint64 user
= 0, nice
= 0, system
= 0, idle
= 0;
606 int vals
= sscanf(stats
.c_str(),
607 "cpu %" PRIu64
" %" PRIu64
" %" PRIu64
" %" PRIu64
, &user
,
608 &nice
, &system
, &idle
);
611 // The values returned from /proc/stat are cumulative totals, so calculate
612 // the difference between the last sample and this one.
613 uint64 active
= user
+ nice
+ system
;
614 uint64 total
= active
+ idle
;
615 uint64 last_total
= last_cpu_active_
+ last_cpu_idle_
;
616 DCHECK_GE(active
, last_cpu_active_
);
617 DCHECK_GE(idle
, last_cpu_idle_
);
618 DCHECK_GE(total
, last_total
);
620 if ((total
- last_total
) > 0) {
622 (100 * (active
- last_cpu_active_
)) / (total
- last_total
);
624 last_cpu_active_
= active
;
625 last_cpu_idle_
= idle
;
628 DCHECK_LE(cpu_usage_percent
, 100);
629 ResourceUsage usage
= {cpu_usage_percent
,
630 base::SysInfo::AmountOfAvailablePhysicalMemory()};
632 resource_usage_
.push_back(usage
);
634 // If our cache of samples is full, throw out old samples to make room for new
636 if (resource_usage_
.size() > kMaxResourceUsageSamples
)
637 resource_usage_
.pop_front();
640 void DeviceStatusCollector::StoreCPUTempInfo(
641 const std::vector
<em::CPUTempInfo
>& info
) {
643 DLOG(WARNING
) << "Unable to read CPU temp information.";
646 if (report_hardware_status_
)
647 cpu_temp_info_
= info
;
650 void DeviceStatusCollector::GetActivityTimes(
651 em::DeviceStatusReportRequest
* request
) {
652 DictionaryPrefUpdate
update(local_state_
, prefs::kDeviceActivityTimes
);
653 base::DictionaryValue
* activity_times
= update
.Get();
655 for (base::DictionaryValue::Iterator
it(*activity_times
); !it
.IsAtEnd();
657 int64 start_timestamp
;
658 int activity_milliseconds
;
659 if (base::StringToInt64(it
.key(), &start_timestamp
) &&
660 it
.value().GetAsInteger(&activity_milliseconds
)) {
661 // This is correct even when there are leap seconds, because when a leap
662 // second occurs, two consecutive seconds have the same timestamp.
663 int64 end_timestamp
= start_timestamp
+ Time::kMillisecondsPerDay
;
665 em::ActiveTimePeriod
* active_period
= request
->add_active_period();
666 em::TimePeriod
* period
= active_period
->mutable_time_period();
667 period
->set_start_timestamp(start_timestamp
);
668 period
->set_end_timestamp(end_timestamp
);
669 active_period
->set_active_duration(activity_milliseconds
);
670 if (start_timestamp
>= last_reported_day_
) {
671 last_reported_day_
= start_timestamp
;
672 duration_for_last_reported_day_
= activity_milliseconds
;
680 void DeviceStatusCollector::GetVersionInfo(
681 em::DeviceStatusReportRequest
* request
) {
682 request
->set_browser_version(version_info::GetVersionNumber());
683 request
->set_os_version(os_version_
);
684 request
->set_firmware_version(firmware_version_
);
687 void DeviceStatusCollector::GetBootMode(
688 em::DeviceStatusReportRequest
* request
) {
689 std::string dev_switch_mode
;
690 if (statistics_provider_
->GetMachineStatistic(
691 chromeos::system::kDevSwitchBootKey
, &dev_switch_mode
)) {
692 if (dev_switch_mode
== chromeos::system::kDevSwitchBootValueDev
)
693 request
->set_boot_mode("Dev");
694 else if (dev_switch_mode
== chromeos::system::kDevSwitchBootValueVerified
)
695 request
->set_boot_mode("Verified");
699 void DeviceStatusCollector::GetLocation(
700 em::DeviceStatusReportRequest
* request
) {
701 em::DeviceLocation
* location
= request
->mutable_device_location();
702 if (!position_
.Validate()) {
703 location
->set_error_code(
704 em::DeviceLocation::ERROR_CODE_POSITION_UNAVAILABLE
);
705 location
->set_error_message(position_
.error_message
);
707 location
->set_latitude(position_
.latitude
);
708 location
->set_longitude(position_
.longitude
);
709 location
->set_accuracy(position_
.accuracy
);
710 location
->set_timestamp(
711 (position_
.timestamp
- Time::UnixEpoch()).InMilliseconds());
712 // Lowest point on land is at approximately -400 meters.
713 if (position_
.altitude
> -10000.)
714 location
->set_altitude(position_
.altitude
);
715 if (position_
.altitude_accuracy
>= 0.)
716 location
->set_altitude_accuracy(position_
.altitude_accuracy
);
717 if (position_
.heading
>= 0. && position_
.heading
<= 360)
718 location
->set_heading(position_
.heading
);
719 if (position_
.speed
>= 0.)
720 location
->set_speed(position_
.speed
);
721 location
->set_error_code(em::DeviceLocation::ERROR_CODE_NONE
);
725 int DeviceStatusCollector::ConvertWifiSignalStrength(int signal_strength
) {
726 // Shill attempts to convert WiFi signal strength from its internal dBm to a
727 // percentage range (from 0-100) by adding 120 to the raw dBm value,
728 // and then clamping the result to the range 0-100 (see
729 // shill::WiFiService::SignalToStrength()).
731 // To convert back to dBm, we subtract 120 from the percentage value to yield
732 // a clamped dBm value in the range of -119 to -20dBm.
734 // TODO(atwilson): Tunnel the raw dBm signal strength from Shill instead of
735 // doing the conversion here so we can report non-clamped values
736 // (crbug.com/463334).
737 DCHECK_GT(signal_strength
, 0);
738 DCHECK_LE(signal_strength
, 100);
739 return signal_strength
- 120;
742 void DeviceStatusCollector::GetNetworkInterfaces(
743 em::DeviceStatusReportRequest
* request
) {
744 // Maps shill device type strings to proto enum constants.
745 static const struct {
746 const char* type_string
;
747 em::NetworkInterface::NetworkDeviceType type_constant
;
748 } kDeviceTypeMap
[] = {
749 { shill::kTypeEthernet
, em::NetworkInterface::TYPE_ETHERNET
, },
750 { shill::kTypeWifi
, em::NetworkInterface::TYPE_WIFI
, },
751 { shill::kTypeWimax
, em::NetworkInterface::TYPE_WIMAX
, },
752 { shill::kTypeBluetooth
, em::NetworkInterface::TYPE_BLUETOOTH
, },
753 { shill::kTypeCellular
, em::NetworkInterface::TYPE_CELLULAR
, },
756 // Maps shill device connection status to proto enum constants.
757 static const struct {
758 const char* state_string
;
759 em::NetworkState::ConnectionState state_constant
;
760 } kConnectionStateMap
[] = {
761 { shill::kStateIdle
, em::NetworkState::IDLE
},
762 { shill::kStateCarrier
, em::NetworkState::CARRIER
},
763 { shill::kStateAssociation
, em::NetworkState::ASSOCIATION
},
764 { shill::kStateConfiguration
, em::NetworkState::CONFIGURATION
},
765 { shill::kStateReady
, em::NetworkState::READY
},
766 { shill::kStatePortal
, em::NetworkState::PORTAL
},
767 { shill::kStateOffline
, em::NetworkState::OFFLINE
},
768 { shill::kStateOnline
, em::NetworkState::ONLINE
},
769 { shill::kStateDisconnect
, em::NetworkState::DISCONNECT
},
770 { shill::kStateFailure
, em::NetworkState::FAILURE
},
771 { shill::kStateActivationFailure
,
772 em::NetworkState::ACTIVATION_FAILURE
},
775 chromeos::NetworkStateHandler::DeviceStateList device_list
;
776 chromeos::NetworkStateHandler
* network_state_handler
=
777 chromeos::NetworkHandler::Get()->network_state_handler();
778 network_state_handler
->GetDeviceList(&device_list
);
780 chromeos::NetworkStateHandler::DeviceStateList::const_iterator device
;
781 for (device
= device_list
.begin(); device
!= device_list
.end(); ++device
) {
782 // Determine the type enum constant for |device|.
784 for (; type_idx
< arraysize(kDeviceTypeMap
); ++type_idx
) {
785 if ((*device
)->type() == kDeviceTypeMap
[type_idx
].type_string
)
789 // If the type isn't in |kDeviceTypeMap|, the interface is not relevant for
790 // reporting. This filters out VPN devices.
791 if (type_idx
>= arraysize(kDeviceTypeMap
))
794 em::NetworkInterface
* interface
= request
->add_network_interface();
795 interface
->set_type(kDeviceTypeMap
[type_idx
].type_constant
);
796 if (!(*device
)->mac_address().empty())
797 interface
->set_mac_address((*device
)->mac_address());
798 if (!(*device
)->meid().empty())
799 interface
->set_meid((*device
)->meid());
800 if (!(*device
)->imei().empty())
801 interface
->set_imei((*device
)->imei());
802 if (!(*device
)->path().empty())
803 interface
->set_device_path((*device
)->path());
806 // Don't write any network state if we aren't in a kiosk or public session.
807 if (!GetAutoLaunchedKioskSessionInfo() &&
808 !user_manager::UserManager::Get()->IsLoggedInAsPublicAccount())
811 // Walk the various networks and store their state in the status report.
812 chromeos::NetworkStateHandler::NetworkStateList state_list
;
813 network_state_handler
->GetNetworkListByType(
814 chromeos::NetworkTypePattern::Default(),
815 true, // configured_only
816 false, // visible_only
817 0, // no limit to number of results
820 for (const chromeos::NetworkState
* state
: state_list
) {
821 // Determine the connection state and signal strength for |state|.
822 em::NetworkState::ConnectionState connection_state_enum
=
823 em::NetworkState::UNKNOWN
;
824 const std::string
connection_state_string(state
->connection_state());
825 for (size_t i
= 0; i
< arraysize(kConnectionStateMap
); ++i
) {
826 if (connection_state_string
== kConnectionStateMap
[i
].state_string
) {
827 connection_state_enum
= kConnectionStateMap
[i
].state_constant
;
832 // Copy fields from NetworkState into the status report.
833 em::NetworkState
* proto_state
= request
->add_network_state();
834 proto_state
->set_connection_state(connection_state_enum
);
836 // Report signal strength for wifi connections.
837 if (state
->type() == shill::kTypeWifi
) {
838 // If shill has provided a signal strength, convert it to dBm and store it
839 // in the status report. A signal_strength() of 0 connotes "no signal"
840 // rather than "really weak signal", so we only report signal strength if
842 if (state
->signal_strength()) {
843 proto_state
->set_signal_strength(
844 ConvertWifiSignalStrength(state
->signal_strength()));
848 if (!state
->device_path().empty())
849 proto_state
->set_device_path(state
->device_path());
851 if (!state
->ip_address().empty())
852 proto_state
->set_ip_address(state
->ip_address());
854 if (!state
->gateway().empty())
855 proto_state
->set_gateway(state
->gateway());
859 void DeviceStatusCollector::GetUsers(em::DeviceStatusReportRequest
* request
) {
860 const user_manager::UserList
& users
=
861 chromeos::ChromeUserManager::Get()->GetUsers();
863 for (const auto& user
: users
) {
864 // Only users with gaia accounts (regular) are reported.
865 if (!user
->HasGaiaAccount())
868 em::DeviceUser
* device_user
= request
->add_user();
869 if (chromeos::ChromeUserManager::Get()->ShouldReportUser(user
->email())) {
870 device_user
->set_type(em::DeviceUser::USER_TYPE_MANAGED
);
871 device_user
->set_email(user
->email());
873 device_user
->set_type(em::DeviceUser::USER_TYPE_UNMANAGED
);
874 // Do not report the email address of unmanaged users.
879 void DeviceStatusCollector::GetHardwareStatus(
880 em::DeviceStatusReportRequest
* status
) {
882 status
->clear_volume_info();
883 for (const em::VolumeInfo
& info
: volume_info_
) {
884 *status
->add_volume_info() = info
;
887 status
->set_system_ram_total(base::SysInfo::AmountOfPhysicalMemory());
888 status
->clear_system_ram_free();
889 status
->clear_cpu_utilization_pct();
890 for (const ResourceUsage
& usage
: resource_usage_
) {
891 status
->add_cpu_utilization_pct(usage
.cpu_usage_percent
);
892 status
->add_system_ram_free(usage
.bytes_of_ram_free
);
895 // Add CPU temp info.
896 status
->clear_cpu_temp_info();
897 for (const em::CPUTempInfo
& info
: cpu_temp_info_
) {
898 *status
->add_cpu_temp_info() = info
;
902 bool DeviceStatusCollector::GetDeviceStatus(
903 em::DeviceStatusReportRequest
* status
) {
904 if (report_activity_times_
)
905 GetActivityTimes(status
);
907 if (report_version_info_
)
908 GetVersionInfo(status
);
910 if (report_boot_mode_
)
913 if (report_location_
)
916 if (report_network_interfaces_
)
917 GetNetworkInterfaces(status
);
922 if (report_hardware_status_
)
923 GetHardwareStatus(status
);
925 return (report_activity_times_
||
926 report_version_info_
||
929 report_network_interfaces_
||
931 report_hardware_status_
);
934 bool DeviceStatusCollector::GetDeviceSessionStatus(
935 em::SessionStatusReportRequest
* status
) {
936 // Only generate session status reports if session status reporting is
938 if (!report_session_status_
)
941 scoped_ptr
<const DeviceLocalAccount
> account
=
942 GetAutoLaunchedKioskSessionInfo();
943 // Only generate session status reports if we are in an auto-launched kiosk
948 // Get the account ID associated with this user.
949 status
->set_device_local_account_id(account
->account_id
);
950 em::AppStatus
* app_status
= status
->add_installed_apps();
951 app_status
->set_app_id(account
->kiosk_app_id
);
953 // Look up the app and get the version.
954 const std::string app_version
= GetAppVersion(account
->kiosk_app_id
);
955 if (app_version
.empty()) {
956 DLOG(ERROR
) << "Unable to get version for extension: "
957 << account
->kiosk_app_id
;
959 app_status
->set_extension_version(app_version
);
964 std::string
DeviceStatusCollector::GetAppVersion(
965 const std::string
& kiosk_app_id
) {
966 Profile
* const profile
=
967 chromeos::ProfileHelper::Get()->GetProfileByUser(
968 user_manager::UserManager::Get()->GetActiveUser());
969 const extensions::ExtensionRegistry
* const registry
=
970 extensions::ExtensionRegistry::Get(profile
);
971 const extensions::Extension
* const extension
= registry
->GetExtensionById(
972 kiosk_app_id
, extensions::ExtensionRegistry::EVERYTHING
);
974 return std::string();
975 return extension
->VersionString();
978 void DeviceStatusCollector::OnSubmittedSuccessfully() {
979 TrimStoredActivityPeriods(last_reported_day_
, duration_for_last_reported_day_
,
980 std::numeric_limits
<int64
>::max());
983 void DeviceStatusCollector::OnOSVersion(const std::string
& version
) {
984 os_version_
= version
;
987 void DeviceStatusCollector::OnOSFirmware(const std::string
& version
) {
988 firmware_version_
= version
;
991 void DeviceStatusCollector::ScheduleGeolocationUpdateRequest() {
992 if (geolocation_update_timer_
.IsRunning() || geolocation_update_in_progress_
)
995 if (position_
.Validate()) {
996 TimeDelta elapsed
= GetCurrentTime() - position_
.timestamp
;
998 TimeDelta::FromSeconds(kGeolocationPollIntervalSeconds
);
999 if (elapsed
<= interval
) {
1000 geolocation_update_timer_
.Start(
1004 &DeviceStatusCollector::ScheduleGeolocationUpdateRequest
);
1009 geolocation_update_in_progress_
= true;
1010 if (location_update_requester_
.is_null()) {
1011 geolocation_subscription_
= content::GeolocationProvider::GetInstance()->
1012 AddLocationUpdateCallback(
1013 base::Bind(&DeviceStatusCollector::ReceiveGeolocationUpdate
,
1014 weak_factory_
.GetWeakPtr()),
1017 location_update_requester_
.Run(base::Bind(
1018 &DeviceStatusCollector::ReceiveGeolocationUpdate
,
1019 weak_factory_
.GetWeakPtr()));
1023 void DeviceStatusCollector::ReceiveGeolocationUpdate(
1024 const content::Geoposition
& position
) {
1025 geolocation_update_in_progress_
= false;
1027 // Ignore update if device location reporting has since been disabled.
1028 if (!report_location_
)
1031 if (position
.Validate()) {
1032 position_
= position
;
1033 base::DictionaryValue location
;
1034 location
.SetDouble(kLatitude
, position
.latitude
);
1035 location
.SetDouble(kLongitude
, position
.longitude
);
1036 location
.SetDouble(kAltitude
, position
.altitude
);
1037 location
.SetDouble(kAccuracy
, position
.accuracy
);
1038 location
.SetDouble(kAltitudeAccuracy
, position
.altitude_accuracy
);
1039 location
.SetDouble(kHeading
, position
.heading
);
1040 location
.SetDouble(kSpeed
, position
.speed
);
1041 location
.SetString(kTimestamp
,
1042 base::Int64ToString(position
.timestamp
.ToInternalValue()));
1043 local_state_
->Set(prefs::kDeviceLocation
, location
);
1046 ScheduleGeolocationUpdateRequest();
1049 void DeviceStatusCollector::ReceiveVolumeInfo(
1050 const std::vector
<em::VolumeInfo
>& info
) {
1051 if (report_hardware_status_
)
1052 volume_info_
= info
;
1055 } // namespace policy