-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapecron
executable file
·745 lines (596 loc) · 16.3 KB
/
chapecron
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
#!/usr/bin/env bash
# chapecron - Look after your crons while you are away
# ====================================================
#
# See https://github.com/notus-sh/chapecron for a complete documentation on how
# to use this software.
#
#
# Parts of these sources are documented and marqued as "Public:". These functions
# and variables can be used by developpers who want to write their own middlewares
# for chapecron.
#
# Public functions and variables are guaranted to not change between minor
# releases of chapecron but may evolve from one major release to another.
##
## Environment variables
##
# Public: Enable Bash debug mode
: ${CHAPECRON_DEBUG:=0}
# These ones exists only for tests purpose
: ${CHAPECRON_BASH_VERSION:=${BASH_VERSINFO[0]}}
# (And those two are made static on build to prevent bad use)
: ${CHAPECRON_PATH_PREFIX:=} # __PKG__ declare -r CHAPECRON_PATH_PREFIX=''
: ${CHAPECRON_PLUGIN_PATTERN:='/*.sh'} # __PKG__ declare -r CHAPECRON_PLUGIN_PATTERN='/*.sh'
##
## Global variables
##
# Public: Complete location of the chapecron script, once every symlinks resolved.
declare -r CHAPECRON_BIN="$(readlink -f "${BASH_SOURCE[0]}")"
# Public: Path to the parent directory of the chapecron script.
declare -r CHAPECRON_DIR="$(dirname "$CHAPECRON_BIN")"
# Public: Current version of chapecron.
declare -r CHAPECRON_VERSION="$(cat $CHAPECRON_DIR/VERSION)" # __PKG__ declare -r CHAPECRON_VERSION="__VERSION__"
## Exit statuses
# See https://goo.gl/6uEMX3 for full reference
declare -r EX_USAGE=64 # Public: Exit code - Command used incorrectly
declare -r EX_UNAVAILABLE=69 # Public: Exit code - Unavailable dependency
declare -r EX_OSFILE=72 # Public: Exit code - Configuration file missing or wrong
declare -r EX_NOPERM=77 # Public: Exit code - Insufficient permissions
declare -r EX_CONFIG=78 # Public: Exit code - Missing or wrong configuration
declare -r EX_TEMPFAIL=75 # Public: Exit code - Temporary failure
## Command line arguments
# Public: The command to be chaperoned
declare COMMAND=''
# Default options
declare CONFIG_FILE=''
# Default flags
declare -i RECALL=0
declare -i VERBOSE=0
declare -i VERSION=0
declare -i HELP=0
##
## Utilities
##
# Public: Ends the program with the specified exit code and an optional error
# message.
#
# $1 - Exit code. See the defined EX_* global variables.
# $2 - (Optional) Message. Will be logged with the 'error' level.
#
# Returns nothing.
utils::fail() {
local exit_code=$1
shift
[ $# -gt 0 ] && log::error "$@"
exit $exit_code
}
# Public: Output the first available file descriptor between 3 and 33.
#
# Returns nothing.
utils::fd() {
pattern="^($(ls -Af "/proc/$$/fd" | sed -E 's/[[:space:]]+/\|/g'))$"
echo {3..33} | tr ' ' $'\n' | pcregrep -v "$pattern" | head -n 1
}
# Public: Output the path to the current user home directory.
#
# Returns nothing.
utils::home() {
# `$(eval echo "~$(whoami)")` seems to be an overly complicated way
# to get $HOME but it prevent any side effect from the current environment.
# (e. g. Sharness mess with $HOME)
echo "$(eval echo "~$(whoami)")"
}
##
## Logging
##
declare -i CHAPECRON_OUT_FD=1
declare -i CHAPECRON_ERR_FD=2
log::redirect() {
[ ${LOG_TMP+isset} ] && return 0
declare -g LOG_TMP
declare -g LOG_OUT
declare -g LOG_ERR
LOG_TMP="$(mktemp -d 'chapecron-log.XXXXXXXXXX')"
LOG_OUT=$LOG_TMP/log.out
CHAPECRON_OUT_FD=$(utils::fd)
eval "exec $CHAPECRON_OUT_FD> $LOG_OUT"
LOG_ERR=$LOG_TMP/log.err
CHAPECRON_ERR_FD=$(utils::fd)
eval "exec $CHAPECRON_ERR_FD> $LOG_ERR"
trap "log::resume" EXIT ERR
}
log::resume() {
[ ${LOG_TMP+isset} ] || return 0
CHAPECRON_OUT_FD=1 && cat $LOG_OUT >&1
CHAPECRON_ERR_FD=2 && cat $LOG_ERR >&2
rm -rf $LOG_TMP
unset -v LOG_TMP
}
log::print() {
[ $VERBOSE -ge $1 ] || return 0
local redirect=" >&$CHAPECRON_OUT_FD"
[ $# -eq 3 ] && ([ "$3" == "stderr" ] || [ "$3" == "STDERR" ]) && redirect=" >&$CHAPECRON_ERR_FD"
eval "echo \"$2\"$redirect"
}
# Public: Log a message with the `error` level (to the error output).
#
# $1.. - Message to be logged
#
# Returns nothing.
log::error() {
log::print 0 "$@" "stderr"
}
# Public: Log a message with the `info` level (to the standard output).
#
# $1.. - Message to be logged
#
# Returns nothing.
log::info() {
log::print 1 "$@"
}
# Public: Log a message with the `debug` level (to the standard output).
#
# $1.. - Message to be logged
#
# Returns nothing.
log::debug() {
log::print 2 "$@"
}
##
## String functions
##
string::trim() {
local var=$(echo "$*" | tr "\\n" " ")
var="${var#"${var%%[![:space:]]*}"}"
var="${var%"${var##*[![:space:]]}"}"
echo -n "$var"
}
##
## Array functions
##
array::search() {
local needle=$1
shift
[[ " $@ " == *" $needle "* ]] && return 0
return 1
}
array::merge() {
local -a merged=()
local value
eval set -- $@
for value in $@; do
if ( ! array::search $value ${merged[@]} ); then
merged+=("$value")
fi
done
echo "${merged[@]}"
}
##
## Dependency management
##
dependencies::getopt() {
local exit_code
set +e
getopt --test > /dev/null
exit_code=$?
set -e
# Test if getopt is GNU Enhanced getopt, long time provided by util-linux.
# See https://stackoverflow.com/a/29754866
[ $exit_code -ne 4 ] && return 1
return 0
}
dependencies::bash4() {
[ $CHAPECRON_BASH_VERSION -lt 4 ] && return 1
return 0
}
dependencies::all() {
dependencies::getopt || \
utils::fail $EX_UNAVAILABLE \
"Missing dependency: enhanced getopt"
dependencies::bash4 || \
utils::fail $EX_UNAVAILABLE \
"Missing dependency: bash 4.0+"
}
##
## Command line options
##
options::version() {
cat <<-_EOF
chapecron - Look after your crons while you are away
Version: $CHAPECRON_VERSION
_EOF
}
options::usage() {
options::version
echo
cat <<-USAGE
Usage:
chapecron [-v,--verbose] [--version] [-h,--help] [-c,--config CONFIG_FILE] [ -e,--exec "COMMAND [ARG]..." ]
chapecron [-v,--verbose] [--version] [-h,--help] [-c,--config CONFIG_FILE] -- [ COMMAND [ARG]... ]
Options:
-c,--config Specify a configuration file (See below)
-e,--exec The command to be executed
-version Print version informations and exit
-h,--help Print this help and exit
-v,--verbose More verbose output.
You can specify this option more than once
By default, chapecron will look for configuration files at:
- /etc/chapecron/chapecron.conf
- XDG_CONFIG_HOME/chapecron/chapecron.conf
(usually ~/.config/chapecron/chapecron.conf)
When specifying a configuration file as a command line option,
only this file will be considered.
USAGE
}
options::get() {
local parsed
parsed=$(getopt --options=hvc:e:r \
--longoptions=help,verbose,config:,exec:,version \
--name "$0" \
-- "$@")
eval set -- "$parsed"
while :; do
case "$1" in
-r)
RECALL=1
shift
;;
-c|--config)
CONFIG_FILE=$2
shift 2
;;
-e|--exec)
COMMAND=$2
shift 2
;;
-v|--verbose)
VERBOSE+=1
shift
;;
--version)
VERSION=1
shift
;;
-h|--help)
HELP=1
shift
;;
--)
shift
break
;;
*)
utils::fail $EX_USAGE \
"Unsupported option $1. Use $0 -h to get help"
;;
esac
done
[ $RECALL -eq 1 ] && return 0
[ $VERSION -eq 1 ] && options::version && exit 0
[ $HELP -eq 1 ] && options::usage && exit 0
[ -z "$COMMAND" ] && COMMAND=$(string::trim "$*")
[ -z "$COMMAND" ] && \
utils::fail $EX_USAGE \
"No command to look after. Use $0 -h to get help"
local command_template='chapecroned_command() { %s; return $?; }'
eval "$(printf "$command_template" "$COMMAND")"
}
##
## Configuration
##
# Public: Store the loaded configuration as an aliased array.
declare -A CONFIG=()
# Public: Array of configuration keys that should be merged instead of
# overwriten when loading more than one configuration file.
declare -a CONFIG_MERGEABLE
CONFIG_MERGEABLE+=('middlewares')
config::dir() {
local path
case "$1" in
sys)
path="/etc"
;;
user)
path=$( ([ -z ${XDG_CONFIG_HOME+x} ] || [ -z "$XDG_CONFIG_HOME" ]) \
&& echo "$(utils::home)/.config" \
|| echo "$XDG_CONFIG_HOME" \
)
;;
esac
echo "${path%/}/chapecron/"
return 0
}
config::defaults() {
CONFIG=( ["middlewares"]="" )
}
config::check() {
if [ -n "${CONFIG['middlewares']}" ]; then
for middleware in $(echo "${CONFIG['middlewares']}" | tr " " "\\n"); do
if ( ! array::search "$middleware" "${AVAILABLE_MIDDLEWARES[@]}"); then
utils::fail $EX_CONFIG "Unknown middleware: $middleware"
fi
done
fi
}
config::loadfile() {
local to_load=$1 tmp_conf name value
[ -e "$to_load" ] || \
utils::fail $EX_OSFILE \
"Configuration file $to_load does not exist"
[ -r "$to_load" ] || \
utils::fail $EX_OSFILE \
"Configuration file $to_load can not be read"
log::info "Loading configuration from file $to_load"
tmp_conf=$(mktemp 'chapecron-config.XXXXXXXXXX')
log::debug "Temporary configuration file created as $tmp_conf"
if [ $CHAPECRON_DEBUG -eq 0 ]; then
trap "{ rm \"$tmp_conf\"; }" EXIT ERR
log::debug "Temporary configuration file set to be deleted after execution"
fi
grep -vE '^$' "$to_load" | grep -vE '^#' > "$tmp_conf"
while IFS="=" read -r name value || [ -n "$name" ]; do
if (array::search "$name" "${CONFIG_MERGEABLE[@]}"); then
CONFIG["$name"]="$(array::merge "${CONFIG["$name"]}" "$value")"
else
CONFIG["$name"]="$value"
fi
done < "$tmp_conf"
}
config::load() {
config::defaults
if [ -n "$CONFIG_FILE" ]; then
config::loadfile "$CONFIG_FILE"
else
local f config_dir_sys config_dir_usr
local -a config_files
config_dir_sys=$(config::dir 'sys')
config_dir_usr=$(config::dir 'user')
config_files=(
"${CHAPECRON_PATH_PREFIX%/}${config_dir_sys%/}/chapecron.conf"
"${CHAPECRON_PATH_PREFIX%/}${config_dir_usr%/}/chapecron.conf"
)
for f in "${config_files[@]}"; do
log::debug "Looking for a configuration file at $f"
if [ -e "$f" ]; then
config::loadfile "$f"
fi
done
fi
config::check
}
##
## Plugins
##
declare -a AVAILABLE_MIDDLEWARES
plugins::load() {
local plugin_dir plugin plugin_realpath f functions
plugin_dir="$(readlink -f "$CHAPECRON_DIR/plugins.d")"
functions=$(declare -F | cut -d ' ' -f3)
for plugin in "$plugin_dir"$CHAPECRON_PLUGIN_PATTERN; do
plugin_realpath="$(readlink -f "$plugin")"
if (! echo $plugin_realpath | grep "^$plugin_dir" > /dev/null); then
utils::fail $EX_USAGE \
"Plugins can not be loaded from outside of $plugin_dir"
fi
[ -r "$plugin" ] || \
utils::fail $EX_NOPERM \
"Plugin $plugin can not be read"
log::debug "Loading plugin from $plugin"
source "$plugin"
done
for f in $(declare -F | cut -d ' ' -f3); do
if ( ! array::search "$f" $functions); then
AVAILABLE_MIDDLEWARES+=("$f")
fi
done
}
##
## Stack management
##
declare -a CHAPECRON_STACK=()
declare -i CHAPECRON_STACK_ITERATOR=0
stack::add() {
CHAPECRON_STACK+=("$@")
}
# Public: Invoke the next middleware in the stack
#
# Returns nothing.
stack::next() {
local next=${CHAPECRON_STACK[$CHAPECRON_STACK_ITERATOR]}
CHAPECRON_STACK_ITERATOR+=1
$next
}
stack::run() {
stack::next
return $?
}
stack::build() {
local middleware
stack::add "chapecron::mktmp"
stack::add "chapecron::capture"
if [ -n "${CONFIG['middlewares']}" ]; then
for middleware in $(echo "${CONFIG['middlewares']}" | tr " " "\\n"); do
stack::add "$middleware"
done
fi
stack::add "chapecron::command"
}
##
## Execution context
##
# Public: Export the execution context in the current environment.
#
# Must be called by middlewares before they recall chapecron with `chapecron -r`
# when `stack::next` can't be used to invoke the next middleware.
#
# Most Unix utilities that take a comand as argument (e. g. timeout, nice, etc.)
# will invoke it in a dedicated subshell. In this context, anything that has not
# been explicitely exported from the parent environment is lost. Considering
# chapecron, this means stack definition and progress pointer, configurations and
# command line options.
#
# To work around this limitation, chepcron can be "recalled" from a middleware
# with `chapecron -r` and this function export the bare minimum it will need to
# rebuild its own context.
#
# Returns nothing.
context::export() {
local options_tpl=$'chapecron_rebuild__options() { COMMAND="%s"; VERBOSE=%i; return 0; }'
eval "$(printf "$options_tpl" "$COMMAND" $VERBOSE)"
export -f chapecron_rebuild__options
local config_tpl=$'chapecron_rebuild__config() { %s return 0; }'
local config_body=""
local config_entry=$'CONFIG["%s"]="%s"; '
local key
for key in "${!CONFIG[@]}"; do
config_body+="$(printf "$config_entry" "$key" "${CONFIG[$key]}")"
done
eval "$(printf "$config_tpl" "$config_body")"
export -f chapecron_rebuild__config
local stack_tpl=$'chapecron_rebuild__stack() { %s CHAPECRON_STACK_ITERATOR=%i; return 0; }'
local stack_body="$(printf $'stack::add "%s"; ' "${CHAPECRON_STACK[@]}")"
eval "$(printf "$stack_tpl" "$stack_body" $CHAPECRON_STACK_ITERATOR)"
export -f chapecron_rebuild__stack
export -f chapecroned_command
}
context::rebuild() {
chapecron_rebuild__options && unset -f chapecron_rebuild__options
plugins::load
chapecron_rebuild__config && unset -f chapecron_rebuild__config
chapecron_rebuild__stack && unset -f chapecron_rebuild__stack
}
##
## Output
##
declare REPORT_INDENT=""
report::options() {
log::info "${REPORT_INDENT}Command to be monitored: $COMMAND"
log::debug "${REPORT_INDENT}-- Command line options detected --"
if [ $RECALL -eq 0 ]; then
log::debug "${REPORT_INDENT}config file = ${CONFIG_FILE:-undefined}"
else
log::debug "${REPORT_INDENT}recall = $RECALL"
fi
log::debug "${REPORT_INDENT}verbose = $VERBOSE"
log::debug "${REPORT_INDENT}-- Command line options ends --"
}
report::config() {
local key
log::debug "${REPORT_INDENT}-- Configuration loaded --"
for key in "${!CONFIG[@]}"; do
log::debug "${REPORT_INDENT}$key = ${CONFIG[$key]}"
done
log::debug "${REPORT_INDENT}-- Configuration ends --"
}
report::middlewares() {
local middleware
log::debug "${REPORT_INDENT}-- Middlewares available --"
for middleware in "${AVAILABLE_MIDDLEWARES[@]}"; do
log::debug "${REPORT_INDENT}$middleware"
done
log::debug "${REPORT_INDENT}-- Middlewares ends --"
}
report::stack() {
local middleware
log::debug "${REPORT_INDENT}-- Stack build --"
for middleware in "${CHAPECRON_STACK[@]}"; do
log::debug "${REPORT_INDENT}$middleware"
done
log::debug "${REPORT_INDENT}-- Stack ends --"
}
report::context() {
log::debug "-- Context rebuild --"
REPORT_INDENT+="= "
report::options
report::middlewares
report::config
report::stack
REPORT_INDENT="${REPORT_INDENT%= }"
log::debug "-- Context ends --"
}
report::trace() {
echo "chapecron detected failure or error output for the command:"
echo "$@"
echo
echo "RESULT CODE: $RESULT"
echo
echo "ERROR OUTPUT:"
cat "$ERR"
echo
echo "STANDARD OUTPUT:"
cat "$OUT"
if [ "$TRACE" != "$ERR" ]; then
echo
echo "TRACE-ERROR OUTPUT:"
cat "$TRACE"
fi
}
##
## Base middlewares
##
chapecron::mktmp() {
declare -g TMP
declare -g OUT
declare -g ERR
declare -g TRACE
TMP=$(mktemp -d 'chapecron.XXXXXXXXXX')
OUT=$TMP/chapecron.out
ERR=$TMP/chapecron.err
TRACE=$TMP/chapecron.trace
log::debug "Output files created in $TMP"
if [ $CHAPECRON_DEBUG -eq 0 ]; then
trap "{ rm -rf \"$TMP\"; }" EXIT ERR
log::debug "Output files set to be deleted after execution"
fi
stack::next
return $?
}
chapecron::capture() {
log::redirect
set +e
stack::next >"$OUT" 2>"$TRACE"
RESULT=$?
set -e
log::resume
PATTERN="^${PS4:0:1}\\+${PS4:1}"
if grep -aq "$PATTERN" "$TRACE"; then
! grep -av "$PATTERN" "$TRACE" > "$ERR"
else
ERR=$TRACE
fi
if ([ $RESULT -ne 0 ] || [ -s "$ERR" ]); then
log::error "$(report::trace "$COMMAND")"
else
log::debug "$(cat "$OUT")"
fi
return $RESULT
}
chapecron::command() {
chapecroned_command
return $?
}
# Prevent execution if sourced instead of called
[ "@$(basename -- "$0")" = "@$(basename -- "$CHAPECRON_BIN")" ] && {
# Turn on the unofficial Bash strict mode
set -euo pipefail
[ $CHAPECRON_DEBUG = 1 ] && set -x
IFS=$'\n\t'
#
# Here we go!
#
dependencies::all
options::get $@
if [ $RECALL -eq 0 ]; then
report::options
plugins::load && report::middlewares
config::load && report::config
stack::build && report::stack
else
context::rebuild && report::context
fi
stack::run
exit $?
}
# Make sure this script ends with code 0 when sourced.
: