Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(43)

Side by Side Diff: chrome/browser/chromeos/policy/device_status_collector.cc

Issue 2314813002: Refactored DeviceStatusCollector to enable truely asynchronous status queries (Closed)
Patch Set: Rebase Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/chromeos/policy/device_status_collector.h" 5 #include "chrome/browser/chromeos/policy/device_status_collector.h"
6 6
7 #include <stddef.h> 7 #include <stddef.h>
8 #include <stdint.h> 8 #include <stdint.h>
9 9
10 #include <algorithm> 10 #include <algorithm>
11 #include <cstdio> 11 #include <cstdio>
12 #include <limits> 12 #include <limits>
13 #include <memory> 13 #include <memory>
14 #include <sstream> 14 #include <sstream>
15 15
16 #include "base/bind.h" 16 #include "base/bind.h"
17 #include "base/bind_helpers.h" 17 #include "base/bind_helpers.h"
18 #include "base/files/file_enumerator.h" 18 #include "base/files/file_enumerator.h"
19 #include "base/files/file_util.h" 19 #include "base/files/file_util.h"
20 #include "base/format_macros.h" 20 #include "base/format_macros.h"
21 #include "base/location.h"
22 #include "base/logging.h" 21 #include "base/logging.h"
23 #include "base/macros.h" 22 #include "base/macros.h"
24 #include "base/memory/ptr_util.h" 23 #include "base/memory/ptr_util.h"
24 #include "base/memory/ref_counted.h"
25 #include "base/posix/eintr_wrapper.h" 25 #include "base/posix/eintr_wrapper.h"
26 #include "base/strings/string_number_conversions.h" 26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_util.h" 27 #include "base/strings/string_util.h"
28 #include "base/strings/stringprintf.h" 28 #include "base/strings/stringprintf.h"
29 #include "base/sys_info.h" 29 #include "base/sys_info.h"
30 #include "base/task_runner_util.h" 30 #include "base/task_runner_util.h"
31 #include "base/threading/sequenced_task_runner_handle.h"
31 #include "base/values.h" 32 #include "base/values.h"
32 #include "base/version.h" 33 #include "base/version.h"
33 #include "chrome/browser/browser_process.h" 34 #include "chrome/browser/browser_process.h"
34 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h" 35 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
35 #include "chrome/browser/chromeos/login/users/chrome_user_manager.h" 36 #include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
36 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" 37 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
37 #include "chrome/browser/chromeos/policy/device_local_account.h" 38 #include "chrome/browser/chromeos/policy/device_local_account.h"
38 #include "chrome/browser/chromeos/profiles/profile_helper.h" 39 #include "chrome/browser/chromeos/profiles/profile_helper.h"
39 #include "chrome/browser/chromeos/settings/cros_settings.h" 40 #include "chrome/browser/chromeos/settings/cros_settings.h"
40 #include "chrome/common/pref_names.h" 41 #include "chrome/common/pref_names.h"
41 #include "chromeos/dbus/dbus_thread_manager.h" 42 #include "chromeos/dbus/dbus_thread_manager.h"
42 #include "chromeos/dbus/update_engine_client.h" 43 #include "chromeos/dbus/update_engine_client.h"
43 #include "chromeos/disks/disk_mount_manager.h" 44 #include "chromeos/disks/disk_mount_manager.h"
44 #include "chromeos/network/device_state.h" 45 #include "chromeos/network/device_state.h"
45 #include "chromeos/network/network_handler.h" 46 #include "chromeos/network/network_handler.h"
46 #include "chromeos/network/network_state.h" 47 #include "chromeos/network/network_state.h"
47 #include "chromeos/network/network_state_handler.h" 48 #include "chromeos/network/network_state_handler.h"
48 #include "chromeos/settings/cros_settings_names.h" 49 #include "chromeos/settings/cros_settings_names.h"
49 #include "chromeos/system/statistics_provider.h" 50 #include "chromeos/system/statistics_provider.h"
50 #include "components/policy/core/common/cloud/cloud_policy_constants.h" 51 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
51 #include "components/policy/proto/device_management_backend.pb.h" 52 #include "components/policy/proto/device_management_backend.pb.h"
52 #include "components/prefs/pref_registry_simple.h" 53 #include "components/prefs/pref_registry_simple.h"
53 #include "components/prefs/pref_service.h" 54 #include "components/prefs/pref_service.h"
54 #include "components/prefs/scoped_user_pref_update.h" 55 #include "components/prefs/scoped_user_pref_update.h"
55 #include "components/user_manager/user.h" 56 #include "components/user_manager/user.h"
56 #include "components/user_manager/user_manager.h" 57 #include "components/user_manager/user_manager.h"
57 #include "components/user_manager/user_type.h" 58 #include "components/user_manager/user_type.h"
58 #include "components/version_info/version_info.h" 59 #include "components/version_info/version_info.h"
60 #include "content/public/browser/browser_thread.h"
59 #include "extensions/browser/extension_registry.h" 61 #include "extensions/browser/extension_registry.h"
60 #include "extensions/common/extension.h" 62 #include "extensions/common/extension.h"
61 #include "storage/browser/fileapi/external_mount_points.h" 63 #include "storage/browser/fileapi/external_mount_points.h"
62 #include "third_party/cros_system_api/dbus/service_constants.h" 64 #include "third_party/cros_system_api/dbus/service_constants.h"
63 65
64 using base::Time; 66 using base::Time;
65 using base::TimeDelta; 67 using base::TimeDelta;
66 68
67 namespace em = enterprise_management; 69 namespace em = enterprise_management;
68 70
69 namespace { 71 namespace {
70 // How many seconds of inactivity triggers the idle state. 72 // How many seconds of inactivity triggers the idle state.
71 const int kIdleStateThresholdSeconds = 300; 73 const int kIdleStateThresholdSeconds = 300;
72 74
73 // How many days in the past to store active periods for. 75 // How many days in the past to store active periods for.
74 const unsigned int kMaxStoredPastActivityDays = 30; 76 const unsigned int kMaxStoredPastActivityDays = 30;
75 77
76 // How many days in the future to store active periods for. 78 // How many days in the future to store active periods for.
77 const unsigned int kMaxStoredFutureActivityDays = 2; 79 const unsigned int kMaxStoredFutureActivityDays = 2;
78 80
79 // How often, in seconds, to update the device location. 81 // How often, in seconds, to sample the hardware resource usage.
80 const unsigned int kGeolocationPollIntervalSeconds = 30 * 60; 82 const unsigned int kResourceUsageSampleIntervalSeconds = 120;
81
82 // How often, in seconds, to sample the hardware state.
83 const unsigned int kHardwareStatusSampleIntervalSeconds = 120;
84
85 // Keys for the geolocation status dictionary in local state.
86 const char kLatitude[] = "latitude";
87 const char kLongitude[] = "longitude";
88 const char kAltitude[] = "altitude";
89 const char kAccuracy[] = "accuracy";
90 const char kAltitudeAccuracy[] = "altitude_accuracy";
91 const char kHeading[] = "heading";
92 const char kSpeed[] = "speed";
93 const char kTimestamp[] = "timestamp";
94 83
95 // The location we read our CPU statistics from. 84 // The location we read our CPU statistics from.
96 const char kProcStat[] = "/proc/stat"; 85 const char kProcStat[] = "/proc/stat";
97 86
98 // The location we read our CPU temperature and channel label from. 87 // The location we read our CPU temperature and channel label from.
99 const char kHwmonDir[] = "/sys/class/hwmon/"; 88 const char kHwmonDir[] = "/sys/class/hwmon/";
100 const char kDeviceDir[] = "device"; 89 const char kDeviceDir[] = "device";
101 const char kHwmonDirectoryPattern[] = "hwmon*"; 90 const char kHwmonDirectoryPattern[] = "hwmon*";
102 const char kCPUTempFilePattern[] = "temp*_input"; 91 const char kCPUTempFilePattern[] = "temp*_input";
103 92
(...skipping 162 matching lines...) Expand 10 before | Expand all | Expand 10 after
266 // (crbug.com/463334). 255 // (crbug.com/463334).
267 DCHECK_GT(signal_strength, 0); 256 DCHECK_GT(signal_strength, 0);
268 DCHECK_LE(signal_strength, 100); 257 DCHECK_LE(signal_strength, 100);
269 return signal_strength - 120; 258 return signal_strength - 120;
270 } 259 }
271 260
272 } // namespace 261 } // namespace
273 262
274 namespace policy { 263 namespace policy {
275 264
265 // Helper class for state tracking of async status queries.
Andrew T Wilson (Slow) 2016/09/26 16:33:42 This does clever stuff in the destructor - you sho
ljusten (tachyonic) 2016/09/27 16:53:54 Done.
266 class GetStatusState : public base::RefCountedThreadSafe<GetStatusState> {
267 public:
268 explicit GetStatusState(
269 const scoped_refptr<base::SequencedTaskRunner> task_runner,
270 const policy::DeviceStatusCollector::StatusCallback& response)
271 : task_runner_(task_runner),
272 response_(response),
273 device_status_(base::MakeUnique<em::DeviceStatusReportRequest>()),
Andrew T Wilson (Slow) 2016/09/26 16:33:42 I thought unique_ptr initialized itself to null -
Thiemo Nagel 2016/09/27 16:39:29 +1 to this. Also, for new code we prefer in-class
ljusten (tachyonic) 2016/09/27 16:53:55 unique_ptr does initialize itself to nullptr, but
274 session_status_(base::MakeUnique<em::SessionStatusReportRequest>()) {}
275
276 inline em::DeviceStatusReportRequest* device_status() {
277 return device_status_.get();
278 }
279
280 inline em::SessionStatusReportRequest* session_status() {
281 return session_status_.get();
282 }
283
284 inline void ResetDeviceStatus() { device_status_.reset(); }
285
286 inline void ResetSessionStatus() { session_status_.reset(); }
287
288 // Queues an async callback to query disk volume information.
289 void SampleVolumeInfo(const policy::DeviceStatusCollector::VolumeInfoFetcher&
290 volume_info_fetcher) {
291 // Create list of mounted disk volumes to query status.
292 std::vector<storage::MountPoints::MountPointInfo> external_mount_points;
293 storage::ExternalMountPoints::GetSystemInstance()->AddMountPointInfosTo(
294 &external_mount_points);
295
296 std::vector<std::string> mount_points;
297 for (const auto& info : external_mount_points)
298 mount_points.push_back(info.path.value());
299
300 for (const auto& mount_info :
301 chromeos::disks::DiskMountManager::GetInstance()->mount_points()) {
302 // Extract a list of mount points to populate.
303 mount_points.push_back(mount_info.first);
304 }
305
306 // Call out to the blocking pool to sample disk volume info.
307 base::PostTaskAndReplyWithResult(
308 content::BrowserThread::GetBlockingPool(), FROM_HERE,
309 base::Bind(volume_info_fetcher, mount_points),
310 base::Bind(&GetStatusState::OnVolumeInfoReceived, this));
311 }
312
313 // Queues an async callback to query CPU temperator information.
Andrew T Wilson (Slow) 2016/09/26 16:33:42 nit: temperator->temperature
ljusten (tachyonic) 2016/09/27 16:53:55 Done.
314 void SampleCPUTempInfo(
315 const policy::DeviceStatusCollector::CPUTempFetcher& cpu_temp_fetcher) {
316 // Call out to the blocking pool to sample CPU temp.
317 base::PostTaskAndReplyWithResult(
318 content::BrowserThread::GetBlockingPool(), FROM_HERE, cpu_temp_fetcher,
319 base::Bind(&GetStatusState::OnCPUTempInfoReceived, this));
320 }
321
322 private:
323 friend class RefCountedThreadSafe<GetStatusState>;
324
325 // Posts the response on the UI thread. As long as there is an outstanding
326 // async query, the query holds a reference to us, so the destructor is
327 // not called.
328 ~GetStatusState() {
329 task_runner_->PostTask(FROM_HERE,
330 base::Bind(response_, base::Passed(&device_status_),
331 base::Passed(&session_status_)));
332 }
333
334 void OnVolumeInfoReceived(const std::vector<em::VolumeInfo>& volume_info) {
335 device_status_->clear_volume_info();
336 for (const em::VolumeInfo& info : volume_info)
337 *device_status_->add_volume_info() = info;
338 }
339
340 void OnCPUTempInfoReceived(
341 const std::vector<em::CPUTempInfo>& cpu_temp_info) {
342 if (cpu_temp_info.empty())
343 DLOG(WARNING) << "Unable to read CPU temp information.";
344
345 device_status_->clear_cpu_temp_info();
346 for (const em::CPUTempInfo& info : cpu_temp_info)
347 *device_status_->add_cpu_temp_info() = info;
348 }
349
350 const scoped_refptr<base::SequencedTaskRunner> task_runner_;
351 policy::DeviceStatusCollector::StatusCallback response_;
352 std::unique_ptr<em::DeviceStatusReportRequest> device_status_;
353 std::unique_ptr<em::SessionStatusReportRequest> session_status_;
354 };
355
276 DeviceStatusCollector::DeviceStatusCollector( 356 DeviceStatusCollector::DeviceStatusCollector(
277 PrefService* local_state, 357 PrefService* local_state,
278 chromeos::system::StatisticsProvider* provider, 358 chromeos::system::StatisticsProvider* provider,
279 const LocationUpdateRequester& location_update_requester,
280 const VolumeInfoFetcher& volume_info_fetcher, 359 const VolumeInfoFetcher& volume_info_fetcher,
281 const CPUStatisticsFetcher& cpu_statistics_fetcher, 360 const CPUStatisticsFetcher& cpu_statistics_fetcher,
282 const CPUTempFetcher& cpu_temp_fetcher) 361 const CPUTempFetcher& cpu_temp_fetcher)
283 : max_stored_past_activity_days_(kMaxStoredPastActivityDays), 362 : max_stored_past_activity_days_(kMaxStoredPastActivityDays),
284 max_stored_future_activity_days_(kMaxStoredFutureActivityDays), 363 max_stored_future_activity_days_(kMaxStoredFutureActivityDays),
285 local_state_(local_state), 364 local_state_(local_state),
286 last_idle_check_(Time()), 365 last_idle_check_(Time()),
287 volume_info_fetcher_(volume_info_fetcher), 366 volume_info_fetcher_(volume_info_fetcher),
288 cpu_statistics_fetcher_(cpu_statistics_fetcher), 367 cpu_statistics_fetcher_(cpu_statistics_fetcher),
289 cpu_temp_fetcher_(cpu_temp_fetcher), 368 cpu_temp_fetcher_(cpu_temp_fetcher),
290 statistics_provider_(provider), 369 statistics_provider_(provider),
291 cros_settings_(chromeos::CrosSettings::Get()), 370 cros_settings_(chromeos::CrosSettings::Get()),
292 location_update_requester_(location_update_requester), 371 task_runner_(nullptr),
293 weak_factory_(this) { 372 weak_factory_(this) {
294 CHECK(content::BrowserThread::GetCurrentThreadIdentifier(&creation_thread_)); 373 // Get the task runner of the current thread, so we can queue status responses
374 // on this thread.
375 CHECK(base::SequencedTaskRunnerHandle::IsSet());
376 task_runner_ = base::SequencedTaskRunnerHandle::Get();
295 377
296 if (volume_info_fetcher_.is_null()) 378 if (volume_info_fetcher_.is_null())
297 volume_info_fetcher_ = base::Bind(&GetVolumeInfo); 379 volume_info_fetcher_ = base::Bind(&GetVolumeInfo);
298 380
299 if (cpu_statistics_fetcher_.is_null()) 381 if (cpu_statistics_fetcher_.is_null())
300 cpu_statistics_fetcher_ = base::Bind(&ReadCPUStatistics); 382 cpu_statistics_fetcher_ = base::Bind(&ReadCPUStatistics);
301 383
302 if (cpu_temp_fetcher_.is_null()) 384 if (cpu_temp_fetcher_.is_null())
303 cpu_temp_fetcher_ = base::Bind(&ReadCPUTempInfo); 385 cpu_temp_fetcher_ = base::Bind(&ReadCPUTempInfo);
304 386
305 idle_poll_timer_.Start(FROM_HERE, 387 idle_poll_timer_.Start(FROM_HERE,
306 TimeDelta::FromSeconds(kIdlePollIntervalSeconds), 388 TimeDelta::FromSeconds(kIdlePollIntervalSeconds),
307 this, &DeviceStatusCollector::CheckIdleState); 389 this, &DeviceStatusCollector::CheckIdleState);
308 hardware_status_sampling_timer_.Start( 390 resource_usage_sampling_timer_.Start(
309 FROM_HERE, 391 FROM_HERE, TimeDelta::FromSeconds(kResourceUsageSampleIntervalSeconds),
310 TimeDelta::FromSeconds(kHardwareStatusSampleIntervalSeconds), 392 this, &DeviceStatusCollector::SampleResourceUsage);
311 this, &DeviceStatusCollector::SampleHardwareStatus);
312 393
313 // Watch for changes to the individual policies that control what the status 394 // Watch for changes to the individual policies that control what the status
314 // reports contain. 395 // reports contain.
315 base::Closure callback = 396 base::Closure callback =
316 base::Bind(&DeviceStatusCollector::UpdateReportingSettings, 397 base::Bind(&DeviceStatusCollector::UpdateReportingSettings,
317 base::Unretained(this)); 398 base::Unretained(this));
318 version_info_subscription_ = cros_settings_->AddSettingsObserver( 399 version_info_subscription_ = cros_settings_->AddSettingsObserver(
319 chromeos::kReportDeviceVersionInfo, callback); 400 chromeos::kReportDeviceVersionInfo, callback);
320 activity_times_subscription_ = cros_settings_->AddSettingsObserver( 401 activity_times_subscription_ = cros_settings_->AddSettingsObserver(
321 chromeos::kReportDeviceActivityTimes, callback); 402 chromeos::kReportDeviceActivityTimes, callback);
322 boot_mode_subscription_ = cros_settings_->AddSettingsObserver( 403 boot_mode_subscription_ = cros_settings_->AddSettingsObserver(
323 chromeos::kReportDeviceBootMode, callback); 404 chromeos::kReportDeviceBootMode, callback);
324 location_subscription_ = cros_settings_->AddSettingsObserver(
325 chromeos::kReportDeviceLocation, callback);
326 network_interfaces_subscription_ = cros_settings_->AddSettingsObserver( 405 network_interfaces_subscription_ = cros_settings_->AddSettingsObserver(
327 chromeos::kReportDeviceNetworkInterfaces, callback); 406 chromeos::kReportDeviceNetworkInterfaces, callback);
328 users_subscription_ = cros_settings_->AddSettingsObserver( 407 users_subscription_ = cros_settings_->AddSettingsObserver(
329 chromeos::kReportDeviceUsers, callback); 408 chromeos::kReportDeviceUsers, callback);
330 hardware_status_subscription_ = cros_settings_->AddSettingsObserver( 409 hardware_status_subscription_ = cros_settings_->AddSettingsObserver(
331 chromeos::kReportDeviceHardwareStatus, callback); 410 chromeos::kReportDeviceHardwareStatus, callback);
332 session_status_subscription_ = cros_settings_->AddSettingsObserver( 411 session_status_subscription_ = cros_settings_->AddSettingsObserver(
333 chromeos::kReportDeviceSessionStatus, callback); 412 chromeos::kReportDeviceSessionStatus, callback);
334 os_update_status_subscription_ = cros_settings_->AddSettingsObserver( 413 os_update_status_subscription_ = cros_settings_->AddSettingsObserver(
335 chromeos::kReportOsUpdateStatus, callback); 414 chromeos::kReportOsUpdateStatus, callback);
336 running_kiosk_app_subscription_ = cros_settings_->AddSettingsObserver( 415 running_kiosk_app_subscription_ = cros_settings_->AddSettingsObserver(
337 chromeos::kReportRunningKioskApp, callback); 416 chromeos::kReportRunningKioskApp, callback);
338 417
339 // The last known location is persisted in local state. This makes location
340 // information available immediately upon startup and avoids the need to
341 // reacquire the location on every user session change or browser crash.
342 device::Geoposition position;
343 std::string timestamp_str;
344 int64_t timestamp;
345 const base::DictionaryValue* location =
346 local_state_->GetDictionary(prefs::kDeviceLocation);
347 if (location->GetDouble(kLatitude, &position.latitude) &&
348 location->GetDouble(kLongitude, &position.longitude) &&
349 location->GetDouble(kAltitude, &position.altitude) &&
350 location->GetDouble(kAccuracy, &position.accuracy) &&
351 location->GetDouble(kAltitudeAccuracy, &position.altitude_accuracy) &&
352 location->GetDouble(kHeading, &position.heading) &&
353 location->GetDouble(kSpeed, &position.speed) &&
354 location->GetString(kTimestamp, &timestamp_str) &&
355 base::StringToInt64(timestamp_str, &timestamp)) {
356 position.timestamp = Time::FromInternalValue(timestamp);
357 position_ = position;
358 }
359
360 // Fetch the current values of the policies. 418 // Fetch the current values of the policies.
361 UpdateReportingSettings(); 419 UpdateReportingSettings();
362 420
363 // Get the the OS and firmware version info. 421 // Get the the OS and firmware version info.
364 base::PostTaskAndReplyWithResult( 422 base::PostTaskAndReplyWithResult(
365 content::BrowserThread::GetBlockingPool(), 423 content::BrowserThread::GetBlockingPool(),
366 FROM_HERE, 424 FROM_HERE,
367 base::Bind(&chromeos::version_loader::GetVersion, 425 base::Bind(&chromeos::version_loader::GetVersion,
368 chromeos::version_loader::VERSION_FULL), 426 chromeos::version_loader::VERSION_FULL),
369 base::Bind(&DeviceStatusCollector::OnOSVersion, 427 base::Bind(&DeviceStatusCollector::OnOSVersion,
370 weak_factory_.GetWeakPtr())); 428 weak_factory_.GetWeakPtr()));
371 base::PostTaskAndReplyWithResult( 429 base::PostTaskAndReplyWithResult(
372 content::BrowserThread::GetBlockingPool(), 430 content::BrowserThread::GetBlockingPool(),
373 FROM_HERE, 431 FROM_HERE,
374 base::Bind(&chromeos::version_loader::GetFirmware), 432 base::Bind(&chromeos::version_loader::GetFirmware),
375 base::Bind(&DeviceStatusCollector::OnOSFirmware, 433 base::Bind(&DeviceStatusCollector::OnOSFirmware,
376 weak_factory_.GetWeakPtr())); 434 weak_factory_.GetWeakPtr()));
377 } 435 }
378 436
379 DeviceStatusCollector::~DeviceStatusCollector() { 437 DeviceStatusCollector::~DeviceStatusCollector() {
380 } 438 }
381 439
382 // static 440 // static
383 void DeviceStatusCollector::RegisterPrefs(PrefRegistrySimple* registry) { 441 void DeviceStatusCollector::RegisterPrefs(PrefRegistrySimple* registry) {
384 registry->RegisterDictionaryPref(prefs::kDeviceActivityTimes, 442 registry->RegisterDictionaryPref(prefs::kDeviceActivityTimes,
385 new base::DictionaryValue); 443 new base::DictionaryValue);
386 registry->RegisterDictionaryPref(prefs::kDeviceLocation,
387 new base::DictionaryValue);
388 } 444 }
389 445
390 void DeviceStatusCollector::CheckIdleState() { 446 void DeviceStatusCollector::CheckIdleState() {
391 CalculateIdleState(kIdleStateThresholdSeconds, 447 CalculateIdleState(kIdleStateThresholdSeconds,
392 base::Bind(&DeviceStatusCollector::IdleStateCallback, 448 base::Bind(&DeviceStatusCollector::IdleStateCallback,
393 base::Unretained(this))); 449 base::Unretained(this)));
394 } 450 }
395 451
396 void DeviceStatusCollector::UpdateReportingSettings() { 452 void DeviceStatusCollector::UpdateReportingSettings() {
397 // Attempt to fetch the current value of the reporting settings. 453 // Attempt to fetch the current value of the reporting settings.
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
431 if (!cros_settings_->GetBoolean( 487 if (!cros_settings_->GetBoolean(
432 chromeos::kReportDeviceHardwareStatus, &report_hardware_status_)) { 488 chromeos::kReportDeviceHardwareStatus, &report_hardware_status_)) {
433 report_hardware_status_ = true; 489 report_hardware_status_ = true;
434 } 490 }
435 491
436 if (!cros_settings_->GetBoolean( 492 if (!cros_settings_->GetBoolean(
437 chromeos::kReportDeviceSessionStatus, &report_session_status_)) { 493 chromeos::kReportDeviceSessionStatus, &report_session_status_)) {
438 report_session_status_ = true; 494 report_session_status_ = true;
439 } 495 }
440 496
441 // Device location reporting is disabled by default because it is
442 // not launched yet.
443 if (!cros_settings_->GetBoolean(
444 chromeos::kReportDeviceLocation, &report_location_)) {
445 report_location_ = false;
446 }
447
448 if (report_location_) {
449 ScheduleGeolocationUpdateRequest();
450 } else {
451 geolocation_update_timer_.Stop();
452 position_ = device::Geoposition();
453 local_state_->ClearPref(prefs::kDeviceLocation);
454 }
455
456 if (!report_hardware_status_) { 497 if (!report_hardware_status_) {
457 ClearCachedHardwareStatus(); 498 ClearCachedResourceUsage();
458 } else if (!already_reporting_hardware_status) { 499 } else if (!already_reporting_hardware_status) {
459 // Turning on hardware status reporting - fetch an initial sample 500 // Turning on hardware status reporting - fetch an initial sample
460 // immediately instead of waiting for the sampling timer to fire. 501 // immediately instead of waiting for the sampling timer to fire.
461 SampleHardwareStatus(); 502 SampleResourceUsage();
462 } 503 }
463 504
464 // Os update status and running kiosk app reporting are disabled by default. 505 // Os update status and running kiosk app reporting are disabled by default.
465 if (!cros_settings_->GetBoolean(chromeos::kReportOsUpdateStatus, 506 if (!cros_settings_->GetBoolean(chromeos::kReportOsUpdateStatus,
466 &report_os_update_status_)) { 507 &report_os_update_status_)) {
467 report_os_update_status_ = false; 508 report_os_update_status_ = false;
468 } 509 }
469 if (!cros_settings_->GetBoolean(chromeos::kReportRunningKioskApp, 510 if (!cros_settings_->GetBoolean(chromeos::kReportRunningKioskApp,
470 &report_running_kiosk_app_)) { 511 &report_running_kiosk_app_)) {
471 report_running_kiosk_app_ = false; 512 report_running_kiosk_app_ = false;
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after
529 midnight += TimeDelta::FromDays(1); 570 midnight += TimeDelta::FromDays(1);
530 int64_t activity = (std::min(end, midnight) - start).InMilliseconds(); 571 int64_t activity = (std::min(end, midnight) - start).InMilliseconds();
531 std::string day_key = base::Int64ToString(TimestampToDayKey(start)); 572 std::string day_key = base::Int64ToString(TimestampToDayKey(start));
532 int previous_activity = 0; 573 int previous_activity = 0;
533 activity_times->GetInteger(day_key, &previous_activity); 574 activity_times->GetInteger(day_key, &previous_activity);
534 activity_times->SetInteger(day_key, previous_activity + activity); 575 activity_times->SetInteger(day_key, previous_activity + activity);
535 start = midnight; 576 start = midnight;
536 } 577 }
537 } 578 }
538 579
539 void DeviceStatusCollector::ClearCachedHardwareStatus() { 580 void DeviceStatusCollector::ClearCachedResourceUsage() {
540 volume_info_.clear();
541 resource_usage_.clear(); 581 resource_usage_.clear();
542 last_cpu_active_ = 0; 582 last_cpu_active_ = 0;
543 last_cpu_idle_ = 0; 583 last_cpu_idle_ = 0;
544 } 584 }
545 585
546 void DeviceStatusCollector::IdleStateCallback(ui::IdleState state) { 586 void DeviceStatusCollector::IdleStateCallback(ui::IdleState state) {
547 // Do nothing if device activity reporting is disabled. 587 // Do nothing if device activity reporting is disabled.
548 if (!report_activity_times_) 588 if (!report_activity_times_)
549 return; 589 return;
550 590
(...skipping 26 matching lines...) Expand all
577 if (chromeos::KioskAppManager::Get()->GetApp(account->kiosk_app_id, 617 if (chromeos::KioskAppManager::Get()->GetApp(account->kiosk_app_id,
578 &current_app) && 618 &current_app) &&
579 current_app.was_auto_launched_with_zero_delay) { 619 current_app.was_auto_launched_with_zero_delay) {
580 return account; 620 return account;
581 } 621 }
582 } 622 }
583 // No auto-launched kiosk session active. 623 // No auto-launched kiosk session active.
584 return std::unique_ptr<DeviceLocalAccount>(); 624 return std::unique_ptr<DeviceLocalAccount>();
585 } 625 }
586 626
587 void DeviceStatusCollector::SampleHardwareStatus() { 627 void DeviceStatusCollector::SampleResourceUsage() {
588 // Results must be written in the creation thread since that's where they 628 // Results must be written in the creation thread since that's where they
589 // are read from in the Get*StatusAsync methods. 629 // are read from in the Get*StatusAsync methods.
590 CHECK(content::BrowserThread::CurrentlyOn(creation_thread_)); 630 DCHECK(thread_checker_.CalledOnValidThread());
591 631
592 // If hardware reporting has been disabled, do nothing here. 632 // If hardware reporting has been disabled, do nothing here.
593 if (!report_hardware_status_) 633 if (!report_hardware_status_)
594 return; 634 return;
595 635
596 // Create list of mounted disk volumes to query status. 636 // Call out to the blocking pool to sample CPU stats.
597 std::vector<storage::MountPoints::MountPointInfo> external_mount_points;
598 storage::ExternalMountPoints::GetSystemInstance()->AddMountPointInfosTo(
599 &external_mount_points);
600
601 std::vector<std::string> mount_points;
602 for (const auto& info : external_mount_points)
603 mount_points.push_back(info.path.value());
604
605 for (const auto& mount_info :
606 chromeos::disks::DiskMountManager::GetInstance()->mount_points()) {
607 // Extract a list of mount points to populate.
608 mount_points.push_back(mount_info.first);
609 }
610
611 // Call out to the blocking pool to measure disk, CPU usage and CPU temp.
612 base::PostTaskAndReplyWithResult(
613 content::BrowserThread::GetBlockingPool(),
614 FROM_HERE,
615 base::Bind(volume_info_fetcher_, mount_points),
616 base::Bind(&DeviceStatusCollector::ReceiveVolumeInfo,
617 weak_factory_.GetWeakPtr()));
618
619 base::PostTaskAndReplyWithResult( 637 base::PostTaskAndReplyWithResult(
620 content::BrowserThread::GetBlockingPool(), FROM_HERE, 638 content::BrowserThread::GetBlockingPool(), FROM_HERE,
621 cpu_statistics_fetcher_, 639 cpu_statistics_fetcher_,
622 base::Bind(&DeviceStatusCollector::ReceiveCPUStatistics, 640 base::Bind(&DeviceStatusCollector::ReceiveCPUStatistics,
623 weak_factory_.GetWeakPtr())); 641 weak_factory_.GetWeakPtr()));
624
625 base::PostTaskAndReplyWithResult(
626 content::BrowserThread::GetBlockingPool(), FROM_HERE, cpu_temp_fetcher_,
627 base::Bind(&DeviceStatusCollector::StoreCPUTempInfo,
628 weak_factory_.GetWeakPtr()));
629 } 642 }
630 643
631 void DeviceStatusCollector::ReceiveCPUStatistics(const std::string& stats) { 644 void DeviceStatusCollector::ReceiveCPUStatistics(const std::string& stats) {
632 int cpu_usage_percent = 0; 645 int cpu_usage_percent = 0;
633 if (stats.empty()) { 646 if (stats.empty()) {
634 DLOG(WARNING) << "Unable to read CPU statistics"; 647 DLOG(WARNING) << "Unable to read CPU statistics";
635 } else { 648 } else {
636 // Parse the data from /proc/stat, whose format is defined at 649 // Parse the data from /proc/stat, whose format is defined at
637 // https://www.kernel.org/doc/Documentation/filesystems/proc.txt. 650 // https://www.kernel.org/doc/Documentation/filesystems/proc.txt.
638 // 651 //
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
674 base::SysInfo::AmountOfAvailablePhysicalMemory()}; 687 base::SysInfo::AmountOfAvailablePhysicalMemory()};
675 688
676 resource_usage_.push_back(usage); 689 resource_usage_.push_back(usage);
677 690
678 // If our cache of samples is full, throw out old samples to make room for new 691 // If our cache of samples is full, throw out old samples to make room for new
679 // sample. 692 // sample.
680 if (resource_usage_.size() > kMaxResourceUsageSamples) 693 if (resource_usage_.size() > kMaxResourceUsageSamples)
681 resource_usage_.pop_front(); 694 resource_usage_.pop_front();
682 } 695 }
683 696
684 void DeviceStatusCollector::StoreCPUTempInfo(
685 const std::vector<em::CPUTempInfo>& info) {
686 if (info.empty()) {
687 DLOG(WARNING) << "Unable to read CPU temp information.";
688 }
689
690 if (report_hardware_status_)
691 cpu_temp_info_ = info;
692 }
693
694 bool DeviceStatusCollector::GetActivityTimes( 697 bool DeviceStatusCollector::GetActivityTimes(
695 em::DeviceStatusReportRequest* request) { 698 em::DeviceStatusReportRequest* status) {
696 DictionaryPrefUpdate update(local_state_, prefs::kDeviceActivityTimes); 699 DictionaryPrefUpdate update(local_state_, prefs::kDeviceActivityTimes);
697 base::DictionaryValue* activity_times = update.Get(); 700 base::DictionaryValue* activity_times = update.Get();
698 701
699 bool anything_reported = false; 702 bool anything_reported = false;
700 for (base::DictionaryValue::Iterator it(*activity_times); !it.IsAtEnd(); 703 for (base::DictionaryValue::Iterator it(*activity_times); !it.IsAtEnd();
701 it.Advance()) { 704 it.Advance()) {
702 int64_t start_timestamp; 705 int64_t start_timestamp;
703 int activity_milliseconds; 706 int activity_milliseconds;
704 if (base::StringToInt64(it.key(), &start_timestamp) && 707 if (base::StringToInt64(it.key(), &start_timestamp) &&
705 it.value().GetAsInteger(&activity_milliseconds)) { 708 it.value().GetAsInteger(&activity_milliseconds)) {
706 // This is correct even when there are leap seconds, because when a leap 709 // This is correct even when there are leap seconds, because when a leap
707 // second occurs, two consecutive seconds have the same timestamp. 710 // second occurs, two consecutive seconds have the same timestamp.
708 int64_t end_timestamp = start_timestamp + Time::kMillisecondsPerDay; 711 int64_t end_timestamp = start_timestamp + Time::kMillisecondsPerDay;
709 712
710 em::ActiveTimePeriod* active_period = request->add_active_period(); 713 em::ActiveTimePeriod* active_period = status->add_active_period();
711 em::TimePeriod* period = active_period->mutable_time_period(); 714 em::TimePeriod* period = active_period->mutable_time_period();
712 period->set_start_timestamp(start_timestamp); 715 period->set_start_timestamp(start_timestamp);
713 period->set_end_timestamp(end_timestamp); 716 period->set_end_timestamp(end_timestamp);
714 active_period->set_active_duration(activity_milliseconds); 717 active_period->set_active_duration(activity_milliseconds);
715 if (start_timestamp >= last_reported_day_) { 718 if (start_timestamp >= last_reported_day_) {
716 last_reported_day_ = start_timestamp; 719 last_reported_day_ = start_timestamp;
717 duration_for_last_reported_day_ = activity_milliseconds; 720 duration_for_last_reported_day_ = activity_milliseconds;
718 } 721 }
719 anything_reported = true; 722 anything_reported = true;
720 } else { 723 } else {
721 NOTREACHED(); 724 NOTREACHED();
722 } 725 }
723 } 726 }
724 return anything_reported; 727 return anything_reported;
725 } 728 }
726 729
727 bool DeviceStatusCollector::GetVersionInfo( 730 bool DeviceStatusCollector::GetVersionInfo(
728 em::DeviceStatusReportRequest* request) { 731 em::DeviceStatusReportRequest* status) {
729 request->set_browser_version(version_info::GetVersionNumber()); 732 status->set_browser_version(version_info::GetVersionNumber());
730 request->set_os_version(os_version_); 733 status->set_os_version(os_version_);
731 request->set_firmware_version(firmware_version_); 734 status->set_firmware_version(firmware_version_);
732 return true; 735 return true;
733 } 736 }
734 737
735 bool DeviceStatusCollector::GetBootMode( 738 bool DeviceStatusCollector::GetBootMode(em::DeviceStatusReportRequest* status) {
736 em::DeviceStatusReportRequest* request) {
737 std::string dev_switch_mode; 739 std::string dev_switch_mode;
738 bool anything_reported = false; 740 bool anything_reported = false;
739 if (statistics_provider_->GetMachineStatistic( 741 if (statistics_provider_->GetMachineStatistic(
740 chromeos::system::kDevSwitchBootKey, &dev_switch_mode)) { 742 chromeos::system::kDevSwitchBootKey, &dev_switch_mode)) {
741 if (dev_switch_mode == chromeos::system::kDevSwitchBootValueDev) 743 if (dev_switch_mode == chromeos::system::kDevSwitchBootValueDev)
742 request->set_boot_mode("Dev"); 744 status->set_boot_mode("Dev");
Andrew T Wilson (Slow) 2016/09/26 16:33:42 This is all fine, although note that your patch is
ljusten (tachyonic) 2016/09/27 16:53:55 Acknowledged.
743 else if (dev_switch_mode == chromeos::system::kDevSwitchBootValueVerified) 745 else if (dev_switch_mode == chromeos::system::kDevSwitchBootValueVerified)
744 request->set_boot_mode("Verified"); 746 status->set_boot_mode("Verified");
745 anything_reported = true; 747 anything_reported = true;
746 } 748 }
747 return anything_reported; 749 return anything_reported;
748 } 750 }
749 751
750 bool DeviceStatusCollector::GetLocation(
751 em::DeviceStatusReportRequest* request) {
752 em::DeviceLocation* location = request->mutable_device_location();
753 if (!position_.Validate()) {
754 location->set_error_code(
755 em::DeviceLocation::ERROR_CODE_POSITION_UNAVAILABLE);
756 location->set_error_message(position_.error_message);
757 } else {
758 location->set_latitude(position_.latitude);
759 location->set_longitude(position_.longitude);
760 location->set_accuracy(position_.accuracy);
761 location->set_timestamp(
762 (position_.timestamp - Time::UnixEpoch()).InMilliseconds());
763 // Lowest point on land is at approximately -400 meters.
764 if (position_.altitude > -10000.)
765 location->set_altitude(position_.altitude);
766 if (position_.altitude_accuracy >= 0.)
767 location->set_altitude_accuracy(position_.altitude_accuracy);
768 if (position_.heading >= 0. && position_.heading <= 360)
769 location->set_heading(position_.heading);
770 if (position_.speed >= 0.)
771 location->set_speed(position_.speed);
772 location->set_error_code(em::DeviceLocation::ERROR_CODE_NONE);
773 }
774 return true;
775 }
776
777 bool DeviceStatusCollector::GetNetworkInterfaces( 752 bool DeviceStatusCollector::GetNetworkInterfaces(
778 em::DeviceStatusReportRequest* request) { 753 em::DeviceStatusReportRequest* status) {
779 // Maps shill device type strings to proto enum constants. 754 // Maps shill device type strings to proto enum constants.
780 static const struct { 755 static const struct {
781 const char* type_string; 756 const char* type_string;
782 em::NetworkInterface::NetworkDeviceType type_constant; 757 em::NetworkInterface::NetworkDeviceType type_constant;
783 } kDeviceTypeMap[] = { 758 } kDeviceTypeMap[] = {
784 { shill::kTypeEthernet, em::NetworkInterface::TYPE_ETHERNET, }, 759 { shill::kTypeEthernet, em::NetworkInterface::TYPE_ETHERNET, },
785 { shill::kTypeWifi, em::NetworkInterface::TYPE_WIFI, }, 760 { shill::kTypeWifi, em::NetworkInterface::TYPE_WIFI, },
786 { shill::kTypeWimax, em::NetworkInterface::TYPE_WIMAX, }, 761 { shill::kTypeWimax, em::NetworkInterface::TYPE_WIMAX, },
787 { shill::kTypeBluetooth, em::NetworkInterface::TYPE_BLUETOOTH, }, 762 { shill::kTypeBluetooth, em::NetworkInterface::TYPE_BLUETOOTH, },
788 { shill::kTypeCellular, em::NetworkInterface::TYPE_CELLULAR, }, 763 { shill::kTypeCellular, em::NetworkInterface::TYPE_CELLULAR, },
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
820 for (; type_idx < arraysize(kDeviceTypeMap); ++type_idx) { 795 for (; type_idx < arraysize(kDeviceTypeMap); ++type_idx) {
821 if ((*device)->type() == kDeviceTypeMap[type_idx].type_string) 796 if ((*device)->type() == kDeviceTypeMap[type_idx].type_string)
822 break; 797 break;
823 } 798 }
824 799
825 // If the type isn't in |kDeviceTypeMap|, the interface is not relevant for 800 // If the type isn't in |kDeviceTypeMap|, the interface is not relevant for
826 // reporting. This filters out VPN devices. 801 // reporting. This filters out VPN devices.
827 if (type_idx >= arraysize(kDeviceTypeMap)) 802 if (type_idx >= arraysize(kDeviceTypeMap))
828 continue; 803 continue;
829 804
830 em::NetworkInterface* interface = request->add_network_interface(); 805 em::NetworkInterface* interface = status->add_network_interface();
831 interface->set_type(kDeviceTypeMap[type_idx].type_constant); 806 interface->set_type(kDeviceTypeMap[type_idx].type_constant);
832 if (!(*device)->mac_address().empty()) 807 if (!(*device)->mac_address().empty())
833 interface->set_mac_address((*device)->mac_address()); 808 interface->set_mac_address((*device)->mac_address());
834 if (!(*device)->meid().empty()) 809 if (!(*device)->meid().empty())
835 interface->set_meid((*device)->meid()); 810 interface->set_meid((*device)->meid());
836 if (!(*device)->imei().empty()) 811 if (!(*device)->imei().empty())
837 interface->set_imei((*device)->imei()); 812 interface->set_imei((*device)->imei());
838 if (!(*device)->path().empty()) 813 if (!(*device)->path().empty())
839 interface->set_device_path((*device)->path()); 814 interface->set_device_path((*device)->path());
840 anything_reported = true; 815 anything_reported = true;
(...skipping 19 matching lines...) Expand all
860 em::NetworkState::UNKNOWN; 835 em::NetworkState::UNKNOWN;
861 const std::string connection_state_string(state->connection_state()); 836 const std::string connection_state_string(state->connection_state());
862 for (size_t i = 0; i < arraysize(kConnectionStateMap); ++i) { 837 for (size_t i = 0; i < arraysize(kConnectionStateMap); ++i) {
863 if (connection_state_string == kConnectionStateMap[i].state_string) { 838 if (connection_state_string == kConnectionStateMap[i].state_string) {
864 connection_state_enum = kConnectionStateMap[i].state_constant; 839 connection_state_enum = kConnectionStateMap[i].state_constant;
865 break; 840 break;
866 } 841 }
867 } 842 }
868 843
869 // Copy fields from NetworkState into the status report. 844 // Copy fields from NetworkState into the status report.
870 em::NetworkState* proto_state = request->add_network_state(); 845 em::NetworkState* proto_state = status->add_network_state();
871 proto_state->set_connection_state(connection_state_enum); 846 proto_state->set_connection_state(connection_state_enum);
872 anything_reported = true; 847 anything_reported = true;
873 848
874 // Report signal strength for wifi connections. 849 // Report signal strength for wifi connections.
875 if (state->type() == shill::kTypeWifi) { 850 if (state->type() == shill::kTypeWifi) {
876 // If shill has provided a signal strength, convert it to dBm and store it 851 // If shill has provided a signal strength, convert it to dBm and store it
877 // in the status report. A signal_strength() of 0 connotes "no signal" 852 // in the status report. A signal_strength() of 0 connotes "no signal"
878 // rather than "really weak signal", so we only report signal strength if 853 // rather than "really weak signal", so we only report signal strength if
879 // it is non-zero. 854 // it is non-zero.
880 if (state->signal_strength()) { 855 if (state->signal_strength()) {
881 proto_state->set_signal_strength( 856 proto_state->set_signal_strength(
882 ConvertWifiSignalStrength(state->signal_strength())); 857 ConvertWifiSignalStrength(state->signal_strength()));
883 } 858 }
884 } 859 }
885 860
886 if (!state->device_path().empty()) 861 if (!state->device_path().empty())
887 proto_state->set_device_path(state->device_path()); 862 proto_state->set_device_path(state->device_path());
888 863
889 if (!state->ip_address().empty()) 864 if (!state->ip_address().empty())
890 proto_state->set_ip_address(state->ip_address()); 865 proto_state->set_ip_address(state->ip_address());
891 866
892 if (!state->gateway().empty()) 867 if (!state->gateway().empty())
893 proto_state->set_gateway(state->gateway()); 868 proto_state->set_gateway(state->gateway());
894 } 869 }
895 return anything_reported; 870 return anything_reported;
896 } 871 }
897 872
898 bool DeviceStatusCollector::GetUsers(em::DeviceStatusReportRequest* request) { 873 bool DeviceStatusCollector::GetUsers(em::DeviceStatusReportRequest* status) {
899 const user_manager::UserList& users = 874 const user_manager::UserList& users =
900 chromeos::ChromeUserManager::Get()->GetUsers(); 875 chromeos::ChromeUserManager::Get()->GetUsers();
901 876
902 bool anything_reported = false; 877 bool anything_reported = false;
903 for (auto* user : users) { 878 for (auto* user : users) {
904 // Only users with gaia accounts (regular) are reported. 879 // Only users with gaia accounts (regular) are reported.
905 if (!user->HasGaiaAccount()) 880 if (!user->HasGaiaAccount())
906 continue; 881 continue;
907 882
908 em::DeviceUser* device_user = request->add_user(); 883 em::DeviceUser* device_user = status->add_user();
909 if (chromeos::ChromeUserManager::Get()->ShouldReportUser(user->email())) { 884 if (chromeos::ChromeUserManager::Get()->ShouldReportUser(user->email())) {
910 device_user->set_type(em::DeviceUser::USER_TYPE_MANAGED); 885 device_user->set_type(em::DeviceUser::USER_TYPE_MANAGED);
911 device_user->set_email(user->email()); 886 device_user->set_email(user->email());
912 } else { 887 } else {
913 device_user->set_type(em::DeviceUser::USER_TYPE_UNMANAGED); 888 device_user->set_type(em::DeviceUser::USER_TYPE_UNMANAGED);
914 // Do not report the email address of unmanaged users. 889 // Do not report the email address of unmanaged users.
915 } 890 }
916 anything_reported = true; 891 anything_reported = true;
917 } 892 }
918 return anything_reported; 893 return anything_reported;
919 } 894 }
920 895
921 bool DeviceStatusCollector::GetHardwareStatus( 896 bool DeviceStatusCollector::GetHardwareStatus(
922 em::DeviceStatusReportRequest* status) { 897 em::DeviceStatusReportRequest* status,
923 // Add volume info. 898 scoped_refptr<GetStatusState> state) {
924 status->clear_volume_info(); 899 // Sample disk volume info in a background thread.
925 for (const em::VolumeInfo& info : volume_info_) { 900 state->SampleVolumeInfo(volume_info_fetcher_);
926 *status->add_volume_info() = info;
927 }
928 901
902 // Sample CPU temperature in a background thread.
903 state->SampleCPUTempInfo(cpu_temp_fetcher_);
904
905 // Add CPU utilization and free RAM. Note that these stats are sampled in
906 // regular intervals. Unlike CPU temp and volume info these are not one-time
907 // sampled values, hence the difference in logic.
929 status->set_system_ram_total(base::SysInfo::AmountOfPhysicalMemory()); 908 status->set_system_ram_total(base::SysInfo::AmountOfPhysicalMemory());
930 status->clear_system_ram_free(); 909 status->clear_system_ram_free();
931 status->clear_cpu_utilization_pct(); 910 status->clear_cpu_utilization_pct();
932 for (const ResourceUsage& usage : resource_usage_) { 911 for (const ResourceUsage& usage : resource_usage_) {
933 status->add_cpu_utilization_pct(usage.cpu_usage_percent); 912 status->add_cpu_utilization_pct(usage.cpu_usage_percent);
934 status->add_system_ram_free(usage.bytes_of_ram_free); 913 status->add_system_ram_free(usage.bytes_of_ram_free);
935 } 914 }
936
937 // Add CPU temp info.
938 status->clear_cpu_temp_info();
939 for (const em::CPUTempInfo& info : cpu_temp_info_) {
940 *status->add_cpu_temp_info() = info;
941 }
942 return true; 915 return true;
943 } 916 }
944 917
945 bool DeviceStatusCollector::GetOsUpdateStatus( 918 bool DeviceStatusCollector::GetOsUpdateStatus(
946 em::DeviceStatusReportRequest* status) { 919 em::DeviceStatusReportRequest* status) {
947 const base::Version platform_version(GetPlatformVersion()); 920 const base::Version platform_version(GetPlatformVersion());
948 if (!platform_version.IsValid()) 921 if (!platform_version.IsValid())
949 return false; 922 return false;
950 923
951 const std::string required_platform_version_string = 924 const std::string required_platform_version_string =
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
993 em::OsUpdateStatus::OS_IMAGE_DOWNLOAD_NOT_STARTED); 966 em::OsUpdateStatus::OS_IMAGE_DOWNLOAD_NOT_STARTED);
994 } 967 }
995 968
996 return true; 969 return true;
997 } 970 }
998 971
999 bool DeviceStatusCollector::GetRunningKioskApp( 972 bool DeviceStatusCollector::GetRunningKioskApp(
1000 em::DeviceStatusReportRequest* status) { 973 em::DeviceStatusReportRequest* status) {
1001 // Must be on creation thread since some stats are written to in that thread 974 // Must be on creation thread since some stats are written to in that thread
1002 // and accessing them from another thread would lead to race conditions. 975 // and accessing them from another thread would lead to race conditions.
1003 CHECK(content::BrowserThread::CurrentlyOn(creation_thread_)); 976 DCHECK(thread_checker_.CalledOnValidThread());
1004 977
1005 std::unique_ptr<const DeviceLocalAccount> account = 978 std::unique_ptr<const DeviceLocalAccount> account =
1006 GetAutoLaunchedKioskSessionInfo(); 979 GetAutoLaunchedKioskSessionInfo();
1007 // Only generate running kiosk app reports if we are in an auto-launched kiosk 980 // Only generate running kiosk app reports if we are in an auto-launched kiosk
1008 // session. 981 // session.
1009 if (!account) 982 if (!account)
1010 return false; 983 return false;
1011 984
1012 em::AppStatus* running_kiosk_app = status->mutable_running_kiosk_app(); 985 em::AppStatus* running_kiosk_app = status->mutable_running_kiosk_app();
1013 running_kiosk_app->set_app_id(account->kiosk_app_id); 986 running_kiosk_app->set_app_id(account->kiosk_app_id);
1014 987
1015 const std::string app_version = GetAppVersion(account->kiosk_app_id); 988 const std::string app_version = GetAppVersion(account->kiosk_app_id);
1016 if (app_version.empty()) { 989 if (app_version.empty()) {
1017 DLOG(ERROR) << "Unable to get version for extension: " 990 DLOG(ERROR) << "Unable to get version for extension: "
1018 << account->kiosk_app_id; 991 << account->kiosk_app_id;
1019 } else { 992 } else {
1020 running_kiosk_app->set_extension_version(app_version); 993 running_kiosk_app->set_extension_version(app_version);
1021 } 994 }
1022 995
1023 chromeos::KioskAppManager::App app_info; 996 chromeos::KioskAppManager::App app_info;
1024 if (chromeos::KioskAppManager::Get()->GetApp(account->kiosk_app_id, 997 if (chromeos::KioskAppManager::Get()->GetApp(account->kiosk_app_id,
1025 &app_info)) { 998 &app_info)) {
1026 running_kiosk_app->set_required_platform_version( 999 running_kiosk_app->set_required_platform_version(
1027 app_info.required_platform_version); 1000 app_info.required_platform_version);
1028 } 1001 }
1029 return true; 1002 return true;
1030 } 1003 }
1031 1004
1032 void DeviceStatusCollector::GetDeviceStatusAsync( 1005 void DeviceStatusCollector::GetDeviceAndSessionStatusAsync(
1033 const DeviceStatusCallback& response) { 1006 const StatusCallback& response) {
1034 // Must be on creation thread since some stats are written to in that thread 1007 // Must be on creation thread since some stats are written to in that thread
1035 // and accessing them from another thread would lead to race conditions. 1008 // and accessing them from another thread would lead to race conditions.
1036 CHECK(content::BrowserThread::CurrentlyOn(creation_thread_)); 1009 DCHECK(thread_checker_.CalledOnValidThread());
1037 1010
1038 std::unique_ptr<em::DeviceStatusReportRequest> status = 1011 // Some of the data we're collecting is gathered in background threads.
1039 base::MakeUnique<em::DeviceStatusReportRequest>(); 1012 // This object keeps track of the state of each async request.
1040 bool got_status = false; 1013 scoped_refptr<GetStatusState> state(
1014 new GetStatusState(task_runner_, response));
1015
1016 // Gather device status (might queue some async queries)
1017 GetDeviceStatus(state);
1018
1019 // Gather device status (might queue some async queries)
1020 GetSessionStatus(state);
1021
1022 // If there are no outstanding async queries, e.g. from GetHardwareStatus(),
1023 // the destructor of |state| calls |response|. If there are async queries, the
1024 // queries hold references to |state|, so that |state| is only destroyed when
1025 // the last async query has finished.
1026 }
1027
1028 void DeviceStatusCollector::GetDeviceStatus(
1029 scoped_refptr<GetStatusState> state) {
1030 em::DeviceStatusReportRequest* status = state->device_status();
1031 bool anything_reported = false;
1041 1032
1042 if (report_activity_times_) 1033 if (report_activity_times_)
1043 got_status |= GetActivityTimes(status.get()); 1034 anything_reported |= GetActivityTimes(status);
1044 1035
1045 if (report_version_info_) 1036 if (report_version_info_)
1046 got_status |= GetVersionInfo(status.get()); 1037 anything_reported |= GetVersionInfo(status);
1047 1038
1048 if (report_boot_mode_) 1039 if (report_boot_mode_)
1049 got_status |= GetBootMode(status.get()); 1040 anything_reported |= GetBootMode(status);
1050
1051 if (report_location_)
1052 got_status |= GetLocation(status.get());
1053 1041
1054 if (report_network_interfaces_) 1042 if (report_network_interfaces_)
1055 got_status |= GetNetworkInterfaces(status.get()); 1043 anything_reported |= GetNetworkInterfaces(status);
1056 1044
1057 if (report_users_) 1045 if (report_users_)
1058 got_status |= GetUsers(status.get()); 1046 anything_reported |= GetUsers(status);
1059 1047
1060 if (report_hardware_status_) 1048 if (report_hardware_status_)
1061 got_status |= GetHardwareStatus(status.get()); 1049 anything_reported |= GetHardwareStatus(status, state);
1062 1050
1063 if (report_os_update_status_) 1051 if (report_os_update_status_)
1064 got_status |= GetOsUpdateStatus(status.get()); 1052 anything_reported |= GetOsUpdateStatus(status);
1065 1053
1066 if (report_running_kiosk_app_) 1054 if (report_running_kiosk_app_)
1067 got_status |= GetRunningKioskApp(status.get()); 1055 anything_reported |= GetRunningKioskApp(status);
1068 1056
1069 // Wipe pointer if we didn't actually add any data. 1057 // Wipe pointer if we didn't actually add any data.
1070 if (!got_status) 1058 if (!anything_reported)
1071 status.reset(); 1059 state->ResetDeviceStatus();
1072
1073 content::BrowserThread::PostTask(creation_thread_, FROM_HERE,
1074 base::Bind(response, base::Passed(&status)));
1075 } 1060 }
1076 1061
1077 void DeviceStatusCollector::GetDeviceSessionStatusAsync( 1062 void DeviceStatusCollector::GetSessionStatus(
1078 const DeviceSessionStatusCallback& response) { 1063 scoped_refptr<GetStatusState> state) {
1079 // Only generate session status reports if session status reporting is 1064 em::SessionStatusReportRequest* status = state->session_status();
1080 // enabled. 1065 bool anything_reported = false;
1081 if (!report_session_status_) {
1082 content::BrowserThread::PostTask(creation_thread_, FROM_HERE,
1083 base::Bind(response, nullptr));
1084 return;
1085 }
1086 1066
1067 if (report_session_status_)
1068 anything_reported |= GetAccountStatus(status);
1069
1070 // Wipe pointer if we didn't actually add any data.
1071 if (!anything_reported)
1072 state->ResetSessionStatus();
1073 }
1074
1075 bool DeviceStatusCollector::GetAccountStatus(
1076 em::SessionStatusReportRequest* status) {
1087 std::unique_ptr<const DeviceLocalAccount> account = 1077 std::unique_ptr<const DeviceLocalAccount> account =
1088 GetAutoLaunchedKioskSessionInfo(); 1078 GetAutoLaunchedKioskSessionInfo();
1089 // Only generate session status reports if we are in an auto-launched kiosk 1079 if (!account)
1090 // session. 1080 return false;
1091 if (!account) {
1092 content::BrowserThread::PostTask(creation_thread_, FROM_HERE,
1093 base::Bind(response, nullptr));
1094 return;
1095 }
1096
1097 std::unique_ptr<em::SessionStatusReportRequest> status =
1098 base::MakeUnique<em::SessionStatusReportRequest>();
1099 1081
1100 // Get the account ID associated with this user. 1082 // Get the account ID associated with this user.
1101 status->set_device_local_account_id(account->account_id); 1083 status->set_device_local_account_id(account->account_id);
1102 em::AppStatus* app_status = status->add_installed_apps(); 1084 em::AppStatus* app_status = status->add_installed_apps();
1103 app_status->set_app_id(account->kiosk_app_id); 1085 app_status->set_app_id(account->kiosk_app_id);
1104 1086
1105 // Look up the app and get the version. 1087 // Look up the app and get the version.
1106 const std::string app_version = GetAppVersion(account->kiosk_app_id); 1088 const std::string app_version = GetAppVersion(account->kiosk_app_id);
1107 if (app_version.empty()) { 1089 if (app_version.empty()) {
1108 DLOG(ERROR) << "Unable to get version for extension: " 1090 DLOG(ERROR) << "Unable to get version for extension: "
1109 << account->kiosk_app_id; 1091 << account->kiosk_app_id;
1110 } else { 1092 } else {
1111 app_status->set_extension_version(app_version); 1093 app_status->set_extension_version(app_version);
1112 } 1094 }
1113 1095
1114 content::BrowserThread::PostTask(creation_thread_, FROM_HERE, 1096 return true;
1115 base::Bind(response, base::Passed(&status)));
1116 } 1097 }
1117 1098
1118 std::string DeviceStatusCollector::GetAppVersion( 1099 std::string DeviceStatusCollector::GetAppVersion(
1119 const std::string& kiosk_app_id) { 1100 const std::string& kiosk_app_id) {
1120 Profile* const profile = 1101 Profile* const profile =
1121 chromeos::ProfileHelper::Get()->GetProfileByUser( 1102 chromeos::ProfileHelper::Get()->GetProfileByUser(
1122 user_manager::UserManager::Get()->GetActiveUser()); 1103 user_manager::UserManager::Get()->GetActiveUser());
1123 const extensions::ExtensionRegistry* const registry = 1104 const extensions::ExtensionRegistry* const registry =
1124 extensions::ExtensionRegistry::Get(profile); 1105 extensions::ExtensionRegistry::Get(profile);
1125 const extensions::Extension* const extension = registry->GetExtensionById( 1106 const extensions::Extension* const extension = registry->GetExtensionById(
1126 kiosk_app_id, extensions::ExtensionRegistry::EVERYTHING); 1107 kiosk_app_id, extensions::ExtensionRegistry::EVERYTHING);
1127 if (!extension) 1108 if (!extension)
1128 return std::string(); 1109 return std::string();
1129 return extension->VersionString(); 1110 return extension->VersionString();
1130 } 1111 }
1131 1112
1132 void DeviceStatusCollector::OnSubmittedSuccessfully() { 1113 void DeviceStatusCollector::OnSubmittedSuccessfully() {
1133 TrimStoredActivityPeriods(last_reported_day_, duration_for_last_reported_day_, 1114 TrimStoredActivityPeriods(last_reported_day_, duration_for_last_reported_day_,
1134 std::numeric_limits<int64_t>::max()); 1115 std::numeric_limits<int64_t>::max());
1135 } 1116 }
1136 1117
1137 void DeviceStatusCollector::OnOSVersion(const std::string& version) { 1118 void DeviceStatusCollector::OnOSVersion(const std::string& version) {
1138 os_version_ = version; 1119 os_version_ = version;
1139 } 1120 }
1140 1121
1141 void DeviceStatusCollector::OnOSFirmware(const std::string& version) { 1122 void DeviceStatusCollector::OnOSFirmware(const std::string& version) {
1142 firmware_version_ = version; 1123 firmware_version_ = version;
1143 } 1124 }
1144 1125
1145 void DeviceStatusCollector::ScheduleGeolocationUpdateRequest() {
1146 if (geolocation_update_timer_.IsRunning() || geolocation_update_in_progress_)
1147 return;
1148
1149 if (position_.Validate()) {
1150 TimeDelta elapsed = GetCurrentTime() - position_.timestamp;
1151 TimeDelta interval =
1152 TimeDelta::FromSeconds(kGeolocationPollIntervalSeconds);
1153 if (elapsed <= interval) {
1154 geolocation_update_timer_.Start(
1155 FROM_HERE,
1156 interval - elapsed,
1157 this,
1158 &DeviceStatusCollector::ScheduleGeolocationUpdateRequest);
1159 return;
1160 }
1161 }
1162
1163 geolocation_update_in_progress_ = true;
1164 if (location_update_requester_.is_null()) {
1165 geolocation_subscription_ =
1166 device::GeolocationProvider::GetInstance()->AddLocationUpdateCallback(
1167 base::Bind(&DeviceStatusCollector::ReceiveGeolocationUpdate,
1168 weak_factory_.GetWeakPtr()),
1169 true);
1170 } else {
1171 location_update_requester_.Run(base::Bind(
1172 &DeviceStatusCollector::ReceiveGeolocationUpdate,
1173 weak_factory_.GetWeakPtr()));
1174 }
1175 }
1176
1177 void DeviceStatusCollector::ReceiveGeolocationUpdate(
1178 const device::Geoposition& position) {
1179 geolocation_update_in_progress_ = false;
1180
1181 // Ignore update if device location reporting has since been disabled.
1182 if (!report_location_)
1183 return;
1184
1185 if (position.Validate()) {
1186 position_ = position;
1187 base::DictionaryValue location;
1188 location.SetDouble(kLatitude, position.latitude);
1189 location.SetDouble(kLongitude, position.longitude);
1190 location.SetDouble(kAltitude, position.altitude);
1191 location.SetDouble(kAccuracy, position.accuracy);
1192 location.SetDouble(kAltitudeAccuracy, position.altitude_accuracy);
1193 location.SetDouble(kHeading, position.heading);
1194 location.SetDouble(kSpeed, position.speed);
1195 location.SetString(kTimestamp,
1196 base::Int64ToString(position.timestamp.ToInternalValue()));
1197 local_state_->Set(prefs::kDeviceLocation, location);
1198 }
1199
1200 ScheduleGeolocationUpdateRequest();
1201 }
1202
1203 void DeviceStatusCollector::ReceiveVolumeInfo(
1204 const std::vector<em::VolumeInfo>& info) {
1205 if (report_hardware_status_)
1206 volume_info_ = info;
1207 }
1208
1209 } // namespace policy 1126 } // namespace policy
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698