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 |
Joshua Hesketh | 221ae74 | 2014-01-22 16:09:58 +1100 | [diff] [blame] | 19 | import requests |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 20 | import select |
Joshua Hesketh | 2e4b611 | 2013-08-12 13:03:06 +1000 | [diff] [blame] | 21 | import shutil |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 22 | import subprocess |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 23 | import swiftclient |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 24 | import time |
| 25 | |
| 26 | |
Michael Still | 9abb2a4 | 2014-01-10 14:13:15 +1100 | [diff] [blame] | 27 | log = logging.getLogger('lib.utils') |
| 28 | |
| 29 | |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 30 | class GitRepository(object): |
| 31 | |
| 32 | """ Manage a git repository for our uses """ |
Joshua Hesketh | 363d004 | 2013-07-26 11:44:07 +1000 | [diff] [blame] | 33 | log = logging.getLogger("lib.utils.GitRepository") |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 34 | |
| 35 | def __init__(self, remote_url, local_path): |
| 36 | self.remote_url = remote_url |
| 37 | self.local_path = local_path |
| 38 | self._ensure_cloned() |
| 39 | |
| 40 | self.repo = git.Repo(self.local_path) |
| 41 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 42 | def _ensure_cloned(self): |
| 43 | if not os.path.exists(self.local_path): |
| 44 | self.log.debug("Cloning from %s to %s" % (self.remote_url, |
| 45 | self.local_path)) |
| 46 | git.Repo.clone_from(self.remote_url, self.local_path) |
| 47 | |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 48 | def fetch(self, ref): |
| 49 | # The git.remote.fetch method may read in git progress info and |
| 50 | # interpret it improperly causing an AssertionError. Because the |
| 51 | # data was fetched properly subsequent fetches don't seem to fail. |
| 52 | # So try again if an AssertionError is caught. |
| 53 | origin = self.repo.remotes.origin |
| 54 | self.log.debug("Fetching %s from %s" % (ref, origin)) |
| 55 | |
| 56 | try: |
| 57 | origin.fetch(ref) |
| 58 | except AssertionError: |
| 59 | origin.fetch(ref) |
| 60 | |
| 61 | def checkout(self, ref): |
| 62 | self.log.debug("Checking out %s" % ref) |
| 63 | return self.repo.git.checkout(ref) |
| 64 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 65 | def reset(self): |
| 66 | self._ensure_cloned() |
| 67 | self.log.debug("Resetting repository %s" % self.local_path) |
| 68 | self.update() |
| 69 | origin = self.repo.remotes.origin |
| 70 | for ref in origin.refs: |
| 71 | if ref.remote_head == 'HEAD': |
| 72 | continue |
| 73 | self.repo.create_head(ref.remote_head, ref, force=True) |
| 74 | |
| 75 | # Reset to remote HEAD (usually origin/master) |
| 76 | self.repo.head.reference = origin.refs['HEAD'] |
| 77 | self.repo.head.reset(index=True, working_tree=True) |
| 78 | self.repo.git.clean('-x', '-f', '-d') |
| 79 | |
| 80 | def update(self): |
| 81 | self._ensure_cloned() |
| 82 | self.log.debug("Updating repository %s" % self.local_path) |
| 83 | origin = self.repo.remotes.origin |
| 84 | origin.update() |
| 85 | # If the remote repository is repacked, the repo object's |
| 86 | # cache may be out of date. Specifically, it caches whether |
| 87 | # to check the loose or packed DB for a given SHA. Further, |
| 88 | # if there was no pack or lose directory to start with, the |
| 89 | # repo object may not even have a database for it. Avoid |
| 90 | # these problems by recreating the repo object. |
| 91 | self.repo = git.Repo(self.local_path) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 92 | |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 93 | |
Joshua Hesketh | 96052bf | 2014-04-05 19:48:06 +1100 | [diff] [blame] | 94 | def execute_to_log(cmd, logfile, timeout=-1, watch_logs=[], heartbeat=30, |
| 95 | env=None, cwd=None): |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 96 | """ Executes a command and logs the STDOUT/STDERR and output of any |
| 97 | supplied watch_logs from logs into a new logfile |
| 98 | |
| 99 | watch_logs is a list of tuples with (name,file) """ |
| 100 | |
| 101 | if not os.path.isdir(os.path.dirname(logfile)): |
| 102 | os.makedirs(os.path.dirname(logfile)) |
| 103 | |
Joshua Hesketh | c7e963b | 2013-09-11 14:11:31 +1000 | [diff] [blame] | 104 | logger = logging.getLogger(logfile) |
Michael Still | 732d25c | 2013-12-05 04:17:25 +1100 | [diff] [blame] | 105 | log_handler = logging.FileHandler(logfile) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 106 | log_formatter = logging.Formatter('%(asctime)s %(message)s') |
Michael Still | 732d25c | 2013-12-05 04:17:25 +1100 | [diff] [blame] | 107 | log_handler.setFormatter(log_formatter) |
| 108 | logger.addHandler(log_handler) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 109 | |
| 110 | descriptors = {} |
| 111 | |
| 112 | for watch_file in watch_logs: |
Michael Still | be74526 | 2014-01-06 19:51:06 +1100 | [diff] [blame] | 113 | if not os.path.exists(watch_file[1]): |
| 114 | logger.warning('Failed to monitor log file %s: file not found' |
| 115 | % watch_file[1]) |
| 116 | continue |
| 117 | |
| 118 | try: |
| 119 | fd = os.open(watch_file[1], os.O_RDONLY) |
| 120 | os.lseek(fd, 0, os.SEEK_END) |
| 121 | descriptors[fd] = {'name': watch_file[0], |
| 122 | 'poll': select.POLLIN, |
| 123 | 'lines': ''} |
| 124 | except Exception as e: |
| 125 | logger.warning('Failed to monitor log file %s: %s' |
| 126 | % (watch_file[1], e)) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 127 | |
| 128 | cmd += ' 2>&1' |
Joshua Hesketh | 96052bf | 2014-04-05 19:48:06 +1100 | [diff] [blame] | 129 | logger.info("[running %s]" % cmd) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 130 | start_time = time.time() |
| 131 | p = subprocess.Popen( |
Michael Still | e8cadae | 2014-01-06 19:47:27 +1100 | [diff] [blame] | 132 | cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 133 | env=env, cwd=cwd) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 134 | |
| 135 | descriptors[p.stdout.fileno()] = dict( |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 136 | name='[output]', |
Joshua Hesketh | 09b2f7f | 2013-07-29 09:05:58 +1000 | [diff] [blame] | 137 | poll=(select.POLLIN | select.POLLHUP), |
| 138 | lines='' |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 139 | ) |
| 140 | |
| 141 | poll_obj = select.poll() |
| 142 | for fd, descriptor in descriptors.items(): |
| 143 | poll_obj.register(fd, descriptor['poll']) |
| 144 | |
| 145 | last_heartbeat = time.time() |
| 146 | |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 147 | def process(fd): |
| 148 | """ Write the fd to log """ |
Joshua Hesketh | 3c0490b | 2013-08-12 10:33:40 +1000 | [diff] [blame] | 149 | global last_heartbeat |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 150 | descriptors[fd]['lines'] += os.read(fd, 1024 * 1024) |
| 151 | # Avoid partial lines by only processing input with breaks |
Joshua Hesketh | 09b2f7f | 2013-07-29 09:05:58 +1000 | [diff] [blame] | 152 | if descriptors[fd]['lines'].find('\n') != -1: |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 153 | elems = descriptors[fd]['lines'].split('\n') |
| 154 | # Take all but the partial line |
| 155 | for l in elems[:-1]: |
| 156 | if len(l) > 0: |
| 157 | l = '%s %s' % (descriptors[fd]['name'], l) |
| 158 | logger.info(l) |
| 159 | last_heartbeat = time.time() |
| 160 | # Place the partial line back into lines to be processed |
| 161 | descriptors[fd]['lines'] = elems[-1] |
| 162 | |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 163 | while p.poll() is None: |
| 164 | if timeout > 0 and time.time() - start_time > timeout: |
| 165 | # Append to logfile |
| 166 | logger.info("[timeout]") |
| 167 | os.kill(p.pid, 9) |
| 168 | |
| 169 | for fd, flag in poll_obj.poll(0): |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 170 | process(fd) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 171 | |
Joshua Hesketh | 96052bf | 2014-04-05 19:48:06 +1100 | [diff] [blame] | 172 | if heartbeat and (time.time() - last_heartbeat > heartbeat): |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 173 | # Append to logfile |
| 174 | logger.info("[heartbeat]") |
| 175 | last_heartbeat = time.time() |
| 176 | |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 177 | # Do one last write to get the remaining lines |
| 178 | for fd, flag in poll_obj.poll(0): |
| 179 | process(fd) |
| 180 | |
Joshua Hesketh | 86ab064 | 2013-08-30 13:41:58 +1000 | [diff] [blame] | 181 | # Clean up |
| 182 | for fd, descriptor in descriptors.items(): |
Joshua Hesketh | 8ca96fb | 2013-08-30 18:17:19 +1000 | [diff] [blame] | 183 | poll_obj.unregister(fd) |
Joshua Hesketh | 6ad492c | 2014-04-08 17:12:02 +1000 | [diff] [blame] | 184 | if fd == p.stdout.fileno(): |
| 185 | # Don't try and close the process, it'll clean itself up |
| 186 | continue |
Joshua Hesketh | 105af41 | 2013-09-02 10:24:36 +1000 | [diff] [blame] | 187 | os.close(fd) |
Joshua Hesketh | 721781d | 2013-09-02 16:06:01 +1000 | [diff] [blame] | 188 | try: |
| 189 | p.kill() |
| 190 | except OSError: |
| 191 | pass |
Joshua Hesketh | 86ab064 | 2013-08-30 13:41:58 +1000 | [diff] [blame] | 192 | |
Joshua Hesketh | 363d004 | 2013-07-26 11:44:07 +1000 | [diff] [blame] | 193 | logger.info('[script exit code = %d]' % p.returncode) |
Michael Still | 732d25c | 2013-12-05 04:17:25 +1100 | [diff] [blame] | 194 | logger.removeHandler(log_handler) |
| 195 | log_handler.flush() |
| 196 | log_handler.close() |
Michael Still | 5231d4c | 2013-12-24 17:47:59 +1100 | [diff] [blame] | 197 | return p.returncode |
Joshua Hesketh | 926502f | 2013-07-31 11:56:40 +1000 | [diff] [blame] | 198 | |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 199 | |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 200 | def push_file(results_set_name, file_path, publish_config): |
Joshua Hesketh | 926502f | 2013-07-31 11:56:40 +1000 | [diff] [blame] | 201 | """ Push a log file to a server. Returns the public URL """ |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 202 | method = publish_config['type'] + '_push_file' |
Joshua Hesketh | 2e4b611 | 2013-08-12 13:03:06 +1000 | [diff] [blame] | 203 | if method in globals() and hasattr(globals()[method], '__call__'): |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 204 | return globals()[method](results_set_name, file_path, publish_config) |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 205 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 206 | |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 207 | def swift_push_file(results_set_name, file_path, swift_config): |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 208 | """ Push a log file to a swift server. """ |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 209 | def _push_individual_file(results_set_name, file_path, swift_config): |
Joshua Hesketh | 7859fde | 2014-01-22 14:53:17 +1100 | [diff] [blame] | 210 | with open(file_path, 'r') as fd: |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 211 | name = os.path.join(results_set_name, os.path.basename(file_path)) |
Joshua Hesketh | 7859fde | 2014-01-22 14:53:17 +1100 | [diff] [blame] | 212 | con = swiftclient.client.Connection( |
| 213 | authurl=swift_config['authurl'], |
| 214 | user=swift_config['user'], |
| 215 | key=swift_config['password'], |
| 216 | os_options={'region_name': swift_config['region']}, |
| 217 | tenant_name=swift_config['tenant'], |
| 218 | auth_version=2.0) |
| 219 | con.put_object(swift_config['container'], name, fd) |
| 220 | |
| 221 | if os.path.isfile(file_path): |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 222 | _push_individual_file(results_set_name, file_path, swift_config) |
Joshua Hesketh | 7859fde | 2014-01-22 14:53:17 +1100 | [diff] [blame] | 223 | elif os.path.isdir(file_path): |
| 224 | for path, folders, files in os.walk(file_path): |
| 225 | for f in files: |
| 226 | f_path = os.path.join(path, f) |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 227 | _push_individual_file(results_set_name, f_path, swift_config) |
Joshua Hesketh | 7859fde | 2014-01-22 14:53:17 +1100 | [diff] [blame] | 228 | |
| 229 | return (swift_config['prepend_url'] + |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 230 | os.path.join(results_set_name, os.path.basename(file_path))) |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 231 | |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 232 | |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 233 | def local_push_file(results_set_name, file_path, local_config): |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 234 | """ Copy the file locally somewhere sensible """ |
Joshua Hesketh | d5d7a21 | 2014-10-29 17:42:59 +1100 | [diff] [blame] | 235 | def _push_file_or_dir(results_set_name, file_path, local_config): |
| 236 | dest_dir = os.path.join(local_config['path'], results_set_name) |
| 237 | dest_filename = os.path.basename(file_path) |
| 238 | if not os.path.isdir(dest_dir): |
| 239 | os.makedirs(dest_dir) |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 240 | |
Joshua Hesketh | d5d7a21 | 2014-10-29 17:42:59 +1100 | [diff] [blame] | 241 | dest_file = os.path.join(dest_dir, dest_filename) |
| 242 | |
| 243 | if os.path.isfile(file_path): |
| 244 | shutil.copyfile(file_path, dest_file) |
| 245 | elif os.path.isdir(file_path): |
| 246 | shutil.copytree(file_path, dest_file) |
Joshua Hesketh | 2e4b611 | 2013-08-12 13:03:06 +1000 | [diff] [blame] | 247 | |
Joshua Hesketh | 7859fde | 2014-01-22 14:53:17 +1100 | [diff] [blame] | 248 | if os.path.isfile(file_path): |
Joshua Hesketh | d5d7a21 | 2014-10-29 17:42:59 +1100 | [diff] [blame] | 249 | _push_file_or_dir(results_set_name, file_path, local_config) |
Joshua Hesketh | 7859fde | 2014-01-22 14:53:17 +1100 | [diff] [blame] | 250 | elif os.path.isdir(file_path): |
Joshua Hesketh | d5d7a21 | 2014-10-29 17:42:59 +1100 | [diff] [blame] | 251 | for f in os.listdir(file_path): |
| 252 | f_path = os.path.join(file_path, f) |
| 253 | _push_file_or_dir(results_set_name, f_path, local_config) |
| 254 | |
| 255 | dest_filename = os.path.basename(file_path) |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 256 | return local_config['prepend_url'] + os.path.join(results_set_name, |
Joshua Hesketh | 0b3fe58 | 2013-09-27 14:52:35 +1000 | [diff] [blame] | 257 | dest_filename) |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 258 | |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 259 | |
Joshua Hesketh | 5a2edd4 | 2014-01-22 15:02:45 +1100 | [diff] [blame] | 260 | def scp_push_file(results_set_name, file_path, local_config): |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 261 | """ Copy the file remotely over ssh """ |
Joshua Hesketh | 7859fde | 2014-01-22 14:53:17 +1100 | [diff] [blame] | 262 | # TODO! |
Joshua Hesketh | 926502f | 2013-07-31 11:56:40 +1000 | [diff] [blame] | 263 | pass |
Joshua Hesketh | 2500696 | 2013-09-24 16:22:40 +1000 | [diff] [blame] | 264 | |
| 265 | |
Joshua Hesketh | 221ae74 | 2014-01-22 16:09:58 +1100 | [diff] [blame] | 266 | def zuul_swift_upload(file_path, job_arguments): |
| 267 | """Upload working_dir to swift as per zuul's instructions""" |
| 268 | # NOTE(jhesketh): Zuul specifies an object prefix in the destination so |
| 269 | # we don't need to be concerned with results_set_name |
| 270 | |
| 271 | file_list = [] |
| 272 | if os.path.isfile(file_path): |
| 273 | file_list.append(file_path) |
| 274 | elif os.path.isdir(file_path): |
| 275 | for path, folders, files in os.walk(file_path): |
| 276 | for f in files: |
| 277 | f_path = os.path.join(path, f) |
| 278 | file_list.append(f_path) |
| 279 | |
| 280 | # We are uploading the file_list as an HTTP POST multipart encoded. |
| 281 | # First grab out the information we need to send back from the hmac_body |
| 282 | payload = {} |
| 283 | (object_prefix, |
| 284 | payload['redirect'], |
| 285 | payload['max_file_size'], |
| 286 | payload['max_file_count'], |
| 287 | payload['expires']) = \ |
| 288 | job_arguments['ZUUL_EXTRA_SWIFT_HMAC_BODY'].split('\n') |
| 289 | |
| 290 | url = job_arguments['ZUUL_EXTRA_SWIFT_URL'] |
| 291 | payload['signature'] = job_arguments['ZUUL_EXTRA_SWIFT_SIGNATURE'] |
| 292 | logserver_prefix = job_arguments['ZUUL_EXTRA_SWIFT_LOGSERVER_PREFIX'] |
| 293 | |
| 294 | files = {} |
| 295 | for i, f in enumerate(file_list): |
| 296 | files['file%d' % (i + 1)] = open(f, 'rb') |
| 297 | |
| 298 | requests.post(url, data=payload, files=files) |
| 299 | |
| 300 | return (logserver_prefix + |
| 301 | job_arguments['ZUUL_EXTRA_SWIFT_DESTINATION_PREFIX']) |