This source file includes following definitions.
- weak_factory_
- LastModificationTime
- Reload
- InitialLoad
- Init
- RefreshPolicies
- ScheduleNextReload
- IsSafeToReload
#include "components/policy/core/common/async_policy_loader.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/sequenced_task_runner.h"
#include "components/policy/core/common/policy_bundle.h"
using base::Time;
using base::TimeDelta;
namespace policy {
namespace {
const int kSettleIntervalSeconds = 5;
const int kReloadIntervalSeconds = 15 * 60;
}
AsyncPolicyLoader::AsyncPolicyLoader(
scoped_refptr<base::SequencedTaskRunner> task_runner)
: task_runner_(task_runner),
weak_factory_(this) {}
AsyncPolicyLoader::~AsyncPolicyLoader() {}
Time AsyncPolicyLoader::LastModificationTime() {
return Time();
}
void AsyncPolicyLoader::Reload(bool force) {
DCHECK(task_runner_->RunsTasksOnCurrentThread());
TimeDelta delay;
Time now = Time::Now();
if (!force && !IsSafeToReload(now, &delay)) {
ScheduleNextReload(delay);
return;
}
scoped_ptr<PolicyBundle> bundle(Load());
if (!force && !IsSafeToReload(now, &delay)) {
ScheduleNextReload(delay);
return;
}
schema_map_->FilterBundle(bundle.get());
update_callback_.Run(bundle.Pass());
ScheduleNextReload(TimeDelta::FromSeconds(kReloadIntervalSeconds));
}
scoped_ptr<PolicyBundle> AsyncPolicyLoader::InitialLoad(
const scoped_refptr<SchemaMap>& schema_map) {
last_modification_time_ = LastModificationTime();
schema_map_ = schema_map;
scoped_ptr<PolicyBundle> bundle(Load());
schema_map_->FilterBundle(bundle.get());
return bundle.Pass();
}
void AsyncPolicyLoader::Init(const UpdateCallback& update_callback) {
DCHECK(task_runner_->RunsTasksOnCurrentThread());
DCHECK(update_callback_.is_null());
DCHECK(!update_callback.is_null());
update_callback_ = update_callback;
InitOnBackgroundThread();
if (LastModificationTime() != last_modification_time_)
Reload(false);
ScheduleNextReload(TimeDelta::FromSeconds(kReloadIntervalSeconds));
}
void AsyncPolicyLoader::RefreshPolicies(scoped_refptr<SchemaMap> schema_map) {
DCHECK(task_runner_->RunsTasksOnCurrentThread());
schema_map_ = schema_map;
Reload(true);
}
void AsyncPolicyLoader::ScheduleNextReload(TimeDelta delay) {
DCHECK(task_runner_->RunsTasksOnCurrentThread());
weak_factory_.InvalidateWeakPtrs();
task_runner_->PostDelayedTask(FROM_HERE,
base::Bind(&AsyncPolicyLoader::Reload,
weak_factory_.GetWeakPtr(),
false ),
delay);
}
bool AsyncPolicyLoader::IsSafeToReload(const Time& now, TimeDelta* delay) {
Time last_modification = LastModificationTime();
if (last_modification.is_null())
return true;
const TimeDelta kSettleInterval(
TimeDelta::FromSeconds(kSettleIntervalSeconds));
if (last_modification != last_modification_time_) {
last_modification_time_ = last_modification;
last_modification_clock_ = now;
*delay = kSettleInterval;
return false;
}
const TimeDelta age = now - last_modification_clock_;
if (age < kSettleInterval) {
*delay = kSettleInterval - age;
return false;
}
return true;
}
}