Skip to content

Commit 1a43d81

Browse files
committed
Guard debug tracing with a TRACE flag
Signed-off-by: Philippe Ombredanne <[email protected]>
1 parent 858189e commit 1a43d81

File tree

6 files changed

+72
-70
lines changed

6 files changed

+72
-70
lines changed

src/container_inspector/cli.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,25 @@
66
# See https://aboutcode.org for more information about nexB OSS projects.
77
#
88

9-
import csv as csv_module
10-
import json as json_module
119
import logging
1210
import os
13-
from os import path
1411
import sys
1512
import tempfile
13+
import csv as csv_module
14+
import json as json_module
15+
from os import path
1616

1717
import click
1818

1919
from container_inspector import image
2020
from container_inspector import dockerfile
2121
from container_inspector import rootfs
2222

23+
TRACE = False
2324
logger = logging.getLogger(__name__)
24-
# un-comment these lines to enable logging
25-
# logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
26-
# logger.setLevel(logging.DEBUG)
25+
if TRACE:
26+
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
27+
logger.setLevel(logging.DEBUG)
2728

2829

2930
@click.command()

src/container_inspector/distro.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,15 @@
1515

1616
from container_inspector import rootfs
1717

18+
TRACE = False
1819
logger = logging.getLogger(__name__)
19-
# un-comment these lines to enable logging
20-
import sys
21-
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
22-
logger.setLevel(logging.DEBUG)
2320

2421

25-
def logger_debug(*args):
26-
return logger.debug(' '.join(isinstance(a, str) and a or repr(a) for a in args))
22+
23+
if TRACE:
24+
import sys
25+
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
26+
logger.setLevel(logging.DEBUG)
2727

2828
"""
2929
Utilities to detect the "distro" of a root filesystem (be it a VM or rootfs
@@ -297,7 +297,7 @@ def from_os_release_file(cls, location):
297297
parsed
298298
"""
299299
if not location or not os.path.exists(location):
300-
logger.debug(f'from_os_release_file: {location!r} does not exists')
300+
if TRACE: logger.debug(f'from_os_release_file: {location!r} does not exists')
301301
return
302302

303303
data = parse_os_release(location) or {}
@@ -334,7 +334,7 @@ def from_os_release_file(cls, location):
334334
if data:
335335
new_data['extra_data'] = data
336336

337-
logger.debug(f'from_os_release_file: new_data: {new_data!r}')
337+
if TRACE: logger.debug(f'from_os_release_file: new_data: {new_data!r}')
338338

339339
return cls(**new_data)
340340

@@ -357,10 +357,10 @@ def from_rootfs(cls, location, base_distro=None):
357357
manifest) and may be missing from the rootfs proper (for instance of an
358358
/etc/os-release is missing in the rootfs for a Linux-based image).
359359
"""
360-
logger.debug(f'from_rootfs: {location!r} base_distro: {base_distro!r}')
360+
if TRACE: logger.debug(f'from_rootfs: {location!r} base_distro: {base_distro!r}')
361361

362362
if not location or not os.path.exists(location):
363-
logger.debug(f'from_rootfs: {location!r} does not exists')
363+
if TRACE: logger.debug(f'from_rootfs: {location!r} does not exists')
364364
return
365365

366366
finders = {
@@ -370,10 +370,10 @@ def from_rootfs(cls, location, base_distro=None):
370370
}
371371

372372
for finder_os, finder in finders.items():
373-
logger.debug(f'from_rootfs: trying finder_os: {finder_os!r}')
373+
if TRACE: logger.debug(f'from_rootfs: trying finder_os: {finder_os!r}')
374374

375375
found = finder(location)
376-
logger.debug(f'from_rootfs: trying found: {found!r}')
376+
if TRACE: logger.debug(f'from_rootfs: trying found: {found!r}')
377377
if found:
378378
if base_distro:
379379
if base_distro.os != finder_os:
@@ -383,11 +383,11 @@ def from_rootfs(cls, location, base_distro=None):
383383
)
384384

385385
merged = base_distro.merge(found)
386-
logger.debug(f'from_rootfs: returning merged: {merged!r}')
386+
if TRACE: logger.debug(f'from_rootfs: returning merged: {merged!r}')
387387
return merged
388388

389389
else:
390-
logger.debug(f'from_rootfs: returning found: {found!r}')
390+
if TRACE: logger.debug(f'from_rootfs: returning found: {found!r}')
391391
return found
392392

393393
@classmethod
@@ -457,7 +457,7 @@ def merge(self, other_distro):
457457
Return a new distro based on this Distro data updated with non-empty
458458
values from the ``other_distro`` Distro object.
459459
"""
460-
logger.debug(f'merge: {self!r} with: {other_distro!r}')
460+
if TRACE: logger.debug(f'merge: {self!r} with: {other_distro!r}')
461461

462462
existing = self.to_dict()
463463
if other_distro:
@@ -466,9 +466,9 @@ def merge(self, other_distro):
466466
if v
467467
}
468468
existing.update(other_non_empty)
469-
logger.debug(f'merge: updated data: {existing!r}')
469+
if TRACE: logger.debug(f'merge: updated data: {existing!r}')
470470

471-
logger.debug(f'merge: merged data: {existing!r}')
471+
if TRACE: logger.debug(f'merge: merged data: {existing!r}')
472472

473473
return type(self)(**existing)
474474

src/container_inspector/dockerfile.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,17 @@
88

99
import logging
1010
import operator
11+
import os
1112
from os import path
1213

1314
import dockerfile_parse
14-
import os
1515

16+
TRACE = False
1617
logger = logging.getLogger(__name__)
17-
# un-comment these lines to enable logging
18-
# logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
19-
# logger.setLevel(logging.DEBUG)
18+
if TRACE:
19+
import sys
20+
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
21+
logger.setLevel(logging.DEBUG)
2022

2123
"""
2224
Analysis helper for Docker Dockerfiles.
@@ -32,7 +34,7 @@ def get_dockerfile(location):
3234
if not 'Dockerfile' in fn:
3335
return {}
3436

35-
logger.debug('Found Dockerfile at: %(location)r' % locals())
37+
if TRACE: logger.debug('Found Dockerfile at: %(location)r' % locals())
3638

3739
try:
3840
# TODO: keep comments instead of ignoring them:
@@ -52,7 +54,7 @@ def get_dockerfile(location):
5254
df_data['instructions'].append(entry)
5355
return {location: df_data}
5456
except:
55-
logger.debug('Error parsing Dockerfile at: %(location)r' % locals())
57+
if TRACE: logger.debug('Error parsing Dockerfile at: %(location)r' % locals())
5658
return {}
5759

5860

@@ -80,7 +82,7 @@ def collect_dockerfiles(location):
8082
for top, dirs, files in os.walk(location):
8183
for f in files:
8284
dfiles.update(get_dockerfile(path.join(top, f)))
83-
logger.debug('collect_dockerfiles: %(dfiles)r' % locals())
85+
if TRACE: logger.debug('collect_dockerfiles: %(dfiles)r' % locals())
8486
return dfiles
8587

8688

src/container_inspector/image.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,12 @@
2121
from container_inspector.utils import load_json
2222
from container_inspector.utils import sha256_digest
2323

24+
TRACE = False
2425
logger = logging.getLogger(__name__)
25-
# un-comment these lines to enable logging
26-
import sys
27-
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
28-
logger.setLevel(logging.DEBUG)
29-
30-
31-
def logger_debug(*args):
32-
return logger.debug(' '.join(isinstance(a, str) and a or repr(a) for a in args))
26+
if TRACE:
27+
import sys
28+
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
29+
logger.setLevel(logging.DEBUG)
3330

3431
"""
3532
Objects to handle Docker and OCI images and Layers.
@@ -419,7 +416,7 @@ def get_images_from_tarball(
419416
If `verify` is True, perform extra checks on the config data and layers
420417
checksums.
421418
"""
422-
logger.debug(f'get_images_from_tarball: {archive_location} , extracting to: {extracted_location}')
419+
if TRACE: logger.debug(f'get_images_from_tarball: {archive_location} , extracting to: {extracted_location}')
423420

424421
Image.extract(
425422
archive_location=archive_location,
@@ -445,14 +442,14 @@ def get_images_from_dir(
445442
If `verify` is True, perform extra checks on the config data and layers
446443
checksums.
447444
"""
448-
logger.debug(f'get_images_from_dir: from {extracted_location} and archive_location: {archive_location}')
445+
if TRACE: logger.debug(f'get_images_from_dir: from {extracted_location} and archive_location: {archive_location}')
449446

450447
if not os.path.isdir(extracted_location):
451448
raise Exception(f'Not a directory: {extracted_location}')
452449

453450
image_format = Image.find_format(extracted_location)
454451

455-
logger.debug(f'get_images_from_dir: image_format: {image_format}')
452+
if TRACE: logger.debug(f'get_images_from_dir: image_format: {image_format}')
456453

457454
if image_format == 'docker':
458455
return Image.get_docker_images_from_dir(
@@ -510,7 +507,7 @@ def get_docker_images_from_dir(
510507
....
511508
]
512509
"""
513-
logger.debug(f'get_docker_images_from_dir: {extracted_location}')
510+
if TRACE: logger.debug(f'get_docker_images_from_dir: {extracted_location}')
514511

515512
if not os.path.isdir(extracted_location):
516513
raise Exception(f'Not a directory: {extracted_location}')
@@ -523,19 +520,19 @@ def get_docker_images_from_dir(
523520

524521
manifest = load_json(manifest_loc)
525522

526-
logger.debug(f'get_docker_images_from_dir: manifest: {manifest}')
523+
if TRACE: logger.debug(f'get_docker_images_from_dir: manifest: {manifest}')
527524

528525
images = []
529526
for manifest_config in manifest:
530-
logger.debug(f'get_docker_images_from_dir: manifest_config: {manifest_config}')
527+
if TRACE: logger.debug(f'get_docker_images_from_dir: manifest_config: {manifest_config}')
531528
img = Image.from_docker_manifest_config(
532529
extracted_location=extracted_location,
533530
archive_location=archive_location,
534531
manifest_config=manifest_config,
535532
verify=verify,
536533

537534
)
538-
logger.debug(f'get_docker_images_from_dir: img: {img!r}')
535+
if TRACE: logger.debug(f'get_docker_images_from_dir: img: {img!r}')
539536

540537
images.append(img)
541538

@@ -612,7 +609,7 @@ def from_docker_manifest_config(
612609
}
613610
}
614611
"""
615-
logger.debug(f'from_docker_manifest_config: manifest_config: {manifest_config!r}')
612+
if TRACE: logger.debug(f'from_docker_manifest_config: manifest_config: {manifest_config!r}')
616613

617614
manifest_config = utils.lower_keys(manifest_config)
618615

src/container_inspector/rootfs.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,12 @@
1414
from commoncode.fileutils import delete
1515
from commoncode.paths import split
1616

17+
TRACE = False
1718
logger = logging.getLogger(__name__)
18-
# un-comment these lines to enable logging
19-
import sys
20-
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
21-
logger.setLevel(logging.DEBUG)
19+
if TRACE:
20+
import sys
21+
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
22+
logger.setLevel(logging.DEBUG)
2223

2324
"""
2425
Utilities to handle image and layer archives and recreate proper rootfs
@@ -64,7 +65,7 @@ def rebuild_rootfs(img, target_dir):
6465
deletions = []
6566

6667
for layer_num, layer in enumerate(img.layers):
67-
logger.debug(
68+
if TRACE: logger.debug(
6869
f'Extracting layer {layer_num} - {layer.layer_id} '
6970
f'tarball: {layer.archive_location}'
7071
)
@@ -73,26 +74,26 @@ def rebuild_rootfs(img, target_dir):
7374
# Note that we are not preserving any special file and any file permission
7475
extracted_loc = tempfile.mkdtemp('container_inspector-docker')
7576
layer.extract(extracted_location=extracted_loc)
76-
logger.debug(f' Extracted layer to: {extracted_loc}')
77+
if TRACE: logger.debug(f' Extracted layer to: {extracted_loc}')
7778

7879
# 2. find whiteouts in that layer.
7980
whiteouts = list(find_whiteouts(extracted_loc))
80-
logger.debug(' Merging extracted layers and applying unionfs whiteouts')
81-
logger.debug(' Whiteouts:\n' + ' \n'.join(map(repr, whiteouts)))
81+
if TRACE: logger.debug(' Merging extracted layers and applying unionfs whiteouts')
82+
if TRACE: logger.debug(' Whiteouts:\n' + ' \n'.join(map(repr, whiteouts)))
8283

8384
# 3. remove whiteouts in the previous layer stack (e.g. the WIP rootfs)
8485
for whiteout_marker_loc, whiteable_path in whiteouts:
85-
logger.debug(f' Deleting dir or file with whiteout marker: {whiteout_marker_loc}')
86+
if TRACE: logger.debug(f' Deleting dir or file with whiteout marker: {whiteout_marker_loc}')
8687
whiteable_loc = os.path.join(target_dir, whiteable_path)
8788
delete(whiteable_loc)
8889
# also delete the whiteout marker file
8990
delete(whiteout_marker_loc)
9091
deletions.append(whiteable_loc)
9192

9293
# 4. finall copy/overwrite the extracted layer over the WIP rootfs
93-
logger.debug(f' Moving extracted layer from: {extracted_loc} to: {target_dir}')
94+
if TRACE: logger.debug(f' Moving extracted layer from: {extracted_loc} to: {target_dir}')
9495
copytree(extracted_loc, target_dir)
95-
logger.debug(f' Moved layer to: {target_dir}')
96+
if TRACE: logger.debug(f' Moved layer to: {target_dir}')
9697
delete(extracted_loc)
9798

9899
return deletions
@@ -227,27 +228,27 @@ def find_root(
227228
228229
``walker`` is a callable behaving like ``os.walk()`` and is used for testing.
229230
"""
230-
logger.debug(
231+
if TRACE: logger.debug(
231232
f'find_root: location={location!r}, max_depth={max_depth!r}, '
232233
f'root_paths={root_paths!r}, min_paths={min_paths!r}'
233234
)
234235
depth = 0
235236
for top, dirs, files in walker(location):
236-
logger.debug(f' find_root: top={top!r}, dirs={dirs!r}, files={files!r}')
237+
if TRACE: logger.debug(f' find_root: top={top!r}, dirs={dirs!r}, files={files!r}')
237238
if max_depth:
238239
depth = compute_path_depth(location, top)
239-
logger.debug(f' find_root: top depth={depth!r}')
240+
if TRACE: logger.debug(f' find_root: top depth={depth!r}')
240241
if depth > max_depth:
241-
logger.debug(
242+
if TRACE: logger.debug(
242243
f' find_root: max_depth={max_depth!r}, '
243244
f'depth={depth!r} returning None')
244245
return
245246

246247
matches = len(set(dirs + files) & root_paths)
247-
logger.debug(f' find_root: top={top!r}, matches={matches!r}')
248+
if TRACE: logger.debug(f' find_root: top={top!r}, matches={matches!r}')
248249

249250
if matches >= min_paths:
250-
logger.debug(f' find_root: matches >= min_paths: returning {top!r}')
251+
if TRACE: logger.debug(f' find_root: matches >= min_paths: returning {top!r}')
251252
return top
252253

253-
logger.debug(f'find_root: noting found: returning None')
254+
if TRACE: logger.debug(f'find_root: noting found: returning None')

src/container_inspector/utils.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,12 @@
1515

1616
from extractcode.extract import extract_file
1717

18+
TRACE = False
1819
logger = logging.getLogger(__name__)
19-
# un-comment these lines to enable logging
20-
import sys
21-
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
22-
logger.setLevel(logging.DEBUG)
20+
if TRACE:
21+
import sys
22+
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
23+
logger.setLevel(logging.DEBUG)
2324

2425

2526
def load_json(location):
@@ -106,7 +107,7 @@ def extract_tar_keeping_symlinks(location, target_dir):
106107
Raise exceptions on possible problematic relative paths.
107108
"""
108109
import tarfile
109-
logger.debug(f'extract_tar_keeping_symlinks: {location} to {target_dir}')
110+
if TRACE: logger.debug(f'extract_tar_keeping_symlinks: {location} to {target_dir}')
110111

111112
fileutils.create_dir(target_dir)
112113

@@ -117,7 +118,7 @@ def extract_tar_keeping_symlinks(location, target_dir):
117118
for tinfo in tarball:
118119
if tinfo.isdev():
119120
continue
120-
logger.debug(f'extract_tar_keeping_symlinks: {tinfo}')
121+
if TRACE: logger.debug(f'extract_tar_keeping_symlinks: {tinfo}')
121122
tarball.extract(
122123
member=tinfo,
123124
path=target_dir,

0 commit comments

Comments
 (0)