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

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

Issue 12189011: Split up chrome/browser/policy subdirectory (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Rebase. Created 7 years, 10 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 | Annotate | Revision Log
OLDNEW
(Empty)
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.
4
5 #include "chrome/browser/policy/device_status_collector.h"
6
7 #include <limits>
8
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/location.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/string_number_conversions.h"
15 #include "base/values.h"
16 #include "chrome/browser/chromeos/settings/cros_settings.h"
17 #include "chrome/browser/chromeos/settings/cros_settings_names.h"
18 #include "chrome/browser/chromeos/system/statistics_provider.h"
19 #include "chrome/browser/policy/proto/device_management_backend.pb.h"
20 #include "chrome/browser/prefs/pref_service.h"
21 #include "chrome/browser/prefs/scoped_user_pref_update.h"
22 #include "chrome/common/chrome_notification_types.h"
23 #include "chrome/common/chrome_version_info.h"
24 #include "chrome/common/pref_names.h"
25 #include "content/public/browser/notification_details.h"
26 #include "content/public/browser/notification_source.h"
27
28 using base::Time;
29 using base::TimeDelta;
30 using chromeos::VersionLoader;
31
32 namespace em = enterprise_management;
33
34 namespace {
35 // How many seconds of inactivity triggers the idle state.
36 const int kIdleStateThresholdSeconds = 300;
37
38 // How many days in the past to store active periods for.
39 const unsigned int kMaxStoredPastActivityDays = 30;
40
41 // How many days in the future to store active periods for.
42 const unsigned int kMaxStoredFutureActivityDays = 2;
43
44 // How often, in seconds, to update the device location.
45 const unsigned int kGeolocationPollIntervalSeconds = 30 * 60;
46
47 const int64 kMillisecondsPerDay = Time::kMicrosecondsPerDay / 1000;
48
49 const char kLatitude[] = "latitude";
50
51 const char kLongitude[] = "longitude";
52
53 const char kAltitude[] = "altitude";
54
55 const char kAccuracy[] = "accuracy";
56
57 const char kAltitudeAccuracy[] = "altitude_accuracy";
58
59 const char kHeading[] = "heading";
60
61 const char kSpeed[] = "speed";
62
63 const char kTimestamp[] = "timestamp";
64
65 // Determine the day key (milliseconds since epoch for corresponding day in UTC)
66 // for a given |timestamp|.
67 int64 TimestampToDayKey(Time timestamp) {
68 Time::Exploded exploded;
69 timestamp.LocalMidnight().LocalExplode(&exploded);
70 return (Time::FromUTCExploded(exploded) - Time::UnixEpoch()).InMilliseconds();
71 }
72
73 } // namespace
74
75 namespace policy {
76
77 DeviceStatusCollector::DeviceStatusCollector(
78 PrefService* local_state,
79 chromeos::system::StatisticsProvider* provider,
80 LocationUpdateRequester location_update_requester)
81 : max_stored_past_activity_days_(kMaxStoredPastActivityDays),
82 max_stored_future_activity_days_(kMaxStoredFutureActivityDays),
83 local_state_(local_state),
84 last_idle_check_(Time()),
85 last_reported_day_(0),
86 duration_for_last_reported_day_(0),
87 geolocation_update_in_progress_(false),
88 statistics_provider_(provider),
89 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
90 location_update_requester_(location_update_requester),
91 report_version_info_(false),
92 report_activity_times_(false),
93 report_boot_mode_(false),
94 report_location_(false) {
95 if (!location_update_requester_)
96 location_update_requester_ = &content::RequestLocationUpdate;
97 idle_poll_timer_.Start(FROM_HERE,
98 TimeDelta::FromSeconds(kIdlePollIntervalSeconds),
99 this, &DeviceStatusCollector::CheckIdleState);
100
101 cros_settings_ = chromeos::CrosSettings::Get();
102
103 // Watch for changes to the individual policies that control what the status
104 // reports contain.
105 cros_settings_->AddSettingsObserver(chromeos::kReportDeviceVersionInfo, this);
106 cros_settings_->AddSettingsObserver(chromeos::kReportDeviceActivityTimes,
107 this);
108 cros_settings_->AddSettingsObserver(chromeos::kReportDeviceBootMode, this);
109 cros_settings_->AddSettingsObserver(chromeos::kReportDeviceLocation, this);
110
111 // The last known location is persisted in local state. This makes location
112 // information available immediately upon startup and avoids the need to
113 // reacquire the location on every user session change or browser crash.
114 content::Geoposition position;
115 std::string timestamp_str;
116 int64 timestamp;
117 const base::DictionaryValue* location =
118 local_state_->GetDictionary(prefs::kDeviceLocation);
119 if (location->GetDouble(kLatitude, &position.latitude) &&
120 location->GetDouble(kLongitude, &position.longitude) &&
121 location->GetDouble(kAltitude, &position.altitude) &&
122 location->GetDouble(kAccuracy, &position.accuracy) &&
123 location->GetDouble(kAltitudeAccuracy, &position.altitude_accuracy) &&
124 location->GetDouble(kHeading, &position.heading) &&
125 location->GetDouble(kSpeed, &position.speed) &&
126 location->GetString(kTimestamp, &timestamp_str) &&
127 base::StringToInt64(timestamp_str, &timestamp)) {
128 position.timestamp = Time::FromInternalValue(timestamp);
129 position_ = position;
130 }
131
132 // Fetch the current values of the policies.
133 UpdateReportingSettings();
134
135 // Get the the OS and firmware version info.
136 version_loader_.GetVersion(
137 VersionLoader::VERSION_FULL,
138 base::Bind(&DeviceStatusCollector::OnOSVersion, base::Unretained(this)),
139 &tracker_);
140 version_loader_.GetFirmware(
141 base::Bind(&DeviceStatusCollector::OnOSFirmware, base::Unretained(this)),
142 &tracker_);
143 }
144
145 DeviceStatusCollector::~DeviceStatusCollector() {
146 cros_settings_->RemoveSettingsObserver(chromeos::kReportDeviceVersionInfo,
147 this);
148 cros_settings_->RemoveSettingsObserver(chromeos::kReportDeviceActivityTimes,
149 this);
150 cros_settings_->RemoveSettingsObserver(chromeos::kReportDeviceBootMode, this);
151 cros_settings_->RemoveSettingsObserver(chromeos::kReportDeviceLocation, this);
152 }
153
154 // static
155 void DeviceStatusCollector::RegisterPrefs(PrefServiceSimple* local_state) {
156 local_state->RegisterDictionaryPref(prefs::kDeviceActivityTimes,
157 new base::DictionaryValue);
158 local_state->RegisterDictionaryPref(prefs::kDeviceLocation,
159 new base::DictionaryValue);
160 }
161
162 void DeviceStatusCollector::CheckIdleState() {
163 CalculateIdleState(kIdleStateThresholdSeconds,
164 base::Bind(&DeviceStatusCollector::IdleStateCallback,
165 base::Unretained(this)));
166 }
167
168 void DeviceStatusCollector::UpdateReportingSettings() {
169 // Attempt to fetch the current value of the reporting settings.
170 // If trusted values are not available, register this function to be called
171 // back when they are available.
172 if (chromeos::CrosSettingsProvider::TRUSTED !=
173 cros_settings_->PrepareTrustedValues(
174 base::Bind(&DeviceStatusCollector::UpdateReportingSettings,
175 weak_factory_.GetWeakPtr()))) {
176 return;
177 }
178 cros_settings_->GetBoolean(
179 chromeos::kReportDeviceVersionInfo, &report_version_info_);
180 cros_settings_->GetBoolean(
181 chromeos::kReportDeviceActivityTimes, &report_activity_times_);
182 cros_settings_->GetBoolean(
183 chromeos::kReportDeviceBootMode, &report_boot_mode_);
184 cros_settings_->GetBoolean(
185 chromeos::kReportDeviceLocation, &report_location_);
186
187 if (report_location_) {
188 ScheduleGeolocationUpdateRequest();
189 } else {
190 geolocation_update_timer_.Stop();
191 position_ = content::Geoposition();
192 local_state_->ClearPref(prefs::kDeviceLocation);
193 }
194 }
195
196 Time DeviceStatusCollector::GetCurrentTime() {
197 return Time::Now();
198 }
199
200 // Remove all out-of-range activity times from the local store.
201 void DeviceStatusCollector::PruneStoredActivityPeriods(Time base_time) {
202 Time min_time =
203 base_time - TimeDelta::FromDays(max_stored_past_activity_days_);
204 Time max_time =
205 base_time + TimeDelta::FromDays(max_stored_future_activity_days_);
206 TrimStoredActivityPeriods(TimestampToDayKey(min_time), 0,
207 TimestampToDayKey(max_time));
208 }
209
210 void DeviceStatusCollector::TrimStoredActivityPeriods(int64 min_day_key,
211 int min_day_trim_duration,
212 int64 max_day_key) {
213 const base::DictionaryValue* activity_times =
214 local_state_->GetDictionary(prefs::kDeviceActivityTimes);
215
216 scoped_ptr<base::DictionaryValue> copy(activity_times->DeepCopy());
217 for (base::DictionaryValue::Iterator it(*activity_times); it.HasNext();
218 it.Advance()) {
219 int64 timestamp;
220 if (base::StringToInt64(it.key(), &timestamp)) {
221 // Remove data that is too old, or too far in the future.
222 if (timestamp >= min_day_key && timestamp < max_day_key) {
223 if (timestamp == min_day_key) {
224 int new_activity_duration = 0;
225 if (it.value().GetAsInteger(&new_activity_duration)) {
226 new_activity_duration =
227 std::max(new_activity_duration - min_day_trim_duration, 0);
228 }
229 copy->SetInteger(it.key(), new_activity_duration);
230 }
231 continue;
232 }
233 }
234 // The entry is out of range or couldn't be parsed. Remove it.
235 copy->Remove(it.key(), NULL);
236 }
237 local_state_->Set(prefs::kDeviceActivityTimes, *copy);
238 }
239
240 void DeviceStatusCollector::AddActivePeriod(Time start, Time end) {
241 DCHECK(start < end);
242
243 // Maintain the list of active periods in a local_state pref.
244 DictionaryPrefUpdate update(local_state_, prefs::kDeviceActivityTimes);
245 base::DictionaryValue* activity_times = update.Get();
246
247 // Assign the period to day buckets in local time.
248 Time midnight = start.LocalMidnight();
249 while (midnight < end) {
250 midnight += TimeDelta::FromDays(1);
251 int64 activity = (std::min(end, midnight) - start).InMilliseconds();
252 std::string day_key = base::Int64ToString(TimestampToDayKey(start));
253 int previous_activity = 0;
254 activity_times->GetInteger(day_key, &previous_activity);
255 activity_times->SetInteger(day_key, previous_activity + activity);
256 start = midnight;
257 }
258 }
259
260 void DeviceStatusCollector::IdleStateCallback(IdleState state) {
261 // Do nothing if device activity reporting is disabled.
262 if (!report_activity_times_)
263 return;
264
265 Time now = GetCurrentTime();
266
267 if (state == IDLE_STATE_ACTIVE) {
268 // If it's been too long since the last report, or if the activity is
269 // negative (which can happen when the clock changes), assume a single
270 // interval of activity.
271 int active_seconds = (now - last_idle_check_).InSeconds();
272 if (active_seconds < 0 ||
273 active_seconds >= static_cast<int>((2 * kIdlePollIntervalSeconds))) {
274 AddActivePeriod(now - TimeDelta::FromSeconds(kIdlePollIntervalSeconds),
275 now);
276 } else {
277 AddActivePeriod(last_idle_check_, now);
278 }
279
280 PruneStoredActivityPeriods(now);
281 }
282 last_idle_check_ = now;
283 }
284
285 void DeviceStatusCollector::GetActivityTimes(
286 em::DeviceStatusReportRequest* request) {
287 DictionaryPrefUpdate update(local_state_, prefs::kDeviceActivityTimes);
288 base::DictionaryValue* activity_times = update.Get();
289
290 for (base::DictionaryValue::key_iterator it = activity_times->begin_keys();
291 it != activity_times->end_keys(); ++it) {
292 int64 start_timestamp;
293 int activity_milliseconds;
294 if (base::StringToInt64(*it, &start_timestamp) &&
295 activity_times->GetInteger(*it, &activity_milliseconds)) {
296 // This is correct even when there are leap seconds, because when a leap
297 // second occurs, two consecutive seconds have the same timestamp.
298 int64 end_timestamp = start_timestamp + kMillisecondsPerDay;
299
300 em::ActiveTimePeriod* active_period = request->add_active_period();
301 em::TimePeriod* period = active_period->mutable_time_period();
302 period->set_start_timestamp(start_timestamp);
303 period->set_end_timestamp(end_timestamp);
304 active_period->set_active_duration(activity_milliseconds);
305 if (start_timestamp >= last_reported_day_) {
306 last_reported_day_ = start_timestamp;
307 duration_for_last_reported_day_ = activity_milliseconds;
308 }
309 } else {
310 NOTREACHED();
311 }
312 }
313 }
314
315 void DeviceStatusCollector::GetVersionInfo(
316 em::DeviceStatusReportRequest* request) {
317 chrome::VersionInfo version_info;
318 request->set_browser_version(version_info.Version());
319 request->set_os_version(os_version_);
320 request->set_firmware_version(firmware_version_);
321 }
322
323 void DeviceStatusCollector::GetBootMode(
324 em::DeviceStatusReportRequest* request) {
325 std::string dev_switch_mode;
326 if (statistics_provider_->GetMachineStatistic(
327 "devsw_boot", &dev_switch_mode)) {
328 if (dev_switch_mode == "1")
329 request->set_boot_mode("Dev");
330 else if (dev_switch_mode == "0")
331 request->set_boot_mode("Verified");
332 }
333 }
334
335 void DeviceStatusCollector::GetLocation(
336 em::DeviceStatusReportRequest* request) {
337 em::DeviceLocation* location = request->mutable_device_location();
338 if (!position_.Validate()) {
339 location->set_error_code(
340 em::DeviceLocation::ERROR_CODE_POSITION_UNAVAILABLE);
341 location->set_error_message(position_.error_message);
342 } else {
343 location->set_latitude(position_.latitude);
344 location->set_longitude(position_.longitude);
345 location->set_accuracy(position_.accuracy);
346 location->set_timestamp(
347 (position_.timestamp - Time::UnixEpoch()).InMilliseconds());
348 // Lowest point on land is at approximately -400 meters.
349 if (position_.altitude > -10000.)
350 location->set_altitude(position_.altitude);
351 if (position_.altitude_accuracy >= 0.)
352 location->set_altitude_accuracy(position_.altitude_accuracy);
353 if (position_.heading >= 0. && position_.heading <= 360)
354 location->set_heading(position_.heading);
355 if (position_.speed >= 0.)
356 location->set_speed(position_.speed);
357 location->set_error_code(em::DeviceLocation::ERROR_CODE_NONE);
358 }
359 }
360
361 void DeviceStatusCollector::GetStatus(em::DeviceStatusReportRequest* request) {
362 // TODO(mnissler): Remove once the old cloud policy stack is retired. The old
363 // stack doesn't support reporting successful submissions back to here, so
364 // just assume whatever ends up in |request| gets submitted successfully.
365 GetDeviceStatus(request);
366 OnSubmittedSuccessfully();
367 }
368
369 bool DeviceStatusCollector::GetDeviceStatus(
370 em::DeviceStatusReportRequest* status) {
371 if (report_activity_times_)
372 GetActivityTimes(status);
373
374 if (report_version_info_)
375 GetVersionInfo(status);
376
377 if (report_boot_mode_)
378 GetBootMode(status);
379
380 if (report_location_)
381 GetLocation(status);
382
383 return true;
384 }
385
386 bool DeviceStatusCollector::GetSessionStatus(
387 em::SessionStatusReportRequest* status) {
388 return false;
389 }
390
391 void DeviceStatusCollector::OnSubmittedSuccessfully() {
392 TrimStoredActivityPeriods(last_reported_day_, duration_for_last_reported_day_,
393 std::numeric_limits<int64>::max());
394 }
395
396 void DeviceStatusCollector::OnOSVersion(const std::string& version) {
397 os_version_ = version;
398 }
399
400 void DeviceStatusCollector::OnOSFirmware(const std::string& version) {
401 firmware_version_ = version;
402 }
403
404 void DeviceStatusCollector::Observe(
405 int type,
406 const content::NotificationSource& source,
407 const content::NotificationDetails& details) {
408 if (type == chrome::NOTIFICATION_SYSTEM_SETTING_CHANGED)
409 UpdateReportingSettings();
410 else
411 NOTREACHED();
412 }
413
414 void DeviceStatusCollector::ScheduleGeolocationUpdateRequest() {
415 if (geolocation_update_timer_.IsRunning() || geolocation_update_in_progress_)
416 return;
417
418 if (position_.Validate()) {
419 TimeDelta elapsed = GetCurrentTime() - position_.timestamp;
420 TimeDelta interval =
421 TimeDelta::FromSeconds(kGeolocationPollIntervalSeconds);
422 if (elapsed > interval) {
423 geolocation_update_in_progress_ = true;
424 location_update_requester_(base::Bind(
425 &DeviceStatusCollector::ReceiveGeolocationUpdate,
426 weak_factory_.GetWeakPtr()));
427 } else {
428 geolocation_update_timer_.Start(
429 FROM_HERE,
430 interval - elapsed,
431 this,
432 &DeviceStatusCollector::ScheduleGeolocationUpdateRequest);
433 }
434 } else {
435 geolocation_update_in_progress_ = true;
436 location_update_requester_(base::Bind(
437 &DeviceStatusCollector::ReceiveGeolocationUpdate,
438 weak_factory_.GetWeakPtr()));
439
440 }
441 }
442
443 void DeviceStatusCollector::ReceiveGeolocationUpdate(
444 const content::Geoposition& position) {
445 geolocation_update_in_progress_ = false;
446
447 // Ignore update if device location reporting has since been disabled.
448 if (!report_location_)
449 return;
450
451 if (position.Validate()) {
452 position_ = position;
453 base::DictionaryValue location;
454 location.SetDouble(kLatitude, position.latitude);
455 location.SetDouble(kLongitude, position.longitude);
456 location.SetDouble(kAltitude, position.altitude);
457 location.SetDouble(kAccuracy, position.accuracy);
458 location.SetDouble(kAltitudeAccuracy, position.altitude_accuracy);
459 location.SetDouble(kHeading, position.heading);
460 location.SetDouble(kSpeed, position.speed);
461 location.SetString(kTimestamp,
462 base::Int64ToString(position.timestamp.ToInternalValue()));
463 local_state_->Set(prefs::kDeviceLocation, location);
464 }
465
466 ScheduleGeolocationUpdateRequest();
467 }
468
469 } // namespace policy
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698