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

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

Issue 6312121: Add initial device policy infrastructure. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: fix race condition and tests. Created 9 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) 2011 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_management_policy_provider.h"
6
7 #include "base/command_line.h"
8 #include "base/file_util.h"
9 #include "base/path_service.h"
10 #include "base/rand_util.h"
11 #include "base/task.h"
12 #include "chrome/browser/browser_thread.h"
13 #include "chrome/browser/policy/device_management_backend.h"
14 #include "chrome/browser/policy/device_management_policy_cache.h"
15 #include "chrome/browser/policy/profile_policy_context.h"
16 #include "chrome/browser/policy/proto/device_management_constants.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "chrome/common/chrome_paths.h"
19 #include "chrome/common/chrome_switches.h"
20 #include "chrome/common/notification_service.h"
21 #include "chrome/common/notification_type.h"
22
23 namespace policy {
24
25 namespace em = enterprise_management;
26
27 // The maximum ratio in percent of the policy refresh rate we use for adjusting
28 // the policy refresh time instant. The rationale is to avoid load spikes from
29 // many devices that were set up in sync for some reason.
30 const int kPolicyRefreshDeviationFactorPercent = 10;
31 // Maximum deviation we are willing to accept.
32 const int64 kPolicyRefreshDeviationMaxInMilliseconds = 30 * 60 * 1000;
33
34 // These are the base values for delays before retrying after an error. They
35 // will be doubled each time they are used.
36 const int64 kPolicyRefreshErrorDelayInMilliseconds = 3 * 1000; // 3 seconds
37 const int64 kDeviceTokenRefreshErrorDelayInMilliseconds = 3 * 1000;
38 // For unmanaged devices, check once per day whether they're still unmanaged.
39 const int64 kPolicyRefreshUnmanagedDeviceInMilliseconds = 24 * 60 * 60 * 1000;
40
41 const FilePath::StringType kDeviceTokenFilename = FILE_PATH_LITERAL("Token");
42 const FilePath::StringType kPolicyFilename = FILE_PATH_LITERAL("Policy");
43
44 // Calls back into the provider to refresh policy.
45 class DeviceManagementPolicyProvider::RefreshTask : public CancelableTask {
46 public:
47 explicit RefreshTask(DeviceManagementPolicyProvider* provider)
48 : provider_(provider) {}
49
50 // Task implementation:
51 virtual void Run() {
52 if (provider_)
53 provider_->RefreshTaskExecute();
54 }
55
56 // CancelableTask implementation:
57 virtual void Cancel() {
58 provider_ = NULL;
59 }
60
61 private:
62 DeviceManagementPolicyProvider* provider_;
63 };
64
65 DeviceManagementPolicyProvider::DeviceManagementPolicyProvider(
66 const ConfigurationPolicyProvider::PolicyDefinitionList* policy_list,
67 DeviceManagementBackend* backend,
68 Profile* profile)
69 : ConfigurationPolicyProvider(policy_list) {
70 Initialize(backend,
71 profile,
72 ProfilePolicyContext::kDefaultPolicyRefreshRateInMilliseconds,
73 kPolicyRefreshDeviationFactorPercent,
74 kPolicyRefreshDeviationMaxInMilliseconds,
75 kPolicyRefreshErrorDelayInMilliseconds,
76 kDeviceTokenRefreshErrorDelayInMilliseconds,
77 kPolicyRefreshUnmanagedDeviceInMilliseconds);
78 }
79
80 DeviceManagementPolicyProvider::~DeviceManagementPolicyProvider() {
81 FOR_EACH_OBSERVER(ConfigurationPolicyProvider::Observer,
82 observer_list_,
83 OnProviderGoingAway());
84 CancelRefreshTask();
85 }
86
87 bool DeviceManagementPolicyProvider::Provide(
88 ConfigurationPolicyStoreInterface* policy_store) {
89 scoped_ptr<DictionaryValue> policies(cache_->GetPolicy());
90 DecodePolicyValueTree(policies.get(), policy_store);
91 return true;
92 }
93
94 bool DeviceManagementPolicyProvider::IsInitializationComplete() const {
95 return !cache_->last_policy_refresh_time().is_null();
96 }
97
98 void DeviceManagementPolicyProvider::HandlePolicyResponse(
99 const em::DevicePolicyResponse& response) {
100 DCHECK(TokenAvailable());
101 if (cache_->SetPolicy(response)) {
102 initial_fetch_done_ = true;
103 NotifyCloudPolicyUpdate();
104 }
105 SetState(STATE_POLICY_VALID);
106 }
107
108 void DeviceManagementPolicyProvider::OnError(
109 DeviceManagementBackend::ErrorCode code) {
110 DCHECK(TokenAvailable());
111 if (code == DeviceManagementBackend::kErrorServiceDeviceNotFound ||
112 code == DeviceManagementBackend::kErrorServiceManagementTokenInvalid) {
113 LOG(WARNING) << "The device token was either invalid or unknown to the "
114 << "device manager, re-registering device.";
115 SetState(STATE_TOKEN_RESET);
116 } else if (code ==
117 DeviceManagementBackend::kErrorServiceManagementNotSupported) {
118 VLOG(1) << "The device is no longer managed, resetting device token.";
119 SetState(STATE_TOKEN_RESET);
120 } else {
121 LOG(WARNING) << "Could not provide policy from the device manager (error = "
122 << code << "), will retry in "
123 << (effective_policy_refresh_error_delay_ms_ / 1000)
124 << " seconds.";
125 SetState(STATE_POLICY_ERROR);
126 }
127 }
128
129 void DeviceManagementPolicyProvider::OnTokenSuccess() {
130 DCHECK(!TokenAvailable());
131 SetState(STATE_TOKEN_VALID);
132 }
133
134 void DeviceManagementPolicyProvider::OnTokenError() {
135 DCHECK(!TokenAvailable());
136 LOG(WARNING) << "Could not retrieve device token.";
137 SetState(STATE_TOKEN_ERROR);
138 }
139
140 void DeviceManagementPolicyProvider::OnNotManaged() {
141 DCHECK(!TokenAvailable());
142 VLOG(1) << "This device is not managed.";
143 cache_->SetDeviceUnmanaged();
144 SetState(STATE_UNMANAGED);
145 }
146
147 void DeviceManagementPolicyProvider::SetRefreshRate(
148 int64 refresh_rate_milliseconds) {
149 policy_refresh_rate_ms_ = refresh_rate_milliseconds;
150
151 // Reschedule the refresh task if necessary.
152 if (state_ == STATE_POLICY_VALID)
153 SetState(STATE_POLICY_VALID);
154 }
155
156 DeviceManagementPolicyProvider::DeviceManagementPolicyProvider(
157 const PolicyDefinitionList* policy_list,
158 DeviceManagementBackend* backend,
159 Profile* profile,
160 int64 policy_refresh_rate_ms,
161 int policy_refresh_deviation_factor_percent,
162 int64 policy_refresh_deviation_max_ms,
163 int64 policy_refresh_error_delay_ms,
164 int64 token_fetch_error_delay_ms,
165 int64 unmanaged_device_refresh_rate_ms)
166 : ConfigurationPolicyProvider(policy_list) {
167 Initialize(backend,
168 profile,
169 policy_refresh_rate_ms,
170 policy_refresh_deviation_factor_percent,
171 policy_refresh_deviation_max_ms,
172 policy_refresh_error_delay_ms,
173 token_fetch_error_delay_ms,
174 unmanaged_device_refresh_rate_ms);
175 }
176
177 void DeviceManagementPolicyProvider::Initialize(
178 DeviceManagementBackend* backend,
179 Profile* profile,
180 int64 policy_refresh_rate_ms,
181 int policy_refresh_deviation_factor_percent,
182 int64 policy_refresh_deviation_max_ms,
183 int64 policy_refresh_error_delay_ms,
184 int64 token_fetch_error_delay_ms,
185 int64 unmanaged_device_refresh_rate_ms) {
186 DCHECK(profile);
187 backend_.reset(backend);
188 profile_ = profile;
189 storage_dir_ = GetOrCreateDeviceManagementDir(profile_->GetPath());
190 state_ = STATE_INITIALIZING;
191 initial_fetch_done_ = false;
192 refresh_task_ = NULL;
193 policy_refresh_rate_ms_ = policy_refresh_rate_ms;
194 policy_refresh_deviation_factor_percent_ =
195 policy_refresh_deviation_factor_percent;
196 policy_refresh_deviation_max_ms_ = policy_refresh_deviation_max_ms;
197 policy_refresh_error_delay_ms_ = policy_refresh_error_delay_ms;
198 effective_policy_refresh_error_delay_ms_ = policy_refresh_error_delay_ms;
199 token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;
200 effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;
201 unmanaged_device_refresh_rate_ms_ = unmanaged_device_refresh_rate_ms;
202
203 const FilePath policy_path = storage_dir_.Append(kPolicyFilename);
204 cache_.reset(new DeviceManagementPolicyCache(policy_path));
205 cache_->LoadPolicyFromFile();
206
207 SetDeviceTokenFetcher(new DeviceTokenFetcher(backend_.get(), profile,
208 GetTokenPath()));
209
210 if (cache_->is_device_unmanaged()) {
211 // This is a non-first login on an unmanaged device.
212 SetState(STATE_UNMANAGED);
213 } else {
214 SetState(STATE_INITIALIZING);
215 }
216 }
217
218 void DeviceManagementPolicyProvider::AddObserver(
219 ConfigurationPolicyProvider::Observer* observer) {
220 observer_list_.AddObserver(observer);
221 }
222
223 void DeviceManagementPolicyProvider::RemoveObserver(
224 ConfigurationPolicyProvider::Observer* observer) {
225 observer_list_.RemoveObserver(observer);
226 }
227
228 void DeviceManagementPolicyProvider::SendPolicyRequest() {
229 em::DevicePolicyRequest policy_request;
230 policy_request.set_policy_scope(kChromePolicyScope);
231 em::DevicePolicySettingRequest* setting =
232 policy_request.add_setting_request();
233 setting->set_key(kChromeDevicePolicySettingKey);
234 setting->set_watermark("");
235 backend_->ProcessPolicyRequest(token_fetcher_->GetDeviceToken(),
236 token_fetcher_->GetDeviceID(),
237 policy_request, this);
238 }
239
240 void DeviceManagementPolicyProvider::RefreshTaskExecute() {
241 DCHECK(refresh_task_);
242 refresh_task_ = NULL;
243
244 switch (state_) {
245 case STATE_INITIALIZING:
246 token_fetcher_->StartFetching();
247 return;
248 case STATE_TOKEN_VALID:
249 case STATE_POLICY_VALID:
250 case STATE_POLICY_ERROR:
251 SendPolicyRequest();
252 return;
253 case STATE_UNMANAGED:
254 case STATE_TOKEN_ERROR:
255 case STATE_TOKEN_RESET:
256 token_fetcher_->Restart();
257 return;
258 }
259
260 NOTREACHED() << "Unhandled state";
261 }
262
263 void DeviceManagementPolicyProvider::CancelRefreshTask() {
264 if (refresh_task_) {
265 refresh_task_->Cancel();
266 refresh_task_ = NULL;
267 }
268 }
269
270 void DeviceManagementPolicyProvider::NotifyCloudPolicyUpdate() {
271 FOR_EACH_OBSERVER(ConfigurationPolicyProvider::Observer,
272 observer_list_,
273 OnUpdatePolicy());
274 }
275
276 FilePath DeviceManagementPolicyProvider::GetTokenPath() {
277 return storage_dir_.Append(kDeviceTokenFilename);
278 }
279
280 void DeviceManagementPolicyProvider::SetDeviceTokenFetcher(
281 DeviceTokenFetcher* token_fetcher) {
282 registrar_.Init(token_fetcher);
283 registrar_.AddObserver(this);
284 token_fetcher_ = token_fetcher;
285 }
286
287 void DeviceManagementPolicyProvider::SetState(
288 DeviceManagementPolicyProvider::ProviderState new_state) {
289 state_ = new_state;
290
291 // If this state transition completes the initial policy fetch, let the
292 // observers now.
293 if (!initial_fetch_done_ &&
294 new_state != STATE_INITIALIZING &&
295 new_state != STATE_TOKEN_VALID) {
296 initial_fetch_done_ = true;
297 NotifyCloudPolicyUpdate();
298 }
299
300 base::Time now(base::Time::NowFromSystemTime());
301 base::Time refresh_at;
302 base::Time last_refresh(cache_->last_policy_refresh_time());
303 if (last_refresh.is_null())
304 last_refresh = now;
305
306 // Determine when to take the next step.
307 switch (state_) {
308 case STATE_INITIALIZING:
309 refresh_at = now;
310 break;
311 case STATE_TOKEN_VALID:
312 effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms_;
313 refresh_at = now;
314 break;
315 case STATE_TOKEN_RESET:
316 refresh_at = now;
317 break;
318 case STATE_UNMANAGED:
319 refresh_at = last_refresh +
320 base::TimeDelta::FromMilliseconds(unmanaged_device_refresh_rate_ms_);
321 break;
322 case STATE_POLICY_VALID:
323 effective_policy_refresh_error_delay_ms_ = policy_refresh_error_delay_ms_;
324 refresh_at =
325 last_refresh + base::TimeDelta::FromMilliseconds(GetRefreshDelay());
326 break;
327 case STATE_TOKEN_ERROR:
328 refresh_at = now + base::TimeDelta::FromMilliseconds(
329 effective_token_fetch_error_delay_ms_);
330 effective_token_fetch_error_delay_ms_ *= 2;
331 if (effective_token_fetch_error_delay_ms_ > policy_refresh_rate_ms_)
332 effective_token_fetch_error_delay_ms_ = policy_refresh_rate_ms_;
333 break;
334 case STATE_POLICY_ERROR:
335 refresh_at = now + base::TimeDelta::FromMilliseconds(
336 effective_policy_refresh_error_delay_ms_);
337 effective_policy_refresh_error_delay_ms_ *= 2;
338 if (effective_policy_refresh_error_delay_ms_ > policy_refresh_rate_ms_)
339 effective_policy_refresh_error_delay_ms_ = policy_refresh_rate_ms_;
340 break;
341 }
342
343 // Update the refresh task.
344 CancelRefreshTask();
345 if (!refresh_at.is_null()) {
346 refresh_task_ = new RefreshTask(this);
347 int64 delay = std::max<int64>((refresh_at - now).InMilliseconds(), 0);
348 BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE, refresh_task_,
349 delay);
350 }
351 }
352
353 int64 DeviceManagementPolicyProvider::GetRefreshDelay() {
354 int64 deviation = (policy_refresh_deviation_factor_percent_ *
355 policy_refresh_rate_ms_) / 100;
356 deviation = std::min(deviation, policy_refresh_deviation_max_ms_);
357 return policy_refresh_rate_ms_ - base::RandGenerator(deviation + 1);
358 }
359
360 bool DeviceManagementPolicyProvider::TokenAvailable() const {
361 return state_ == STATE_TOKEN_VALID ||
362 state_ == STATE_POLICY_VALID ||
363 state_ == STATE_POLICY_ERROR;
364 }
365
366 // static
367 std::string DeviceManagementPolicyProvider::GetDeviceManagementURL() {
368 return CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
369 switches::kDeviceManagementUrl);
370 }
371
372 // static
373 FilePath DeviceManagementPolicyProvider::GetOrCreateDeviceManagementDir(
374 const FilePath& user_data_dir) {
375 const FilePath device_management_dir = user_data_dir.Append(
376 FILE_PATH_LITERAL("Device Management"));
377 if (!file_util::DirectoryExists(device_management_dir)) {
378 if (!file_util::CreateDirectory(device_management_dir))
379 NOTREACHED();
380 }
381 return device_management_dir;
382 }
383
384 } // namespace policy
OLDNEW
« no previous file with comments | « chrome/browser/policy/device_management_policy_provider.h ('k') | chrome/browser/policy/device_policy_controller.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698