Skip to content

Commit 597e78a

Browse files
author
Thomas Kishel
authored
Merge pull request #52 from m0dular/aph/shell-work
Better error handling in tidy script
2 parents bcf37f0 + 7a72f69 commit 597e78a

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

files/metrics_tidy

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,23 @@
11
#!/bin/bash
22

3+
fail() {
4+
# Restore stdout by pointing it to fd 3 and send any errors to it
5+
exec >&3
6+
cat "$tmp"
7+
rm "$tmp"
8+
9+
exit 1
10+
}
11+
12+
# Clone, i.e. preserve, original stdout using fd 3.
13+
exec 3>&1
14+
# Send stderr and stdout to a temp file
15+
tmp="$(mktemp)"
16+
exec &>"$tmp"
17+
18+
# Run the fail() method on error
19+
trap fail ERR
20+
321
while [[ $1 ]]; do
422
case "$1" in
523
'-d'|'--directory')
@@ -11,11 +29,12 @@ while [[ $1 ]]; do
1129
shift 2
1230
done
1331

14-
# Arguments and defaults.
32+
1533

1634
# Guard against deleting or archiving files outside of a Puppet service metrics directory.
1735
valid_paths=(puppetserver puppetdb orchestrator ace bolt activemq)
1836

37+
# Arguments and defaults.
1938
metrics_directory="${metrics_directory:-/opt/puppetlabs/puppet-metrics-collector/puppetserver}"
2039
retention_days="${retention_days:-90}"
2140

@@ -26,12 +45,13 @@ metrics_type="${metrics_directory##*/}"
2645
paths_regex="$(IFS='|'; echo "${valid_paths[*]}")"
2746
[[ $metrics_directory =~ ${paths_regex}$ ]] || {
2847
echo "Error: Invalid metrics directory. Must end in one of: $(echo -n "${valid_paths[@]}")."
29-
exit 1
48+
fail
3049
}
3150

3251
# Delete files in a Puppet service metrics directory older than the retention period, in days.
3352
find "$metrics_directory" -type f -ctime +"$retention_days" -delete
3453

3554
# Compress the remaining files in a Puppet service metrics directory.
55+
# The return code of a pipeline is the rightmost command, which means we trigger our trap if tar fails
3656
find "$metrics_directory" -type f -name "*json" | \
37-
tar --create --gzip --file "${metrics_directory}/${metrics_type}-$(date +%Y.%m.%d.%H.%M.%S).tar.gz" --files-from - 2>/dev/null
57+
tar --create --gzip --file "${metrics_directory}/${metrics_type}-$(date +%Y.%m.%d.%H.%M.%S).tar.gz" --files-from -

0 commit comments

Comments
 (0)