blob: bd81b09498d0202a9018b2c282e09d081da4861a [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
Xixuan Wu27a61f82017-09-14 11:42:37 -070041
42class TriggerEvent(webapp2.RequestHandler):
43 """Trigger events regularly to schedule tasks for suite_scheduler."""
44
45 def get(self):
Xixuan Wu9be29082017-10-11 08:49:10 -070046 # Don't kick off cron job in staging instance. This cron job can be
47 # kicked off On local development env or prod instance.
Xixuan Wua5a29442017-10-11 11:03:02 -070048 if global_config.is_in_staging():
Xixuan Wu9be29082017-10-11 08:49:10 -070049 return
50
Xixuan Wu27a61f82017-09-14 11:42:37 -070051 start_time = time_converter.pst_now()
Xixuan Wu69a5e782017-11-06 14:32:05 -080052 utc_start_time = time_converter.utc_now()
Xixuan Wu27a61f82017-09-14 11:42:37 -070053 suite_trigger = trigger_receiver.TriggerReceiver()
54 suite_trigger.cron()
55 end_time = time_converter.pst_now()
Xixuan Wu69a5e782017-11-06 14:32:05 -080056 utc_end_time = time_converter.utc_now()
Xixuan Wu27a61f82017-09-14 11:42:37 -070057 calendar_client = rest_client.CalendarRestClient(
58 rest_client.BaseRestClient(
59 constants.RestClient.CALENDAR_CLIENT.scopes,
60 constants.RestClient.CALENDAR_CLIENT.service_name,
61 constants.RestClient.CALENDAR_CLIENT.service_version))
Xixuan Wu69a5e782017-11-06 14:32:05 -080062 str_start_time, str_end_time = _adjust_log_time(
63 utc_start_time, utc_end_time)
64 log_url = _LOGGING_URL_FORMAT % (
65 constants.server_name(), str_start_time, str_end_time,
66 '/cron/trigger_event')
67 logging.info('URL for logs of current round of event trigger: %s', log_url)
Xixuan Wu27a61f82017-09-14 11:42:37 -070068
69 for keyword, results in suite_trigger.event_results.iteritems():
70 # No finished tasks for the given keyword
71 if not results:
72 continue
73
Xixuan Wu69a5e782017-11-06 14:32:05 -080074 _add_to_calendar(keyword, results, log_url, start_time, end_time,
75 calendar_client, _PROD_CALENDAR_ID_MAPPING[keyword])
Xixuan Wu27a61f82017-09-14 11:42:37 -070076
77
78class ExecuteTask(webapp2.RequestHandler):
79 """Run scheduled tasks regularly for suite_scheduler."""
80
81 def get(self):
Xixuan Wua5a29442017-10-11 11:03:02 -070082 if global_config.is_in_staging():
Xixuan Wu9be29082017-10-11 08:49:10 -070083 return
84
Xixuan Wu27a61f82017-09-14 11:42:37 -070085 task_processor = task_executor.TaskProcessor(task_executor.SUITES_QUEUE)
86 task_processor.batch_execute()
87
88
Xixuan Wua5a29442017-10-11 11:03:02 -070089class TestPush(webapp2.RequestHandler):
90 """Test push for suite_scheduler on staging instance."""
91
92 def get(self):
Xixuan Wu7f8330f2017-10-13 16:00:52 -070093 if not global_config.is_in_staging():
Xixuan Wua5a29442017-10-11 11:03:02 -070094 return
95
96 # Test Cron jobs
97 # 1) No tasks will be filtered by nightly/weekly constraints.
98 # 2) Randomly select builds in |get_cros_builds_since_date_from_db|.
99 # 3) Every task will be kicked off with dummy swarming run |dummy_run|.
Xixuan Wu69a5e782017-11-06 14:32:05 -0800100 start_time = time_converter.pst_now()
101 utc_start_time = time_converter.utc_now()
Xixuan Wua5a29442017-10-11 11:03:02 -0700102 suite_trigger = trigger_receiver.TriggerReceiver()
103 suite_trigger.cron()
Xixuan Wu69a5e782017-11-06 14:32:05 -0800104 end_time = time_converter.pst_now()
105 utc_end_time = time_converter.utc_now()
106 calendar_client = rest_client.CalendarRestClient(
107 rest_client.BaseRestClient(
108 constants.RestClient.CALENDAR_CLIENT.scopes,
109 constants.RestClient.CALENDAR_CLIENT.service_name,
110 constants.RestClient.CALENDAR_CLIENT.service_version))
111 str_start_time, str_end_time = _adjust_log_time(
112 utc_start_time, utc_end_time)
113 log_url = _LOGGING_URL_FORMAT % (
114 constants.server_name(), str_start_time, str_end_time,
115 '/cron/test_push')
116 logging.info('URL for logs of current round of test_push: %s', log_url)
Xixuan Wua5a29442017-10-11 11:03:02 -0700117
118 task_processor = task_executor.TaskProcessor(task_executor.SUITES_QUEUE)
119 task_processor.batch_execute()
120 # In testing, after one round of batch_execute() to execute all tasks,
121 # the suite queue will be purged.
122 task_processor.purge()
123
Xixuan Wu69a5e782017-11-06 14:32:05 -0800124 for keyword, results in suite_trigger.event_results.iteritems():
125 # No finished tasks for the given keyword
126 if not results:
127 continue
128
129 _add_to_calendar(keyword, results, log_url, start_time, end_time,
130 calendar_client, _STAGING_CALENDAR_ID_MAPPING[keyword])
131
132
133def _adjust_log_time(utc_start_time, utc_end_time):
134 """Adjust the start and end time for logging.
135
136 In order to ensure that logs can be fetched by a proper time window,
137 slightly enlarge the log time window by extending 2 * _LOG_TIME_ADDON_MIN.
138
139 Args:
140 utc_start_time: a datetime.datetime object in UTC indicating when the logs
141 are started.
142 utc_end_time: a datetime.datetime object in UTC indicating when the logs
143 are ended.
144
145 Returns:
146 A tuple of two strings indicating start_time and end_time in format
147 time_converter.STACKDRIVER_TIME_FORMAT.
148 """
149 real_start_time = utc_start_time - datetime.timedelta(
150 minutes=_LOG_TIME_ADDON_MIN)
151 real_end_time = utc_end_time + datetime.timedelta(
152 minutes=_LOG_TIME_ADDON_MIN)
153 return (
154 real_start_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT),
155 real_end_time.strftime(time_converter.STACKDRIVER_TIME_FORMAT))
156
157
158def _add_to_calendar(keyword, task_results, log_url, start_time, end_time,
159 calendar_client, calendar_id):
160 """Formalize task results and add them to calendar.
161
162 Args:
163 keyword: the suite scheduler event type.
164 task_results: the finished tasks, represented by a list.
165 log_url: a string url for fetching the logs.
166 start_time: a datetime.datetime object in PST.
167 end_time: a datetime.datetime object in PST.
168 calendar_client: a rest_client.CalendarRestClient object.
169 calendar_id: a string calendar ID.
170 """
171 event = {}
172 event['summary'] = '%s Suite Tasks - Scheduled' % keyword
173 description = '<a href=%s>Running Logs</a>\n%d scheduled tasks: \n' % (
174 log_url, len(task_results))
175 for task_name in task_results:
176 description += task_name + '\n'
177 event['description'] = description
178 # The start time is exactly when the cron job is triggered, i.e. when
179 # all tasks of this event are pushed into the task queue. It's not
180 # when the tasks are 'really' kicked off in lab because there will be
181 # some time delay since task queue will schedule tasks batch by batch.
182 # However, the end time is not exactly when the cron job is finished,
183 # since this cron job's runtime is very short, but the calendar won't
184 # show any item that's shorter than 30 minutes. So no matter what
185 # endtime we set here, it will show a half-an-hour event.
186 event['start'] = {
187 'dateTime': start_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
188 'timeZone': _CALENDAR_TIMEZONE,
189 }
190 event['end'] = {
191 'dateTime': end_time.strftime(time_converter.CALENDAR_TIME_FORMAT),
192 'timeZone': _CALENDAR_TIMEZONE,
193 }
194 if constants.environment() == constants.RunningEnv.ENV_PROD:
195 calendar_client.add_event(calendar_id, event)
196 else:
197 logging.info(event)
198
Xixuan Wua5a29442017-10-11 11:03:02 -0700199
Xixuan Wu27a61f82017-09-14 11:42:37 -0700200app = webapp2.WSGIApplication([
201 ('/cron/trigger_event', TriggerEvent),
202 ('/cron/execute_task', ExecuteTask),
Xixuan Wua5a29442017-10-11 11:03:02 -0700203 ('/cron/test_push', TestPush),
Xixuan Wu27a61f82017-09-14 11:42:37 -0700204], debug=True)