blob: d445379d27285e2bc4a2c03e1003a51b73f7f107 [file] [log] [blame]
Joshua Heskethe76a0dd2014-01-16 17:57:45 +11001# Copyright 2013 Rackspace Australia
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
15
16import copy
17import json
18import logging
19import os
20
Joshua Hesketh62245542014-01-16 18:00:56 +110021from turbo_hipster.lib import common
Joshua Heskethe76a0dd2014-01-16 17:57:45 +110022from turbo_hipster.lib import utils
23
24
25class Task(object):
26
27 log = logging.getLogger("lib.models.Task")
28
29 def __init__(self, global_config, plugin_config, job_name):
30 self.global_config = global_config
31 self.plugin_config = plugin_config
32 self.job_name = job_name
Joshua Hesketh81f87ed2014-01-18 15:24:48 +110033 self._reset()
Joshua Heskethe76a0dd2014-01-16 17:57:45 +110034
Joshua Hesketh81f87ed2014-01-18 15:24:48 +110035 # Define the number of steps we will do to determine our progress.
36 self.total_steps = 0
37
38 def _reset(self):
Joshua Heskethe76a0dd2014-01-16 17:57:45 +110039 self.job = None
40 self.job_arguments = None
41 self.work_data = None
42 self.cancelled = False
Joshua Hesketh81f87ed2014-01-18 15:24:48 +110043 self.success = True
44 self.messages = []
Joshua Heskethe76a0dd2014-01-16 17:57:45 +110045 self.current_step = 0
Joshua Hesketh81f87ed2014-01-18 15:24:48 +110046
47 def start_job(self, job):
48 self._reset()
49 self.job = job
50
51 if self.job is not None:
52 try:
53 self.job_arguments = \
54 json.loads(self.job.arguments.decode('utf-8'))
55 self.log.debug("Got job from ZUUL %s" % self.job_arguments)
56
57 # Send an initial WORK_DATA and WORK_STATUS packets
58 self._send_work_data()
59
60 # Execute the job_steps
61 self.do_job_steps()
62
63 # Finally, send updated work data and completed packets
64 self._send_final_results()
65
66 except Exception as e:
67 self.log.exception('Exception handling log event.')
68 if not self.cancelled:
69 self.job.sendWorkException(str(e).encode('utf-8'))
Joshua Heskethe76a0dd2014-01-16 17:57:45 +110070
71 def stop_worker(self, number):
72 # Check the number is for this job instance
73 # (makes it possible to run multiple workers with this task
74 # on this server)
75 if number == self.job.unique:
76 self.log.debug("We've been asked to stop by our gearman manager")
77 self.cancelled = True
78 # TODO: Work out how to kill current step
79
Joshua Heskethe76a0dd2014-01-16 17:57:45 +110080 def _get_work_data(self):
81 if self.work_data is None:
82 hostname = os.uname()[1]
83 self.work_data = dict(
84 name=self.job_name,
85 number=self.job.unique,
86 manager='turbo-hipster-manager-%s' % hostname,
87 url='http://localhost',
88 )
89 return self.work_data
90
91 def _send_work_data(self):
92 """ Send the WORK DATA in json format for job """
93 self.log.debug("Send the work data response: %s" %
94 json.dumps(self._get_work_data()))
Joshua Hesketh3cda79f2014-01-31 13:10:29 +110095 if self.success:
96 self.work_data['result'] = 'SUCCESS'
97 else:
98 self.work_data['result'] = '\n'.join(self.messages)
Joshua Heskethe76a0dd2014-01-16 17:57:45 +110099 self.job.sendWorkData(json.dumps(self._get_work_data()))
100
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100101 def _send_final_results(self):
102 self._send_work_data()
103
Joshua Heskethb5f99b62014-01-30 16:03:19 +1100104 if self.success:
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100105 self.job.sendWorkComplete(
106 json.dumps(self._get_work_data()))
107 else:
108 self.job.sendWorkFail()
109
Joshua Heskethe76a0dd2014-01-16 17:57:45 +1100110 def _do_next_step(self):
111 """ Send a WORK_STATUS command to the gearman server.
112 This can provide a progress bar. """
113
114 # Each opportunity we should check if we need to stop
115 if self.cancelled:
116 self.work_data['result'] = "Failed: Job cancelled"
117 self.job.sendWorkStatus(self.current_step, self.total_steps)
118 self.job.sendWorkFail()
119 raise Exception('Job cancelled')
120
121 self.current_step += 1
122 self.job.sendWorkStatus(self.current_step, self.total_steps)
Joshua Hesketh91778762014-01-16 18:24:46 +1100123
124
125class ShellTask(Task):
126 log = logging.getLogger("lib.models.ShellTask")
127
128 def __init__(self, global_config, plugin_config, job_name):
129 super(ShellTask, self).__init__(global_config, plugin_config, job_name)
130 # Define the number of steps we will do to determine our progress.
Joshua Heskethc73328c2014-01-18 16:09:54 +1100131 self.total_steps = 5
Joshua Hesketh91778762014-01-16 18:24:46 +1100132
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100133 def _reset(self):
134 super(ShellTask, self)._reset()
135 self.git_path = None
Joshua Heskethc73328c2014-01-18 16:09:54 +1100136 self.job_working_dir = None
137 self.shell_output_log = None
Joshua Hesketh91778762014-01-16 18:24:46 +1100138
Joshua Hesketh235b13d2014-01-30 15:14:04 +1100139 def do_job_steps(self):
Joshua Hesketh1f2d1a22014-01-30 15:41:21 +1100140 # Step 1: Prep job working dir
Joshua Heskethc73328c2014-01-18 16:09:54 +1100141 self._prep_working_dir()
142
Joshua Hesketh1f2d1a22014-01-30 15:41:21 +1100143 # Step 2: Checkout updates from git
144 self._grab_patchset(self.job_arguments)
145
Joshua Heskethc73328c2014-01-18 16:09:54 +1100146 # Step 3: Run shell script
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100147 self._execute_script()
Joshua Hesketh91778762014-01-16 18:24:46 +1100148
Joshua Heskethc73328c2014-01-18 16:09:54 +1100149 # Step 4: Analyse logs for errors
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100150 self._parse_and_check_results()
Joshua Hesketh91778762014-01-16 18:24:46 +1100151
Joshua Heskethc73328c2014-01-18 16:09:54 +1100152 # Step 5: handle the results (and upload etc)
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100153 self._handle_results()
Joshua Hesketh91778762014-01-16 18:24:46 +1100154
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100155 @common.task_step
Joshua Hesketh1f2d1a22014-01-30 15:41:21 +1100156 def _prep_working_dir(self):
Joshua Hesketh99005542014-01-30 16:34:36 +1100157 self.job_identifier = utils.determine_job_identifier(
158 self.job_arguments,
159 self.plugin_config['function'],
160 self.job.unique
161 )
Joshua Hesketh1f2d1a22014-01-30 15:41:21 +1100162 self.job_working_dir = os.path.join(
163 self.global_config['jobs_working_dir'],
Joshua Hesketh99005542014-01-30 16:34:36 +1100164 self.job_identifier
Joshua Hesketh1f2d1a22014-01-30 15:41:21 +1100165 )
166 self.shell_output_log = os.path.join(
167 self.job_working_dir,
168 'shell_output.log'
169 )
170
171 if not os.path.isdir(os.path.dirname(self.shell_output_log)):
172 os.makedirs(os.path.dirname(self.shell_output_log))
173
174 @common.task_step
175 def _grab_patchset(self, job_args):
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100176 """ Checkout the reference into config['git_working_dir'] """
Joshua Hesketh91778762014-01-16 18:24:46 +1100177
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100178 self.log.debug("Grab the patchset we want to test against")
179 local_path = os.path.join(self.global_config['git_working_dir'],
180 self.job_name, job_args['ZUUL_PROJECT'])
181 if not os.path.exists(local_path):
182 os.makedirs(local_path)
Joshua Hesketh91778762014-01-16 18:24:46 +1100183
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100184 git_args = copy.deepcopy(job_args)
Joshua Hesketh91778762014-01-16 18:24:46 +1100185
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100186 cmd = os.path.join(os.path.join(os.path.dirname(__file__),
187 'gerrit-git-prep.sh'))
Joshua Hesketh15e1e692014-01-31 13:53:35 +1100188 cmd += ' ' + self.global_config['zuul_server']['gerrit_site']
189 cmd += ' ' + self.global_config['zuul_server']['zuul_site']
Joshua Hesketh1f2d1a22014-01-30 15:41:21 +1100190 utils.execute_to_log(cmd, self.shell_output_log, env=git_args,
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100191 cwd=local_path)
192 self.git_path = local_path
193 return local_path
194
195 @common.task_step
196 def _execute_script(self):
197 # Run script
Joshua Heskethc73328c2014-01-18 16:09:54 +1100198 cmd = self.plugin_config['shell_script']
199 cmd += (
200 (' %(git_path)s %(job_working_dir)s %(unique_id)s')
201 % {
202 'git_path': self.git_path,
203 'job_working_dir': self.job_working_dir,
204 'unique_id': self.job.unique
205 }
206 )
207 self.script_return_code = utils.execute_to_log(
208 cmd,
209 self.shell_output_log
210 )
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100211
212 @common.task_step
213 def _parse_and_check_results(self):
214 if self.script_return_code > 0:
215 self.success = False
216 self.messages.append('Return code from test script was non-zero '
217 '(%d)' % self.script_return_code)
218
219 @common.task_step
220 def _handle_results(self):
Joshua Hesketh6055f312014-01-22 15:04:54 +1100221 """Upload the contents of the working dir either using the instructions
222 provided by zuul and/or our configuration"""
Joshua Hesketh221ae742014-01-22 16:09:58 +1100223
Joshua Hesketh6055f312014-01-22 15:04:54 +1100224 self.log.debug("Process the resulting files (upload/push)")
Joshua Hesketh221ae742014-01-22 16:09:58 +1100225
226 if 'publish_logs' in self.global_config:
Joshua Hesketh99005542014-01-30 16:34:36 +1100227 index_url = utils.push_file(self.job_identifier,
Joshua Heskethae4ef1e2014-01-31 13:13:27 +1100228 self.shell_output_log,
Joshua Hesketh221ae742014-01-22 16:09:58 +1100229 self.global_config['publish_logs'])
230 self.log.debug("Index URL found at %s" % index_url)
231 self.work_data['url'] = index_url
232
233 if 'ZUUL_EXTRA_SWIFT_URL' in self.job_arguments:
234 # Upload to zuul's url as instructed
235 utils.zuul_swift_upload(self.job_working_dir, self.job_arguments)
Joshua Hesketh99005542014-01-30 16:34:36 +1100236 self.work_data['url'] = self.job_identifier