blob: d48523648904c625505cfe1a5fc1b2f6d5e707ef [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
Xixuan Wua5a29442017-10-11 11:03:02 -070013import global_config
Xixuan Wu27a61f82017-09-14 11:42:37 -070014import rest_client
15import task_executor
16import time_converter
17import trigger_receiver
18
19
20_PROD_CALENDAR_ID_MAPPING = {
21 'new_build': constants.CalendarID.PROD_NEW_BUILD,
22 'nightly': constants.CalendarID.PROD_NIGHTLY,
23 'weekly': constants.CalendarID.PROD_WEEKLY,
24}
25
26_STAGING_CALENDAR_ID_MAPPING = {
27 'new_build': constants.CalendarID.STAGING_NEW_BUILD,
28 'nightly': constants.CalendarID.STAGING_NIGHTLY,
29 'weekly': constants.CalendarID.STAGING_WEEKLY,
30}
31
Xixuan Wu69a5e782017-11-06 14:32:05 -080032# Timezone used in calendar, indicating PST.
Xixuan Wu27a61f82017-09-14 11:42:37 -070033_CALENDAR_TIMEZONE = 'America/Los_Angeles'
34
Xixuan Wu69a5e782017-11-06 14:32:05 -080035# Log time extension minutes.
36_LOG_TIME_ADDON_MIN = 1
37
38# The format of url of loggings.
39_LOGGING_URL_FORMAT = 'http://%s/logger?start_time=%s&end_time=%s&resource=%s'
40
Xinan Lin80a9d932019-10-17 09:24:43 -070041# The past number of hours to check if jobs are well scheduled.
42_PAST_HOURS = 6
Xixuan Wu7d142a92019-04-26 12:03:02 -070043
Xinan Lin80a9d932019-10-17 09:24:43 -070044# The minimum number of jobs scheduled in past hours.
45_MIN_SCHEDULED_SUITES_NUMS = 5
Xixuan Wu7d142a92019-04-26 12:03:02 -070046
Xixuan Wu27a61f82017-09-14 11:42:37 -070047
48class TriggerEvent(webapp2.RequestHandler):
49 """Trigger events regularly to schedule tasks for suite_scheduler."""
50
51 def get(self):
Xixuan Wu9be29082017-10-11 08:49:10 -070052 # Don't kick off cron job in staging instance. This cron job can be
53 # kicked off On local development env or prod instance.
Xixuan Wua5a29442017-10-11 11:03:02 -070054 if global_config.is_in_staging():
Xixuan Wu9be29082017-10-11 08:49:10 -070055 return
56
Xixuan Wu27a61f82017-09-14 11:42:37 -070057 start_time = time_converter.pst_now()
Xixuan Wu69a5e782017-11-06 14:32:05 -080058 utc_start_time = time_converter.utc_now()
Xixuan Wu27a61f82017-09-14 11:42:37 -070059 suite_trigger = trigger_receiver.TriggerReceiver()
60 suite_trigger.cron()
61 end_time = time_converter.pst_now()
Xixuan Wu69a5e782017-11-06 14:32:05 -080062 utc_end_time = time_converter.utc_now()
Xixuan Wu27a61f82017-09-14 11:42:37 -070063 calendar_client = rest_client.CalendarRestClient(
64 rest_client.BaseRestClient(
65 constants.RestClient.CALENDAR_CLIENT.scopes,
66 constants.RestClient.CALENDAR_CLIENT.service_name,
67 constants.RestClient.CALENDAR_CLIENT.service_version))
Xixuan Wu69a5e782017-11-06 14:32:05 -080068 str_start_time, str_end_time = _adjust_log_time(
69 utc_start_time, utc_end_time)
70 log_url = _LOGGING_URL_FORMAT % (
71 constants.server_name(), str_start_time, str_end_time,
72 '/cron/trigger_event')
73 logging.info('URL for logs of current round of event trigger: %s', log_url)
Xixuan Wu27a61f82017-09-14 11:42:37 -070074
75 for keyword, results in suite_trigger.event_results.iteritems():
76 # No finished tasks for the given keyword
77 if not results:
78 continue
79
Xixuan Wu69a5e782017-11-06 14:32:05 -080080 _add_to_calendar(keyword, results, log_url, start_time, end_time,
81 calendar_client, _PROD_CALENDAR_ID_MAPPING[keyword])
Xixuan Wu27a61f82017-09-14 11:42:37 -070082
83
84class ExecuteTask(webapp2.RequestHandler):
85 """Run scheduled tasks regularly for suite_scheduler."""
86
87 def get(self):
Xixuan Wua5a29442017-10-11 11:03:02 -070088 if global_config.is_in_staging():
Xixuan Wu9be29082017-10-11 08:49:10 -070089 return
90
Prathmesh Prabhu46331482020-03-07 00:18:10 -080091 task_processor = task_executor.new_task_processor()
Xixuan Wu27a61f82017-09-14 11:42:37 -070092 task_processor.batch_execute()
93
94
Xixuan Wua5a29442017-10-11 11:03:02 -070095class TestPush(webapp2.RequestHandler):
96 """Test push for suite_scheduler on staging instance."""
97
98 def get(self):
Xixuan Wu7f8330f2017-10-13 16:00:52 -070099 if not global_config.is_in_staging():
Xixuan Wua5a29442017-10-11 11:03:02 -0700100 return
101
102 # Test Cron jobs
103 # 1) No tasks will be filtered by nightly/weekly constraints.
Xinan Linea1efcb2019-12-30 23:46:42 -0800104 # 2) Randomly select builds in |get_cros_builds|.
Xixuan Wua5a29442017-10-11 11:03:02 -0700105 # 3) Every task will be kicked off with dummy swarming run |dummy_run|.
Xixuan Wu69a5e782017-11-06 14:32:05 -0800106 start_time = time_converter.pst_now()
107 utc_start_time = time_converter.utc_now()
Xixuan Wua5a29442017-10-11 11:03:02 -0700108 suite_trigger = trigger_receiver.TriggerReceiver()
109 suite_trigger.cron()
Xixuan Wu69a5e782017-11-06 14:32:05 -0800110 end_time = time_converter.pst_now()
111 utc_end_time = time_converter.utc_now()
112 calendar_client = rest_client.CalendarRestClient(
113 rest_client.BaseRestClient(
114 constants.RestClient.CALENDAR_CLIENT.scopes,
115 constants.RestClient.CALENDAR_CLIENT.service_name,
116 constants.RestClient.CALENDAR_CLIENT.service_version))
117 str_start_time, str_end_time = _adjust_log_time(
118 utc_start_time, utc_end_time)
119 log_url = _LOGGING_URL_FORMAT % (
120 constants.server_name(), str_start_time, str_end_time,
121 '/cron/test_push')
122 logging.info('URL for logs of current round of test_push: %s', log_url)
Xixuan Wua5a29442017-10-11 11:03:02 -0700123
Prathmesh Prabhu46331482020-03-07 00:18:10 -0800124 task_processor = task_executor.new_task_processor()
Xixuan Wua5a29442017-10-11 11:03:02 -0700125 task_processor.batch_execute()
126 # In testing, after one round of batch_execute() to execute all tasks,
127 # the suite queue will be purged.
128 task_processor.purge()
129
Xixuan Wu69a5e782017-11-06 14:32:05 -0800130 for keyword, results in suite_trigger.event_results.iteritems():
131 # No finished tasks for the given keyword
132 if not results:
133 continue
134
135 _add_to_calendar(keyword, results, log_url, start_time, end_time,
136 calendar_client, _STAGING_CALENDAR_ID_MAPPING[keyword])
137
138
139def _adjust_log_time(utc_start_time, utc_end_time):
140 """Adjust the start and end time for logging.
141
142 In order to ensure that logs can be fetched by a proper time window,
143 slightly enlarge the log time window by extending 2 * _LOG_TIME_ADDON_MIN.
144
145 Args:
146 utc_start_time: a datetime.datetime object in UTC indicating when the logs
147 are started.
148 utc_end_time: a datetime.datetime object in UTC indicating when the logs
149 are ended.
150
151 Returns:
152 A tuple of two strings indicating start_time and end_time in format
153 time_converter.STACKDRIVER_TIME_FORMAT.
154 """
155 real_start_time = utc_start_time - datetime.timedelta(
156 minutes=_LOG_TIME_ADDON_MIN)
157 real_end_time = utc_end_time + datetime.timedelta(
158 minutes=_LOG_TIME_ADDON_MIN)
159 return (
160 real_start_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT),
161 real_end_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT))
162
163
164def _add_to_calendar(keyword, task_results, log_url, start_time, end_time,
165 calendar_client, calendar_id):
166 """Formalize task results and add them to calendar.
167
168 Args:
169 keyword: the suite scheduler event type.
170 task_results: the finished tasks, represented by a list.
171 log_url: a string url for fetching the logs.
172 start_time: a datetime.datetime object in PST.
173 end_time: a datetime.datetime object in PST.
174 calendar_client: a rest_client.CalendarRestClient object.
175 calendar_id: a string calendar ID.
176 """
177 event = {}
178 event['summary'] = '%s Suite Tasks - Scheduled' % keyword
179 description = '<a href=%s>Running Logs</a>\n%d scheduled tasks: \n' % (
180 log_url, len(task_results))
181 for task_name in task_results:
182 description += task_name + '\n'
183 event['description'] = description
184 # The start time is exactly when the cron job is triggered, i.e. when
185 # all tasks of this event are pushed into the task queue. It's not
186 # when the tasks are 'really' kicked off in lab because there will be
187 # some time delay since task queue will schedule tasks batch by batch.
188 # However, the end time is not exactly when the cron job is finished,
189 # since this cron job's runtime is very short, but the calendar won't
190 # show any item that's shorter than 30 minutes. So no matter what
191 # endtime we set here, it will show a half-an-hour event.
192 event['start'] = {
193 'dateTime': start_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
194 'timeZone': _CALENDAR_TIMEZONE,
195 }
196 event['end'] = {
197 'dateTime': end_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
198 'timeZone': _CALENDAR_TIMEZONE,
199 }
200 if constants.environment() == constants.RunningEnv.ENV_PROD:
201 calendar_client.add_event(calendar_id, event)
202 else:
203 logging.info(event)
204
Xixuan Wua5a29442017-10-11 11:03:02 -0700205
Xinan Lin80a9d932019-10-17 09:24:43 -0700206class CheckJobs(webapp2.RequestHandler):
207 """Check if jobs are well scheduled."""
Xixuan Wu7d142a92019-04-26 12:03:02 -0700208
209 def get(self):
210 if global_config.is_in_staging():
211 return
212
Xinan Lin80a9d932019-10-17 09:24:43 -0700213 bq_client = rest_client.CrOSTestPlatformBigqueryClient(
Xixuan Wu7d142a92019-04-26 12:03:02 -0700214 rest_client.BaseRestClient(
215 constants.RestClient.BIGQUERY_CLIENT.scopes,
216 constants.RestClient.BIGQUERY_CLIENT.service_name,
217 constants.RestClient.BIGQUERY_CLIENT.service_version))
Xinan Lin80a9d932019-10-17 09:24:43 -0700218 res = bq_client.get_past_job_nums(_PAST_HOURS)
219 if res <= _MIN_SCHEDULED_SUITES_NUMS:
220 raise ValueError('Too few (%d) suite tests scheduled to frontdoor'
221 'in the past %d hours.' % (res, _PAST_HOURS))
Xixuan Wu7d142a92019-04-26 12:03:02 -0700222
223
Xixuan Wu27a61f82017-09-14 11:42:37 -0700224app = webapp2.WSGIApplication([
225 ('/cron/trigger_event', TriggerEvent),
226 ('/cron/execute_task', ExecuteTask),
Xixuan Wua5a29442017-10-11 11:03:02 -0700227 ('/cron/test_push', TestPush),
Xinan Lin80a9d932019-10-17 09:24:43 -0700228 ('/cron/check_jobs', CheckJobs),
Xixuan Wu27a61f82017-09-14 11:42:37 -0700229], debug=True)