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+
321while [[ $1 ]]; do
422 case " $1 " in
523 ' -d' |' --directory' )
@@ -11,11 +29,12 @@ while [[ $1 ]]; do
1129 shift 2
1230done
1331
14- # Arguments and defaults.
32+
1533
1634# Guard against deleting or archiving files outside of a Puppet service metrics directory.
1735valid_paths=(puppetserver puppetdb orchestrator ace bolt activemq)
1836
37+ # Arguments and defaults.
1938metrics_directory=" ${metrics_directory:-/ opt/ puppetlabs/ puppet-metrics-collector/ puppetserver} "
2039retention_days=" ${retention_days:- 90} "
2140
@@ -26,12 +45,13 @@ metrics_type="${metrics_directory##*/}"
2645paths_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.
3352find " $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
3656find " $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