-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshlib_template_standalone.sh
More file actions
executable file
·493 lines (427 loc) · 14.9 KB
/
shlib_template_standalone.sh
File metadata and controls
executable file
·493 lines (427 loc) · 14.9 KB
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
#!/usr/bin/env bash
### Environment variables
DEBUG=${DEBUG:-}
# Defaulting to 'INFO'. Can be controled by setting the verbosity level.
# Set to '7' to debug argument parsing (tip set it on the CLI).
VERBOSE=${VERBOSE:-6} # 7 = debug -> 0 = emergency
FORCE=${FORCE:-}
NOCOLOR=${NOCOLOR:-}
# colored logging
__color_info="\\e[32m"
__color_notice="\\e[34m"
__color_warning="\\e[33m"
__color_error="\\e[31m"
__color_error="\\e[31m"
__color_critical="\\e[1;31m"
__color_alert="\\e[1;33;41m"
__color_emergency="\\e[1;4;5;33;41m"
__color_reset="\\033[0m"
__color_bold="\\E[1m"
### Shell OPTIONS and script META variables
# Exit immediately on error. Same as '-e'. Use of '|| true' or '|| :' may be
# handy. We purposely avoid setting this in interactive shell. We use posix
# compatible case statement for portability because in simple '[' tests the
# *i* pattern would expand filenames in pwd instead...
case "$-" in
*i*) :;;
*) [ -n "${ZSH_VERSION}" ] && setopt ERR_EXIT || set -o errexit;;
esac
# Any trap on ERR is inherited by any functions or subshells. Available on bash
# only.
[ -n "${BASH_VERSION:-}" ] && set -o errtrace || true
# Return value of a pipeline is the one of right most cmd with non-zero exit
# code. Available on bash only.
[ -n "${BASH_VERSION:-}" ] && set -o pipefail || true
# Errors on unset variables and parameters. Same as '-u'. Use '${VAR:-}'.
set -o nounset
# mac osx path handling
if [ "${OSTYPE:-}" = "darwin*" ]; then
alias date=/usr/bin/date
alias readlink=/usr/bin/readlink
else
alias date=/bin/date
alias readlink=/bin/readlink
fi
# handling cases where $0 is bash|sh. E.g.: when sourcing.
if [ -f "${0}" ]; then
__file__=$(readlink --no-newline --canonicalize-existing "${0}")
fi
if [ ! -f "${0}" -a -f "${1:-}" ]; then
__file__=$(readlink -o-no-newline --canonicalize-existing "${1}")
fi
if [ -n "${__file__:-}" ]; then
__name__="${__file__##*/}"
__path__=${__file__%/*} || true
if [ -r ${__path__}/VERSION ]; then
__version__=$(< "${__path__}/VERSION")
else
__version__=
fi
fi
if [ -z "${LS_COLORS:-}" ]; then
# Try and see if there is color support
if [ ! -x /usr/bin/dircolors >/dev/null 2>&1 ]; then
[ -r ~/.dircolors ] && eval "$(/usr/bin/dircolors -b ~/.dircolors)" \
|| eval "$(/usr/bin/dircolors -b)"
fi
[ -z "${LS_COLORS:-}" ] && NOCOLOR="${NOCOLOR:-}" || true
fi
### Error handling
ERROR_MSG='Error at \`$0.${FUNCNAME[0]}:$LINENO\` \
command \`$@\` exited with return code \`$?\`'
_catch_notify() {
die ${*//\`/\'}
}
try_cmd() {
trap "_catch_notify $ERROR_MSG" ERR SIGINT
run $@
}
### Functions
_log() {
local log_level="${1}"
shift
local msg=
if [ ${NOCOLOR:-} ] || [ ! -t 2 ]; then
local color=""; local color_reset=""
else
# portable indirection to resolve the color
eval local color="\${__color_${log_level}:-}"
local color_reset="${__color_reset}"
fi
# print date in debug mode only to reduce
if [ "${log_level}" = "debug" ]; then
# printf '%b' "$(date --iso-8601=seconds) ${color}[${log_level}]${color_reset}: $@\n" 1>&2
printf '%b' "$(date --rfc-3339=seconds) ${color}[${log_level}]${color_reset}: $@\n" 1>&2
else
printf '%b' "${color}[${log_level}]${color_reset}: $@\n" 1>&2
fi
}
# see https://en.wikipedia.org/wiki/Syslog#Severity_levels as reference
emergency() { _log emergency "$@"; exit 1; }
alert() { [ "${VERBOSE}" -ge 1 ] && _log alert "$@"; true; }
critical() { [ "${VERBOSE}" -ge 2 ] && _log critical "$@"; true; }
error() { [ "${VERBOSE}" -ge 3 ] && _log error "$@"; true; }
warning() { [ "${VERBOSE}" -ge 4 ] && _log warning "$@"; true; }
notice() { [ "${VERBOSE}" -ge 5 ] && _log notice "$@"; true; }
info() { [ "${VERBOSE}" -ge 6 ] && _log info "$@"; true; }
debug() { [ "${VERBOSE}" -ge 7 ] && _log debug "$@"; true; }
# Alternate simpler logging system.
verbose() { if [ -n "$VERBOSE" ]; then printf "%s\n" "$*" 1>&2; fi; }
die_with_status () {
local status=$1
shift; printf >&2 '%s\n' "$*"; exit "$status"
}
die() { die_with_status 1 "$@"; }
lock() {
local prog=$1
local lock_fd=${2:-200}
local lock_file=/run/lock/${prog}.lock
# create lock file
eval "exec ${lock_fd}>${lock_file}"
info "acquier the lock"
flock --nonblock ${lock_fd} && return 0 || return 1
}
_is_option() { case ${1:-} in -*) return 0;; *) return 1;; esac; }
_normalize_args() {
# Allow more flavorfull arg parsing capabilities
debug "_normalize_args input args: '$*'"
while [ $# -gt 0 ]; do
case $1 in
# break '-xyz' into '-x -y -z'
-[!-]?*)
OPTIND=1
while getopts ${1#-} opt "$1"; do
__argv="${__argv:-} -${opt}"
done ;;
# break --foo=bar style long options
--?*=*) __argv="${__argv:-} ${1%%=*} ${1#*=}";;
# add other args exactly as they are
*) __argv="${__argv:-} ${1}";;
esac
shift
done
# strip a leading whitespace that may be introduced
__argv=${__argv# }
debug "_normalize_args output args: '$__argv'"
}
do_test() {
# do_test test_fct <log_level> arg1 arg2 ... argN
local fct=$1; shift
case $1 in
debug|info|notice|warning|error|critical|alert|emergency)
local log_level=${1}; shift;;
esac
# return on first failing
# set -x
while [ $# -gt 0 ]; do
if ! $fct $1 ${log_level:='warning'}; then
return 1
fi
shift
done
}
is_cmd() {
# test a cmd is available on system.
local cmd=${1}
local log_level=${2:-'debug'}
debug "searching for '$1' cmd on system"
if ! type "${cmd}" >/dev/null 2>&1; then
$log_level "cmd '${cmd}' is undefined."
return 1
fi
debug "found $1 on system!"
return 0
}
is_defined() {
# Test a variable is defined.
local var=${1}
local log_level=${2:-'debug'}
debug "Testing '$1' is defined"
if eval [ -z "\${${var}}" ]; then
$log_level "Variable '${var}' is undefined!"
return 1
else
return 0
fi
}
tmux_run_in_pane() {
# send command to pane (e.g.: run a command inside a running interactive shell)
# INPUT: '<session-name>:<pane-name>'
local target_pane=${1}; shift
local session_name=${target_pane%%:*}
local pane_name=${target_pane##*:}
if ! tmux has-session -t "${session_name}"; then
tmux new-session -t "${session_name}"
fi
tmux send-keys -t ${target_pane} "$*" C-m
}
post_slack_msg() {
# Sends notifications via Slack
# usage: post_slack_msg [ <slack_channel> ] <slack_msg>
# Optionally define slack_channel and/or slack_webhook_url in a config file
local slack_channel=
. ~/.post_slack_msg.conf >/dev/null 2>&1 || true
. post_slack_msg.conf >/dev/null 2>&1 || true
# channel passed as env variable precedes what is in config file
slack_channel="""\"channel\": \"#${slack_channel:-$SLACK_CHANNEL}\","""
# channel passed as positional arg precedes env variable
if [ $# -ge 2 ]; then
slack_channel="""\"channel\": \"#${1}\","""
shift
fi
# slack webhook url passed as env variable precedes what is in config file
SLACK_WEBHOOK_URL=${SLACK_WEBHOOK_URL:-$slack_webhook_url}
curl --silent -X POST \
--output /dev/null \
--data-urlencode "payload={${slack_channel} \"text\": \"$@\"}" \
${SLACK_WEBHOOK_URL}
}
timeit() {
# usage: timeit [ --output FILE ] cmd
# -o|--output Write the resource use statistics to FILE instead of to the
# standard error stream
# Format options:
# E Elapsed real (wall clock) time used by the process, in
# [hours:]minutes:seconds.
# U Total number of CPU-seconds that the process used directly (in
# user mode), in seconds.
# S Total number of CPU-seconds used by the system on behalf of the
# process (in kernel mode), in seconds.
/usr/bin/time --format "\t%E real,\t%U user,\t%S sys" $@
}
run() {
# Wrapper around command execution to allow
# dry-run mode, mardown output | post msg to third party
# type debug >/dev/null 2>&1 && debug "Executing command '$*'" || :
if [ -z "${DRY_RUN:-}" ]; then
if [ -z "${MARKDOWN_OUTPUT:-}" ]; then
# post some msg
if [ -n "${POST_SLACK_MSG:-}" ]; then
if type post_slack_msg >/dev/null 2>&1; then
post_slack_msg "$(hostnamectl --static): Executing command \`$*\`"
else
debug "post_slack_msg not found"
fi
fi
# run cmd
type info >/dev/null 2>&1 && info "Executing command '$*'" || :
"$@"
type info >/dev/null 2>&1 && info "Command '$*' completed!" || :
# post some msg
if [ -n "${POST_SLACK_MSG:-}" ]; then
if type post_slack_msg >/dev/null 2>&1; then
post_slack_msg "$(hostnamectl --static): command \`$*\` completed!"
else
debug "post_slack_msg not found"
fi
fi
else
# run cmd; output cmd and its output in markdown format
echo -e "```"; echo "$@"; $*; echo -e "```\n"
fi
else
# dry-run
if [ -z "${MARKDOWN_OUTPUT:-}" ]; then
echo "$*"
else
# dry-run; output cmd only in markdown format
echo -e '```'; echo "$@"; echo -e '```\n'
fi
fi
# type debug >/dev/null 2>&1 && debug "Command '$*' completed" || :
}
_version() { echo "${__version__:-No version string available}" 1>&2; }
_usage() { echo "${__doc__:-No usage available}" 1>&2; }
_hook_pre_exec() {
### Runtime
#############################################################################
info "script '__name__ ': '${__name__:-}'"
info "script '__file__': '${__file__:-}'"
info "script '__path__': '${__path__:-}'"
info "script '__version__': '${__version__:-}'"
debug "'VERBOSE': '${VERBOSE}'"
debug "'DEBUG': '${DEBUG}'"
debug "'DRY_RUN': '${DRY_RUN:-}'"
debug "'FORCE': '${FORCE:-}'"
debug "'QUIET': '${QUIET:-}'"
}
. shlib
# From this point below put your business value adding code.
__doc__="\
This script here is an example leveraging shlib core functions and is used to
selftest shlib itself. It can be used as a genereric template if you decide to
source the 'shlib' shell code library. As an alternative you can use the
'shlib_template_standalone_standalone.sh' which is as the name implies a standalone
equivalent should you need extra portability at the cost of duplictation
maintainability and storage.
USAGE
${__name__:-} CMD [OPTIONS] ARGS
OPTIONS
-h|--help Display this help and exit.
-V|--version Output version information.
-v|--verbose [level] Increase verbosity level as per standart severity
levels. Accepts a number ranging from 1 to 7.
-n|-D|--dry-run Dry run. Print what would be executed.
-d|--debug Enable shell tracing mode (set -O xtrace) at beginning
of main.
-f|--force Skip all user interaction. Implied 'Yes' to all actions.
-u|--username <username> Prompt for username.
-p|--password <password> Propmt for password.
-q|--quiet Supresse STDOUT output.
-m|--markdown Output to STDOUT commands and results as markdown
cells.
CMD
test_log Test and showcase various 'log_level' output
test_is_defined Test the 'is_defined' provided function
test_is_cmd Test the 'is_cmd' provided function
"
_parse_options() {
# Parse short and long options. May be called multiple times.
debug "_parse_options input args: $*"
while _is_option ${1:-}; do
case $1 in
-h|--help) _usage; exit 0;;
-V|--version) _usage; exit 0;;
-v|--verbose)
if [ -z "${2#?}" ]; then shift
# will throw an error if not a single digit number
[ $1 -le 9 ] && VERBOSE=$1 || true
fi ;;
# convenient options
-D|-n|--dry-run) DRY_RUN=true;;
-f|--force) FORCE=true;;
-d|--debug) VERBOSE=8;;
-q|--quiet) QUIET=true;;
# credentials prompting
-u|--username) shift; username=${1};;
-p|--password) echo "Enter Password: "; stty -echo
read __password; stty echo; echo ;;
# misc
--m|--markdown) MARKDOWN_OUTPUT=true;;
--) shift; break;;
*) die "Invalid option: '$1'";;
esac
shift
done
__argv=$@
debug "_parse_options remaining args: '$*'"
}
_parse_args() {
# Parse script options and args. Call this from your main().
debug "_parse_args input args: '$*'"
_normalize_args $@; set -- ${__argv:-}
# parse script global options and set args to to what remains
_parse_options $@
set -- ${__argv:-}
# Print main script flags.
_hook_pre_exec
# Parse positional args.
while [ $# -gt 0 ]; do
case $1 in
# parse global options allowed after subcommand
show|list) shift; _parse_options $; set -- ${__argv:-};;
set_something) shift; __somevar=$1;;
test_log) _test_log;;
test_is_defined) _test_is_defined;;
test_is_cmd) _test_is_cmd;;
*) die "Invalid positional argument: '$1'";;
--) shift; break;;
esac
shift
done
__argv=$@
debug "_parse_args remaining args: '$@'"
}
_test_log() {
# All of these go to STDERR so you can safely pipe STDOUT to other software.
debug "Messages that contain information normally of use only when \n\
debugging a program."
info "Informational messages. May be harvested for reporting and/or measuring"
notice "Conditions that are not error conditions, but that may require \n\
special handling."
warning "Warning messages. Not an error but an indication that one will \n\
occur if action is not taken"
error "Errors. Not urgent failures to resolve in a given time"
critical "Critical conditions (e.g.: Hardware errors). Indicates failure \n\
in a primary system. Should be corrected immediately"
alert "Action must be taken immediately (e.g.: corrupted data or loss of
network connection). "
emergency "Panic condition (e.g.: System is unusable).Multiple \n\
apps servers or sites are affected."
}
_test_is_cmd() {
# Abort script if any required commands are missing.
info 'Testing availabity of cmd: "do_test is_cmd warning wget bar"'
do_test is_cmd warning bash bar \
|| die "aborting... missing required 'cmd'."
}
_test_is_defined() {
# Abort script if any required variables are undefined.
info 'Defining vars: "foo=bar; baz="'
foo=bar; baz=
info 'Testing for defined variables: "do_test is_defined warning foo baz"'
do_test is_defined warning foo baz \
|| die "aborting... missing required variable."
}
main() {
if [ $# -eq 0 ]; then _usage; exit 0; fi
# Parse script args setting '__argv' to remainder.
_parse_args $@; set -- ${__argv:-};
# Add code you want to run here. Depending on your script architecture you
# may however never get to this point if you branch to the desired function
# from the positional argument parser.
# func_a
# func_b
# do_c
}
# Customize this to match your script filename.
shlib_template_standalone.sh() {
echo 'Running "shlib_template_standalone.sh"'
main
}
if [ "${__name__:-}" = "shlib_template_standalone.sh" ]; then
main $@
else
# Run script after importing in current shell namespace.
[ -n "${BASH_VERSION:-}" ] && export -f shlib_template_standalone.sh || true
fi