-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker-lib-core.sh
More file actions
980 lines (853 loc) · 27.7 KB
/
docker-lib-core.sh
File metadata and controls
980 lines (853 loc) · 27.7 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
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
#!/usr/bin/env bash
#
# docker-lib-core.sh - Core Utilities Module
# Essential output, formatting, logging, and validation functions
# Part of Docker Maintainer library split (Phase 2)
#
# This module contains fundamental utilities used by all scripts:
# - Color definitions and colorization
# - Exit codes and constants
# - Logging functions (debug, info, warn, error)
# - Print functions (headers, sections, tables)
# - Docker access checks
# - Format functions (bytes, age, time)
# - Table formatting
# - Safe Docker commands
# - JSON helpers
# - Size parsing
# - Confirmation prompts
# - Array utilities
#
# Version: 1.0.0
# Requires: bash 4.0+, docker, jq, coreutils
#
# Guard against multiple sourcing - return early if already loaded
[[ -n "${DOCKER_LIB_CORE_LOADED:-}" ]] && return 0
set -euo pipefail
# ═══════════════════════════════════════════════════════════
# COLOR DEFINITIONS
# ═══════════════════════════════════════════════════════════
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[0;33m'
readonly RED='\033[0;31m'
readonly CYAN='\033[0;36m'
readonly BLUE='\033[0;34m'
readonly MAGENTA='\033[0;35m'
readonly BOLD='\033[1m'
readonly NC='\033[0m' # No Color
# Legacy color definitions for backward compatibility
readonly COLOR_RED="$RED"
readonly COLOR_GREEN="$GREEN"
readonly COLOR_YELLOW="$YELLOW"
readonly COLOR_BLUE="$BLUE"
readonly COLOR_CYAN="$CYAN"
readonly COLOR_RESET="$NC"
readonly COLOR_BOLD="$BOLD"
# ═══════════════════════════════════════════════════════════
# EXIT CODES
# ═══════════════════════════════════════════════════════════
readonly EXIT_SUCCESS=0
readonly EXIT_ERROR=1
readonly EXIT_DOCKER_NOT_ACCESSIBLE=2
readonly EXIT_MISSING_DEPENDENCY=3
readonly EXIT_INVALID_ARGS=4
# ═══════════════════════════════════════════════════════════
# LOG LEVELS
# ═══════════════════════════════════════════════════════════
readonly LOG_DEBUG=0
readonly LOG_INFO=1
readonly LOG_WARN=2
readonly LOG_ERROR=3
# Current log level (can be overridden by scripts)
LOG_LEVEL=${LOG_LEVEL:-$LOG_INFO}
# ═══════════════════════════════════════════════════════════
# COLOR CONTROL
# ═══════════════════════════════════════════════════════════
# Enable/disable colors based on terminal capability and NO_COLOR environment variable
USE_COLORS=true
if [[ ! -t 1 ]] || [[ -n "${NO_COLOR:-}" ]]; then
USE_COLORS=false
fi
# ═══════════════════════════════════════════════════════════
# CORE FUNCTIONS
# ═══════════════════════════════════════════════════════════
#######################################
# Apply ANSI color codes to text
# Globals:
# GREEN, YELLOW, RED, CYAN, BLUE, MAGENTA, BOLD, NC, USE_COLORS
# Arguments:
# $1 - Color name (green, yellow, red, cyan, blue, magenta, bold) OR color code
# $2 - Text to colorize (optional, if not provided $1 is treated as color code)
# Returns:
# 0 on success
# Outputs:
# Colored text to stdout
# Examples:
# colorize green "Success"
# colorize red "Error"
# colorize "text" "$RED" # Legacy format
#######################################
colorize() {
local color=""
local text=""
# Support both new format: colorize green "text" and legacy format: colorize "text" "$RED"
if [[ $# -eq 1 ]]; then
# Legacy: single argument, no coloring
echo "$1"
return 0
elif [[ "$2" =~ ^\\033 ]]; then
# Legacy: colorize "text" "$COLOR_CODE"
text="$1"
color="$2"
else
# New: colorize green "text"
local color_name="${1:-}"
text="${2:-}"
case "${color_name,,}" in
green) color="$GREEN" ;;
yellow) color="$YELLOW" ;;
red) color="$RED" ;;
cyan) color="$CYAN" ;;
blue) color="$BLUE" ;;
magenta) color="$MAGENTA" ;;
bold) color="$BOLD" ;;
*) echo "$text"; return 0 ;;
esac
fi
if [[ "$USE_COLORS" == "true" ]]; then
echo -e "${color}${text}${NC}"
else
echo "$text"
fi
}
#######################################
# Log message with DEBUG level
# Globals:
# LOG_LEVEL, LOG_DEBUG, CYAN, NC
# Arguments:
# $@ - Message to log
# Outputs:
# Log message to stderr if LOG_LEVEL <= LOG_DEBUG
#######################################
log_debug() {
if [[ $LOG_LEVEL -le $LOG_DEBUG ]]; then
echo -e "${CYAN}[DEBUG]${NC} $*" >&2
fi
}
#######################################
# Log message with INFO level
# Globals:
# LOG_LEVEL, LOG_INFO, GREEN, NC
# Arguments:
# $@ - Message to log
# Outputs:
# Log message to stderr if LOG_LEVEL <= LOG_INFO
#######################################
log_info() {
if [[ $LOG_LEVEL -le $LOG_INFO ]]; then
echo -e "${GREEN}[INFO]${NC} $*" >&2
fi
}
#######################################
# Log message with WARN level
# Globals:
# LOG_LEVEL, LOG_WARN, YELLOW, NC
# Arguments:
# $@ - Message to log
# Outputs:
# Log message to stderr if LOG_LEVEL <= LOG_WARN
#######################################
log_warn() {
if [[ $LOG_LEVEL -le $LOG_WARN ]]; then
echo -e "${YELLOW}[WARN]${NC} $*" >&2
fi
}
#######################################
# Log message with ERROR level
# Globals:
# LOG_LEVEL, LOG_ERROR, RED, NC
# Arguments:
# $@ - Message to log
# Outputs:
# Log message to stderr if LOG_LEVEL <= LOG_ERROR
#######################################
log_error() {
if [[ $LOG_LEVEL -le $LOG_ERROR ]]; then
echo -e "${RED}[ERROR]${NC} $*" >&2
fi
}
# Legacy print functions (for backward compatibility)
print_error() {
colorize "ERROR: $*" "$COLOR_RED" >&2
}
print_warning() {
colorize "WARNING: $*" "$COLOR_YELLOW" >&2
}
print_success() {
colorize "$*" "$COLOR_GREEN"
}
print_info() {
colorize "$*" "$COLOR_CYAN"
}
#######################################
# Print a header with separator lines
# Globals:
# BOLD, NC
# Arguments:
# $1 - Header text
# $2 - Separator character (default: =)
# Outputs:
# Formatted header to stdout
#######################################
print_header() {
local title="$1"
local separator="${2:-=}"
echo
echo -e "${BOLD}${title}${NC}"
printf '%*s' "${#title}" | tr ' ' "$separator"
echo
}
#######################################
# Print a section title
# Globals:
# BOLD, NC
# Arguments:
# $1 - Section title
# $2 - Separator character (default: -)
# Outputs:
# Formatted section title to stdout
#######################################
print_section() {
local title="$1"
local separator="${2:--}"
echo
echo -e "${BOLD}${title}${NC}"
printf '%*s' "${#title}" | tr ' ' "$separator"
echo
}
#######################################
# Draw a horizontal separator line
# Globals:
# None
# Arguments:
# $1 - Character to use (default: -)
# $2 - Length (default: 70)
# Outputs:
# Separator line to stdout
#######################################
print_separator() {
local char="${1:--}"
local length="${2:-70}"
printf "%${length}s\n" | tr ' ' "$char"
}
#######################################
# Check if Docker daemon is accessible
# Verifies Docker socket connectivity and permissions
# Globals:
# EXIT_DOCKER_NOT_ACCESSIBLE
# Arguments:
# None
# Returns:
# 0 if Docker is accessible
# EXIT_DOCKER_NOT_ACCESSIBLE if not accessible
# Outputs:
# Error message to stderr if check fails
#######################################
check_docker_access() {
if ! command -v docker &> /dev/null; then
log_error "Docker command not found. Please install Docker."
return $EXIT_DOCKER_NOT_ACCESSIBLE
fi
if ! docker info &> /dev/null; then
log_error "Cannot connect to Docker daemon. Please check:"
log_error " 1. Docker daemon is running"
log_error " 2. Current user has Docker socket permissions (add user to 'docker' group)"
log_error " 3. DOCKER_HOST environment variable is set correctly (if using remote Docker)"
return $EXIT_DOCKER_NOT_ACCESSIBLE
fi
return $EXIT_SUCCESS
}
#######################################
# Check if required dependencies are installed
# Globals:
# EXIT_MISSING_DEPENDENCY
# Arguments:
# List of required commands
# Returns:
# 0 if all dependencies are available
# EXIT_MISSING_DEPENDENCY if any dependency is missing
# Outputs:
# Error message to stderr for missing dependencies
#######################################
check_dependencies() {
local missing_deps=()
for cmd in "$@"; do
if ! command -v "$cmd" &> /dev/null; then
missing_deps+=("$cmd")
fi
done
if [[ ${#missing_deps[@]} -gt 0 ]]; then
log_error "Missing required dependencies: ${missing_deps[*]}"
log_error "Please install the missing tools before running this script."
return $EXIT_MISSING_DEPENDENCY
fi
return $EXIT_SUCCESS
}
# Legacy function for backward compatibility
check_requirements() {
check_dependencies jq awk sort
}
#######################################
# Convert bytes to human-readable format
# Supports KB, MB, GB, TB with appropriate precision
# Globals:
# None
# Arguments:
# $1 - Number of bytes (integer)
# $2 - Format style: "short" (default) or "long"
# Returns:
# 0 on success
# Outputs:
# Human-readable size string to stdout
# Examples:
# format_bytes 1024 # Output: 1.0K
# format_bytes 1048576 # Output: 1.0M
# format_bytes 1073741824 # Output: 1.0G
# format_bytes 1536 "long" # Output: 1.5 KiB
#######################################
format_bytes() {
local bytes="${1:-0}"
local format="${2:-short}"
if [[ -z "$bytes" ]] || [[ "$bytes" == "null" ]] || [[ "$bytes" == "0" ]]; then
if [[ "$format" == "long" ]]; then
echo "0 B"
else
echo "0"
fi
return $EXIT_SUCCESS
fi
# Handle invalid input
if ! [[ "$bytes" =~ ^[0-9]+$ ]]; then
echo "0"
return $EXIT_ERROR
fi
# Use numfmt if available (faster and more reliable)
if command -v numfmt &> /dev/null; then
if [[ "$format" == "long" ]]; then
numfmt --to=iec-i --suffix=B --format="%.1f" "$bytes" 2>/dev/null || echo "0 B"
else
# Short format without 'iB' suffix
numfmt --to=iec --format="%.1f" "$bytes" 2>/dev/null || echo "0"
fi
return $EXIT_SUCCESS
fi
# Fallback to awk
awk -v bytes="$bytes" -v format="$format" 'BEGIN {
if (format == "long") {
units[0] = "B"
units[1] = "KiB"
units[2] = "MiB"
units[3] = "GiB"
units[4] = "TiB"
} else {
units[0] = "B"
units[1] = "K"
units[2] = "M"
units[3] = "G"
units[4] = "T"
}
unit = 0
while (bytes >= 1024 && unit < 4) {
bytes /= 1024
unit++
}
if (unit == 0) {
printf "%d %s\n", bytes, units[unit]
} else {
printf "%.1f %s\n", bytes, units[unit]
}
}'
}
# Parse duration to days
# Usage: parse_duration "30d" or "7d" or "2w"
parse_duration_to_days() {
local duration="$1"
local value="${duration%[dDwWmMyY]*}"
local unit="${duration: -1}"
case "$unit" in
d|D) echo "$value" ;;
w|W) echo $((value * 7)) ;;
m|M) echo $((value * 30)) ;;
y|Y) echo $((value * 365)) ;;
*) echo "$value" ;;
esac
}
# Calculate days ago from ISO date
# Usage: days_ago "2024-01-15T10:30:00Z"
days_ago() {
local date_str="$1"
if [[ -z "$date_str" ]] || [[ "$date_str" == "null" ]]; then
echo "unknown"
return
fi
# Convert ISO date to epoch
local date_epoch
local now_epoch
date_epoch=$(date -d "$date_str" +%s 2>/dev/null || date -j -f "%Y-%m-%dT%H:%M:%S" "${date_str%.*}" +%s 2>/dev/null)
if [[ -z "$date_epoch" ]]; then
echo "unknown"
return
fi
now_epoch=$(date +%s)
local diff_seconds=$((now_epoch - date_epoch))
local diff_days=$((diff_seconds / 86400))
# SAFETY: Handle future dates (negative days)
if [[ $diff_days -lt 0 ]]; then
echo "0" # Treat future dates as 0 days old
return $EXIT_SUCCESS
fi
echo "$diff_days"
}
# Format age from days
# Usage: format_age 45
format_age() {
local days="$1"
if [[ -z "$days" ]] || [[ "$days" == "unknown" ]]; then
echo "unknown"
return
fi
if [[ $days -eq 0 ]]; then
echo "today"
elif [[ $days -eq 1 ]]; then
echo "1 day ago"
elif [[ $days -lt 30 ]]; then
echo "$days days ago"
elif [[ $days -lt 365 ]]; then
local months=$((days / 30))
echo "$months month(s) ago"
else
local years=$((days / 365))
echo "$years year(s) ago"
fi
}
#######################################
# Format data as aligned tables using column
# Reads tabular data and outputs aligned columns
# Globals:
# None
# Arguments:
# $1 - Separator character (default: |)
# Returns:
# 0 on success
# Outputs:
# Formatted table to stdout
# Usage:
# echo -e "NAME|SIZE|STATUS\nvolume1|1GB|active" | print_table
# echo -e "NAME\tSIZE\tSTATUS\nvolume1\t1GB\tactive" | print_table $'\t'
#######################################
print_table() {
local separator="${1:-|}"
if command -v column &> /dev/null; then
# Use column with table mode for best formatting
column -t -s "$separator"
else
# Fallback: just pass through
cat
fi
return $EXIT_SUCCESS
}
# Safe command execution with error handling
safe_docker_cmd() {
local output
local exit_code
output=$(docker "$@" 2>&1)
exit_code=$?
if [[ $exit_code -ne 0 ]]; then
print_error "Docker command failed: docker $*"
echo "$output" >&2
return $exit_code
fi
echo "$output"
return 0
}
# JSON output helpers
json_start() {
echo "{"
}
json_end() {
echo "}"
}
json_array_start() {
echo "["
}
json_array_end() {
echo "]"
}
json_field() {
local key="$1"
local value="$2"
local comma="${3:-,}"
printf ' "%s": "%s"%s\n' "$key" "$value" "$comma"
}
json_number_field() {
local key="$1"
local value="$2"
local comma="${3:-,}"
printf ' "%s": %s%s\n' "$key" "$value" "$comma"
}
#######################################
# Parse size string to bytes
# Converts human-readable sizes to bytes, supporting multiple formats:
# - Docker format: "5.554GB", "31.26MB" (with trailing B)
# - IEC format: "5GiB", "31MiB" (binary units, 1024-based)
# - SI format: "5GB", "31MB" (decimal units, 1000-based if specified)
# - Simple format: "5G", "31M" (binary units assumed, 1024-based)
# - Raw bytes: "1234567" (no unit, returns as-is)
#
# Globals:
# None
# Arguments:
# $1 - Size string (e.g., "1K", "2.5MB", "3GiB", "100")
# Returns:
# 0 on success, 1 on error
# Outputs:
# Number of bytes to stdout, or "0" on error
# Examples:
# parse_size "1K" # Output: 1024
# parse_size "2.5MB" # Output: 2621440
# parse_size "3GiB" # Output: 3221225472
# parse_size "5.554GB" # Output: 5963489280 (Docker format)
# parse_size "100" # Output: 100
#######################################
parse_size() {
local size_str="${1:-0}"
# Handle empty, null, or zero input
if [[ -z "$size_str" ]] || [[ "$size_str" == "null" ]] || [[ "$size_str" == "0" ]]; then
echo "0"
return $EXIT_SUCCESS
fi
# Try numfmt first if available (handles most formats automatically)
if command -v numfmt &> /dev/null; then
# numfmt can handle: 1K, 1M, 1G, 1Ki, 1Mi, 1Gi, etc.
local result
result=$(numfmt --from=iec "$size_str" 2>/dev/null || \
numfmt --from=auto "$size_str" 2>/dev/null || \
echo "")
if [[ -n "$result" ]]; then
echo "$result"
return $EXIT_SUCCESS
fi
# numfmt failed, try manual parsing for Docker format (e.g., "5.554GB")
# which has a trailing 'B' that numfmt doesn't handle well
fi
# Manual parsing for all format types
local number=""
local unit=""
local is_binary=true # Default to binary (1024-based) for backward compatibility
# Match various size formats:
# - Docker: "5.554GB" or "31.26MB" (number + unit with trailing B)
# - IEC: "5GiB" or "31MiB" (number + unit + iB)
# - SI: "5GB" or "31MB" (number + unit + B, treated as binary by default)
# - Simple: "5G" or "31M" (number + unit, no suffix)
# - Raw: "1234567" (just a number)
if [[ "$size_str" =~ ^([0-9]+\.?[0-9]*)([KMGTP]?)(i?)(B?)$ ]]; then
number="${BASH_REMATCH[1]}"
unit="${BASH_REMATCH[2]}"
local binary_indicator="${BASH_REMATCH[3]}" # 'i' for IEC format
local byte_suffix="${BASH_REMATCH[4]}" # 'B' suffix
# Determine if we should use binary (1024) or decimal (1000) multipliers
# IEC format (KiB, MiB, GiB) explicitly uses binary
# All others default to binary for backward compatibility
if [[ -n "$binary_indicator" ]]; then
is_binary=true
fi
else
# Invalid format
echo "0"
return $EXIT_ERROR
fi
# If no unit specified, return the number as-is (assumed to be bytes)
if [[ -z "$unit" ]]; then
# Use printf to handle potential floating point and round to integer
if command -v awk &> /dev/null; then
echo "$number" | awk '{printf "%.0f\n", $1}'
else
echo "${number%.*}" # Truncate decimal part
fi
return $EXIT_SUCCESS
fi
# Calculate multiplier based on unit and whether binary or decimal
local multiplier=1
if [[ "$is_binary" == true ]]; then
# Binary (1024-based) - IEC standard and default
case "${unit^^}" in
K) multiplier=1024 ;; # 1024^1
M) multiplier=1048576 ;; # 1024^2
G) multiplier=1073741824 ;; # 1024^3
T) multiplier=1099511627776 ;; # 1024^4
P) multiplier=1125899906842624 ;; # 1024^5
*) multiplier=1 ;;
esac
else
# Decimal (1000-based) - SI standard (rarely used)
case "${unit^^}" in
K) multiplier=1000 ;; # 1000^1
M) multiplier=1000000 ;; # 1000^2
G) multiplier=1000000000 ;; # 1000^3
T) multiplier=1000000000000 ;; # 1000^4
P) multiplier=1000000000000000 ;; # 1000^5
*) multiplier=1 ;;
esac
fi
# Multiply number by multiplier, handling floating point
# Prefer bc > awk > bash arithmetic (in order of precision)
if command -v bc &> /dev/null; then
# bc provides best precision for floating point
echo "$number * $multiplier" | bc | cut -d. -f1
elif command -v awk &> /dev/null; then
# awk provides good precision
echo "$number" | awk -v mult="$multiplier" '{printf "%.0f\n", $1 * mult}'
else
# Last resort: bash integer arithmetic (loses decimal precision)
# Truncate decimal part before multiplication
echo $((${number%.*} * multiplier))
fi
return $EXIT_SUCCESS
}
#######################################
# Confirm action with timeout
# Arguments:
# $1 - Prompt message
# $2 - Default answer (optional, default 'n')
# $3 - Timeout in seconds (optional, default 30)
# Returns:
# 0 if yes, 1 if no
#######################################
confirm() {
local prompt="$1"
local default="${2:-n}"
local timeout="${3:-30}" # Default 30 second timeout
local answer
# Add default indicator to prompt
if [[ "$default" == "y" ]]; then
prompt="$prompt [Y/n] "
else
prompt="$prompt [y/N] "
fi
# Add timeout to read
if read -r -t "$timeout" -p "$prompt" answer; then
# User responded within timeout
answer="${answer:-$default}"
answer=$(echo "$answer" | tr '[:upper:]' '[:lower:]')
[[ "$answer" == "y" || "$answer" == "yes" ]]
return $?
else
# Timeout or EOF
log_warn "Prompt timed out after ${timeout}s, using default: $default"
[[ "$default" == "y" ]]
return $?
fi
}
#######################################
# Create secure temporary directory with comprehensive validation
# Implements defense-in-depth against TOCTOU, symlink attacks, etc.
# Globals:
# USER
# Arguments:
# $1 - Template suffix (optional, default: docker-maintainer.XXXXXXXXXX)
# Returns:
# 0 on success, 1 on failure
# Outputs:
# Temp directory path to stdout
#######################################
create_secure_temp_directory() {
local template="${1:-docker-maintainer.XXXXXXXXXX}"
# Create directory with secure permissions (CWE-377 mitigation)
local temp_dir
temp_dir=$(mktemp -d -t "$template" 2>/dev/null)
# Validation 1: Check mktemp succeeded
if [[ $? -ne 0 ]]; then
log_error "Failed to create temporary directory"
return 1
fi
# Validation 2: Verify path not empty
if [[ -z "$temp_dir" ]]; then
log_error "Temporary directory path is empty"
return 1
fi
# Validation 3: Verify directory exists
if [[ ! -d "$temp_dir" ]]; then
log_error "Temporary directory does not exist: $temp_dir"
return 1
fi
# Validation 4: Verify ownership
local dir_owner
dir_owner=$(stat -c '%U' "$temp_dir" 2>/dev/null)
if [[ "$dir_owner" != "$USER" ]]; then
log_error "Temporary directory owner mismatch: expected $USER, got $dir_owner"
rm -rf "$temp_dir"
return 1
fi
# Validation 5: Verify permissions 700
local dir_perms
dir_perms=$(stat -c '%a' "$temp_dir" 2>/dev/null)
if [[ "$dir_perms" != "700" ]]; then
log_error "Temporary directory has incorrect permissions: $dir_perms (expected 700)"
rm -rf "$temp_dir"
return 1
fi
echo "$temp_dir"
return 0
}
#######################################
# Parse JSON array to bash array
# Globals:
# None
# Arguments:
# $1 - JSON array string
# $2 - Variable name to store result
# Returns:
# 0 on success
#######################################
json_to_array() {
local json="${1:-[]}"
local -n result_array=$2
if ! command -v jq &> /dev/null; then
result_array=()
return $EXIT_ERROR
fi
mapfile -t result_array < <(echo "$json" | jq -r '.[]' 2>/dev/null)
return $EXIT_SUCCESS
}
#######################################
# Check if a value exists in an array
# Globals:
# None
# Arguments:
# $1 - Value to search for
# $@ - Array elements
# Returns:
# 0 if found, 1 if not found
#######################################
in_array() {
local needle="$1"
shift
local item
for item in "$@"; do
[[ "$item" == "$needle" ]] && return 0
done
return 1
}
#######################################
# Print usage information
# Globals:
# None
# Arguments:
# None
# Outputs:
# Usage information to stdout
#######################################
usage() {
cat << EOF
Docker Maintainer - Core Utilities Module
This module provides essential output, formatting, logging, and validation functions.
It is meant to be sourced by other Docker Maintainer scripts.
Core Functions:
colorize() Apply ANSI color codes to text
log_debug() Log debug message
log_info() Log info message
log_warn() Log warning message
log_error() Log error message
print_header() Print formatted header
print_section() Print section title
print_separator() Draw horizontal separator line
check_docker_access() Verify Docker daemon connectivity
check_dependencies() Check for required commands
format_bytes() Convert bytes to human-readable format
parse_size() Convert size string to bytes
days_ago() Calculate days ago from ISO date
format_age() Format age from days
parse_duration_to_days() Parse duration string to days
print_table() Format data as aligned tables
safe_docker_cmd() Safe Docker command execution
confirm() Prompt for yes/no confirmation
json_to_array() Parse JSON array to bash array
in_array() Check if value exists in array
Legacy Functions (backward compatibility):
print_error() Print error message
print_warning() Print warning message
print_success() Print success message
print_info() Print info message
check_requirements() Check for jq, awk, sort
JSON Helpers:
json_start() Output opening brace
json_end() Output closing brace
json_array_start() Output opening bracket
json_array_end() Output closing bracket
json_field() Output JSON field
json_number_field() Output JSON number field
Environment Variables:
NO_COLOR Disable colored output
LOG_LEVEL Set log level (0-3: DEBUG, INFO, WARN, ERROR)
Exit Codes:
0 - Success
1 - General error
2 - Docker not accessible
3 - Missing dependency
4 - Invalid arguments
EOF
}
# ═══════════════════════════════════════════════════════════
# EXPORTS
# ═══════════════════════════════════════════════════════════
# Color functions
export -f colorize
# Logging functions
export -f log_debug
export -f log_info
export -f log_warn
export -f log_error
# Legacy print functions
export -f print_error
export -f print_warning
export -f print_success
export -f print_info
# Print functions
export -f print_header
export -f print_section
export -f print_separator
# Docker access functions
export -f check_docker_access
export -f check_dependencies
export -f check_requirements
# Format functions
export -f format_bytes
export -f parse_duration_to_days
export -f days_ago
export -f format_age
# Table and output functions
export -f print_table
export -f safe_docker_cmd
# JSON helpers
export -f json_start
export -f json_end
export -f json_array_start
export -f json_array_end
export -f json_field
export -f json_number_field
# Size parsing
export -f parse_size
# Confirmation and prompts
export -f confirm
# Temporary directory utilities
export -f create_secure_temp_directory
# Array utilities
export -f json_to_array
export -f in_array
# Mark module as loaded
readonly DOCKER_LIB_CORE_LOADED=1
# If script is run directly (not sourced), show usage
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
usage
exit $EXIT_SUCCESS
fi