Joshua Hesketh | 39a0fee | 2013-07-31 12:00:53 +1000 | [diff] [blame] | 1 | # 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 | |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 15 | |
| 16 | import git |
| 17 | import logging |
| 18 | import os |
| 19 | import select |
Joshua Hesketh | 2e4b611 | 2013-08-12 13:03:06 +1000 | [diff] [blame] | 20 | import shutil |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 21 | import subprocess |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 22 | import swiftclient |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 23 | import time |
| 24 | |
| 25 | |
| 26 | class GitRepository(object): |
| 27 | |
| 28 | """ Manage a git repository for our uses """ |
Joshua Hesketh | 363d004 | 2013-07-26 11:44:07 +1000 | [diff] [blame] | 29 | log = logging.getLogger("lib.utils.GitRepository") |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 30 | |
| 31 | def __init__(self, remote_url, local_path): |
| 32 | self.remote_url = remote_url |
| 33 | self.local_path = local_path |
| 34 | self._ensure_cloned() |
| 35 | |
| 36 | self.repo = git.Repo(self.local_path) |
| 37 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 38 | def _ensure_cloned(self): |
| 39 | if not os.path.exists(self.local_path): |
| 40 | self.log.debug("Cloning from %s to %s" % (self.remote_url, |
| 41 | self.local_path)) |
| 42 | git.Repo.clone_from(self.remote_url, self.local_path) |
| 43 | |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 44 | def fetch(self, ref): |
| 45 | # The git.remote.fetch method may read in git progress info and |
| 46 | # interpret it improperly causing an AssertionError. Because the |
| 47 | # data was fetched properly subsequent fetches don't seem to fail. |
| 48 | # So try again if an AssertionError is caught. |
| 49 | origin = self.repo.remotes.origin |
| 50 | self.log.debug("Fetching %s from %s" % (ref, origin)) |
| 51 | |
| 52 | try: |
| 53 | origin.fetch(ref) |
| 54 | except AssertionError: |
| 55 | origin.fetch(ref) |
| 56 | |
| 57 | def checkout(self, ref): |
| 58 | self.log.debug("Checking out %s" % ref) |
| 59 | return self.repo.git.checkout(ref) |
| 60 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 61 | def reset(self): |
| 62 | self._ensure_cloned() |
| 63 | self.log.debug("Resetting repository %s" % self.local_path) |
| 64 | self.update() |
| 65 | origin = self.repo.remotes.origin |
| 66 | for ref in origin.refs: |
| 67 | if ref.remote_head == 'HEAD': |
| 68 | continue |
| 69 | self.repo.create_head(ref.remote_head, ref, force=True) |
| 70 | |
| 71 | # Reset to remote HEAD (usually origin/master) |
| 72 | self.repo.head.reference = origin.refs['HEAD'] |
| 73 | self.repo.head.reset(index=True, working_tree=True) |
| 74 | self.repo.git.clean('-x', '-f', '-d') |
| 75 | |
| 76 | def update(self): |
| 77 | self._ensure_cloned() |
| 78 | self.log.debug("Updating repository %s" % self.local_path) |
| 79 | origin = self.repo.remotes.origin |
| 80 | origin.update() |
| 81 | # If the remote repository is repacked, the repo object's |
| 82 | # cache may be out of date. Specifically, it caches whether |
| 83 | # to check the loose or packed DB for a given SHA. Further, |
| 84 | # if there was no pack or lose directory to start with, the |
| 85 | # repo object may not even have a database for it. Avoid |
| 86 | # these problems by recreating the repo object. |
| 87 | self.repo = git.Repo(self.local_path) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 88 | |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 89 | |
| 90 | def execute_to_log(cmd, logfile, timeout=-1, |
| 91 | watch_logs=[ |
| 92 | ('[syslog]', '/var/log/syslog'), |
| 93 | ('[sqlslo]', '/var/log/mysql/slow-queries.log'), |
| 94 | ('[sqlerr]', '/var/log/mysql/error.log') |
| 95 | ], |
Michael Still | e8cadae | 2014-01-06 19:47:27 +1100 | [diff] [blame^] | 96 | heartbeat=True, env=None, cwd=None |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 97 | ): |
| 98 | """ Executes a command and logs the STDOUT/STDERR and output of any |
| 99 | supplied watch_logs from logs into a new logfile |
| 100 | |
| 101 | watch_logs is a list of tuples with (name,file) """ |
| 102 | |
| 103 | if not os.path.isdir(os.path.dirname(logfile)): |
| 104 | os.makedirs(os.path.dirname(logfile)) |
| 105 | |
Joshua Hesketh | c7e963b | 2013-09-11 14:11:31 +1000 | [diff] [blame] | 106 | logger = logging.getLogger(logfile) |
Michael Still | 732d25c | 2013-12-05 04:17:25 +1100 | [diff] [blame] | 107 | log_handler = logging.FileHandler(logfile) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 108 | log_formatter = logging.Formatter('%(asctime)s %(message)s') |
Michael Still | 732d25c | 2013-12-05 04:17:25 +1100 | [diff] [blame] | 109 | log_handler.setFormatter(log_formatter) |
| 110 | logger.addHandler(log_handler) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 111 | |
| 112 | descriptors = {} |
| 113 | |
| 114 | for watch_file in watch_logs: |
Michael Still | be74526 | 2014-01-06 19:51:06 +1100 | [diff] [blame] | 115 | if not os.path.exists(watch_file[1]): |
| 116 | logger.warning('Failed to monitor log file %s: file not found' |
| 117 | % watch_file[1]) |
| 118 | continue |
| 119 | |
| 120 | try: |
| 121 | fd = os.open(watch_file[1], os.O_RDONLY) |
| 122 | os.lseek(fd, 0, os.SEEK_END) |
| 123 | descriptors[fd] = {'name': watch_file[0], |
| 124 | 'poll': select.POLLIN, |
| 125 | 'lines': ''} |
| 126 | except Exception as e: |
| 127 | logger.warning('Failed to monitor log file %s: %s' |
| 128 | % (watch_file[1], e)) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 129 | |
| 130 | cmd += ' 2>&1' |
| 131 | start_time = time.time() |
| 132 | p = subprocess.Popen( |
Michael Still | e8cadae | 2014-01-06 19:47:27 +1100 | [diff] [blame^] | 133 | cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 134 | env=env, cwd=cwd) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 135 | |
| 136 | descriptors[p.stdout.fileno()] = dict( |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 137 | name='[output]', |
Joshua Hesketh | 09b2f7f | 2013-07-29 09:05:58 +1000 | [diff] [blame] | 138 | poll=(select.POLLIN | select.POLLHUP), |
| 139 | lines='' |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 140 | ) |
| 141 | |
| 142 | poll_obj = select.poll() |
| 143 | for fd, descriptor in descriptors.items(): |
| 144 | poll_obj.register(fd, descriptor['poll']) |
| 145 | |
| 146 | last_heartbeat = time.time() |
| 147 | |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 148 | def process(fd): |
| 149 | """ Write the fd to log """ |
Joshua Hesketh | 3c0490b | 2013-08-12 10:33:40 +1000 | [diff] [blame] | 150 | global last_heartbeat |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 151 | descriptors[fd]['lines'] += os.read(fd, 1024 * 1024) |
| 152 | # Avoid partial lines by only processing input with breaks |
Joshua Hesketh | 09b2f7f | 2013-07-29 09:05:58 +1000 | [diff] [blame] | 153 | if descriptors[fd]['lines'].find('\n') != -1: |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 154 | elems = descriptors[fd]['lines'].split('\n') |
| 155 | # Take all but the partial line |
| 156 | for l in elems[:-1]: |
| 157 | if len(l) > 0: |
| 158 | l = '%s %s' % (descriptors[fd]['name'], l) |
| 159 | logger.info(l) |
| 160 | last_heartbeat = time.time() |
| 161 | # Place the partial line back into lines to be processed |
| 162 | descriptors[fd]['lines'] = elems[-1] |
| 163 | |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 164 | while p.poll() is None: |
| 165 | if timeout > 0 and time.time() - start_time > timeout: |
| 166 | # Append to logfile |
| 167 | logger.info("[timeout]") |
| 168 | os.kill(p.pid, 9) |
| 169 | |
| 170 | for fd, flag in poll_obj.poll(0): |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 171 | process(fd) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 172 | |
| 173 | if time.time() - last_heartbeat > 30: |
| 174 | # Append to logfile |
| 175 | logger.info("[heartbeat]") |
| 176 | last_heartbeat = time.time() |
| 177 | |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 178 | # Do one last write to get the remaining lines |
| 179 | for fd, flag in poll_obj.poll(0): |
| 180 | process(fd) |
| 181 | |
Joshua Hesketh | 86ab064 | 2013-08-30 13:41:58 +1000 | [diff] [blame] | 182 | # Clean up |
| 183 | for fd, descriptor in descriptors.items(): |
Joshua Hesketh | 8ca96fb | 2013-08-30 18:17:19 +1000 | [diff] [blame] | 184 | poll_obj.unregister(fd) |
Joshua Hesketh | 105af41 | 2013-09-02 10:24:36 +1000 | [diff] [blame] | 185 | os.close(fd) |
Joshua Hesketh | 721781d | 2013-09-02 16:06:01 +1000 | [diff] [blame] | 186 | try: |
| 187 | p.kill() |
| 188 | except OSError: |
| 189 | pass |
Joshua Hesketh | 86ab064 | 2013-08-30 13:41:58 +1000 | [diff] [blame] | 190 | |
Joshua Hesketh | 363d004 | 2013-07-26 11:44:07 +1000 | [diff] [blame] | 191 | logger.info('[script exit code = %d]' % p.returncode) |
Michael Still | 732d25c | 2013-12-05 04:17:25 +1100 | [diff] [blame] | 192 | logger.removeHandler(log_handler) |
| 193 | log_handler.flush() |
| 194 | log_handler.close() |
Michael Still | 5231d4c | 2013-12-24 17:47:59 +1100 | [diff] [blame] | 195 | return p.returncode |
Joshua Hesketh | 926502f | 2013-07-31 11:56:40 +1000 | [diff] [blame] | 196 | |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 197 | |
Joshua Hesketh | 0c1d0c6 | 2013-09-24 22:33:18 +1000 | [diff] [blame] | 198 | def push_file(job_log_dir, file_path, publish_config): |
Joshua Hesketh | 926502f | 2013-07-31 11:56:40 +1000 | [diff] [blame] | 199 | """ Push a log file to a server. Returns the public URL """ |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 200 | method = publish_config['type'] + '_push_file' |
Joshua Hesketh | 2e4b611 | 2013-08-12 13:03:06 +1000 | [diff] [blame] | 201 | if method in globals() and hasattr(globals()[method], '__call__'): |
Joshua Hesketh | ee6a4f8 | 2013-09-27 11:04:08 +1000 | [diff] [blame] | 202 | return globals()[method](job_log_dir, file_path, publish_config) |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 203 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 204 | |
Joshua Hesketh | 0c1d0c6 | 2013-09-24 22:33:18 +1000 | [diff] [blame] | 205 | def swift_push_file(job_log_dir, file_path, swift_config): |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 206 | """ Push a log file to a swift server. """ |
| 207 | with open(file_path, 'r') as fd: |
Michael Still | a497d3a | 2013-12-12 15:44:40 +1100 | [diff] [blame] | 208 | name = os.path.join(job_log_dir, os.path.basename(file_path)) |
| 209 | con = swiftclient.client.Connection( |
| 210 | authurl=swift_config['authurl'], |
| 211 | user=swift_config['user'], |
| 212 | key=swift_config['password'], |
| 213 | os_options={'region_name': swift_config['region']}, |
| 214 | tenant_name=swift_config['tenant'], |
| 215 | auth_version=2.0) |
Joshua Hesketh | d8b23ad | 2013-12-16 11:51:50 +1100 | [diff] [blame] | 216 | con.put_object(swift_config['container'], name, fd) |
| 217 | return swift_config['prepend_url'] + name |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 218 | |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 219 | |
Joshua Hesketh | 0c1d0c6 | 2013-09-24 22:33:18 +1000 | [diff] [blame] | 220 | def local_push_file(job_log_dir, file_path, local_config): |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 221 | """ Copy the file locally somewhere sensible """ |
Joshua Hesketh | 0c1d0c6 | 2013-09-24 22:33:18 +1000 | [diff] [blame] | 222 | dest_dir = os.path.join(local_config['path'], job_log_dir) |
Joshua Hesketh | c76ecde | 2013-08-12 13:46:54 +1000 | [diff] [blame] | 223 | dest_filename = os.path.basename(file_path) |
| 224 | if not os.path.isdir(dest_dir): |
| 225 | os.makedirs(dest_dir) |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 226 | |
Joshua Hesketh | c76ecde | 2013-08-12 13:46:54 +1000 | [diff] [blame] | 227 | dest_file = os.path.join(dest_dir, dest_filename) |
Joshua Hesketh | 2e4b611 | 2013-08-12 13:03:06 +1000 | [diff] [blame] | 228 | |
| 229 | shutil.copyfile(file_path, dest_file) |
Joshua Hesketh | 0b3fe58 | 2013-09-27 14:52:35 +1000 | [diff] [blame] | 230 | return local_config['prepend_url'] + os.path.join(job_log_dir, |
| 231 | dest_filename) |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 232 | |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 233 | |
Joshua Hesketh | 0c1d0c6 | 2013-09-24 22:33:18 +1000 | [diff] [blame] | 234 | def scp_push_file(job_log_dir, file_path, local_config): |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 235 | """ Copy the file remotely over ssh """ |
Joshua Hesketh | 926502f | 2013-07-31 11:56:40 +1000 | [diff] [blame] | 236 | pass |
Joshua Hesketh | 2500696 | 2013-09-24 16:22:40 +1000 | [diff] [blame] | 237 | |
| 238 | |
| 239 | def determine_job_identifier(zuul_arguments, job, unique): |
Joshua Hesketh | 4343b95 | 2013-11-20 12:11:55 +1100 | [diff] [blame] | 240 | if 'build:' in job: |
| 241 | job = job.split('build:')[1] |
Joshua Hesketh | 2500696 | 2013-09-24 16:22:40 +1000 | [diff] [blame] | 242 | return os.path.join(zuul_arguments['ZUUL_CHANGE'][:2], |
| 243 | zuul_arguments['ZUUL_CHANGE'], |
| 244 | zuul_arguments['ZUUL_PATCHSET'], |
| 245 | zuul_arguments['ZUUL_PIPELINE'], |
| 246 | job, |
| 247 | unique[:7]) |