blob: d1aefef18c32841ba6c1433a13bbc77a59f46530 [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
Xixuan Wu7d142a92019-04-26 12:03:02 -070044# The past number of hours to check if skylab jobs are well scheduled.
45_PAST_HOURS = 2
46
47# The minimum number of skylab jobs scheduled in past hours.
48_MIN_SCHEDULED_SKYLAB_JOB_NUMS = 5
49
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
Craig Bergstrom3212fb42018-04-17 19:24:15 -060094 lab_config = config_reader.LabConfig(config_reader.ConfigReader(
95 file_getter.LAB_CONFIG_FILE))
96 afe_server = lab_config.get_dedicated_afe()
Xixuan Wu5d700dc2018-08-21 15:13:10 -070097 task_processor = task_executor.TaskProcessor(
98 task_executor.SUITES_QUEUE,
99 afe_server,
Prathmesh Prabhucf670742018-09-27 15:13:48 -0700100 swarming_lib.SKYLAB_SWARMING_SERVER)
Xixuan Wu27a61f82017-09-14 11:42:37 -0700101 task_processor.batch_execute()
102
103
Xixuan Wua5a29442017-10-11 11:03:02 -0700104class TestPush(webapp2.RequestHandler):
105 """Test push for suite_scheduler on staging instance."""
106
107 def get(self):
Xixuan Wu7f8330f2017-10-13 16:00:52 -0700108 if not global_config.is_in_staging():
Xixuan Wua5a29442017-10-11 11:03:02 -0700109 return
110
111 # Test Cron jobs
112 # 1) No tasks will be filtered by nightly/weekly constraints.
Xixuan Wu6ec23e32019-05-23 11:56:02 -0700113 # 2) Randomly select builds in |get_cros_builds_since_date|.
Xixuan Wua5a29442017-10-11 11:03:02 -0700114 # 3) Every task will be kicked off with dummy swarming run |dummy_run|.
Xixuan Wu69a5e782017-11-06 14:32:05 -0800115 start_time = time_converter.pst_now()
116 utc_start_time = time_converter.utc_now()
Xixuan Wua5a29442017-10-11 11:03:02 -0700117 suite_trigger = trigger_receiver.TriggerReceiver()
118 suite_trigger.cron()
Xixuan Wu69a5e782017-11-06 14:32:05 -0800119 end_time = time_converter.pst_now()
120 utc_end_time = time_converter.utc_now()
121 calendar_client = rest_client.CalendarRestClient(
122 rest_client.BaseRestClient(
123 constants.RestClient.CALENDAR_CLIENT.scopes,
124 constants.RestClient.CALENDAR_CLIENT.service_name,
125 constants.RestClient.CALENDAR_CLIENT.service_version))
126 str_start_time, str_end_time = _adjust_log_time(
127 utc_start_time, utc_end_time)
128 log_url = _LOGGING_URL_FORMAT % (
129 constants.server_name(), str_start_time, str_end_time,
130 '/cron/test_push')
131 logging.info('URL for logs of current round of test_push: %s', log_url)
Xixuan Wua5a29442017-10-11 11:03:02 -0700132
Craig Bergstrombdf45212018-05-04 12:07:59 -0600133 lab_config = config_reader.LabConfig(config_reader.ConfigReader(
134 file_getter.LAB_CONFIG_FILE))
135 afe_server = lab_config.get_dedicated_afe()
Xixuan Wu5d700dc2018-08-21 15:13:10 -0700136 task_processor = task_executor.TaskProcessor(
137 task_executor.SUITES_QUEUE,
138 afe_server,
Prathmesh Prabhucf670742018-09-27 15:13:48 -0700139 swarming_lib.SKYLAB_STAGING_SWARMING_SERVER)
Xixuan Wua5a29442017-10-11 11:03:02 -0700140 task_processor.batch_execute()
141 # In testing, after one round of batch_execute() to execute all tasks,
142 # the suite queue will be purged.
143 task_processor.purge()
144
Xixuan Wu69a5e782017-11-06 14:32:05 -0800145 for keyword, results in suite_trigger.event_results.iteritems():
146 # No finished tasks for the given keyword
147 if not results:
148 continue
149
150 _add_to_calendar(keyword, results, log_url, start_time, end_time,
151 calendar_client, _STAGING_CALENDAR_ID_MAPPING[keyword])
152
153
154def _adjust_log_time(utc_start_time, utc_end_time):
155 """Adjust the start and end time for logging.
156
157 In order to ensure that logs can be fetched by a proper time window,
158 slightly enlarge the log time window by extending 2 * _LOG_TIME_ADDON_MIN.
159
160 Args:
161 utc_start_time: a datetime.datetime object in UTC indicating when the logs
162 are started.
163 utc_end_time: a datetime.datetime object in UTC indicating when the logs
164 are ended.
165
166 Returns:
167 A tuple of two strings indicating start_time and end_time in format
168 time_converter.STACKDRIVER_TIME_FORMAT.
169 """
170 real_start_time = utc_start_time - datetime.timedelta(
171 minutes=_LOG_TIME_ADDON_MIN)
172 real_end_time = utc_end_time + datetime.timedelta(
173 minutes=_LOG_TIME_ADDON_MIN)
174 return (
175 real_start_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT),
176 real_end_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT))
177
178
179def _add_to_calendar(keyword, task_results, log_url, start_time, end_time,
180 calendar_client, calendar_id):
181 """Formalize task results and add them to calendar.
182
183 Args:
184 keyword: the suite scheduler event type.
185 task_results: the finished tasks, represented by a list.
186 log_url: a string url for fetching the logs.
187 start_time: a datetime.datetime object in PST.
188 end_time: a datetime.datetime object in PST.
189 calendar_client: a rest_client.CalendarRestClient object.
190 calendar_id: a string calendar ID.
191 """
192 event = {}
193 event['summary'] = '%s Suite Tasks - Scheduled' % keyword
194 description = '<a href=%s>Running Logs</a>\n%d scheduled tasks: \n' % (
195 log_url, len(task_results))
196 for task_name in task_results:
197 description += task_name + '\n'
198 event['description'] = description
199 # The start time is exactly when the cron job is triggered, i.e. when
200 # all tasks of this event are pushed into the task queue. It's not
201 # when the tasks are 'really' kicked off in lab because there will be
202 # some time delay since task queue will schedule tasks batch by batch.
203 # However, the end time is not exactly when the cron job is finished,
204 # since this cron job's runtime is very short, but the calendar won't
205 # show any item that's shorter than 30 minutes. So no matter what
206 # endtime we set here, it will show a half-an-hour event.
207 event['start'] = {
208 'dateTime': start_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
209 'timeZone': _CALENDAR_TIMEZONE,
210 }
211 event['end'] = {
212 'dateTime': end_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
213 'timeZone': _CALENDAR_TIMEZONE,
214 }
215 if constants.environment() == constants.RunningEnv.ENV_PROD:
216 calendar_client.add_event(calendar_id, event)
217 else:
218 logging.info(event)
219
Xixuan Wua5a29442017-10-11 11:03:02 -0700220
Xixuan Wu7d142a92019-04-26 12:03:02 -0700221class CheckSkylabJobs(webapp2.RequestHandler):
222 """Check if skylab jobs are well scheduled."""
223
224 def get(self):
225 if global_config.is_in_staging():
226 return
227
Xixuan Wu55d38c52019-05-21 14:26:23 -0700228 bq_client = rest_client.CrOSSwarmingBigqueryClient(
Xixuan Wu7d142a92019-04-26 12:03:02 -0700229 rest_client.BaseRestClient(
230 constants.RestClient.BIGQUERY_CLIENT.scopes,
231 constants.RestClient.BIGQUERY_CLIENT.service_name,
232 constants.RestClient.BIGQUERY_CLIENT.service_version))
233 res = bq_client.get_past_skylab_job_nums(_PAST_HOURS)
Xixuan Wu55d38c52019-05-21 14:26:23 -0700234 if res <= _MIN_SCHEDULED_SKYLAB_JOB_NUMS:
235 raise ValueError('Too few (%d) Skylab jobs scheduled in the past '
236 '%d hours.' % (res, _PAST_HOURS))
Xixuan Wu7d142a92019-04-26 12:03:02 -0700237
238
Xixuan Wu27a61f82017-09-14 11:42:37 -0700239app = webapp2.WSGIApplication([
240 ('/cron/trigger_event', TriggerEvent),
241 ('/cron/execute_task', ExecuteTask),
Xixuan Wua5a29442017-10-11 11:03:02 -0700242 ('/cron/test_push', TestPush),
Xixuan Wu7d142a92019-04-26 12:03:02 -0700243 ('/cron/check_skylab_jobs', CheckSkylabJobs),
Xixuan Wu27a61f82017-09-14 11:42:37 -0700244], debug=True)