File: scheduled_task_util.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (301 lines) | stat: -rw-r--r-- 10,225 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/policy/scheduled_task_handler/scheduled_task_util.h"

#include <memory>
#include <string>

#include "ash/constants/ash_switches.h"
#include "base/check.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "third_party/icu/source/i18n/unicode/gregocal.h"

namespace policy {
namespace {

constexpr base::TimeDelta kDefaultGracePeriod = base::Hours(1);

ScheduledTaskExecutor::Frequency GetFrequency(const std::string& frequency) {
  if (frequency == "DAILY")
    return ScheduledTaskExecutor::Frequency::kDaily;

  if (frequency == "WEEKLY")
    return ScheduledTaskExecutor::Frequency::kWeekly;

  DCHECK_EQ(frequency, "MONTHLY");
  return ScheduledTaskExecutor::Frequency::kMonthly;
}

// Convert the string day of week to UCalendarDaysOfWeek.
UCalendarDaysOfWeek StringDayOfWeekToIcuDayOfWeek(
    const std::string& day_of_week) {
  if (day_of_week == "SUNDAY")
    return UCAL_SUNDAY;
  if (day_of_week == "MONDAY")
    return UCAL_MONDAY;
  if (day_of_week == "TUESDAY")
    return UCAL_TUESDAY;
  if (day_of_week == "WEDNESDAY")
    return UCAL_WEDNESDAY;
  if (day_of_week == "THURSDAY")
    return UCAL_THURSDAY;
  if (day_of_week == "FRIDAY")
    return UCAL_FRIDAY;
  DCHECK_EQ(day_of_week, "SATURDAY");
  return UCAL_SATURDAY;
}

bool IsAfter(const icu::Calendar& a, const icu::Calendar& b) {
  UErrorCode status = U_ZERO_ERROR;
  if (a.after(b, status)) {
    DCHECK(U_SUCCESS(status));
    return true;
  }

  return false;
}

// Returns a valid time based on the policy represented by
// |scheduled_task_data|.
std::unique_ptr<icu::Calendar> SnapToValidTimeBasedOnPolicy(
    const icu::Calendar& time,
    const ScheduledTaskExecutor::ScheduledTaskData& scheduled_task_data) {
  auto res_time = base::WrapUnique(time.clone());

  // Set the daily fields first as they will be common across different policy
  // types.
  res_time->set(UCAL_HOUR_OF_DAY, scheduled_task_data.hour);
  res_time->set(UCAL_MINUTE, scheduled_task_data.minute);
  res_time->set(UCAL_SECOND, 0);
  res_time->set(UCAL_MILLISECOND, 0);

  switch (scheduled_task_data.frequency) {
    case ScheduledTaskExecutor::Frequency::kDaily:
      return res_time;

    case ScheduledTaskExecutor::Frequency::kWeekly:
      DCHECK(scheduled_task_data.day_of_week);
      res_time->set(UCAL_DAY_OF_WEEK, scheduled_task_data.day_of_week.value());
      return res_time;

    case ScheduledTaskExecutor::Frequency::kMonthly: {
      DCHECK(scheduled_task_data.day_of_month);
      UErrorCode status = U_ZERO_ERROR;
      // If policy's |day_of_month| is greater than the maximum days in |time|'s
      // current month then it's set to the last day in the month.
      int cur_max_days_in_month =
          res_time->getActualMaximum(UCAL_DAY_OF_MONTH, status);
      DCHECK(U_SUCCESS(status));

      res_time->set(UCAL_DAY_OF_MONTH,
                    std::min(scheduled_task_data.day_of_month.value(),
                             cur_max_days_in_month));
      return res_time;
    }
  }
}

UCalendarDateFields GetFieldToAdvanceFor(
    ScheduledTaskExecutor::Frequency frequency) {
  switch (frequency) {
    case ScheduledTaskExecutor::Frequency::kDaily:
      return UCAL_DAY_OF_MONTH;
    case ScheduledTaskExecutor::Frequency::kWeekly:
      return UCAL_WEEK_OF_YEAR;
    case ScheduledTaskExecutor::Frequency::kMonthly:
      return UCAL_MONTH;
  }
  NOTREACHED();
}

// Returns a valid time that is advanced in comparison to |time| based on the
// policy represented by |scheduled_task_data|.
//
// For daily policy - Advances |time| by 1 day.
// For weekly policy - Advances |time| by 1 week.
// For monthly policy - Advances |time| by 1 month.
std::unique_ptr<icu::Calendar> AdvanceToNextValidTimeBasedOnPolicy(
    const icu::Calendar& time,
    const ScheduledTaskExecutor::ScheduledTaskData& scheduled_task_data) {
  auto res_time = base::WrapUnique(time.clone());
  UErrorCode status = U_ZERO_ERROR;
  res_time->add(GetFieldToAdvanceFor(scheduled_task_data.frequency), 1, status);
  DCHECK(U_SUCCESS(status));
  // Need to run SnapToValid again, as we might be in a month with less days
  // than the previous month.
  return SnapToValidTimeBasedOnPolicy(*res_time, scheduled_task_data);
}

}  // namespace

namespace scheduled_task_util {
std::optional<ScheduledTaskExecutor::ScheduledTaskData> ParseScheduledTask(
    const base::Value& value,
    const std::string& task_time_field_name) {
  const base::Value::Dict& dict = value.GetDict();
  ScheduledTaskExecutor::ScheduledTaskData result;
  // Parse mandatory values first i.e. hour, minute and frequency of update
  // check. These should always be present due to schema validation at higher
  // layers.
  const base::Value::Dict* task_time_field_dict =
      dict.FindDict(task_time_field_name);
  DCHECK(task_time_field_dict);
  std::optional<int> hour_opt = task_time_field_dict->FindInt("hour");
  DCHECK(hour_opt);
  // Validated by schema validation at higher layers.
  DCHECK(*hour_opt >= 0 && *hour_opt <= 23);
  result.hour = *hour_opt;

  std::optional<int> minute_opt = task_time_field_dict->FindInt("minute");
  DCHECK(minute_opt);
  // Validated by schema validation at higher layers.
  DCHECK(*minute_opt >= 0 && *minute_opt <= 59);
  result.minute = *minute_opt;

  // Validated by schema validation at higher layers.
  const std::string* frequency = dict.FindString({"frequency"});
  DCHECK(frequency);
  result.frequency = GetFrequency(*frequency);

  // Parse extra fields for weekly and monthly frequencies.
  switch (result.frequency) {
    case ScheduledTaskExecutor::Frequency::kDaily:
      break;

    case ScheduledTaskExecutor::Frequency::kWeekly: {
      const std::string* day_of_week = dict.FindString({"day_of_week"});
      if (!day_of_week) {
        LOG(ERROR) << "Day of week missing";
        return std::nullopt;
      }

      // Validated by schema validation at higher layers.
      result.day_of_week = StringDayOfWeekToIcuDayOfWeek(*day_of_week);
      break;
    }

    case ScheduledTaskExecutor::Frequency::kMonthly: {
      std::optional<int> day_of_month = dict.FindInt("day_of_month");
      if (!day_of_month) {
        LOG(ERROR) << "Day of month missing";
        return std::nullopt;
      }

      // Validated by schema validation at higher layers.
      result.day_of_month = day_of_month.value();
      break;
    }
  }

  return result;
}

base::TimeDelta GetDiff(const icu::Calendar& a, const icu::Calendar& b) {
  UErrorCode status = U_ZERO_ERROR;
  UDate a_ms = a.getTime(status);
  DCHECK(U_SUCCESS(status));
  UDate b_ms = b.getTime(status);
  DCHECK(U_SUCCESS(status));
  DCHECK(a_ms >= b_ms);
  return base::Milliseconds(a_ms - b_ms);
}

std::unique_ptr<icu::Calendar> ConvertUtcToTzIcuTime(base::Time cur_time,
                                                     const icu::TimeZone& tz) {
  // Get ms from epoch for |cur_time| and use it to get the new time in |tz|.
  UErrorCode status = U_ZERO_ERROR;
  std::unique_ptr<icu::Calendar> cal_tz =
      std::make_unique<icu::GregorianCalendar>(tz, status);
  if (U_FAILURE(status)) {
    LOG(ERROR) << "Couldn't create calendar";
    return nullptr;
  }
  // Erase current time from the calendar.
  cal_tz->clear();
  // Use Time::InMillisecondsSinceUnixEpoch() to get ms since epoch in int64_t
  // format.
  cal_tz->setTime(cur_time.InMillisecondsSinceUnixEpoch(), status);
  if (U_FAILURE(status)) {
    LOG(ERROR) << "Couldn't create calendar";
    return nullptr;
  }

  return cal_tz;
}

std::optional<base::TimeDelta> CalculateNextScheduledTaskTimerDelay(
    const ScheduledTaskExecutor::ScheduledTaskData& data,
    base::Time time,
    const icu::TimeZone& time_zone) {
  const auto cal = ConvertUtcToTzIcuTime(time, time_zone);
  if (!cal) {
    LOG(ERROR) << "Failed to get current ICU time";
    return std::nullopt;
  }

  auto scheduled_task_time = CalculateNextScheduledTimeAfter(data, *cal);

  return GetDiff(*scheduled_task_time, *cal);
}

std::unique_ptr<icu::Calendar> CalculateNextScheduledTimeAfter(
    const ScheduledTaskExecutor::ScheduledTaskData& data,
    const icu::Calendar& time) {
  auto scheduled_task_time = SnapToValidTimeBasedOnPolicy(time, data);

  // If the time has already passed it means that the scheduled task needs to be
  // advanced based on the policy i.e. by a day, week or month. The equal to
  // case happens when the timer_expired_cb runs and sets the next
  // |scheduled_task_timer_|. In this case |scheduled_task_time| definitely
  // needs to advance as per the policy.
  if (!IsAfter(*scheduled_task_time, time)) {
    scheduled_task_time =
        AdvanceToNextValidTimeBasedOnPolicy(*scheduled_task_time, data);
  }

  DCHECK(IsAfter(*scheduled_task_time, time));

  return scheduled_task_time;
}

// Returns grace from commandline if present and valid. Returns default grace
// time otherwise.
base::TimeDelta GetScheduledRebootGracePeriod() {
  const base::CommandLine* command_line =
      base::CommandLine::ForCurrentProcess();

  std::string grace_time_string = command_line->GetSwitchValueASCII(
      ash::switches::kScheduledRebootGracePeriodInSecondsForTesting);

  if (grace_time_string.empty()) {
    return kDefaultGracePeriod;
  }

  int grace_time_in_seconds;
  if (!base::StringToInt(grace_time_string, &grace_time_in_seconds) ||
      grace_time_in_seconds < 0) {
    LOG(ERROR) << "Ignored "
               << ash::switches::kScheduledRebootGracePeriodInSecondsForTesting
               << "=" << grace_time_string;
    return kDefaultGracePeriod;
  }

  return base::Seconds(grace_time_in_seconds);
}

bool ShouldSkipRebootDueToGracePeriod(base::Time boot_time,
                                      base::Time reboot_time) {
  // Skip reboot if reboot scheduled within [boot time, boot time + grace time]
  // interval.
  return boot_time + GetScheduledRebootGracePeriod() >= reboot_time;
}

}  // namespace scheduled_task_util
}  // namespace policy