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 | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 20 | #import shutils |
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 | ], |
| 96 | heartbeat=True |
| 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 | |
| 106 | logger = logging.getLogger('execute_to_log') |
| 107 | log_hanlder = logging.FileHandler(logfile) |
| 108 | log_formatter = logging.Formatter('%(asctime)s %(message)s') |
| 109 | log_hanlder.setFormatter(log_formatter) |
| 110 | logger.addHandler(log_hanlder) |
| 111 | |
| 112 | descriptors = {} |
| 113 | |
| 114 | for watch_file in watch_logs: |
| 115 | fd = os.open(watch_file[1], os.O_RDONLY) |
| 116 | os.lseek(fd, 0, os.SEEK_END) |
| 117 | descriptors[fd] = dict( |
| 118 | name=watch_file[0], |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 119 | poll=select.POLLIN, |
| 120 | lines='' |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 121 | ) |
| 122 | |
| 123 | cmd += ' 2>&1' |
| 124 | start_time = time.time() |
| 125 | p = subprocess.Popen( |
| 126 | cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 127 | |
| 128 | descriptors[p.stdout.fileno()] = dict( |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 129 | name='[output]', |
Joshua Hesketh | 09b2f7f | 2013-07-29 09:05:58 +1000 | [diff] [blame] | 130 | poll=(select.POLLIN | select.POLLHUP), |
| 131 | lines='' |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 132 | ) |
| 133 | |
| 134 | poll_obj = select.poll() |
| 135 | for fd, descriptor in descriptors.items(): |
| 136 | poll_obj.register(fd, descriptor['poll']) |
| 137 | |
| 138 | last_heartbeat = time.time() |
| 139 | |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 140 | def process(fd): |
| 141 | """ Write the fd to log """ |
Joshua Hesketh | 3c0490b | 2013-08-12 10:33:40 +1000 | [diff] [blame^] | 142 | global last_heartbeat |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 143 | descriptors[fd]['lines'] += os.read(fd, 1024 * 1024) |
| 144 | # Avoid partial lines by only processing input with breaks |
Joshua Hesketh | 09b2f7f | 2013-07-29 09:05:58 +1000 | [diff] [blame] | 145 | if descriptors[fd]['lines'].find('\n') != -1: |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 146 | elems = descriptors[fd]['lines'].split('\n') |
| 147 | # Take all but the partial line |
| 148 | for l in elems[:-1]: |
| 149 | if len(l) > 0: |
| 150 | l = '%s %s' % (descriptors[fd]['name'], l) |
| 151 | logger.info(l) |
| 152 | last_heartbeat = time.time() |
| 153 | # Place the partial line back into lines to be processed |
| 154 | descriptors[fd]['lines'] = elems[-1] |
| 155 | |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 156 | while p.poll() is None: |
| 157 | if timeout > 0 and time.time() - start_time > timeout: |
| 158 | # Append to logfile |
| 159 | logger.info("[timeout]") |
| 160 | os.kill(p.pid, 9) |
| 161 | |
| 162 | for fd, flag in poll_obj.poll(0): |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 163 | process(fd) |
Joshua Hesketh | 0ddd638 | 2013-07-26 10:33:36 +1000 | [diff] [blame] | 164 | |
| 165 | if time.time() - last_heartbeat > 30: |
| 166 | # Append to logfile |
| 167 | logger.info("[heartbeat]") |
| 168 | last_heartbeat = time.time() |
| 169 | |
Joshua Hesketh | 1ab465f | 2013-07-26 13:57:28 +1000 | [diff] [blame] | 170 | # Do one last write to get the remaining lines |
| 171 | for fd, flag in poll_obj.poll(0): |
| 172 | process(fd) |
| 173 | |
Joshua Hesketh | 363d004 | 2013-07-26 11:44:07 +1000 | [diff] [blame] | 174 | logger.info('[script exit code = %d]' % p.returncode) |
Joshua Hesketh | 926502f | 2013-07-31 11:56:40 +1000 | [diff] [blame] | 175 | |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 176 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 177 | def push_file(job_name, file_path, publish_config): |
Joshua Hesketh | 926502f | 2013-07-31 11:56:40 +1000 | [diff] [blame] | 178 | """ Push a log file to a server. Returns the public URL """ |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 179 | method = publish_config['type'] + '_push_file' |
| 180 | if method in locals(): |
Joshua Hesketh | 3c0490b | 2013-08-12 10:33:40 +1000 | [diff] [blame^] | 181 | return locals(method)(job_name, file_path, publish_config) |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 182 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 183 | |
| 184 | def swift_push_file(job_name, file_path, swift_config): |
| 185 | """ Push a log file to a swift server. """ |
| 186 | with open(file_path, 'r') as fd: |
Joshua Hesketh | 27a0e27 | 2013-08-12 10:21:09 +1000 | [diff] [blame] | 187 | name = job_name + '_' + os.path.basename(file_path) |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 188 | con = swiftclient.client.Connection(swift_config['authurl'], |
| 189 | swift_config['user'], |
| 190 | swift_config['apikey']) |
| 191 | obj = con.put_object(swift_config['container'], name, fd) |
Joshua Hesketh | 27a0e27 | 2013-08-12 10:21:09 +1000 | [diff] [blame] | 192 | return obj |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 193 | |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 194 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 195 | def local_push_file(job_name, file_path, local_config): |
| 196 | """ Copy the file locally somewhere sensible """ |
| 197 | dest = os.path.join(local_config['path'], job_name) |
| 198 | os.makedirs(dest) |
| 199 | |
| 200 | dest_file = os.path.join(dest, os.path.basename(file_path)) |
| 201 | os.copyfile(file_path, dest_file) |
| 202 | return dest_file |
| 203 | |
Joshua Hesketh | 9f89805 | 2013-08-09 10:52:34 +1000 | [diff] [blame] | 204 | |
Joshua Hesketh | 11ed32c | 2013-08-09 10:42:36 +1000 | [diff] [blame] | 205 | def scp_push_file(job_name, file_path, local_config): |
| 206 | """ Copy the file remotely over ssh """ |
Joshua Hesketh | 926502f | 2013-07-31 11:56:40 +1000 | [diff] [blame] | 207 | pass |