forked from BretFisher/docker-vackup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vackup
1881 lines (1625 loc) · 59.8 KB
/
vackup
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
# Copyright (C) 2024 Guiorgy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Docker Volume File Backup and Restore Tool
# Easily tar up a volume on a local (or remote) engine
# Base on vackup by Bret Fisher
# Inspired by CLIP from Lukasz Lach
#
# This script targets bash for better error handling, which isn't required
# It checks the BASH variable, and falls back to POSIX compliance if not set
# It (hopefully) works with any POSIX shell
# The file name of the script in case it was renamed
VACKUP=$(basename "$0")
# Some shells don't support this (looking at you dash)
if [ -z "$LINENO" ]; then
LINENO='unknown'
fi
# Silently check if the caller command is defined
if command -v caller 1> /dev/null 2>&1; then
CALLER=1
else
CALLER=0
fi
# Check if we are in bash
if [ -z "$BASH" ]; then
BASH=''
fi
# Define VACKUP_FAILURE_SHELL and VACKUP_FAILURE_SCRIPT if not defined
if [ -z "$VACKUP_FAILURE_SHELL" ]; then
VACKUP_FAILURE_SHELL=''
fi
if [ -z "$VACKUP_FAILURE_SCRIPT" ]; then
VACKUP_FAILURE_SCRIPT=''
fi
# Modify shell behavior
if [ -n "$BASH" ]; then
# -E: The trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment
# -e: Exit immediately if a pipeline returns a non-zero status
# -u: The shell shall write a message to standard error when it tries to expand a variable that is not set and immediately exit
# -o pipefail: The return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully
set -Eeuo pipefail
else
set -eu
fi
# Executes the VACKUP_FAILURE_SCRIPT script with line number and error code as arguments using the VACKUP_FAILURE_SHELL shell and exit
# Remark: Line number may be 'unknown' on some shells, e.g. dash
# Executed when an error is trapped, or the error function is called
# Parameters:
# LineNumber (required): The line number of the failed command
# ExitCode: The error code of the failed command
handle_error() {
case $# in
1) LINE_NUMBER=$1; EXIT_CODE=$? ;;
2) LINE_NUMBER=$1; EXIT_CODE=$2 ;;
*) LINE_NUMBER=$LINENO; EXIT_CODE=1 ;;
esac
if [ -n "$VACKUP_FAILURE_SCRIPT" ]; then
if [ -z "$VACKUP_FAILURE_SHELL" ]; then
if [ -n "$BASH" ]; then
VACKUP_FAILURE_SHELL="$BASH"
else
VACKUP_FAILURE_SHELL=$(command -v sh 2> /dev/null) || 'sh'
fi
fi
"$VACKUP_FAILURE_SHELL" "$VACKUP_FAILURE_SCRIPT" "$LINE_NUMBER" "$EXIT_CODE"
fi
exit "$EXIT_CODE"
}
# Set up a trap
if [ -n "$BASH" ]; then
trap 'handle_error $LINENO' ERR
else
trap 'handle_error $LINENO $?' EXIT
fi
# Initialize colors for STDOUT if it's connected to a tty
if [ -t 1 ]; then
RESET_COLOR='\033[0m'
BLACK_COLOR='\033[0;30m'
RED_COLOR='\033[0;31m'
GREEN_COLOR='\033[0;32m'
YELLOW_COLOR='\033[0;33m'
BLUE_COLOR='\033[0;34m'
PURPLE_COLOR='\033[0;35m'
CYAN_COLOR='\033[0;36m'
WHITE_COLOR='\033[0;37m'
BOLD_BLACK_COLOR='\033[1;30m'
BOLD_RED_COLOR='\033[1;31m'
BOLD_GREEN_COLOR='\033[1;32m'
BOLD_YELLOW_COLOR='\033[1;33m'
BOLD_BLUE_COLOR='\033[1;34m'
BOLD_PURPLE_COLOR='\033[1;35m'
BOLD_CYAN_COLOR='\033[1;36m'
BOLD_WHITE_COLOR='\033[1;37m'
else
RESET_COLOR=''
BLACK_COLOR=''
RED_COLOR=''
GREEN_COLOR=''
YELLOW_COLOR=''
BLUE_COLOR=''
PURPLE_COLOR=''
CYAN_COLOR=''
WHITE_COLOR=''
BOLD_BLACK_COLOR=''
BOLD_RED_COLOR=''
BOLD_GREEN_COLOR=''
BOLD_YELLOW_COLOR=''
BOLD_BLUE_COLOR=''
BOLD_PURPLE_COLOR=''
BOLD_CYAN_COLOR=''
BOLD_WHITE_COLOR=''
fi
# Initialize colors for STDERR if it's connected to a tty
if [ -t 2 ]; then
RESET_COLOR_ERR='\033[0m'
BLACK_COLOR_ERR='\033[0;30m'
RED_COLOR_ERR='\033[0;31m'
GREEN_COLOR_ERR='\033[0;32m'
YELLOW_COLOR_ERR='\033[0;33m'
BLUE_COLOR_ERR='\033[0;34m'
PURPLE_COLOR_ERR='\033[0;35m'
CYAN_COLOR_ERR='\033[0;36m'
WHITE_COLOR_ERR='\033[0;37m'
BOLD_BLACK_COLOR_ERR='\033[1;30m'
BOLD_RED_COLOR_ERR='\033[1;31m'
BOLD_GREEN_COLOR_ERR='\033[1;32m'
BOLD_YELLOW_COLOR_ERR='\033[1;33m'
BOLD_BLUE_COLOR_ERR='\033[1;34m'
BOLD_PURPLE_COLOR_ERR='\033[1;35m'
BOLD_CYAN_COLOR_ERR='\033[1;36m'
BOLD_WHITE_COLOR_ERR='\033[1;37m'
else
RESET_COLOR_ERR=''
BLACK_COLOR_ERR=''
RED_COLOR_ERR=''
GREEN_COLOR_ERR=''
YELLOW_COLOR_ERR=''
BLUE_COLOR_ERR=''
PURPLE_COLOR_ERR=''
CYAN_COLOR_ERR=''
WHITE_COLOR_ERR=''
BOLD_BLACK_COLOR_ERR=''
BOLD_RED_COLOR_ERR=''
BOLD_GREEN_COLOR_ERR=''
BOLD_YELLOW_COLOR_ERR=''
BOLD_BLUE_COLOR_ERR=''
BOLD_PURPLE_COLOR_ERR=''
BOLD_CYAN_COLOR_ERR=''
BOLD_WHITE_COLOR_ERR=''
fi
# The default extension of the exported/imported archive
EXTENSION='.tar.gz'
# Prints usage and exits if necessary
# Flags:
# --err: Print to STDERR instead of STDOUT
# --exit: Exit after printing usage.
# If --err is also set, exit with the error code 1
# Parameters:
# For (optional, main by default): One of main, export, import, all, export-all or import-all
print_usage() {
STDERR=0
EXIT=0
while [ $# -ne 0 ]; do
case "$1" in
-*)
OPTION="$1"
shift
case "$OPTION" in
--err) STDERR=1 ;;
--exit) EXIT=1 ;;
*) warning "'$OPTION' is not a recognized print_usage option"
esac
;;
*) break ;;
esac
done
if [ $# -eq 0 ]; then
FOR='main'
else
FOR="$1"
if [ $# -gt 1 ]; then
warning 'Wrong number of arguments in the print_usage function'
fi
fi
case "$FOR" in
main)
TEXT=$(cat <<EOF
Usage: $VACKUP [OPTIONS] COMMAND
"Docker Volume Backup". Replicates image management commands for volumes.
Commands:
help Print this help page and exit
export Export a docker volume into an archive file
import Import a docker volume from an archive file
all Export/import multiple docker volumes to/from archive files
Options:
-h, --help Print this help page and exit
-l, --license Print the license notice and exit
-q, --quiet Silence the outputs to STDOUT, except if the help page is
explicitly requested
-v, --verbose Verbose printing
-H, --host Do the export/import by running the archive program on the
host instead of a container
Run '$VACKUP COMMAND --help' for more information on a command.
EOF
) || error "Failed to generate the usage text"
;;
export)
TEXT=$(cat <<EOF
Usage: $VACKUP export [OPTIONS] VOLUME_NAME [OUTPUT]
Export a docker volume into an archive file
Parameters:
VOLUME_NAME The docker volume to export
OUTPUT The path to the output archive file. If the path points to a
directory, a file inside the said directory with the name of
the volume and archive extension will be assumed
Options:
-h, --help Print this help page and exit
-p, --parents Create parent directories for the archive file as needed
-f, --force Overwrite the archive file if a file already exists
-s, --stop Stop running containers that have the specified volume as a
mount point before exporting, and restart them after
-P, --pause Pause containers instead of stopping them. This option is
valid only in conjunction with --stop
EOF
) || error "Failed to generate the usage text"
;;
import)
TEXT=$(cat <<EOF
Usage:
$VACKUP import [OPTIONS] INPUT VOLUME_NAME
$VACKUP import [OPTIONS] VOLUME_NAME
Import a docker volume from an archive file
Parameters:
INPUT The path to the intput archive file. If the path points to a
directory, a file inside the said directory with the name of
the volume and archive extension will be assumed
VOLUME_NAME The docker volume to import
Options:
-h, --help Print this help page and exit
-s, --stop Stop running containers that have the specified volume as a
mount point before importing, and restart them after
-P, --pause Pause containers instead of stopping them. This option is
valid only in conjunction with --stop
EOF
) || error "Failed to generate the usage text"
;;
all)
TEXT=$(cat <<EOF
Usage: $VACKUP all [OPTIONS] COMMAND
Export/import multiple docker volumes to/from archive files
Commands:
help Print this help page and exit
export Export multiple docker volumes into archive files
import Import multiple docker volumes from archive files
Options:
-h, --help Print this help page and exit
Run '$VACKUP all COMMAND --help' for more information on a command.
EOF
) || error "Failed to generate the usage text"
;;
export-all)
TEXT=$(cat <<EOF
Usage: $VACKUP all export [OPTIONS] OUTPUT
Export multiple docker volumes into archive files
All exported archives will be named as the name of the volume and archive
extension, e.g. my_docker_volume$EXTENSION
Parameters:
OUTPUT The path to the output directory where the archive files will be
exported to
Options:
-h, --help Print this help page and exit
-p, --parents Create parent directories for the archive files as
needed
-f, --force Overwrite the archive files if a file already exists
-i, --in-use Only export volumes that are in use by at least one
container
-s, --stop Stop the running containers that mount a volume
before exporting, and restart them after. Takes
priority over the -S, --stop-all flag
-S, --stop-all Stop all running containers before exporting, and
restart them after
-P, --pause Pause containers instead of stopping them. This
option is valid only in conjunction with either
--stop or --stop_all
--exclude-containers=CONTAINERS
Exclude the specified containers from being
stopped, where CONTAINERS is a comma separated list
of container names. This option is valid only in
conjunction with either --stop or --stop_all
--exclude-volumes=VOLUMES
Exlcude the specified volumes from being exported,
where VOLUMES is a comma separated list of volume
names
-d, --date Add the current date in the yyyy-MM-dd_HH-mm-ss
ISOish format to the start of the archive file names.
If the flag is passed in a second time, append the
date to the end of the archive file names instead.
Mutually exclusive with the -D, --date-dir flag
-D, --date-dir Use the current date in the yyyy-MM-dd_HH-mm-ss
ISOish format as the output directory where the
archive files will be exported to. This directory
will be created inside the directory defined with the
OUTPUT parameter. If the flag is passed in a second
time, append the date to the start of the OUTPUT
directory name, instead of creating a new directory
inside the OUTPUT directory. If the flag is passed in
a third time, append the date to the end of the
OUTPUT directory name instead. Mutually exclusive
with the -d, --date flag
-u, --utc Use UTC instead of the local timezone. This option is
valid only in conjunction with either --date or
--date-dir
-k, --keep=N Keep the most recent N exported directories/archives,
and remove older ones. This option is valid only in
conjunction with either --date or --date-dir.
Mutually exclusive with the -K, --keep-days option
-K, --keep-days=DAYS Remove exported directories/archives older than DAYS
days. This option is valid only in conjunction with
either --date or --date-dir. Mutually exclusive with
the -k, --keep option
EOF
) || error "Failed to generate the usage text"
;;
import-all)
TEXT=$(cat <<EOF
Usage: $VACKUP all import [OPTIONS] INPUT
Import multiple docker volumes from archive files
All imported archives will be assumed to be named as the name of the volume and
archive extension, e.g. my_docker_volume$EXTENSION
Parameters:
INPUT The path to the intput directory where all the archive files
to be imported are
Options:
-h, --help Print this help page and exit
-s, --stop Stop the running containers that mount a volume
before importing, and restart them after. Takes
priority over the -S, --stop-all flag
-S, --stop-all Stop all running containers before importing, and
restart them after
-P, --pause Pause containers instead of stopping them. This
option is valid only in conjunction with either
--stop or --stop_all
--exclude-containers=CONTAINERS
Exclude the specified containers from being
stopped, where CONTAINERS is a comma separated list
of container names. This option is valid only in
conjunction with either --stop or --stop_all
--exclude-volumes=VOLUMES
Exlcude the specified volumes from being imported,
where VOLUMES is a comma separated list of volume
names
EOF
) || error "Failed to generate the usage text"
;;
*)
warning "'$FOR' is not a recognized print_usage target"
if [ $STDERR -eq 1 ]; then
print_usage --err
else
print_usage
fi
TEXT=''
;;
esac
if [ $STDERR -eq 1 ]; then
echo 1>&2 "$TEXT"
else
echo 1>&3 "$TEXT"
fi
if [ $EXIT -eq 1 ]; then
if [ $STDERR -eq 1 ]; then
if [ $CALLER -eq 1 ]; then
LINE_NUMBER=$(caller | awk '{ print $1 }') || LINE_NUMBER='unknown'
handle_error "$LINE_NUMBER" 1
else
exit 1
fi
else
exit 0
fi
fi
}
# Prints license notice and exits if necessary
# Flags:
# --err: Print to STDERR instead of STDOUT
# --exit: Exit after printing usage.
# If --err is also set, exit with the error code 1
print_license() {
STDERR=0
EXIT=0
while [ $# -ne 0 ]; do
case "$1" in
-*)
OPTION="$1"
shift
case "$OPTION" in
--err) STDERR=1 ;;
--exit) EXIT=1 ;;
*) warning "'$OPTION' is not a recognized print_license option"
esac
;;
*) break ;;
esac
done
if [ $# -ne 0 ]; then
warning 'Wrong number of arguments in the print_license function'
fi
TEXT=$(cat <<EOF
$VACKUP Copyright (C) 2024 Guiorgy
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it under certain
conditions.
Visit https://www.gnu.org/licenses/gpl-3.0.html for details.
EOF
) || error "Failed to generate the license notice text"
if [ $STDERR -eq 1 ]; then
echo 1>&2 "$TEXT"
else
echo 1>&3 "$TEXT"
fi
if [ $EXIT -eq 1 ]; then
if [ $STDERR -eq 1 ]; then
if [ $CALLER -eq 1 ]; then
LINE_NUMBER=$(caller | awk '{ print $1 }') || LINE_NUMBER='unknown'
handle_error "$LINE_NUMBER" 1
else
exit 1
fi
else
exit 0
fi
fi
}
# Prints a warning message to STDERR in yellow
# Options:
# {u|usage} Target: Print usage for the specified target to STDERR after printing the warning message
# Parameters:
# Message (optional, empty by default): The message to print
warning() {
if [ $# -gt 0 ]; then
if [ "$1" = 'u' ] || [ "$1" = 'usage' ]; then
shift
if [ $# -gt 0 ]; then
USAGE="$1"
else
USAGE='main'
warning 'Wrong number of arguments in the warning function'
fi
shift
else
USAGE=''
fi
case $# in
0) WARNING_MESSAGE='' ;;
1) WARNING_MESSAGE=$1 ;;
*) WARNING_MESSAGE="$*"; warning 'Wrong number of arguments in the warning function' ;;
esac
if [ -n "$WARNING_MESSAGE" ]; then
WARNING_MESSAGE=": $WARNING_MESSAGE"
fi
else
USAGE=''
WARNING_MESSAGE=''
fi
printf 1>&2 '%b' "${BOLD_YELLOW_COLOR_ERR}Warning${RESET_COLOR_ERR}${WARNING_MESSAGE}\n"
if [ -n "$USAGE" ]; then
print_usage --err "$USAGE"
fi
}
# Prints an error message to STDERR in red and exits
# Options:
# {u|usage} Target: Print usage for the specified target to STDERR after printing the error message
# Parameters:
# Message (optional, empty by default): The message to print
# ErrorCode (optional, 1 by default): The error code to exit with
error() {
if [ $# -gt 0 ]; then
if [ "$1" = 'u' ] || [ "$1" = 'usage' ]; then
shift
if [ $# -gt 0 ]; then
USAGE="$1"
else
USAGE='main'
warning 'Wrong number of arguments in the error function'
fi
shift
else
USAGE=''
fi
case $# in
0) ERROR_MESSAGE=''; CODE=1 ;;
1) ERROR_MESSAGE=$1; CODE=1 ;;
2) ERROR_MESSAGE=$1; CODE=$2 ;;
*) ERROR_MESSAGE="$*"; CODE=1; warning 'Wrong number of arguments in the error function' ;;
esac
if [ -n "$ERROR_MESSAGE" ]; then
ERROR_MESSAGE=": $ERROR_MESSAGE"
fi
else
USAGE=''
ERROR_MESSAGE=''
CODE=1
fi
printf 1>&2 '%b' "${BOLD_RED_COLOR_ERR}Error${RESET_COLOR_ERR}${ERROR_MESSAGE}\n"
if [ -n "$USAGE" ]; then
print_usage --err "$USAGE"
fi
if [ $CALLER -eq 1 ]; then
LINE_NUMBER=$(caller | awk '{ print $1 }') || LINE_NUMBER='unknown'
handle_error "$LINE_NUMBER" "$CODE"
else
exit "$CODE"
fi
}
# Prints an information message to STDOUT in the specified color
# Flags:
# --{no-color,black,red,green,yellow,blue,purple,cyan,white} (--blue by default): The color of the output
# Parameters:
# Message (optional, empty by default): The message to print
information() {
COLOR="$BLUE_COLOR"
if [ $# -ne 0 ]; then
case "$1" in
--*)
case "$1" in
--no-color) COLOR="$RESET_COLOR" ;;
--black) COLOR="$BLACK_COLOR" ;;
--red) COLOR="$RED_COLOR" ;;
--green) COLOR="$GREEN_COLOR" ;;
--yellow) COLOR="$YELLOW_COLOR" ;;
--blue) COLOR="$BLUE_COLOR" ;;
--purple) COLOR="$PURPLE_COLOR" ;;
--cyan) COLOR="$CYAN_COLOR" ;;
--white) COLOR="$WHITE_COLOR" ;;
*) warning "'$1' is an unrecognized color option in the information function" ;;
esac
shift
;;
*) ;;
esac
fi
case $# in
1) INFORMATION_MESSAGE=$1 ;;
2) INFORMATION_MESSAGE="${COLOR}$1${RESET_COLOR}: $2" ;;
*) INFORMATION_MESSAGE="$*"; warning 'Wrong number of arguments in the information function' ;;
esac
printf '%b' "$INFORMATION_MESSAGE\n"
}
# Silently check if the tac command is defined, and define it if it doesn't
if ! command -v tac 1> /dev/null 2>&1; then
# Reverses the order of lines
tac() {
sed '1!G;h;$!d'
}
fi
# Splits a string into individual characters, skipping the specified number of characters from the start
# Remark: Iterating over the resulting sequence using a normal for loop will drop all space characters
# Parameters:
# Skip (optional, 0 by default): The number of characters to skip
# String (required): The string to split into separate characters
# Return: A newline separated sequence of characters from the input string
chars() {
case $# in
1) STR="$1" ;;
2)
STR="$2"
SKIP="$1"
# Make sure SKIP is not larger than the length of the string
LEN="${#STR}"
if [ $LEN -lt $SKIP ]; then
SKIP="$LEN"
fi
# Remove a single character from the start of the string one character at a time
while [ "$SKIP" -gt 0 ]; do
STR="${STR#?}"
SKIP=$((SKIP - 1))
done
;;
*) STR="$1"; warning 'Wrong number of arguments in the chars function' ;;
esac
while [ -n "$STR" ]; do
# Remove the first character and store the remaining string in a temporary variable
REST="${STR#?}"
# Remove REST (everything but the first character) from the end of the string, resulting in the first character only
CHAR="${STR%"$REST"}"
echo "$CHAR"
STR="$REST"
done
}
# Prefixes every element in a sequence with the specified prefix
# Remark: Iterating over the resulting sequence using a normal for loop will split by any spaces in the prefix
# Parameters:
# Prefix (required): The prefix to prepend to the start of every element
# Elements.. (required): The elements to prepend the prefix to
# Return: A newline separated list of prefixed elements
prefix_all() {
case $# in
0 | 1) LIST=''; warning 'Wrong number of arguments in the prefix_all function' ;;
*) PREFIX="$1"; shift; LIST="$*" ;;
esac
for ITEM in $LIST; do
ITEM="$PREFIX$ITEM"
# Use printf to handle cases where the prefix is a dash ('-') and the item is either 'n', 'e' or 'E'
printf '%s\n' "$ITEM"
done
}
# Separates option and value from the input in the format OPTION=VALUE
# Remark: This function uses and modifies the global OPTION and VALUE variables
# Parameters:
# Option (optional, global OPTION variable by default): The option and its value delimited by an equals character
get_option_value() {
case $# in
0) ;;
1) OPTION="$1" ;;
*) OPTION="$1"; warning 'Wrong number of arguments in the get_option_value function' ;;
esac
case "$OPTION" in
*=*) ;;
*) error "'$OPTION' is not in the correct format" ;;
esac
VALUE="${OPTION#*=}"
OPTION="${OPTION%%=*}"
}
# Parses a string into a base 10 integer number
# Flags:
# {--negative|--non-positive|--non-negative|--positive}: The condition the parsed number must meet
# Parameters:
# Number (required): The string to be parsed
# Return: The parsed number
parse_integer() {
error_format() {
error "'$NUMBER' is not in the correct number format"
}
error_condition() {
error "'$NUMBER' must be ${FLAG#??}"
}
case $# in
1) FLAG=''; NUMBER="$1" ;;
2) FLAG="$1"; NUMBER="$2" ;;
*) FLAG=''; NUMBER="$1"; warning 'Wrong number of arguments in the parse_integer function' ;;
esac
if [ -z "$NUMBER" ]; then
error_format
fi
case "$NUMBER" in
-*) NEGATIVE=1; NUMBER="${NUMBER#?}" ;;
+*) NEGATIVE=0; NUMBER="${NUMBER#?}" ;;
*) NEGATIVE=0 ;;
esac
case "$NUMBER" in
*[!0123456789]*) error_format ;;
0*)
# Remove leading zeros to prevent the number being interpreted in base 8
LEADING_ZEROS="${NUMBER%%[!0]*}"
if [ -n "$LEADING_ZEROS" ]; then
NUMBER="${NUMBER#"$LEADING_ZEROS"}"
if [ -z "$NUMBER" ]; then NUMBER=0; fi
fi
;;
esac
if [ $NEGATIVE -eq 1 ]; then
NUMBER=$(( 0 - NUMBER ))
else
NUMBER=$(( NUMBER ))
fi
case "$FLAG" in
--negative) if [ $NUMBER -ge 0 ]; then error_condition; fi ;;
--non-positive) if [ $NUMBER -gt 0 ]; then error_condition; fi ;;
--non-negative) if [ $NUMBER -lt 0 ]; then error_condition; fi ;;
--positive) if [ $NUMBER -le 0 ]; then error_condition; fi ;;
*) warning "'$FLAG' is not a recognized parse_integer option" ;;
esac
echo $NUMBER
}
# Determines the absolute path to a file or directory
# Parameters:
# Path (required): The relative or absolute path to a file or directory
# Return: Absolute path to the specified file or directory
absolute_path() {
ABSOLUTE_PATH=$(readlink -m "$1") || error "Failed to get the full path for $1"
echo "$ABSOLUTE_PATH"
}
# Determines the absolute path to the parent directory
# Parameters:
# Path (required): The relative or absolute path to a file or directory
# Return: Absolute path to the parent directory, or root if the input path is already root ('/')
absolute_dirname() {
ABSOLUTE_PATH=$(absolute_path "$1")
PARENT=$(dirname "$ABSOLUTE_PATH") || error "Failed to get the parent directory for $ABSOLUTE_PATH ($1)"
echo "$PARENT"
}
# Determines the base name of a file or directory
# Parameters:
# Path (required): The relative or absolute path to a file or directory
# Return: The base name of the specified file or directory
absolute_basename() {
ABSOLUTE_PATH=$(absolute_path "$1")
BASENAME=$(basename "$ABSOLUTE_PATH") || error "Failed to get the base name for $ABSOLUTE_PATH ($1)"
echo "$BASENAME"
}
# Ensures that the specified path is not an existing file, and appends a slash if missing
# Remark: This function uses and modifies the global DIRECTORY variable
# Parameters:
# Path (optional, global DIRECTORY variable by default): The path to be tested
assert_is_directory() {
if [ $# -gt 0 ]; then
DIRECTORY="$1"
fi
case "$DIRECTORY" in
*/) ;;
*)
if [ -f "$DIRECTORY" ]; then
error "'$DIRECTORY' is a file"
fi
DIRECTORY="$DIRECTORY/"
;;
esac
}
# Checks if the specified path ends on a slash, or is an existing directory and appends the specified file; Otherwise, leaves the path as is
# Parameters:
# Path (required): Path to a directory or file
# File (required): The file name to append to the input path if it's a directory
# Return: If the input path is a directory, the combined path of the directory with the imput file; Otherwise, the original path
append_file_if_dir() {
DIR_OR_FILE="$1"
FILE="$2"
case "$DIR_OR_FILE" in
*/) echo "$DIR_OR_FILE$FILE" ;;
*)
if [ -d "$DIR_OR_FILE" ]; then
echo "$DIR_OR_FILE/$FILE"
else
echo "$DIR_OR_FILE"
fi
;;
esac
}
# Checks if the specified docker volume exists, and prints a warning if it doesn't
# Flags:
# --error: Exit with an error if the volume doesn't exist.
# Takes priority over the --create flag
# --create: Create a new volume if it doesn't exist
# Parameters:
# VolumeName (optional, global VOLUME_NAME variable by default): The docker volume to be checked
volume_doesnot_exists() {
ERROR=0
CREATE=0
while [ $# -ne 0 ]; do
case "$1" in
-*)
OPTION="$1"
shift
case "$OPTION" in
--error) ERROR=1 ;;
--create) CREATE=1 ;;
*) warning "'$OPTION' is not a recognized volume_doesnot_exists option"
esac
;;
*) break ;;
esac
done
if [ $# -gt 0 ]; then
VOLUME_NAME="$1"
fi
if ! docker volume inspect --format '{{.Name}}' "$VOLUME_NAME" 1> /dev/null 2>&1; then
if [ $ERROR -eq 1 ]; then
error "Volume $VOLUME_NAME does not exist"
elif [ $CREATE -eq 1 ]; then
warning "Volume $VOLUME_NAME does not exist, creating..."
docker volume create "$VOLUME_NAME" 1> /dev/null || error "Failed to create volume $VOLUME_NAME"
else
warning "Volume $VOLUME_NAME does not exist"
fi
fi
}
# Gets a space separated list of docker volumes
# Remark: This function uses and modifies the global VOLUME_NAMES variable
# Flags:
# -i, --in-use: Only get volumes in use by at least one container
# Options:
# -e, --exclude ExcludeList: Exclude the specified volumes from the final list.
# ExcludeList must be a comma separated list of volume names
get_volumes() {
INUSE=0
EXCLUDES=''
while [ $# -ne 0 ]; do
case "$1" in
-*)
OPTION="$1"
shift
case "$OPTION" in
-i | --in-use) INUSE=1 ;;
-e | --exclude)
if [ $# -ne 0 ]; then
EXCLUDES=$(echo "$1" | tr ',' ' ') || error 'Failed to replace commas with spaces'
shift
else
warning 'Wrong number of arguments in the get_volumes function'
fi
;;
*) warning "'$OPTION' is not a recognized get_volumes option"
esac
;;
*) break ;;
esac
done
VOLUME_NAMES=$(docker volume ls -q | tr '\n' ' ' | awk '{$1=$1;print}') || error 'Failed to get the list of volumes'
if [ -n "$EXCLUDES" ]; then
VOLUMES=''
for VOLUME_NAME in $VOLUME_NAMES; do
SHOULD_EXCLUDE=0
for EXCLUDE in $EXCLUDES; do
if [ "$VOLUME_NAME" = "$EXCLUDE" ]; then
SHOULD_EXCLUDE=1
break
fi
done
if [ $SHOULD_EXCLUDE -eq 0 ]; then
if [ -z "$VOLUMES" ]; then
VOLUMES="$VOLUME_NAME"
else
VOLUMES="$VOLUMES $VOLUME_NAME"
fi
fi
done
VOLUME_NAMES="$VOLUMES"
fi
if [ $INUSE -eq 1 ]; then
VOLUMES=''
for VOLUME_NAME in $VOLUME_NAMES; do
CONTAINERS=$(docker ps -q -a --filter volume="$VOLUME_NAME") || error "Failed to get the list of containers using volume $VOLUME_NAME"
if [ -n "$CONTAINERS" ]; then
if [ -z "$VOLUMES" ]; then
VOLUMES="$VOLUME_NAME"
else
VOLUMES="$VOLUMES $VOLUME_NAME"
fi
fi
done
VOLUME_NAMES="$VOLUMES"
fi
}
# Transform a list of container names to 12 character container IDs
# Parameters:
# Containers..: Container names