blob: b937cf456a1e7008b384f1bcee1c39d603bad60c [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
17import task_executor
18import time_converter
19import trigger_receiver
20
21
22_PROD_CALENDAR_ID_MAPPING = {
23 'new_build': constants.CalendarID.PROD_NEW_BUILD,
24 'nightly': constants.CalendarID.PROD_NIGHTLY,
25 'weekly': constants.CalendarID.PROD_WEEKLY,
26}
27
28_STAGING_CALENDAR_ID_MAPPING = {
29 'new_build': constants.CalendarID.STAGING_NEW_BUILD,
30 'nightly': constants.CalendarID.STAGING_NIGHTLY,
31 'weekly': constants.CalendarID.STAGING_WEEKLY,
32}
33
Xixuan Wu69a5e782017-11-06 14:32:05 -080034# Timezone used in calendar, indicating PST.
Xixuan Wu27a61f82017-09-14 11:42:37 -070035_CALENDAR_TIMEZONE = 'America/Los_Angeles'
36
Xixuan Wu69a5e782017-11-06 14:32:05 -080037# Log time extension minutes.
38_LOG_TIME_ADDON_MIN = 1
39
40# The format of url of loggings.
41_LOGGING_URL_FORMAT = 'http://%s/logger?start_time=%s&end_time=%s&resource=%s'
42
Xixuan Wu27a61f82017-09-14 11:42:37 -070043
44class TriggerEvent(webapp2.RequestHandler):
45 """Trigger events regularly to schedule tasks for suite_scheduler."""
46
47 def get(self):
Xixuan Wu9be29082017-10-11 08:49:10 -070048 # Don't kick off cron job in staging instance. This cron job can be
49 # kicked off On local development env or prod instance.
Xixuan Wua5a29442017-10-11 11:03:02 -070050 if global_config.is_in_staging():
Xixuan Wu9be29082017-10-11 08:49:10 -070051 return
52
Xixuan Wu27a61f82017-09-14 11:42:37 -070053 start_time = time_converter.pst_now()
Xixuan Wu69a5e782017-11-06 14:32:05 -080054 utc_start_time = time_converter.utc_now()
Xixuan Wu27a61f82017-09-14 11:42:37 -070055 suite_trigger = trigger_receiver.TriggerReceiver()
56 suite_trigger.cron()
57 end_time = time_converter.pst_now()
Xixuan Wu69a5e782017-11-06 14:32:05 -080058 utc_end_time = time_converter.utc_now()
Xixuan Wu27a61f82017-09-14 11:42:37 -070059 calendar_client = rest_client.CalendarRestClient(
60 rest_client.BaseRestClient(
61 constants.RestClient.CALENDAR_CLIENT.scopes,
62 constants.RestClient.CALENDAR_CLIENT.service_name,
63 constants.RestClient.CALENDAR_CLIENT.service_version))
Xixuan Wu69a5e782017-11-06 14:32:05 -080064 str_start_time, str_end_time = _adjust_log_time(
65 utc_start_time, utc_end_time)
66 log_url = _LOGGING_URL_FORMAT % (
67 constants.server_name(), str_start_time, str_end_time,
68 '/cron/trigger_event')
69 logging.info('URL for logs of current round of event trigger: %s', log_url)
Xixuan Wu27a61f82017-09-14 11:42:37 -070070
71 for keyword, results in suite_trigger.event_results.iteritems():
72 # No finished tasks for the given keyword
73 if not results:
74 continue
75
Xixuan Wu69a5e782017-11-06 14:32:05 -080076 _add_to_calendar(keyword, results, log_url, start_time, end_time,
77 calendar_client, _PROD_CALENDAR_ID_MAPPING[keyword])
Xixuan Wu27a61f82017-09-14 11:42:37 -070078
79
80class ExecuteTask(webapp2.RequestHandler):
81 """Run scheduled tasks regularly for suite_scheduler."""
82
83 def get(self):
Xixuan Wua5a29442017-10-11 11:03:02 -070084 if global_config.is_in_staging():
Xixuan Wu9be29082017-10-11 08:49:10 -070085 return
86
Craig Bergstrom3212fb42018-04-17 19:24:15 -060087 lab_config = config_reader.LabConfig(config_reader.ConfigReader(
88 file_getter.LAB_CONFIG_FILE))
89 afe_server = lab_config.get_dedicated_afe()
90 task_processor = task_executor.TaskProcessor(task_executor.SUITES_QUEUE,
91 afe_server)
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.
104 # 2) Randomly select builds in |get_cros_builds_since_date_from_db|.
105 # 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
Craig Bergstrombdf45212018-05-04 12:07:59 -0600124 lab_config = config_reader.LabConfig(config_reader.ConfigReader(
125 file_getter.LAB_CONFIG_FILE))
126 afe_server = lab_config.get_dedicated_afe()
127 task_processor = task_executor.TaskProcessor(task_executor.SUITES_QUEUE,
128 afe_server)
Xixuan Wua5a29442017-10-11 11:03:02 -0700129 task_processor.batch_execute()
130 # In testing, after one round of batch_execute() to execute all tasks,
131 # the suite queue will be purged.
132 task_processor.purge()
133
Xixuan Wu69a5e782017-11-06 14:32:05 -0800134 for keyword, results in suite_trigger.event_results.iteritems():
135 # No finished tasks for the given keyword
136 if not results:
137 continue
138
139 _add_to_calendar(keyword, results, log_url, start_time, end_time,
140 calendar_client, _STAGING_CALENDAR_ID_MAPPING[keyword])
141
142
143def _adjust_log_time(utc_start_time, utc_end_time):
144 """Adjust the start and end time for logging.
145
146 In order to ensure that logs can be fetched by a proper time window,
147 slightly enlarge the log time window by extending 2 * _LOG_TIME_ADDON_MIN.
148
149 Args:
150 utc_start_time: a datetime.datetime object in UTC indicating when the logs
151 are started.
152 utc_end_time: a datetime.datetime object in UTC indicating when the logs
153 are ended.
154
155 Returns:
156 A tuple of two strings indicating start_time and end_time in format
157 time_converter.STACKDRIVER_TIME_FORMAT.
158 """
159 real_start_time = utc_start_time - datetime.timedelta(
160 minutes=_LOG_TIME_ADDON_MIN)
161 real_end_time = utc_end_time + datetime.timedelta(
162 minutes=_LOG_TIME_ADDON_MIN)
163 return (
164 real_start_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT),
165 real_end_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT))
166
167
168def _add_to_calendar(keyword, task_results, log_url, start_time, end_time,
169 calendar_client, calendar_id):
170 """Formalize task results and add them to calendar.
171
172 Args:
173 keyword: the suite scheduler event type.
174 task_results: the finished tasks, represented by a list.
175 log_url: a string url for fetching the logs.
176 start_time: a datetime.datetime object in PST.
177 end_time: a datetime.datetime object in PST.
178 calendar_client: a rest_client.CalendarRestClient object.
179 calendar_id: a string calendar ID.
180 """
181 event = {}
182 event['summary'] = '%s Suite Tasks - Scheduled' % keyword
183 description = '<a href=%s>Running Logs</a>\n%d scheduled tasks: \n' % (
184 log_url, len(task_results))
185 for task_name in task_results:
186 description += task_name + '\n'
187 event['description'] = description
188 # The start time is exactly when the cron job is triggered, i.e. when
189 # all tasks of this event are pushed into the task queue. It's not
190 # when the tasks are 'really' kicked off in lab because there will be
191 # some time delay since task queue will schedule tasks batch by batch.
192 # However, the end time is not exactly when the cron job is finished,
193 # since this cron job's runtime is very short, but the calendar won't
194 # show any item that's shorter than 30 minutes. So no matter what
195 # endtime we set here, it will show a half-an-hour event.
196 event['start'] = {
197 'dateTime': start_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
198 'timeZone': _CALENDAR_TIMEZONE,
199 }
200 event['end'] = {
201 'dateTime': end_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
202 'timeZone': _CALENDAR_TIMEZONE,
203 }
204 if constants.environment() == constants.RunningEnv.ENV_PROD:
205 calendar_client.add_event(calendar_id, event)
206 else:
207 logging.info(event)
208
Xixuan Wua5a29442017-10-11 11:03:02 -0700209
Xixuan Wu27a61f82017-09-14 11:42:37 -0700210app = webapp2.WSGIApplication([
211 ('/cron/trigger_event', TriggerEvent),
212 ('/cron/execute_task', ExecuteTask),
Xixuan Wua5a29442017-10-11 11:03:02 -0700213 ('/cron/test_push', TestPush),
Xixuan Wu27a61f82017-09-14 11:42:37 -0700214], debug=True)