-
Notifications
You must be signed in to change notification settings - Fork 0
/
glue_helpers.py
511 lines (438 loc) · 20.8 KB
/
glue_helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
#! /usr/bin/env python
#
# Utility functions for writing glue scripts, such as implementing functionality
# available in Unix scripting (e.g., basename command).
#
# TODO:
# - Add more functions to facilitate command-line scripting (check bash scripts for commonly used features).
# - Add functions to facilitate functional programming (e.g., to simply debugging traces).
# - Use functions integrated into juju/common to minimize dual mainentance issues.
#
#
"""Helpers gluing scripts together"""
import glob
import inspect
import os
import re
import shutil
import sys
import tempfile
import textwrap
import debug
import tpo_common as tpo
from tpo_common import debug_format, debug_print, print_stderr, setenv
if sys.version_info[0] < 3:
from commands import getoutput # pylint: disable=import-error
else:
from subprocess import getoutput # pylint: disable=no-name-in-module
# note: ALLOW_SUBCOMMAND_TRACING should be interepreted in terms of detailed
# tracing. Now, basic tracing is still done unless disable_subcommand_tracing()
# invoked. (This way, subscript start/end time shown by default)
ALLOW_SUBCOMMAND_TRACING = tpo.getenv_boolean("ALLOW_SUBCOMMAND_TRACING", False)
default_subtrace_level = min(tpo.USUAL, tpo.debugging_level())
if ALLOW_SUBCOMMAND_TRACING:
default_subtrace_level = tpo.debugging_level()
INDENT = " " # default indentation
#------------------------------------------------------------------------
def get_temp_file(delete=None):
"""Return name of unique temporary file, optionally with DELETE"""
if ((delete is None) and tpo.detailed_debugging()):
delete = False
temp_file_name = tempfile.NamedTemporaryFile(delete=delete).name
# HACK: get rid of double backslashes in Win32 filenames
# ex: r'c:\\temp\\fubar' => r'c:\temp\fubar'
## if os.pathsep == r'\\':
## double_pathspec = os.pathsep + os.pathsep
## temp_file_name = temp_file_name.replace(double_pathspec, os.pathsep)
debug_format("get_temp_file() => {r}", 5, r=temp_file_name)
return temp_file_name
#
TEMP_LOG_FILE = tpo.getenv_text(
# "Log file for stderr (e.g., for issue function)"
"TEMP_LOG_FILE", get_temp_file())
def basename(filename, extension=None):
"""Remove directory from FILENAME along with optional EXTENSION, as with Unix basename command. Note: the period in the extension must be explicitly supplied (e.g., '.data' not 'data')"""
# EX: basename("fubar.py", ".py") => "fubar"
# EX: basename("fubar.py", "py") => "fubar."
# EX: basename("/tmp/solr-4888.log", ".log") => "solr-4888"
base = os.path.basename(filename)
## OLD: if extension != None:
if extension is None:
pos = base.find(extension)
if pos > -1:
base = base[:pos]
debug_print("basename(%s, %s) => %s" % (filename, extension, base), 5)
return base
def remove_extension(filename, extension):
"""Returns FILENAME without EXTENSION. Note: similar to basename() but retainting directory portion."""
# EX: remove_extension("/tmp/solr-4888.log", ".log") => "/tmp/solr-4888"
# EX: remove_extension("/tmp/fubar.py", ".py") => "/tmp/fubar"
# EX: remove_extension("/tmp/fubar.py", "py") => "/tmp/fubar."
# NOTE: Unlike os.path.splitext, only the specific extension is removed (not whichever extension used).
pos = filename.find(extension)
base = filename[:pos] if (pos > -1) else filename
debug_print("remove_extension(%s, %s) => %s" % (filename, extension, base), 5)
return base
def file_exists(filename):
"""Returns indication that FILENAME exists"""
ok = os.path.exists(filename)
debug_print("file_exists(%s) => %s" % (filename, ok), 7)
return ok
def non_empty_file(filename):
"""Whether FILENAME exists and is non-empty"""
size = (os.path.getsize(filename) if os.path.exists(filename) else -1)
non_empty = (size > 0)
debug_print("non_empty_file(%s) => %s (filesize=%s)" % (filename, non_empty, size), 5)
return non_empty
def resolve_path(filename, base_dir=None):
"""Resolves path for FILENAME related to BASE_DIR if not in current directory. Note: this uses the script directory for the calling module if BASE_DIR not specified (i.e., as if os.path.dirname(__file__) passed)."""
path = filename
if not os.path.exists(path):
if not base_dir:
frame = None
try:
frame = inspect.currentframe().f_back
base_dir = os.path.dirname(frame.f_globals['__file__'])
except (AttributeError, KeyError):
base_dir = ""
debug_print("Exception during resolve_path: " + str(sys.exc_info()), 5)
finally:
if frame:
del frame
path = os.path.join(base_dir, path)
debug_format("resolve_path({f}) => {p}", 4, f=filename, p=path)
return path
def form_path(*filenames):
"""Wrapper around os.path.join over FILENAMEs (with tracing)"""
path = os.path.join(*filenames)
debug_format("form_path{f} => {p}", 6, f=tuple(filenames), p=path)
return path
def is_directory(path):
"""Determins wther PATH represents a directory"""
is_dir = os.path.isdir(path)
debug_format("is_dir{p} => {r}", 6, p=path, r=is_dir)
return is_dir
def create_directory(path):
"""Wrapper around os.mkdir over PATH (with tracing)"""
if not os.path.exists(path):
os.mkdir(path)
debug_format("os.mkdir({p})", 6, p=path)
else:
assertion(os.path.isdir(path))
return
def indent(text, indentation=INDENT, max_width=512):
"""Indent TEXT with INDENTATION at beginning of each line, returning string ending in a newline unless empty and with resulting lines longer than max_width characters wrapped. Text is treated as a single paragraph."""
# Note: an empty text is returned without trailing newline
tw = textwrap.TextWrapper(width=max_width, initial_indent=indentation, subsequent_indent=indentation)
wrapped_text = "\n".join(tw.wrap(text))
if wrapped_text:
wrapped_text += "\n"
return wrapped_text
def indent_lines(text, indentation=INDENT, max_width=512):
"""Like indent, except that each line is indented separately. That is, the text is not treated as a single paragraph."""
# Sample usage: print("log contents: {{\n{log}\n}}".format(log=indent_lines(lines)))
# TODO: add support to simplify above idiom (e.g., indent_lines_bracketed); rename to avoid possible confusion that input is array (as wih write_lines)
result = ""
for line in text.split("\n"):
indented_line = indent(line, indentation, max_width)
if not indented_line:
indented_line = "\n"
result += indented_line
return result
MAX_ELIDED_TEXT_LEN = tpo.getenv_integer("MAX_ELIDED_TEXT_LEN", 128)
#
def elide(text, max_len=MAX_ELIDED_TEXT_LEN):
"""Returns TEXT elided to at most MAX_LEN characters (with '...' used to indicate remainder). Note: intended for tracing long string."""
# TODO: add support for eliding at word-boundaries
result = text
if len(result) > max_len:
result = result[:max_len] + "..."
tpo.debug_print("elide({%s}, [{%s}]) => {%s}" % (text, max_len, result), 7)
return result
def disable_subcommand_tracing():
"""Disables tracing in scripts invoked via run()."""
# Note this works by having run() temporarily setting DEBUG_LEVEL to 0."""
global default_subtrace_level
default_subtrace_level = 0
def run(command, trace_level=4, subtrace_level=None, just_issue=False, **namespace):
"""Invokes COMMAND via system shell, using TRACE_LEVEL for debugging output, returning result. The command can use format-style templates, resolved from caller's namespace. The optional SUBTRACE_LEVEL sets tracing for invoked commands (default is same as TRACE_LEVEL); this works around problem with stderr not being separated, which can be a problem when tracing unit tests. Notes: This function doesn't work fully under Win32. Tabs are not preserved, so redirect stdout to a file if needed."""
# TODO: make sure no template markers left in command text (e.g., "tar cvfz {tar_file}")
# EX: "root" in run("ls /")
# Note: Script tracing controlled DEBUG_LEVEL environment variable.
assertion(isinstance(trace_level, int))
debug_print("run(%s, [trace_level=%s], [subtrace_level=%s])" % (command, trace_level, subtrace_level), (trace_level + 2))
global default_subtrace_level
# Keep track of current debug level setting
debug_level_env = None
if subtrace_level is None:
subtrace_level = default_subtrace_level
if subtrace_level != trace_level:
debug_level_env = os.getenv("DEBUG_LEVEL")
setenv("DEBUG_LEVEL", str(subtrace_level))
# Expand the command template
# TODO: make this optional
command_line = command
if re.search("{.*}", command):
command_line = tpo.format(command_line, indirect_caller=True, ignore_exception=False, **namespace)
debug_print("issuing: %s" % command_line, trace_level)
# Run the command
# TODO: check for errors (e.g., "sh: filter_file.py: not found"); make wait explicit
wait = not command.endswith("&")
assertion(wait or not just_issue)
# Note: Unix supports the '>|' pipe operator (i.e., output with overwrite); but,
# it is not supported under Windows. To avoid unexpected porting issues, clients
# should replace 'run("... >| f")' usages with 'delete_file(f); run(...)'.
assertion(">|" not in command_line)
result = None
## TODO: if (just_issue or not wait): ... else: ...
result = getoutput(command_line) if wait else str(os.system(command_line))
# Restore debug level setting in environment
if debug_level_env:
setenv("DEBUG_LEVEL", debug_level_env)
debug_print("run(_) => {\n%s\n}" % indent_lines(result), (trace_level + 1))
return result
def issue(command, trace_level=4, subtrace_level=None, **namespace):
"""Wrapper around run() for when output is not being saved (i.e., just issues command).
Note:
- Nothing is returned.
- Traces stdout when debugging at quite-detailed level (6).
- Captures stderr unless redirected and traces at error level (1)."""
# EX: issue("ls /") => ""
# EX: issue("xeyes &")
debug_print("issue(%s, [trace_level=%s], [subtrace_level=%s])"
% (command, trace_level, subtrace_level), (trace_level + 1))
# Add stderr redirect to temporary log file, unless redirection already present
log_file = None
if tpo.debugging() and (not "2>" in command) and (not "2|&1" in command):
## TODO: use a different suffix each time to aid in debugging
log_file = TEMP_LOG_FILE
## BAD: command += " 2>| " + log_file
delete_file(log_file)
command += " 2> " + log_file
# Run the command and trace output
command_line = command
if re.search("{.*}", command_line):
command_line = tpo.format(command_line, indirect_caller=True, ignore_exception=False, **namespace)
output = run(command_line, trace_level, subtrace_level, just_issue=True)
tpo.debug_print("stdout from command: {\n%s\n}\n" % indent(output), (2 + trace_level))
# Trace out any standard error output and remove temporary log file (unless debugging)
if log_file:
if tpo.debugging() and non_empty_file(log_file):
stderr_output = indent(read_file(log_file))
tpo.debug_print("stderr output from command: {\n%s\n}\n" % indent(stderr_output))
if not tpo.detailed_debugging():
delete_file(log_file)
return
def get_hex_dump(text, break_newlines=False):
"""Get hex dump for TEXT, optionally BREAKing lines on NEWLINES"""
# TODO: implement entirely within Pyton (e.g., via binascii.hexlify)
# EX: get_hex_dump
debug.trace_fmt(6, "get_hex_dump{{t}, {bn})", t=text, bn=break_newlines)
in_file = get_temp_file() + ".in.list"
out_file = get_temp_file() + ".out.list"
write_file(in_file, text)
run("perl -Ss hexview.perl -newlines {i} > {o}", i=in_file, o=out_file)
result = read_file(out_file)
return result
def extract_matches(pattern, lines, fields=1):
"""Checks for PATTERN matches in LINES of text returning list of tuples with replacement groups"""
# ex: extract_matches(r"^(\S+) \S+", ["John D.", "Jane D.", "Plato"]) => ["John", "Jane"]
## assert type(lines) == list
assert isinstance(lines, list)
if pattern.find("(") == -1:
pattern = "(" + pattern + ")"
matches = []
for line in lines:
try:
match = re.search(pattern, line)
if match:
result = match.group(1) if (fields == 1) else [match.group(i + 1) for i in range(fields)]
matches.append(result)
except (re.error, IndexError):
debug_print("Warning: Exception in pattern matching: %s" % str(sys.exc_info()), 2)
debug_print("extract_matches(%s, _, [%s]) => %s" % (pattern, fields, matches), 7)
double_indent = INDENT + INDENT
debug_format("{ind}input lines: {{\n{res}\n{ind}}}", 8,
ind=INDENT, res=indent_lines("\n".join(lines), double_indent))
return matches
def extract_match(pattern, lines, fields=1):
"""Extracts first match of PATTERN in LINES for FIELDS"""
matches = extract_matches(pattern, lines, fields)
result = (matches[0] if matches else None)
debug_print("match: %s" % result, 5)
return result
def extract_match_from_text(pattern, text, fields=1):
"""Wrapper around extract_match for single match"""
## TODO: rework to allow for multiple-line matching
return extract_match(pattern, text.split("\n"), fields)
def read_lines(filename=None, make_unicode=False):
"""Returns list of lines from FILENAME without newlines (or other extra whitespace)
@notes: Uses stdin if filename is None. Optionally returned as unicode."""
# TODO: use enumerate(f); refine exception in except;
# TODO: force unicode if UTF8 encountered
lines = []
f = None
try:
# Open the file
if not filename:
tpo.debug_format("Reading from stdin", 4)
f = sys.stdin
else:
f = open(filename)
if not f:
raise IOError
# Read line by line
for line in f:
line = line.strip("\n")
if make_unicode:
line = tpo.ensure_unicode(line)
lines.append(line)
except IOError:
debug_print("Warning: Exception reading file %s: %s" % (filename, str(sys.exc_info())), 2)
finally:
if f:
f.close()
debug_print("read_lines(%s) => %s" % (filename, lines), 6)
return lines
def write_lines(filename, text_lines, append=False):
"""Creates FILENAME using TEXT_LINES with newlines added and optionally for APPEND"""
debug_print("write_lines(%s, _)" % (filename), 5)
debug_print(" text_lines=%s" % text_lines, 6)
f = None
try:
mode = 'a' if append else 'w'
f = open(filename, mode)
for line in text_lines:
line = tpo.normalize_unicode(line)
f.write(line + "\n")
except IOError:
debug_print("Warning: Exception writing file %s: %s" % (filename, str(sys.exc_info())), 2)
finally:
if f:
f.close()
return
def read_file(filename, make_unicode=False):
"""Returns text from FILENAME (single string), including newline(s).
Note: optionally returned as unicde."""
debug_print("read_file(%s)" % filename, 7)
text = "\n".join(read_lines(filename, make_unicode=make_unicode))
return (text + "\n") if text else ""
def write_file(filename, text, append=False):
"""Writes FILENAME using contents in TEXT, adding trailing newline and optionally for APPEND"""
## TEST: debug_print(u"write_file(%s, %s)" % (filename, text), 7)
## TEST: debug_print(u"write_file(%s, %s)" % (filename, tpo.normalize_unicode(text)), 7)
debug_print("write_file(%s, %s)" % (tpo.normalize_unicode(filename), tpo.normalize_unicode(text)), 7)
text_lines = text.rstrip("\n").split("\n")
return write_lines(filename, text_lines, append)
def copy_file(source, target):
"""Copy SOURCE file to TARGET file"""
# Note: meta data is not copied (e.g., access control lists)); see
# https://docs.python.org/2/library/shutil.html
debug_print("copy_file(%s, %s)" % (tpo.normalize_unicode(source), tpo.normalize_unicode(target)), 5)
assertion(non_empty_file(source))
shutil.copy(source, target)
assertion(non_empty_file(target))
return
def delete_file(filename):
"""Deletes FILENAME"""
debug_print("delete_file(%s)" % tpo.normalize_unicode(filename), 5)
assertion(os.path.exists(filename))
ok = False
try:
ok = os.remove(filename)
debug_format("remove{f} => {r}", 6, f=filename, r=ok)
except OSError:
debug_print("Exception during deletion of {filename}: " + str(sys.exc_info()), 5)
return ok
def delete_existing_file(filename):
"""Deletes FILENAME if it exists and is not a directory or other special file"""
ok = False
if file_exists(filename):
ok = delete_file(filename)
tpo.debug_format("delete_existing_file({f}) => {r}", 5, f=filename, r=ok)
return ok
def file_size(filename):
"""Returns size of FILENAME in bytes (or -1 if not found)"""
size = -1
if os.path.exists(filename):
size = os.path.getsize(filename)
tpo.debug_format("file_size({f}) => {s}", 5, f=filename, s=size)
return size
def get_matching_files(pattern):
"""Get list of files matching pattern via shell globbing"""
files = glob.glob(pattern)
tpo.debug_format("get_matching_files({p}) => {l}", 5,
p=pattern, l=files)
return files
def get_directory_listing(dirname, make_unicode=False):
"""Returns files in DIRNAME"""
all_file_names = []
try:
all_file_names = os.listdir(dirname)
except OSError:
tpo.debug_format("Exception during get_directory_listing: {exc}", 4,
exc=str(sys.exc_info()))
if make_unicode:
all_file_names = [tpo.ensure_unicode(f) for f in all_file_names]
tpo.debug_format("get_directory_listing({dir}) => {files}", 5,
dir=dirname, files=all_file_names)
return all_file_names
#-------------------------------------------------------------------------------
# Extensions to tpo_common included here due to inclusion of functions
# defined here.
def getenv_filename(var, default="", description=None):
"""Returns text filename based on environment variable VAR (or string version of DEFAULT)
with optional DESCRIPTION. This includes a sanity check for file being non-empty."""
debug_format("getenv_filename({v}, {d}, {desc})", 6,
v=var, d=default, desc=description)
filename = tpo.getenv_text(var, default, description)
if filename and not non_empty_file(filename):
tpo.print_stderr("Error: filename %s empty or missing for environment option %s" % (filename, var))
return filename
if __debug__:
def assertion(condition):
"""Issues warning if CONDITION doesn't hold"""
# EX: assertion(2 + 2 != 5)
# TODO: rename as soft_assertion???; add to tpo_common.py (along with run???)
if not condition:
# Try to get file and line number from stack frame
# note: not available during interactive use
filename = None
line_num = -1
frame = None
try:
frame = inspect.currentframe().f_back
tpo.debug_trace("frame=%s", frame, level=8)
tpo.trace_object(frame, 9, "frame")
filename = frame.f_globals.get("__file__")
if filename and filename.endswith(".pyc"):
filename = filename[:-1]
line_num = frame.f_lineno
finally:
if frame:
del frame
# Get text for line and extract the condition from invocation,
# ignoring comments and function name.
# TODO: define function for extracting line, so this can be put in tpo_common.py
line = "???"
if filename:
line = run("tail --lines=+{l} '{f}' | head -1",
subtrace_level=8, f=filename, l=line_num)
condition = re.sub(r"^\s*\S*assertion\((.*)\)\s*(\#.*)?$",
"\\1", line)
# Print the assertion warning
line_spec = "???"
if filename:
line_spec = "{f}:{l}".format(f=filename, l=line_num)
debug_format("*** Warning: assertion failed: ({c}) at {ls}",
tpo.WARNING, c=condition, ls=line_spec)
return
else:
def assertion(_condition):
"""Non-debug stub for assertion"""
return
#------------------------------------------------------------------------
# Warn if invoked standalone
#
if __name__ == '__main__':
print_stderr("Warning: %s is not intended to be run standalone" % __file__)