blob: 3505b80624e2a484280fd834b19d64821c7b23e8 [file] [log] [blame]
Xixuan Wu27a61f82017-09-14 11:42:37 -07001# Copyright 2017 The Chromium OS 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"""Module for cron jobs kicked off by suite scheduler."""
6# pylint: disable=g-bad-import-order
7
Xixuan Wu69a5e782017-11-06 14:32:05 -08008import datetime
Xixuan Wu27a61f82017-09-14 11:42:37 -07009import logging
10import webapp2
11
12import constants
Craig Bergstrom3212fb42018-04-17 19:24:15 -060013import config_reader
14import file_getter
Xixuan Wua5a29442017-10-11 11:03:02 -070015import global_config
Xixuan Wu27a61f82017-09-14 11:42:37 -070016import rest_client
Xixuan Wu5d700dc2018-08-21 15:13:10 -070017import swarming_lib
Xixuan Wu27a61f82017-09-14 11:42:37 -070018import task_executor
19import time_converter
20import trigger_receiver
21
22
23_PROD_CALENDAR_ID_MAPPING = {
24 'new_build': constants.CalendarID.PROD_NEW_BUILD,
25 'nightly': constants.CalendarID.PROD_NIGHTLY,
26 'weekly': constants.CalendarID.PROD_WEEKLY,
27}
28
29_STAGING_CALENDAR_ID_MAPPING = {
30 'new_build': constants.CalendarID.STAGING_NEW_BUILD,
31 'nightly': constants.CalendarID.STAGING_NIGHTLY,
32 'weekly': constants.CalendarID.STAGING_WEEKLY,
33}
34
Xixuan Wu69a5e782017-11-06 14:32:05 -080035# Timezone used in calendar, indicating PST.
Xixuan Wu27a61f82017-09-14 11:42:37 -070036_CALENDAR_TIMEZONE = 'America/Los_Angeles'
37
Xixuan Wu69a5e782017-11-06 14:32:05 -080038# Log time extension minutes.
39_LOG_TIME_ADDON_MIN = 1
40
41# The format of url of loggings.
42_LOGGING_URL_FORMAT = 'http://%s/logger?start_time=%s&end_time=%s&resource=%s'
43
Xinan Lin80a9d932019-10-17 09:24:43 -070044# The past number of hours to check if jobs are well scheduled.
45_PAST_HOURS = 6
Xixuan Wu7d142a92019-04-26 12:03:02 -070046
Xinan Lin80a9d932019-10-17 09:24:43 -070047# The minimum number of jobs scheduled in past hours.
48_MIN_SCHEDULED_SUITES_NUMS = 5
Xixuan Wu7d142a92019-04-26 12:03:02 -070049
Xixuan Wu27a61f82017-09-14 11:42:37 -070050
51class TriggerEvent(webapp2.RequestHandler):
52 """Trigger events regularly to schedule tasks for suite_scheduler."""
53
54 def get(self):
Xixuan Wu9be29082017-10-11 08:49:10 -070055 # Don't kick off cron job in staging instance. This cron job can be
56 # kicked off On local development env or prod instance.
Xixuan Wua5a29442017-10-11 11:03:02 -070057 if global_config.is_in_staging():
Xixuan Wu9be29082017-10-11 08:49:10 -070058 return
59
Xixuan Wu27a61f82017-09-14 11:42:37 -070060 start_time = time_converter.pst_now()
Xixuan Wu69a5e782017-11-06 14:32:05 -080061 utc_start_time = time_converter.utc_now()
Xixuan Wu27a61f82017-09-14 11:42:37 -070062 suite_trigger = trigger_receiver.TriggerReceiver()
63 suite_trigger.cron()
64 end_time = time_converter.pst_now()
Xixuan Wu69a5e782017-11-06 14:32:05 -080065 utc_end_time = time_converter.utc_now()
Xixuan Wu27a61f82017-09-14 11:42:37 -070066 calendar_client = rest_client.CalendarRestClient(
67 rest_client.BaseRestClient(
68 constants.RestClient.CALENDAR_CLIENT.scopes,
69 constants.RestClient.CALENDAR_CLIENT.service_name,
70 constants.RestClient.CALENDAR_CLIENT.service_version))
Xixuan Wu69a5e782017-11-06 14:32:05 -080071 str_start_time, str_end_time = _adjust_log_time(
72 utc_start_time, utc_end_time)
73 log_url = _LOGGING_URL_FORMAT % (
74 constants.server_name(), str_start_time, str_end_time,
75 '/cron/trigger_event')
76 logging.info('URL for logs of current round of event trigger: %s', log_url)
Xixuan Wu27a61f82017-09-14 11:42:37 -070077
78 for keyword, results in suite_trigger.event_results.iteritems():
79 # No finished tasks for the given keyword
80 if not results:
81 continue
82
Xixuan Wu69a5e782017-11-06 14:32:05 -080083 _add_to_calendar(keyword, results, log_url, start_time, end_time,
84 calendar_client, _PROD_CALENDAR_ID_MAPPING[keyword])
Xixuan Wu27a61f82017-09-14 11:42:37 -070085
86
87class ExecuteTask(webapp2.RequestHandler):
88 """Run scheduled tasks regularly for suite_scheduler."""
89
90 def get(self):
Xixuan Wua5a29442017-10-11 11:03:02 -070091 if global_config.is_in_staging():
Xixuan Wu9be29082017-10-11 08:49:10 -070092 return
93
Xinan Lin9e4917d2019-11-04 10:58:47 -080094 task_processor = task_executor.TaskProcessor(task_executor.SUITES_QUEUE)
Xixuan Wu27a61f82017-09-14 11:42:37 -070095 task_processor.batch_execute()
96
97
Xixuan Wua5a29442017-10-11 11:03:02 -070098class TestPush(webapp2.RequestHandler):
99 """Test push for suite_scheduler on staging instance."""
100
101 def get(self):
Xixuan Wu7f8330f2017-10-13 16:00:52 -0700102 if not global_config.is_in_staging():
Xixuan Wua5a29442017-10-11 11:03:02 -0700103 return
104
105 # Test Cron jobs
106 # 1) No tasks will be filtered by nightly/weekly constraints.
Xixuan Wu6ec23e32019-05-23 11:56:02 -0700107 # 2) Randomly select builds in |get_cros_builds_since_date|.
Xixuan Wua5a29442017-10-11 11:03:02 -0700108 # 3) Every task will be kicked off with dummy swarming run |dummy_run|.
Xixuan Wu69a5e782017-11-06 14:32:05 -0800109 start_time = time_converter.pst_now()
110 utc_start_time = time_converter.utc_now()
Xixuan Wua5a29442017-10-11 11:03:02 -0700111 suite_trigger = trigger_receiver.TriggerReceiver()
112 suite_trigger.cron()
Xixuan Wu69a5e782017-11-06 14:32:05 -0800113 end_time = time_converter.pst_now()
114 utc_end_time = time_converter.utc_now()
115 calendar_client = rest_client.CalendarRestClient(
116 rest_client.BaseRestClient(
117 constants.RestClient.CALENDAR_CLIENT.scopes,
118 constants.RestClient.CALENDAR_CLIENT.service_name,
119 constants.RestClient.CALENDAR_CLIENT.service_version))
120 str_start_time, str_end_time = _adjust_log_time(
121 utc_start_time, utc_end_time)
122 log_url = _LOGGING_URL_FORMAT % (
123 constants.server_name(), str_start_time, str_end_time,
124 '/cron/test_push')
125 logging.info('URL for logs of current round of test_push: %s', log_url)
Xixuan Wua5a29442017-10-11 11:03:02 -0700126
Xinan Lin9e4917d2019-11-04 10:58:47 -0800127 task_processor = task_executor.TaskProcessor(task_executor.SUITES_QUEUE)
Xixuan Wua5a29442017-10-11 11:03:02 -0700128 task_processor.batch_execute()
129 # In testing, after one round of batch_execute() to execute all tasks,
130 # the suite queue will be purged.
131 task_processor.purge()
132
Xixuan Wu69a5e782017-11-06 14:32:05 -0800133 for keyword, results in suite_trigger.event_results.iteritems():
134 # No finished tasks for the given keyword
135 if not results:
136 continue
137
138 _add_to_calendar(keyword, results, log_url, start_time, end_time,
139 calendar_client, _STAGING_CALENDAR_ID_MAPPING[keyword])
140
141
142def _adjust_log_time(utc_start_time, utc_end_time):
143 """Adjust the start and end time for logging.
144
145 In order to ensure that logs can be fetched by a proper time window,
146 slightly enlarge the log time window by extending 2 * _LOG_TIME_ADDON_MIN.
147
148 Args:
149 utc_start_time: a datetime.datetime object in UTC indicating when the logs
150 are started.
151 utc_end_time: a datetime.datetime object in UTC indicating when the logs
152 are ended.
153
154 Returns:
155 A tuple of two strings indicating start_time and end_time in format
156 time_converter.STACKDRIVER_TIME_FORMAT.
157 """
158 real_start_time = utc_start_time - datetime.timedelta(
159 minutes=_LOG_TIME_ADDON_MIN)
160 real_end_time = utc_end_time + datetime.timedelta(
161 minutes=_LOG_TIME_ADDON_MIN)
162 return (
163 real_start_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT),
164 real_end_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT))
165
166
167def _add_to_calendar(keyword, task_results, log_url, start_time, end_time,
168 calendar_client, calendar_id):
169 """Formalize task results and add them to calendar.
170
171 Args:
172 keyword: the suite scheduler event type.
173 task_results: the finished tasks, represented by a list.
174 log_url: a string url for fetching the logs.
175 start_time: a datetime.datetime object in PST.
176 end_time: a datetime.datetime object in PST.
177 calendar_client: a rest_client.CalendarRestClient object.
178 calendar_id: a string calendar ID.
179 """
180 event = {}
181 event['summary'] = '%s Suite Tasks - Scheduled' % keyword
182 description = '<a href=%s>Running Logs</a>\n%d scheduled tasks: \n' % (
183 log_url, len(task_results))
184 for task_name in task_results:
185 description += task_name + '\n'
186 event['description'] = description
187 # The start time is exactly when the cron job is triggered, i.e. when
188 # all tasks of this event are pushed into the task queue. It's not
189 # when the tasks are 'really' kicked off in lab because there will be
190 # some time delay since task queue will schedule tasks batch by batch.
191 # However, the end time is not exactly when the cron job is finished,
192 # since this cron job's runtime is very short, but the calendar won't
193 # show any item that's shorter than 30 minutes. So no matter what
194 # endtime we set here, it will show a half-an-hour event.
195 event['start'] = {
196 'dateTime': start_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
197 'timeZone': _CALENDAR_TIMEZONE,
198 }
199 event['end'] = {
200 'dateTime': end_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
201 'timeZone': _CALENDAR_TIMEZONE,
202 }
203 if constants.environment() == constants.RunningEnv.ENV_PROD:
204 calendar_client.add_event(calendar_id, event)
205 else:
206 logging.info(event)
207
Xixuan Wua5a29442017-10-11 11:03:02 -0700208
Xinan Lin80a9d932019-10-17 09:24:43 -0700209class CheckJobs(webapp2.RequestHandler):
210 """Check if jobs are well scheduled."""
Xixuan Wu7d142a92019-04-26 12:03:02 -0700211
212 def get(self):
213 if global_config.is_in_staging():
214 return
215
Xinan Lin80a9d932019-10-17 09:24:43 -0700216 bq_client = rest_client.CrOSTestPlatformBigqueryClient(
Xixuan Wu7d142a92019-04-26 12:03:02 -0700217 rest_client.BaseRestClient(
218 constants.RestClient.BIGQUERY_CLIENT.scopes,
219 constants.RestClient.BIGQUERY_CLIENT.service_name,
220 constants.RestClient.BIGQUERY_CLIENT.service_version))
Xinan Lin80a9d932019-10-17 09:24:43 -0700221 res = bq_client.get_past_job_nums(_PAST_HOURS)
222 if res <= _MIN_SCHEDULED_SUITES_NUMS:
223 raise ValueError('Too few (%d) suite tests scheduled to frontdoor'
224 'in the past %d hours.' % (res, _PAST_HOURS))
Xixuan Wu7d142a92019-04-26 12:03:02 -0700225
226
Xixuan Wu27a61f82017-09-14 11:42:37 -0700227app = webapp2.WSGIApplication([
228 ('/cron/trigger_event', TriggerEvent),
229 ('/cron/execute_task', ExecuteTask),
Xixuan Wua5a29442017-10-11 11:03:02 -0700230 ('/cron/test_push', TestPush),
Xinan Lin80a9d932019-10-17 09:24:43 -0700231 ('/cron/check_jobs', CheckJobs),
Xixuan Wu27a61f82017-09-14 11:42:37 -0700232], debug=True)