-
Notifications
You must be signed in to change notification settings - Fork 3
/
shtdlib.sh
executable file
·3079 lines (2844 loc) · 124 KB
/
shtdlib.sh
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# shellcheck disable=SC2034,SC2174,SC2016,SC2026,SC2206,SC2128
#
# This is a collection of shared functions used by SD Elements products
#
# Copyright (c) 2018 SD Elements Inc.
#
# All Rights Reserved.
#
# NOTICE: All information contained herein is, and remains
# the property of SD Elements Incorporated and its suppliers,
# if any. The intellectual and technical concepts contained
# herein are proprietary to SD Elements Incorporated
# and its suppliers and may be covered by U.S., Canadian and other Patents,
# patents in process, and are protected by trade secret or copyright law.
#
# Set a debug log file to be used in addition to stderr/stdout
# debug_log_file="/tmp/${0}.log"
# If there is no TTY then it's not interactive
if ! [[ -t 1 ]]; then
interactive=false
fi
# Default is interactive mode unless already set
interactive="${interactive:-true}"
# Create which -s alias (whichs), same as POSIX: -s
# No output, just return 0 if all of the executables are found, or 1 if some were not found.
function whichs {
command -v "${*}" > /dev/null 2>&1
return "${PIPESTATUS}"
}
# Unless disabled set strict mode for non-interactive mode
if ${strict_mode:-true} && ! ${interactive} ; then
set -euo pipefail
fi
# Set Version
shtdlib_version='0.2'
# Timestamp, the date/time we started
start_timestamp=$(date +"%Y%m%d%H%M")
# Store original arguments/parameters
#base_arguments="${@:-}"
# Store original tty
init_tty="$(tty || true)"
# Check if shell supports array append syntax
array_append_supported="$(bash -c 'a=(); a+=1 > /dev/null 2>&1 && echo true || echo false')"
# Exit unless syntax supports array append
if ! "${array_append_supported}" ; then
echo "This library (${0}) requires bash version 3.1+ with array append support to work properly"
exit 1
fi
# Determine OS family and OS type
OS="${OS:-}"
os_family='Unknown'
os_name='Unknown'
os_codename='Unknown'
# Preferred methods
if [ -e '/etc/redhat-release' ] ; then
os_family='RedHat'
elif [ -e '/etc/lsb-release' ] ; then
os_family='Debian'
else
# Educated guesses
yum help help > /dev/null 2>&1 && os_family='RedHat'
apt-get help > /dev/null 2>&1 && os_family='Debian'
echo "${OSTYPE}" | grep -q 'darwin' && os_family='MacOSX'
if [ "${OS}" == 'SunOS' ]; then os_family='Solaris'; fi
if [ "${OSTYPE}" == 'cygwin' ]; then os_family='Cygwin'; fi
if [ -f '/etc/alpine-release' ] ; then os_family='Alpine'; fi
fi
os_type="$(uname)"
# Determine virtualization platform in a way that ignores SIGPIPE, requires root
if [ "${EUID}" == 0 ] && command -v virt-what > /dev/null 2>&1 ; then
if [ -f '/.dockerenv' ] ; then
virt_platform='Docker'
else
virt_platform="$(virt-what | head -1 || if [[ ${?} -eq 141 ]]; then true; else exit ${?}; fi)"
fi
elif [ "${os_type}" == "Linux" ] && grep -Eq '/(lxc|docker)/[[:xdigit:]]{64}' /proc/self/cgroup; then
# A method of detecting if Docker is the virtual platform on Linux containers
virt_platform='Docker'
else
virt_platform="Unknown"
fi
# Set major and minor version variables
if [ "${os_family}" == 'RedHat' ]; then
major_version="$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | awk -F. '{print $1}')"
minor_version="$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | awk -F. '{print $2}')"
if ! [[ ${major_version} =~ ^-?[0-9]+$ ]] ; then # If major version is not an integer
major_version="$(rpm -qa \*-release | grep -Ei 'oracle|redhat|centos' | cut -d'-' -f3)"
fi
if ! [[ ${minor_version} =~ ^-?[0-9]+$ ]] ; then # If minor version is not an integer
minor_version="$(rpm -qa \*-release | grep -Ei 'oracle|redhat|centos' | cut -d'-' -f4 | cut -d'.' -f1)"
fi
# The following is a more robust way of determining the OS name than
# `rpm-qa \*release | grep -q -Ei "^(redhat|centos)"`
if grep -qEi 'centos' /etc/redhat-release; then
os_name='centos';
elif grep -qEi 'red ?hat' /etc/redhat-release; then
os_name='redhat';
fi
patch_version=0
elif [ "${os_family}" == 'Debian' ]; then
if [ -e '/etc/os-release' ] ; then
# VERSION_CODENAME is the built-in optional identifier
grep -q VERSION_CODENAME /etc/os-release && os_codename="$(grep VERSION_CODENAME /etc/os-release | awk -F= '{print $2}')"
# For oses based on Ubuntu we often need the Ubuntu (parent distro) codename (e.g. repository configuration)
grep -q UBUNTU_CODENAME /etc/os-release && os_codename="$(grep UBUNTU_CODENAME /etc/os-release | awk -F= '{print $2}')"
fi
if [ -e '/etc/lsb-release' ] ; then
major_version="$(grep DISTRIB_RELEASE /etc/lsb-release | awk -F= '{print $2}' | awk -F. '{print $1}')"
minor_version="$(grep DISTRIB_RELEASE /etc/lsb-release | awk -F= '{print $2}' | awk -F. '{print $2}')"
os_name="$(grep DISTRIB_ID /etc/lsb-release | awk -F= '{print $2}')"
else
major_version="$(awk -F. '{print $1}' /etc/debian_version)"
minor_version="$(awk -F. '{print $2}' /etc/debian_version)"
os_name='debian'
fi
patch_version=0
elif [ "${os_family}" == 'Alpine' ]; then
major_version="$(awk -F. '{print $1}' /etc/alpine-release)"
minor_version="$(awk -F. '{print $2}' /etc/alpine-release)"
patch_version="$(awk -F. '{print $3}' /etc/alpine-release)"
os_name='alpine'
fi
# Encode the given string
# We encode by substituting the hex unicode of special characters
function url_encode {
local url_length=${#1}
for ((i=0 ; i<url_length ; i++)); do
char=${1:i:1}
case "${char}" in
[a-zA-Z0-9.~_-])
printf "%s" "${char}" ;;
' ')
printf + ;;
*)
printf %%%X "'${char}" ;;
esac
done
}
# Gets local IP addresses (excluding localhost) and prints one per line
function get_local_ip_addresses {
# Print non-loopback IPv4 addresses
awk '/32 host/ { print "\inet " f } {f=$2}' </proc/net/fib_trie | \
awk -F '[ \t]+|/' '{print $2}' | grep -Ev "^127" | sort -Vu
# Print non-loopback IPv6 addresses
if [ -r "/proc/net/if_inet6" ]; then
awk '{
if (length($0) > 0) {
for (i=1;i<=32;i=i+4) {
if (i > 1) {
printf ":" substr($0,i,4)
} else {
printf substr($0,i,4);
}
}
printf "\n"
}
}' <<< "$(grep -Ev '(lo|fe80)' /proc/net/if_inet6 | sort -Vu)"
fi
}
local_ip_addresses="$(get_local_ip_addresses)"
# Color Constants
export black='\e[0;30m'
export red='\e[0;31m'
export green='\e[0;32m'
export yellow='\e[0;33m'
export blue='\e[0;34m'
export magenta='\e[0;35m'
export purple="${magenta}" # Alias
export cyan='\e[0;36m'
export white='\e[0;37m'
export blank='\e[0m' # No Color
# Join/Copy/Rename associative array(s)
# First argument is the name of the new array
# Any subsequent argument is assumed to be an assosiative array which content
# will be copied to the new array
function create_associative_array {
new_array_name="${1}"
assert test -n "${2}" # At least one array name was provided
assert test -n "${new_array_name}" # A name was provided
declare -gA "${new_array_name}"
for array_name in "${@:2}" ; do
for key in $(eval 'echo ${!'"${array_name}"'[@]}') ; do
value="$(eval echo '${'${array_name}'['${key}']}')"
debug 10 "Setting key: ${key} in associative array: ${new_array_name} to: ${value}"
eval ${new_array_name}[${key}]=${value}
done
done
}
# Check if a variable is in array
# First parameter is the variable, rest is the array
function in_array {
local x
for x in "${@:2}"; do [[ "${x}" == "${1}" ]] && return 0; done
return 1
}
# Return octal permissions for a file system object
# Only return the last three octets
function get_octal_perm {
case "${os_type:-}" in
'Darwin')
stat -f '%p' "${*}" | cut -c 4-6
;;
'Linux')
stat -c '%a' "${*}"
;;
esac
}
# Returns the number of arguments passed to it
function count_arguments {
echo "${#:-0}"
}
# Prints the number of elements in an array using the name passed as an
# argument in a bash version agnostic way.
# This is important because of changes in handling of empty arrays with the -u
# flag set which was different from bash v 4.0 until 4.4
function count_array_elements {
shopt_decorator_option_name='nounset'
shopt_decorator_option_value='false'
# shellcheck disable=2015
shopt_decorator "${FUNCNAME[0]}" "${@:-}" && return || conditional_exit_on_fail 121 "Failed to run ${FUNCNAME[0]} with shopt_decorator"
array_ref="${1}[@]"
count_arguments "${!array_ref}"
}
# Returns 0 if an array is empty, else return 1 if it contains data.
# The array should be passed in by name (indirect)
function empty_array {
assert test -n "${1}"
if [ "$(count_array_elements "${1}")" -gt 0 ] ; then
return 1
else
return 0
fi
}
# Default verbosity, common levels are 0,1,5,10
export verbosity="${verbosity:-1}"
############################# Deprecated #######################################
############## Use variable=${variable:-value} instead ########################
# Takes a variable name and sets it to the second parameter
# if it's not already been set use debug if it's available
function init_variable {
debug 9 "init_variable is deprecated, use variable=${variable:-value} instead"
# shellcheck disable=SC2086
export $1=${!1:-${2:-}}
}
# Colored echo
# takes color and message(s) as parameters, valid colors are listed in the constants section
function color_echo {
printf "${!1}%s${blank}\\n" "${*:2}"
if [ -n "${debug_log_file:-}" ] ; then
#shellcheck disable=1117
printf '%s - %s\n' "$(date +%F_%T)" "${*:2}" >> "${debug_log_file}"
fi
}
# Debug function for verbose debugging
# Note debug is special because it's safe even in subshells because it bypasses
# the stdin/stdout and writes directly to the terminal
function debug {
if [ "${verbosity:-1}" -ge "${1}" ]; then
if [ -w "${init_tty}" ] ; then
color_echo yellow "${*:2}" > "${init_tty}"
else
color_echo yellow "${*:2}" >&2
fi
fi
}
# Error function for verbose explicit error messages
# First argument is the priority, second is the log message
# A priority of 0 will disable writing of errors to the syslog
function error {
if whichs logger ; then
logger --priority "${1}" "${*:2}"
else
debug 3 "Unable to fing logger command to write to syslog"
fi
if [ -w "${init_tty}" ] ; then
color_echo red "${*:2}" > "${init_tty}"
else
color_echo red "${*:2}" >&2
fi
}
# Fails/exits if the exit code of the last command does not match the one
# specified in the first argument.
# Example use:
# touch /tmp/test_file || conditional_exit_on_fail 128 "Failed to create tmp file and touch did not return 128"
function conditional_exit_on_fail {
valid_exit_codes=(0 "${1}")
if ! in_array "${?}" "${valid_exit_codes[@]}" ; then
exit_on_fail "${@}"
fi
}
# Umask decorator, changes the umask for a function
# To use this add a line like the following (without #) as the first line of a function
# umask_decorator "${FUNCNAME[0]}" "${@:-}" && return
# umask_decorator "${FUNCNAME[0]}" "${@:-}" && return || conditional_exit_on_fail 121 "Failed to run ${FUNCNAME[0]} with umask_decorator"
# To specify a different umask set the umask_decorator_mask variable to the
# desired umask.
function umask_decorator {
if [ "${FUNCNAME[0]}" != "${FUNCNAME[2]:-}" ] ; then
local mask="${umask_decorator_mask:-0007}"
local original_mask
original_mask="$(umask)"
umask "${mask}"
debug 10 "Set umask to ${mask}"
#shellcheck disable=2068
${@}
umask "${original_mask}"
debug 10 "Set umask to ${original_mask}"
return 0
fi
return 1
}
# Bash behaviour option decorator
# Allows changing/setting bash options for a command/function (code block) restoring
# the original once it's been executed and it's calls are complete.
# Requires an option name (see shopt) and a truthyness value "true"/"false" or
# other command/function that returns 0/1. These are set using the variables
# shopt_decorator_option_name and shopt_decorator_option_value
# To use this add a line like the following (without #) as the first line of a function
# Example:
# function smarter_sort {
# # 'sort' doesn't properly handle SIGPIPE
# shopt_decorator_option_name='pipefail'
# shopt_decorator_option_value='false'
# shopt_decorator "${FUNCNAME[0]}" "${@:-}" && return || conditional_exit_on_fail 121 "Failed to run ${FUNCNAME[0]} with shopt_decorator"
#
# echo "Bash option pipefail is set to false for this code"
# }
function shopt_decorator {
debug 10 "${FUNCNAME} called with ${*}"
if [ -n "${shopt_decorator_option_value:-}" ] && [ -n "$(shopt -o "${shopt_decorator_option_name:-}")" ] ; then
if [ "${FUNCNAME[0]}" != "${FUNCNAME[2]:-}" ] ; then
if shopt -qo "${shopt_decorator_option_name}" ; then
# Option is set
if ! "${shopt_decorator_option_value}" ; then
# Option should not be set
debug 10 "Temporarily unsetting bash option ${shopt_decorator_option_name}"
shopt -uo "${shopt_decorator_option_name}"
else
debug 10 "No need to set ${shopt_decorator_option_name}, it's already ${shopt_decorator_option_value}"
fi
"${@}"
return_code="${?}"
debug 10 "Got return code ${return_code}"
# Set the option again in case it was unset
debug 10 "(Re)Setting ${shopt_decorator_option_name}"
shopt -so "${shopt_decorator_option_name}"
return ${return_code}
else
# Option is not set
if "${shopt_decorator_option_value}" ; then
# Option should be set
debug 10 "Temporarily setting bash option ${shopt_decorator_option_name}"
shopt -so "${shopt_decorator_option_name}"
else
debug 10 "No need to unset ${shopt_decorator_option_name}, it's already ${shopt_decorator_option_value}"
fi
"${@}"
return_code="${?}"
debug 10 "Got return code ${return_code}"
# Unset the option in case it was set
debug 10 "(Re)Unsetting ${shopt_decorator_option_name}"
shopt -uo "${shopt_decorator_option_name}"
return ${return_code}
fi
fi
# Calling function is the decorator, skip
debug 10 "Already decorated, returning 121"
return 121
else
color_echo red "Called ${FUNCNAME[*]} without setting required variables with valid option name/value. The variables shopt_decorator_option_name and shopt_decorator_option_value need to be set to a valid shopt option and a command/function that evaluates true/false, 'true'/'false' are valid commands"
exit 126
fi
# We should never get here
exit 127
}
# Test decorator
# Forces a function to be executed in all bash variants using the bashtester
# submodule and containers. Requires docker to be installed and git submodules
# to be present and up do date.
# To use this add a line like the following (without #) as the first line of a function
# test_decorator "${FUNCNAME[0]}" "${@:-}" && return
# test_decorator "${FUNCNAME[0]}" "${@:-}" && return || conditional_exit_on_fail 121 "Failed to run ${FUNCNAME[0]} with test_decorator"
# To specify a different set of bash versions set supported-bash_versions to a
# space separated string of the supported versions.
function test_decorator {
# If not running in a container
if [ "${FUNCNAME[0]}" != "${FUNCNAME[2]:-}" ] && ! grep -q docker /proc/1/cgroup 2> /dev/null ; then
default_bash_versions=( '3.2.57' \
'4.0.44' \
'4.1.17' \
'4.2.53' \
'4.3.48' \
'4.4.23' \
'5.0-beta' )
supported_bash_versions=( ${supported_bash_versions[@]:-"${default_bash_versions[@]}"} )
verbosity="${verbosity:-}" bash_images="${supported_bash_versions[*]}" bashtester/run.sh ". /code/$(basename ${BASH_SOURCE[0]}) && ${*}"
return 0
fi
return 1
}
# Imports/Sources an external script if it's not already been imported/sourced
# or is being imported/sourced as determined by BASH_SOURCE
# Only accepts one argument, the file to source.
# Returns 0 if file is successfully imported or has already been imported.
# For opertunistic usage use the following pattern:
# file_to_import='my_file_path'
# type -t import | grep -q '^function$' && import "${file_to_import}" || source "${file_to_import}"
declare -a sourced_imported_files
sourced_imported_files=()
function import {
assert test -n "${1}"
assert test -e "${1}"
local hasher
if whichs shasum; then
hasher='shasum'
elif whichs md5sum; then
hasher='md5sum'
elif whichs cksum; then
hasher='cksum'
else
debug 1 "Unable to find a valid hashing command, blindly importing/sourcing!"
# shellcheck disable=1090
source "${1}" && return 0
fi
# Create a hash of the target file
target_file_hash="$("${hasher}" "${1}")"
# Add all files in source history to the list of imported files
for source_file in "${BASH_SOURCE[@]}"; do
source_file_hash="$("${hasher}" "${source_file}" | awk '{print $0}')"
if ! in_array "${source_file_hash}" "${sourced_imported_files[@]:-}" ; then
sourced_imported_files+=( "${source_file_hash}" )
fi
done
# Check if file has already been sourced/imported
if in_array "${target_file_hash}" "${sourced_imported_files[@]}" ; then
debug 5 "Source file ${1} has already been imported/sourced, skipping"
return 0
fi
# Finally import/source the file if needed
debug 7 "Sourcing file ${1}"
sourced_imported_files+=( "${target_file_hash}" )
# shellcheck disable=1090
source "${1}" && return 0
}
# A platform (readlink implementation) neutral way to follow symlinks
function readlink_m {
debug 10 "readlink_m called with: ${*}"
args=( ${@} )
if [ "${#args[@]}" -eq 0 ] ; then
color_echo red 'readlink_m needs at least one argument, none were provided'
return 64
elif [ "${#args[@]}" -gt 1 ] ; then
base_path="$(dirname "${args[0]}")"
new_path="${base_path}/${args[1]}"
elif whichs readlink && readlink -f "${args[0]}" > /dev/null 2>&1 ; then
readlink -f "${args[0]}"
return 0
elif whichs readlink && readlink -m "${args[0]}" > /dev/null 2>&1 ; then
readlink -m "${args[0]}"
return 0
elif whichs realpath && realpath -m "${args[0]}" > /dev/null 2>&1 ; then
realpath -m "${args[0]}"
return 0
elif whichs greadink ; then
greadlink -m "${args[0]}"
return 0
elif whichs grealpath ; then
grealpath "${args[0]}"
return 0
elif whichs realpath ; then
realpath "${args[0]}"
return 0
elif [ -e "${args[0]}" ] ; then
if stat -f "%N %Y" "${args[0]}" > /dev/null 2>&1 ; then
new_path="$(stat -f "%N %Y" "${args[0]}")"
elif stat -f "%n %N" "${args[0]}" > /dev/null 2>&1 ; then
new_path="$(stat --format '%n %N' "${args[0]}" | tr -d "‘’")"
else
color_echo red "Unable to find a usable way to determine full path (readlink_m)"
exit_on_fail
fi
else
color_echo red "Unable to find a usable way to determine full path (readlink_m)"
exit_on_fail
fi
new_path=( ${new_path} )
debug 10 "Processed path is: ${new_path[*]}"
if [ ${#new_path[@]} -gt 1 ] || [ -L "${new_path[0]}" ] ; then
readlink_m "${new_path[@]}"
elif [ -e "${new_path[0]}" ] ; then
echo "${new_path[0]}"
return 0
elif command -v realpath ; then
realpath "${args[0]}"
return 0
else
debug 10 "Failed to resolve path: ${new_path[*]}"
return 1
fi
}
# Platform independent version sort
# When input is piped it's assumed to be space and/or newline (NL) delimited
# When passed as parameters each one is processed independently
function _version_sort {
debug 12 "${FUNCNAME} called with ${*}"
# 'sort' doesn't properly handle SIGPIPE
shopt_decorator_option_name='pipefail'
shopt_decorator_option_value='false'
# shellcheck disable=2015
shopt_decorator "${FUNCNAME[0]}" "${@:-}" && return || conditional_exit_on_fail 121 "Failed to run ${FUNCNAME[0]} with shopt_decorator"
if sort --help 2>&1 | grep -q version-sort ; then
local vsorter='sort --version-sort'
else
debug 10 "Using suboptimal version sort due to old Coreutils/Platform"
local vsorter='sort -t. -k1,1n -k2,2n -k3,3n -k4,4n'
fi
for arg in "${@}" ; do
echo "${arg}"
done | ${vsorter}
}
# shellcheck disable=2120
function version_sort {
# First command needs to be read, this way any piped input goes to it
while read -rt "${read_timeout:-1}" piped_data; do
declare -a piped_versions
debug 10 "Versions piped to ${FUNCNAME}: ${piped_data}"
# shellcheck disable=2086
piped_versions+=( ${piped_data} )
done
shopt_decorator_option_name='nounset'
shopt_decorator_option_value='false'
# shellcheck disable=2015
shopt_decorator "${FUNCNAME[0]}" "${@:-}" && return || conditional_exit_on_fail 121 "Failed to run ${FUNCNAME[0]} with shopt_decorator"
# shellcheck disable=2068
_version_sort ${@} ${piped_versions[@]}
}
# Increment a version number by 1
function version_increment {
declare -a segment=( ${1//\./ } )
declare new_version
declare -i carry=1
for (( n=${#segment[@]}-1; n>=0; n-=1 )); do
length=${#segment[n]}
new_version=$((segment[n]+carry))
[ "${#new_version}" -gt "${length}" ] && carry=1 || carry=0
[ "${n}" -gt 0 ] && segment[n]=${new_version: -length} || segment[n]=${new_version}
done
new_version="${segment[*]}"
echo -e "${new_version// /.}"
}
# Allows clear assert syntax
function assert {
debug 10 "Assertion made: ${*}"
# shellcheck disable=SC2068
if ! "${@}" ; then
color_echo red "Assertion failed: '${*}'"
exit_on_fail
fi
}
# A bash only version of basename -s
function basename_s {
local path="${*}"
local path_no_ext="${path%.*}"
local basename="${path_no_ext##*/}"
echo "${basename}"
}
# Converts relative paths to full paths, ignores invalid paths
# Accepts either the path or name of a variable holding the path
function finalize_path {
local setvar
assert test -n "${1}"
# Check if there is a filesystem object matching the path
if [ -e "${1}" ] || [[ "${1}" =~ '/' ]] || [[ "${1}" =~ '~' ]]; then
debug 10 "Assuming path argument: ${1} is a path"
path="${1}"
setvar=false
else
debug 5 "Assuming path argument: ${1} is a variable name"
declare path="${!1}"
setvar=true
fi
if [ -n "${path}" ] && [ -e "${path}" ] ; then
if [ "$(basename "$(readlink "$(command -v readlink)")")" == 'busybox' ] || [ "${os_family}" == 'MacOSX' ] ; then
full_path=$(readlink_m "${path}")
else
full_path="$(readlink -m "${path}")"
fi
debug 10 "Finalized path: '${path}' to full path: '${full_path}'"
if [ -n "${full_path}" ]; then
if ${setvar} ; then
export "$1"="${full_path}"
else
echo "${full_path}"
fi
fi
else
debug 5 "Unable to finalize path: ${path}"
fi
}
# Store full path to this script
script_full_path="${0}"
if [ ! -f "${script_full_path}" ] ; then
script_full_path="$(pwd)"
fi
finalize_path script_full_path
run_dir="${run_dir:-$(dirname "${script_full_path}")}"
debug 10 "Set 'script_full_path' to: ${script_full_path}"
debug 10 "Set 'run_dir' to: ${run_dir}"
# Allows checking of exit status, on error print debugging info and exit.
# Takes an optional error message in which case only it will be shown
# This is typically only used when running in non-strict mode but when errors
# should be raised and to help with debugging
function exit_on_fail {
message="${*:-}"
if [ -z "${message}" ] ; then
color_echo red "Last command did not execute successfully but is required!" >&2
else
color_echo red "${*}" >&2
fi
debug 10 "[$( caller )] ${*:-}"
debug 10 "BASH_SOURCE: ${BASH_SOURCE[*]}"
debug 10 "BASH_LINENO: ${BASH_LINENO[*]}"
debug 0 "FUNCNAME: ${FUNCNAME[*]}"
# Exit if we are running as a script, else return
if [ -f "${script_full_path}" ]; then
exit 1
else
return 1
fi
}
# Returns the index number of the lowest version, in effect this means it
# returns true if the first value is the smallest but will always return
# the index of the lowest version. In the case of multiple matches, the lowest
# (the first match) index is returned.
# Example:
# compare_versions '1.1.1 1.2.2test' -> returns 0 # True
# compare_versions '1.2.2 1.1.1' -> returns 1 # False
# compare_versions '1.0.0 1.1.1 2.2.2' -> returns 0 # True
# compare_versions '4.0.0 3.0.0 2.0.0 1.1.1test 1.0.0 v5.0' -> returns 4 (the
# index number, which also evaluates to False since its a non-zero return code)
function compare_versions {
debug 10 "${FUNCNAME} called with ${*}"
# 'printf' doesn't properly handle SIGPIPE
shopt_decorator_option_name='pipefail'
shopt_decorator_option_value='false'
# shellcheck disable=2015
shopt_decorator "${FUNCNAME[0]}" "${@:-}" && return || conditional_exit_on_fail 121 "Failed to run ${FUNCNAME[0]} with shopt_decorator"
items=( ${@} )
assert [ ${#items[@]} -gt 0 ]
# shellcheck disable=2119
lowest_ver="$(printf "%s\\n" "${items[@]}" | version_sort | head -n1)"
for (( i=0; i<${#items[@]}; i++ )) ; do
if [ "${items[i]}" == "${lowest_ver}" ] ; then
debug 10 "${FUNCNAME} returning ${i}"
return "${i}"
fi
done
color_echo red "Failed to compare versions!"
exit_on_fail
}
# Set conveniece variable for bash v4 compat
if compare_versions "${BASH_VERSION}" "4" ; then
bash_pre_v4=true
else
bash_pre_v4=false
fi
# Set timeout value to use for read, v3 does not support decimal seconds
if "${bash_pre_v4}" ; then
read_timeout='1'
else
read_timeout='0.1'
fi
# Prints the version of a command, arguments include:
# 1. Full or relative path to command (required)
# 2. Text to display before version info (optional)
# 3+. Flag(s)/Argument(s) to command to get version (optional, defaults to --version)
# error_msg variable: Error message if command is not found, to ignore redirect
# stderr run this like so: print_version bash 2> /dev/null
function print_version {
local error_msg
error_msg="${error_msg:-Unable to find command ${1}}"
if command -v "${1}" > /dev/null ; then
echo -n "${2:-}"
if [ -n "${3}" ] ; then
${1} "${@:3}"
else
${1} --version
fi
else
(>&2 echo "${error_msg}")
fi
}
# Default is to clean up after ourselves
cleanup="${cleanup:-true}"
# Create NSS Wrapper passwd and group files
# Accepts 4 optional arguments, uid:gid, username, group and home directory
# Defaults to current uid/gid, bob, builders and a temporary directory
# Note that if a home directory is specified and it's temporary it will need to
# be removed/cleaned up by the code calling this function
function init_nss_wrapper {
umask_decorator_mask=${NSS_WRAPPED_FILE_MASK:-0002}
umask_decorator "${FUNCNAME[0]}" "${@:-}" && return
GUID="${1:-${GUID:-${UID:-$(id -u)}:$(id -g)}}"
debug 8 "Initializing NSS Wrapper with ${GUID}"
export TMP_USER="${2:-bob}"
export TMP_GROUP="${3:-builders}"
# The ordering of -t and -d is important so this works on both BSD/OSX an
# linux since template and -t have different meanings and syntaxes
tmp_passwd_file="$(mktemp -t "passwd.${$}.XXXXXXXXXX")" && add_on_exit "rm -f '${tmp_passwd_file}'" && chmod "${NSS_WRAPPED_FILE_PERM:-0664}" "${tmp_passwd_file}"
tmp_group_file="$(mktemp -t "group.${$}.XXXXXXXXXX")" && add_on_exit "rm -f '${tmp_group_file}'" && chmod "${NSS_WRAPPED_FILE_PERM:-0664}" "${tmp_group_file}"
tmp_hosts_file="$(mktemp -t "hosts.${$}.XXXXXXXXXX")" && add_on_exit "rm -f '${tmp_hosts_file}'" && chmod "${NSS_WRAPPED_FILE_PERM:-0664}" "${tmp_hosts_file}"
if [ -n "${4:-}" ] ; then
TMP_HOME_PATH="${4}"
else
TMP_HOME_PATH="$(mktemp -d -t "home.${TMP_USER}.XXXXXXXXXX")" && add_on_exit "rm -Rf '${TMP_HOME_PATH}'" && chown -R "${GUID}" "${TMP_HOME_PATH}" > /dev/null 2>&1
fi
export TMP_HOME_PATH
mkdir -p "${TMP_HOME_PATH}"
cat '/etc/passwd' > "${tmp_passwd_file}"
cat '/etc/group' > "${tmp_group_file}"
cat '/etc/hosts' > "${tmp_hosts_file}"
export BUID="${GUID%:*}"
export BGID="${GUID#*:}"
passwd_string="${TMP_USER}:x:${BUID}:${BGID}:Bob the builder:${TMP_HOME_PATH}:/bin/false"
group_string="${TMP_GROUP}:x:${BUID}:"
passwd_name_pattern='^'"${TMP_USER}"':x:.*:.*:.*:.*:.*$'
passwd_pattern='^.*:x:'"${BUID}"':.*:.*:.*:.*$'
group_name_pattern="^${TMP_GROUP}"':x:.*:.*$'
group_pattern='^.*:x:'"${BGID}"':.*$'
sed -i "s|${passwd_pattern}||g" "${tmp_passwd_file}"
sed -i "s|${passwd_name_pattern}||g" "${tmp_passwd_file}"
sed -i "s|${group_pattern}||g" "${tmp_group_file}"
sed -i "s|${group_name_pattern}||g" "${tmp_group_file}"
echo "${passwd_string}" >> "${tmp_passwd_file}"
echo "${group_string}" >> "${tmp_group_file}"
export LD_PRELOAD="libnss_wrapper.so"
export NSS_WRAPPER_PASSWD="${tmp_passwd_file}"
export NSS_WRAPPER_GROUP="${tmp_group_file}"
export NSS_WRAPPER_HOSTS="${tmp_hosts_file}"
}
# Enable a Python Software Collection, SCL allows multiple versions of the same RPMs to be
# installed at the same time. Accepts one required argument, the version of
# python to enable, this should be in the format '3.6'
function enable_scl_python {
assert [ "${os_name}" = "redhat" ]
shopt_decorator_option_name='nounset'
shopt_decorator_option_value='false'
assert test -n "${1}"
python_version="${1}"
short_version="$(echo "${python_version}" | tr -dc '0-9')"
python_enable_path="${2:-${PYTHON_ENABLE_PATH:-/opt/rh/python${short_version}/enable}}"
# shellcheck disable=SC2015
shopt_decorator "${FUNCNAME[0]}" && return || conditional_exit_on_fail 121 "Failed to run ${FUNCNAME[0]} with shopt_decorator"
color_echo green "Enabling SCL environment for python version: ${python_version}"
# shellcheck disable=SC1090
source "${python_enable_path}}"
}
#Set username not available (unattended run) if passwd record exists
if [ -z "${USER:-}" ] && whoami > /dev/null 2>&1 ; then
USER="$(whoami)"
export USER
fi
# Set home directory if not available (unattended run)
if [ -z "${HOME:-}" ]; then
HOME="$(getent passwd "${USER}" | awk -F: '{print $6}')"
export HOME
fi
# Find the best way to escalate our privileges
function set_priv_esc_cmd {
if [ "${EUID}" != "0" ]; then
if [ -x "$(command -v sudo)" ]; then
priv_esc_cmd='sudo -E'
elif [ -x "$(command -v su)" ]; then
priv_esc_cmd='su -c'
else
color_echo red "Not running as root and unable to locate/run sudo or su for privilege escalation"
return 1
fi
else
priv_esc_cmd=''
fi
return 0
}
set_priv_esc_cmd
# Magical sudo/su which preserves all ssh keys, kerb creds and def. ssh user
# and tty/pty
function priv_esc_with_env {
debug 10 "Calling: \"${priv_esc_cmd} ${*}\" on tty: \"${init_tty}\" with priv esc command as: \"${priv_esc_cmd}\" and user: \"${USER}\""
debug 11 "${priv_esc_cmd} /bin/bash -c export SSH_AUTH_SOCK='${SSH_AUTH_SOCK}' && export SUDO_USER_HOME='${HOME}' && export KRB5CCNAME='${KRB5CCNAME}' && export GPG_TTY='${init_tty}' && alias ssh='ssh -l ${USER}' && ${*}"
${priv_esc_cmd} /bin/bash -c "export SSH_AUTH_SOCK='${SSH_AUTH_SOCK}' && export SUDO_USER_HOME='${HOME}' && export KRB5CCNAME='${KRB5CCNAME}' && export GPG_TTY='${init_tty}' && alias ssh='ssh -l ${USER}' && ${*}"
return ${?}
}
# Create a custom ssh auth agent, socket and pid if the script is not running
# in a container.
function create_custom_ssh_agent {
custom_ssh_auth_socket_path="${1:-${HOME}/custom-ssh-agent}"
custom_ssh_auth_pid_file="${2:-${HOME}/.custom-ssh-agent.pid}"
if [[ "${virt_platform:-}" != 'Docker' ]]; then
debug 10 "Creating custom ssh-agent with socket: ${custom_ssh_auth_socket_path}"
assert whichs ssh-agent
if rm -f "${custom_ssh_auth_socket_path}" ; then
eval $(ssh-agent -a ${custom_ssh_auth_socket_path})
echo "${SSH_AGENT_PID}" > "${custom_ssh_auth_pid_file}"
else
color_echo red "Unable to reset/create named socket ${custom_ssh_auth_socket_path}, please verify path and permissions"
return 1
fi
else
color_echo green "Virtual platform is Docker, skipping"
fi
}
# Create and manage a custom ssh auth agent, socket and pid
# Create a special ssh-agent for docker, accepts two optional
# parameters/arguments, the location of the named socket and the pid file
# Optionally accepts any number of ssh key files to import, these can include
# wildcards.
function get_custom_ssh_auth_agent {
custom_ssh_auth_socket_path="${1:-${HOME}/custom-ssh-agent}"
custom_ssh_auth_pid_file="${2:-${HOME}/.custom-ssh-agent.pid}"
ssh_key_files=( ${@:3} )
if [ -S "${custom_ssh_auth_socket_path}" ] ; then
color_echo cyan "Found custom ssh-agent with socket: ${custom_ssh_auth_socket_path}"
export SSH_AUTH_SOCK="${custom_ssh_auth_socket_path}"
if [ -f "${custom_ssh_auth_pid_file}" ] && pgrep -F "${custom_ssh_auth_pid_file}" > /dev/null 2>&1 ; then
read -r SSH_AGENT_PID < "${custom_ssh_auth_pid_file}"
export SSH_AGENT_PID
else
create_custom_ssh_agent "${custom_ssh_auth_socket_path}" "${custom_ssh_auth_pid_file}"
fi
else
create_custom_ssh_agent "${custom_ssh_auth_socket_path}" "${custom_ssh_auth_pid_file}"
fi
color_echo cyan "Checking ssh-agent key status"
assert whichs ssh-add
if [ -n "${ssh_key_files:-}" ] ; then
color_echo green "Loading key files: ${ssh_key_files[*]}"
for ssh_key_file in "${ssh_key_files[@]}" ; do
debug 10 "Processing ssh key file: ${ssh_key_file}"
if ! ssh-add -l | grep -q "${ssh_key_file}" ; then
ssh-add ${ssh_key_file:-} || exit_on_fail "Unable to load ssh key file ${ssh_key_file} into agent"
else
color_echo green "Key file: ${ssh_key_file} already loaded into custom ssh agent"
fi
done
else
if ! ssh-add -l > /dev/null 2>&1 ; then
color_echo green "No ssh key specified, loading default key"
ssh-add || exit_on_fail "Unable to load ssh key into agent"
else
color_echo green "Found existing ssh key in custom ssh agent, no key specified to load, skipping"
fi
fi
assert test -n "${SSH_AUTH_SOCK}"
}
# A subprocess which performs a command when it receives a signal
# First parameter is the signal and the rest is assumed to be the command
# Returns the PID of the subprocess
function signal_processor {
local signal="${1}"
local command="${*:2}"
bash -c "trap '${command}' ${signal} && while true; do sleep 1 ; done" > /dev/null 2>&1 &
echo "${!}"
}
# Signals a process by either exact name or pid
# Accepts name/pid as first parameter and optionally signal as second parameter
function signal_process {
debug 8 "Signaling PID: ${1} with signal: ${2:-SIGTERM}"
if [[ "${1}" =~ ^[0-9]+$ ]] ; then
if [ "${2}" != '' ] ; then
kill -s "${2}" "${1}"
else
kill "${1}"
fi
else
assert whichs pkill
if [ "${2}" != '' ] ; then
pkill --exact --signal "${2}" "${1}"
else
pkill --exact "${1}"
fi
fi
}
# This function watches a set of files/directories and lets you run commands
# when file system events (using inotifywait) are detected on them
# - Param 1: command/function to run
# - Param 2..N: files/directories to monitor. Note: Absolute paths to the
# modified objects are passed to the command/function
# Custom variables:
# - on_mod_max_frequency: the frequency, in seconds, to run command/function
# (acts as a debounce). If set to 0 then multiple instances of
# the command/function can run at the same time. Default: 1s
# - on_mod_refresh: determines if command/function should run again at the end
# of the timeout if re-triggered during the previous run.
# Default: true
# - on_mod_max_queue_depth: determines event queue size. Default: 1 event
#
# File system modification events:
# - MODIFY | CLOSE_WRITE
# - MOVED_TO | CREATE
# - MOVED_FROM | DELETE | MOVE_SELF
# - DELETE_SELF | UNMOUNT
#
# Example use: Create a callback function and register it for events
#
# path_to_monitor="/tmp"
# function callback {
# modified_obj="${1}"
# modified_dir=$(dirname "${modified_obj}")
# modified_file=$(basename "${modified_obj}")
# current_dir="${PWD}"
# cd ${modified_dir}
# echo "Do something with '${modified_file}' in '${modified_dir}'"
# ls -la ${modified_file}
# cd ${current_dir}
# }
# add_on_mod callback "${path_to_monitor}"
#
function add_on_mod {