mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # |
| 3 | # Copyright 2007 Google Inc. Released under the GPL v2 |
| 4 | |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 5 | """ |
| 6 | Miscellaneous small functions. |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 7 | """ |
| 8 | |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 9 | __author__ = """ |
| 10 | mbligh@google.com (Martin J. Bligh), |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 11 | poirier@google.com (Benjamin Poirier), |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 12 | stutsman@google.com (Ryan Stutsman) |
| 13 | """ |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 14 | |
mbligh | f1c5284 | 2007-10-16 15:21:38 +0000 | [diff] [blame] | 15 | import atexit, os, select, shutil, signal, StringIO, subprocess, tempfile |
| 16 | import time, types, urllib, re |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 17 | |
mbligh | f1c5284 | 2007-10-16 15:21:38 +0000 | [diff] [blame] | 18 | import hosts, errors |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 19 | |
mbligh | bea5682 | 2007-08-31 08:53:40 +0000 | [diff] [blame] | 20 | # A dictionary of pid and a list of tmpdirs for that pid |
| 21 | __tmp_dirs = {} |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 22 | |
| 23 | |
| 24 | def sh_escape(command): |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 25 | """ |
| 26 | Escape special characters from a command so that it can be passed |
mbligh | c8949b8 | 2007-07-23 16:33:58 +0000 | [diff] [blame] | 27 | as a double quoted (" ") string in a (ba)sh command. |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 28 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 29 | Args: |
| 30 | command: the command string to escape. |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 31 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 32 | Returns: |
| 33 | The escaped command string. The required englobing double |
| 34 | quotes are NOT added and so should be added at some point by |
| 35 | the caller. |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 36 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 37 | See also: http://www.tldp.org/LDP/abs/html/escapingsection.html |
| 38 | """ |
| 39 | command= command.replace("\\", "\\\\") |
| 40 | command= command.replace("$", r'\$') |
| 41 | command= command.replace('"', r'\"') |
| 42 | command= command.replace('`', r'\`') |
| 43 | return command |
| 44 | |
| 45 | |
| 46 | def scp_remote_escape(filename): |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 47 | """ |
| 48 | Escape special characters from a filename so that it can be passed |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 49 | to scp (within double quotes) as a remote file. |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 50 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 51 | Bis-quoting has to be used with scp for remote files, "bis-quoting" |
| 52 | as in quoting x 2 |
| 53 | scp does not support a newline in the filename |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 54 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 55 | Args: |
| 56 | filename: the filename string to escape. |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 57 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 58 | Returns: |
| 59 | The escaped filename string. The required englobing double |
| 60 | quotes are NOT added and so should be added at some point by |
| 61 | the caller. |
| 62 | """ |
| 63 | escape_chars= r' !"$&' "'" r'()*,:;<=>?[\]^`{|}' |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 64 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 65 | new_name= [] |
| 66 | for char in filename: |
| 67 | if char in escape_chars: |
| 68 | new_name.append("\\%s" % (char,)) |
| 69 | else: |
| 70 | new_name.append(char) |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 71 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 72 | return sh_escape("".join(new_name)) |
| 73 | |
| 74 | |
| 75 | def get(location): |
| 76 | """Get a file or directory to a local temporary directory. |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 77 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 78 | Args: |
| 79 | location: the source of the material to get. This source may |
| 80 | be one of: |
| 81 | * a local file or directory |
| 82 | * a URL (http or ftp) |
| 83 | * a python file-like object |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 84 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 85 | Returns: |
| 86 | The location of the file or directory where the requested |
| 87 | content was saved. This will be contained in a temporary |
mbligh | c8949b8 | 2007-07-23 16:33:58 +0000 | [diff] [blame] | 88 | directory on the local host. If the material to get was a |
| 89 | directory, the location will contain a trailing '/' |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 90 | """ |
| 91 | tmpdir = get_tmp_dir() |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 92 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 93 | # location is a file-like object |
| 94 | if hasattr(location, "read"): |
| 95 | tmpfile = os.path.join(tmpdir, "file") |
| 96 | tmpfileobj = file(tmpfile, 'w') |
| 97 | shutil.copyfileobj(location, tmpfileobj) |
| 98 | tmpfileobj.close() |
| 99 | return tmpfile |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 100 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 101 | if isinstance(location, types.StringTypes): |
| 102 | # location is a URL |
| 103 | if location.startswith('http') or location.startswith('ftp'): |
| 104 | tmpfile = os.path.join(tmpdir, os.path.basename(location)) |
| 105 | urllib.urlretrieve(location, tmpfile) |
| 106 | return tmpfile |
| 107 | # location is a local path |
| 108 | elif os.path.exists(os.path.abspath(location)): |
| 109 | tmpfile = os.path.join(tmpdir, os.path.basename(location)) |
| 110 | if os.path.isdir(location): |
| 111 | tmpfile += '/' |
| 112 | shutil.copytree(location, tmpfile, symlinks=True) |
| 113 | return tmpfile |
| 114 | shutil.copyfile(location, tmpfile) |
| 115 | return tmpfile |
| 116 | # location is just a string, dump it to a file |
| 117 | else: |
| 118 | tmpfd, tmpfile = tempfile.mkstemp(dir=tmpdir) |
| 119 | tmpfileobj = os.fdopen(tmpfd, 'w') |
| 120 | tmpfileobj.write(location) |
| 121 | tmpfileobj.close() |
| 122 | return tmpfile |
| 123 | |
| 124 | |
mbligh | cf965b0 | 2007-07-25 16:49:45 +0000 | [diff] [blame] | 125 | def run(command, timeout=None, ignore_status=False): |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 126 | """ |
| 127 | Run a command on the host. |
| 128 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 129 | Args: |
| 130 | command: the command line string |
| 131 | timeout: time limit in seconds before attempting to |
| 132 | kill the running process. The run() function |
| 133 | will take a few seconds longer than 'timeout' |
| 134 | to complete if it has to kill the process. |
mbligh | 8b85dfb | 2007-08-28 09:50:31 +0000 | [diff] [blame] | 135 | ignore_status: do not raise an exception, no matter what |
| 136 | the exit code of the command is. |
| 137 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 138 | Returns: |
| 139 | a hosts.CmdResult object |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 140 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 141 | Raises: |
| 142 | AutoservRunError: the exit code of the command |
| 143 | execution was not 0 |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 144 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 145 | TODO(poirier): Add a "tee" option to send the command's |
| 146 | stdout and stderr to python's stdout and stderr? At |
| 147 | the moment, there is no way to see the command's |
| 148 | output as it is running. |
| 149 | TODO(poirier): Should a timeout raise an exception? Should |
| 150 | exceptions be raised at all? |
| 151 | """ |
| 152 | result= hosts.CmdResult() |
| 153 | result.command= command |
| 154 | sp= subprocess.Popen(command, stdout=subprocess.PIPE, |
| 155 | stderr=subprocess.PIPE, close_fds=True, shell=True, |
| 156 | executable="/bin/bash") |
mbligh | 0dd2ae0 | 2007-08-01 17:31:10 +0000 | [diff] [blame] | 157 | |
| 158 | try: |
| 159 | # We are holding ends to stdin, stdout pipes |
| 160 | # hence we need to be sure to close those fds no mater what |
| 161 | start_time= time.time() |
| 162 | if timeout: |
| 163 | stop_time= start_time + timeout |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 164 | time_left= stop_time - time.time() |
mbligh | 0dd2ae0 | 2007-08-01 17:31:10 +0000 | [diff] [blame] | 165 | while time_left > 0: |
| 166 | # select will return when stdout is ready |
| 167 | # (including when it is EOF, that is the |
| 168 | # process has terminated). |
| 169 | (retval, tmp, tmp) = select.select( |
| 170 | [sp.stdout], [], [], time_left) |
| 171 | if len(retval): |
| 172 | # os.read() has to be used instead of |
| 173 | # sp.stdout.read() which will |
| 174 | # otherwise block |
| 175 | result.stdout += os.read( |
| 176 | sp.stdout.fileno(), 1024) |
| 177 | |
| 178 | (pid, exit_status_indication) = os.waitpid( |
| 179 | sp.pid, os.WNOHANG) |
| 180 | if pid: |
| 181 | stop_time= time.time() |
| 182 | time_left= stop_time - time.time() |
| 183 | |
| 184 | # the process has not terminated within timeout, |
| 185 | # kill it via an escalating series of signals. |
| 186 | if not pid: |
| 187 | signal_queue = [signal.SIGTERM, signal.SIGKILL] |
| 188 | for sig in signal_queue: |
| 189 | try: |
| 190 | os.kill(sp.pid, sig) |
| 191 | # handle race condition in which |
| 192 | # process died before we could kill it. |
| 193 | except OSError: |
| 194 | pass |
| 195 | |
| 196 | for i in range(5): |
| 197 | (pid, exit_status_indication |
| 198 | ) = os.waitpid(sp.pid, |
| 199 | os.WNOHANG) |
| 200 | if pid: |
| 201 | break |
| 202 | else: |
| 203 | time.sleep(1) |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 204 | if pid: |
| 205 | break |
mbligh | 0dd2ae0 | 2007-08-01 17:31:10 +0000 | [diff] [blame] | 206 | else: |
| 207 | exit_status_indication = os.waitpid(sp.pid, 0)[1] |
| 208 | |
| 209 | result.duration = time.time() - start_time |
| 210 | result.aborted = exit_status_indication & 127 |
| 211 | if result.aborted: |
| 212 | result.exit_status= None |
| 213 | else: |
| 214 | result.exit_status= exit_status_indication / 256 |
| 215 | result.stdout += sp.stdout.read() |
| 216 | result.stderr = sp.stderr.read() |
| 217 | |
| 218 | finally: |
| 219 | # close our ends of the pipes to the sp no matter what |
| 220 | sp.stdout.close() |
| 221 | sp.stderr.close() |
mbligh | cf965b0 | 2007-07-25 16:49:45 +0000 | [diff] [blame] | 222 | |
| 223 | if not ignore_status and result.exit_status > 0: |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 224 | raise errors.AutoservRunError("command execution error", |
| 225 | result) |
mbligh | 0dd2ae0 | 2007-08-01 17:31:10 +0000 | [diff] [blame] | 226 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 227 | return result |
| 228 | |
| 229 | |
mbligh | 5f876ad | 2007-10-12 23:59:53 +0000 | [diff] [blame] | 230 | def system(command, timeout=None, ignore_status=False): |
| 231 | return run(command, timeout, ignore_status).exit_status |
| 232 | |
| 233 | |
| 234 | def system_output(command, timeout=None, ignore_status=False): |
| 235 | return run(command, timeout, ignore_status).stdout |
| 236 | |
| 237 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 238 | def get_tmp_dir(): |
| 239 | """Return the pathname of a directory on the host suitable |
| 240 | for temporary file storage. |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 241 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 242 | The directory and its content will be deleted automatically |
| 243 | at the end of the program execution if they are still present. |
| 244 | """ |
| 245 | global __tmp_dirs |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 246 | |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 247 | dir_name= tempfile.mkdtemp(prefix="autoserv-") |
mbligh | bea5682 | 2007-08-31 08:53:40 +0000 | [diff] [blame] | 248 | pid = os.getpid() |
| 249 | if not pid in __tmp_dirs: |
| 250 | __tmp_dirs[pid] = [] |
| 251 | __tmp_dirs[pid].append(dir_name) |
mbligh | dcd57a8 | 2007-07-11 23:06:47 +0000 | [diff] [blame] | 252 | return dir_name |
| 253 | |
| 254 | |
| 255 | @atexit.register |
| 256 | def __clean_tmp_dirs(): |
| 257 | """Erase temporary directories that were created by the get_tmp_dir() |
| 258 | function and that are still present. |
| 259 | """ |
| 260 | global __tmp_dirs |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 261 | |
mbligh | bea5682 | 2007-08-31 08:53:40 +0000 | [diff] [blame] | 262 | pid = os.getpid() |
| 263 | if pid not in __tmp_dirs: |
| 264 | return |
| 265 | for dir in __tmp_dirs[pid]: |
| 266 | try: |
| 267 | shutil.rmtree(dir) |
| 268 | except OSError, e: |
| 269 | if e.errno == 2: |
| 270 | pass |
| 271 | __tmp_dirs[pid] = [] |
mbligh | c8949b8 | 2007-07-23 16:33:58 +0000 | [diff] [blame] | 272 | |
| 273 | |
| 274 | def unarchive(host, source_material): |
| 275 | """Uncompress and untar an archive on a host. |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 276 | |
mbligh | c8949b8 | 2007-07-23 16:33:58 +0000 | [diff] [blame] | 277 | If the "source_material" is compresses (according to the file |
| 278 | extension) it will be uncompressed. Supported compression formats |
| 279 | are gzip and bzip2. Afterwards, if the source_material is a tar |
| 280 | archive, it will be untarred. |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 281 | |
mbligh | c8949b8 | 2007-07-23 16:33:58 +0000 | [diff] [blame] | 282 | Args: |
| 283 | host: the host object on which the archive is located |
| 284 | source_material: the path of the archive on the host |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 285 | |
mbligh | c8949b8 | 2007-07-23 16:33:58 +0000 | [diff] [blame] | 286 | Returns: |
| 287 | The file or directory name of the unarchived source material. |
| 288 | If the material is a tar archive, it will be extracted in the |
| 289 | directory where it is and the path returned will be the first |
| 290 | entry in the archive, assuming it is the topmost directory. |
| 291 | If the material is not an archive, nothing will be done so this |
| 292 | function is "harmless" when it is "useless". |
| 293 | """ |
| 294 | # uncompress |
| 295 | if (source_material.endswith(".gz") or |
| 296 | source_material.endswith(".gzip")): |
| 297 | host.run('gunzip "%s"' % (sh_escape(source_material))) |
| 298 | source_material= ".".join(source_material.split(".")[:-1]) |
| 299 | elif source_material.endswith("bz2"): |
| 300 | host.run('bunzip2 "%s"' % (sh_escape(source_material))) |
| 301 | source_material= ".".join(source_material.split(".")[:-1]) |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 302 | |
mbligh | c8949b8 | 2007-07-23 16:33:58 +0000 | [diff] [blame] | 303 | # untar |
| 304 | if source_material.endswith(".tar"): |
| 305 | retval= host.run('tar -C "%s" -xvf "%s"' % ( |
| 306 | sh_escape(os.path.dirname(source_material)), |
| 307 | sh_escape(source_material),)) |
| 308 | source_material= os.path.join(os.path.dirname(source_material), |
| 309 | retval.stdout.split()[0]) |
mbligh | dc735a2 | 2007-08-02 16:54:37 +0000 | [diff] [blame] | 310 | |
mbligh | c8949b8 | 2007-07-23 16:33:58 +0000 | [diff] [blame] | 311 | return source_material |
mbligh | f1c5284 | 2007-10-16 15:21:38 +0000 | [diff] [blame] | 312 | |
| 313 | |
| 314 | def write_keyval(dirname, dictionary): |
| 315 | keyval = open(os.path.join(dirname, 'keyval'), 'w') |
| 316 | for key in dictionary.keys(): |
| 317 | value = '%s' % dictionary[key] # convert numbers to strings |
| 318 | if re.search(r'\W', key): |
| 319 | raise 'Invalid key: ' + key |
| 320 | keyval.write('%s=%s\n' % (key, str(value))) |
| 321 | keyval.close() |
| 322 | |