blob: d4a273882d683f290788f585caf855e9a83092bb [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()))
95 self.job.sendWorkData(json.dumps(self._get_work_data()))
96
Joshua Hesketh81f87ed2014-01-18 15:24:48 +110097 def _send_final_results(self):
98 self._send_work_data()
99
100 if self.work_data['result'] is 'SUCCESS':
101 self.job.sendWorkComplete(
102 json.dumps(self._get_work_data()))
103 else:
104 self.job.sendWorkFail()
105
Joshua Heskethe76a0dd2014-01-16 17:57:45 +1100106 def _do_next_step(self):
107 """ Send a WORK_STATUS command to the gearman server.
108 This can provide a progress bar. """
109
110 # Each opportunity we should check if we need to stop
111 if self.cancelled:
112 self.work_data['result'] = "Failed: Job cancelled"
113 self.job.sendWorkStatus(self.current_step, self.total_steps)
114 self.job.sendWorkFail()
115 raise Exception('Job cancelled')
116
117 self.current_step += 1
118 self.job.sendWorkStatus(self.current_step, self.total_steps)
Joshua Hesketh91778762014-01-16 18:24:46 +1100119
120
121class ShellTask(Task):
122 log = logging.getLogger("lib.models.ShellTask")
123
124 def __init__(self, global_config, plugin_config, job_name):
125 super(ShellTask, self).__init__(global_config, plugin_config, job_name)
126 # Define the number of steps we will do to determine our progress.
Joshua Heskethc73328c2014-01-18 16:09:54 +1100127 self.total_steps = 5
Joshua Hesketh91778762014-01-16 18:24:46 +1100128
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100129 def _reset(self):
130 super(ShellTask, self)._reset()
131 self.git_path = None
Joshua Heskethc73328c2014-01-18 16:09:54 +1100132 self.job_working_dir = None
133 self.shell_output_log = None
Joshua Hesketh91778762014-01-16 18:24:46 +1100134
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100135 def do_job_steps(self, job):
136 # Step 1: Checkout updates from git
137 self._grab_patchset(self.job_arguments,
138 self.job_datasets[0]['job_log_file_path'])
Joshua Hesketh91778762014-01-16 18:24:46 +1100139
Joshua Heskethc73328c2014-01-18 16:09:54 +1100140 # Step 2: Prep job working dir
141 self._prep_working_dir()
142
143 # Step 3: Run shell script
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100144 self._execute_script()
Joshua Hesketh91778762014-01-16 18:24:46 +1100145
Joshua Heskethc73328c2014-01-18 16:09:54 +1100146 # Step 4: Analyse logs for errors
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100147 self._parse_and_check_results()
Joshua Hesketh91778762014-01-16 18:24:46 +1100148
Joshua Heskethc73328c2014-01-18 16:09:54 +1100149 # Step 5: handle the results (and upload etc)
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100150 self._handle_results()
Joshua Hesketh91778762014-01-16 18:24:46 +1100151
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100152 @common.task_step
153 def _grab_patchset(self, job_args, job_log_file_path):
154 """ Checkout the reference into config['git_working_dir'] """
Joshua Hesketh91778762014-01-16 18:24:46 +1100155
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100156 self.log.debug("Grab the patchset we want to test against")
157 local_path = os.path.join(self.global_config['git_working_dir'],
158 self.job_name, job_args['ZUUL_PROJECT'])
159 if not os.path.exists(local_path):
160 os.makedirs(local_path)
Joshua Hesketh91778762014-01-16 18:24:46 +1100161
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100162 git_args = copy.deepcopy(job_args)
163 git_args['GIT_ORIGIN'] = 'git://git.openstack.org/'
Joshua Hesketh91778762014-01-16 18:24:46 +1100164
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100165 cmd = os.path.join(os.path.join(os.path.dirname(__file__),
166 'gerrit-git-prep.sh'))
167 cmd += ' https://review.openstack.org'
168 cmd += ' http://zuul.rcbops.com'
169 utils.execute_to_log(cmd, job_log_file_path, env=git_args,
170 cwd=local_path)
171 self.git_path = local_path
172 return local_path
173
174 @common.task_step
Joshua Heskethc73328c2014-01-18 16:09:54 +1100175 def _prep_working_dir(self):
176 self.job_working_dir = os.path.join(
177 self.global_config['jobs_working_dir'],
178 utils.determine_job_identifier(self.job_arguments,
179 self.plugin_config['function'],
180 self.job.unique)
181 )
182 self.shell_output_log = os.path.join(
183 self.job_working_dir,
184 'shell_output.log'
185 )
186
187 if not os.path.isdir(os.path.dirname(self.shell_output_log)):
188 os.makedirs(os.path.dirname(self.shell_output_log))
189
190 @common.task_step
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100191 def _execute_script(self):
192 # Run script
Joshua Heskethc73328c2014-01-18 16:09:54 +1100193 cmd = self.plugin_config['shell_script']
194 cmd += (
195 (' %(git_path)s %(job_working_dir)s %(unique_id)s')
196 % {
197 'git_path': self.git_path,
198 'job_working_dir': self.job_working_dir,
199 'unique_id': self.job.unique
200 }
201 )
202 self.script_return_code = utils.execute_to_log(
203 cmd,
204 self.shell_output_log
205 )
Joshua Hesketh81f87ed2014-01-18 15:24:48 +1100206
207 @common.task_step
208 def _parse_and_check_results(self):
209 if self.script_return_code > 0:
210 self.success = False
211 self.messages.append('Return code from test script was non-zero '
212 '(%d)' % self.script_return_code)
213
214 @common.task_step
215 def _handle_results(self):
216 pass