-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdockerctl
More file actions
executable file
·595 lines (520 loc) · 16.8 KB
/
Copy pathdockerctl
File metadata and controls
executable file
·595 lines (520 loc) · 16.8 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
#!/usr/bin/env bash
loadConfig() {
configDir="${XDG_CONFIG_HOME:-$HOME/.config}/pkgmgr"
configFile="$configDir/config.toml"
createDefaultConfig() {
mkdir -p "$(dirname "$configFile")"
cat >"$configFile" <<'EOF'
# Compose directories (supports multiple paths)
composeDir = ["."]
scriptDir = ["."]
ignoreFiles = []
# map of compose file -> script + args
[postStartScripts]
# "diun.yml" = "webhooknotif.py --port 9999"
EOF
}
if [[ ! -f "$configFile" ]]; then
createDefaultConfig
fi
declare -ga composeDir=()
declare -ga scriptDir=()
declare -ga ignoreFiles=()
declare -gA postStartScripts=()
parseTomlConfig() {
expandVars() {
local str="$1"
if command -v envsubst >/dev/null 2>&1; then
echo "$str" | envsubst
else
str="${str//\$HOME/$HOME}"
str="${str//\$USER/$USER}"
echo "$str"
fi
}
parseArray() {
local key="$1"
local arrName="$2"
local line
line=$(sed -n "s/^[[:space:]]*${key}[[:space:]]*=[[:space:]]*\(.*\)/\1/p" "$configFile" | head -1)
[[ -z "$line" ]] && return
# Extract all double-quoted strings, remove quotes, expand vars
local items=()
while IFS= read -r quoted; do
local item="${quoted#\"}"
item="${item%\"}"
item=$(expandVars "$item")
items+=("$item")
done < <(echo "$line" | grep -oE '"([^"]*)"')
eval "${arrName}=(\"\${items[@]}\")"
}
parseArray "composeDir" "composeDir"
parseArray "scriptDir" "scriptDir"
parseArray "ignoreFiles" "ignoreFiles"
local startLine endLine
startLine=$(sed -n '/^[[:space:]]*\[postStartScripts\][[:space:]]*$/=' "$configFile" | head -1)
if [[ -n "$startLine" ]]; then
endLine=$(sed -n "$((startLine + 1)),\$ { /^[[:space:]]*\[/ { =; q } }" "$configFile")
[[ -z "$endLine" ]] && endLine=$(wc -l <"$configFile")
while IFS= read -r line; do
[[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" =~ ^[[:space:]]*\"([^\"]+)\"[[:space:]]*=[[:space:]]*\"([^\"]*)\"[[:space:]]*$ ]]; then
local key="${BASH_REMATCH[1]}"
local val="${BASH_REMATCH[2]}"
val=$(expandVars "$val")
postStartScripts["$key"]="$val"
fi
done < <(sed -n "$((startLine + 1)),$((endLine - 1))p" "$configFile")
fi
}
parseTomlConfig
}
loadConfig
debugMain() {
echo "$configFile"
echo "$configDir"
declare -p composeDir
declare -p scriptDir
declare -p ignoreFiles
declare -p postStartScripts
echo
}
startSkipped=()
startFailed=()
startSuccess=()
startPostStartScriptSuccess=()
startPostStartScriptFailed=()
stopSkipped=()
stopFailed=()
stopSuccess=()
stopPostStartScriptSuccess=()
stopPostStartScriptFailed=()
stopPostStartScriptSkipped=()
restartFailed=()
restartSuccess=()
updateFailed=()
updateSuccess=()
isIgnored() {
local file="$1"
for ignore in "${ignoreFiles[@]}"; do
if [[ "$(basename "$file")" == "$ignore" ]]; then
return 0
fi
done
return 1
}
isRunning() {
local composeFile="$1"
local projectName
projectName=$(getProjectName "$composeFile")
local containers
containers=$(docker compose -f "$composeFile" -p "$projectName" ps -q)
[[ -z "$containers" ]] && return 1
local total=0
local running=0
for container in $containers; do
((total++))
if [[ "$(docker inspect -f '{{.State.Running}}' "$container" 2>/dev/null)" == "true" ]]; then
((running++))
fi
done
[[ $running -eq $total ]]
}
postStartScriptAction() {
local action="$1"
local composeFile="$2"
local composeFileBasename
composeFileBasename=$(basename "$composeFile")
[[ -z "${postStartScripts[$composeFileBasename]}" ]] && return
local -a postStartScript=()
read -r -a postStartScript <<<"${postStartScripts[$composeFileBasename]}"
local postStartScriptBase="${postStartScript[0]}"
local -a postStartScriptArgs=("${postStartScript[@]:1}")
local postStartScriptName=""
local matches=()
for scriptdir in "${scriptDir[@]}"; do
[[ -z "$scriptdir" ]] && continue
[[ ! -d "$scriptdir" ]] && continue
while IFS= read -r match; do
[[ -n "$match" ]] && matches+=("$match")
done < <(
find "$scriptdir" -maxdepth 2 -type f -name "$postStartScriptBase" -print
)
done
case ${#matches[@]} in
1)
postStartScriptName="${matches[0]}"
echo " Found script at: $postStartScriptName"
chmod +x "$postStartScriptName"
if [[ "$action" == "start" ]]; then
echo " Running: $postStartScriptName ${postStartScriptArgs[*]}"
nohup "$postStartScriptName" "${postStartScriptArgs[@]}" >/dev/null 2>&1 &
pid=$!
echo "$pid" >"/tmp/${postStartScriptBase}.pid"
sleep 1
if kill -0 "$pid" 2>/dev/null; then
echo " Successfully Started Script"
startPostStartScriptSuccess+=("$postStartScriptName ${postStartScriptArgs[*]}")
else
echo " Couldnot Start Script"
startPostStartScriptFailed+=("$postStartScriptName ${postStartScriptArgs[*]}")
fi
elif [[ "$action" == "stop" ]]; then
echo " Stopping: $postStartScriptName ${postStartScriptArgs[*]}"
pid_file="/tmp/${postStartScriptBase}.pid"
if [[ -f "$pid_file" ]]; then
pid=$(cat "$pid_file")
if kill -9 "$pid" >/dev/null 2>&1; then
rm -f "$pid_file"
echo " Successfully stopped Script"
stopPostStartScriptSuccess+=("$postStartScriptName ${postStartScriptArgs[*]}")
else
echo " Couldnot stop script"
stopPostStartScriptFailed+=("$postStartScriptBase ${postStartScriptArgs[*]}")
return 1
fi
else
echo " Script was already stopped"
stopPostStartScriptSkipped+=("$postStartScriptBase ${postStartScriptArgs[*]}")
fi
else
echo "Unknown Action for Script"
fi
;;
0)
echo " Warning: Could not find $postStartScriptBase within scriptDir. Skipping." >&2
if [[ "$action" == "start" ]]; then
startPostStartScriptFailed+=("$postStartScriptBase ${postStartScriptArgs[*]}")
elif [[ "$action" == "stop" ]]; then
stopPostStartScriptFailed+=("$postStartScriptBase ${postStartScriptArgs[*]}")
else
echo "Unknown Action for Script"
fi
return 1
;;
*)
echo "Error: multiple scripts found for '$postStartScriptBase':" >&2
printf ' %s\n' "${matches[@]}" >&2
if [[ "$action" == "start" ]]; then
startPostStartScriptFailed+=("$postStartScriptBase ${postStartScriptArgs[*]}")
elif [[ "$action" == "stop" ]]; then
stopPostStartScriptFailed+=("$postStartScriptBase ${postStartScriptArgs[*]}")
else
echo "Unknown Action for Script"
fi
return 1
;;
esac
}
startScript() {
postStartScriptAction start "$1"
}
stopScript() {
postStartScriptAction stop "$1"
}
findComposeFile() {
local input="$1"
local dir
for dir in "${composeDir[@]:-.}"; do
if [[ -n "$input" ]]; then
if [[ "$input" =~ \.(yml|yaml)$ ]]; then
find "$dir" -maxdepth 2 -type f -name "$input"
else
find "$dir" -maxdepth 2 -type f \( -name "$input.yml" -o -name "$input.yaml" \)
fi
else
find "$dir" -maxdepth 2 -type f \( -name "*.yml" -o -name "*.yaml" \)
fi
done
}
resolveComposeFile() {
local input="$1"
local output
if [[ -f "$input" ]]; then
realpath "$input"
return
fi
output=$(findComposeFile "$input" | head -n 1)
if [[ -z "$output" ]]; then
echo "Error: no specified yml/yaml file found" >&2
return 1
fi
realpath "$output"
}
runComposeFiles() {
local output
if [[ -n "$1" ]]; then
findComposeFile "$1" | head -n 1
else
findComposeFile
fi
}
getProjectName() {
basename "${1%.*}" | tr '.' '_'
}
runAction() {
local action="$1"
local composeFile="$2"
local projectName
projectName=$(getProjectName "$composeFile")
echo "=> $action $composeFile"
case "$action" in
start)
docker compose -f "$composeFile" -p "$projectName" up -d
return $?
;;
stop)
docker compose -f "$composeFile" -p "$projectName" down
return $?
;;
update)
docker compose -f "$composeFile" -p "$projectName" pull
return $?
;;
status)
shift
local followLogs=false
local containerName=""
while [[ $# -gt 0 ]]; do
case "$1" in
-f)
followLogs=true
;;
*)
if [[ -n "$containerName" ]]; then
echo "Error: status accepts only one container name"
return 1
fi
containerName="$1"
;;
esac
shift
done
if [[ -z "$containerName" ]]; then
echo "Error: container name required"
return 1
fi
if $followLogs; then
docker logs -f "$containerName"
else
docker logs "$containerName"
fi
return $?
;;
esac
}
processFile() {
local action="$1"
local composeFile="$2"
local projectName
projectName=$(getProjectName "$composeFile")
if isIgnored "$composeFile"; then
echo "Skipping ignored file: $composeFile"
return
fi
case "$action" in
start)
if isRunning "$composeFile"; then
echo "$projectName is already Running!!!"
startSkipped+=("$composeFile")
else
if runAction start "$composeFile"; then
startSuccess+=("$composeFile")
startScript "$composeFile"
else
startFailed+=("$composeFile")
fi
fi
;;
stop)
if isRunning "$composeFile"; then
if runAction stop "$composeFile"; then
stopSuccess+=("$composeFile")
stopScript "$composeFile"
else
stopFailed+=("$composeFile")
fi
else
echo "$projectName is already Stopped!!!"
stopSkipped+=("$composeFile")
fi
;;
restart)
if isRunning "$composeFile"; then
if runAction stop "$composeFile"; then
stopSuccess+=("$composeFile")
if ! stopScript "$composeFile"; then
restartFailed+=("$composeFile")
return 1
fi
else
stopFailed+=("$composeFile")
restartFailed+=("$composeFile")
return 1
fi
else
echo "$projectName is already Stopped!!!"
stopSkipped+=("$composeFile")
fi
if isRunning "$composeFile"; then
echo "$projectName is already Running!!!"
startSkipped+=("$composeFile")
else
if runAction start "$composeFile"; then
startSuccess+=("$composeFile")
startScript "$composeFile"
else
startFailed+=("$composeFile")
restartFailed+=("$composeFile")
return 1
fi
fi
if isRunning "$composeFile"; then
restartSuccess+=("$composeFile")
else
restartFailed+=("$composeFile")
fi
;;
update)
if runAction update "$composeFile"; then
updateSuccess+=("$composeFile")
if isRunning "$composeFile"; then
if runAction stop "$composeFile"; then
stopSuccess+=("$composeFile")
if ! stopScript "$composeFile"; then
restartFailed+=("$composeFile")
return 1
fi
else
stopFailed+=("$composeFile")
restartFailed+=("$composeFile")
return 1
fi
else
echo "$projectName is already Stopped!!!"
stopSkipped+=("$composeFile")
fi
if isRunning "$composeFile"; then
echo "$projectName is already Running!!!"
startSkipped+=("$composeFile")
else
if runAction start "$composeFile"; then
startSuccess+=("$composeFile")
startScript "$composeFile"
else
startFailed+=("$composeFile")
restartFailed+=("$composeFile")
return 1
fi
fi
else
updateFailed+=("$composeFile")
return 1
fi
if isRunning "$composeFile"; then
restartSuccess+=("$composeFile")
else
restartFailed+=("$composeFile")
fi
;;
esac
}
runMain() {
local showIgnored=false
local action="$1"
shift
if [ $# -eq 0 ]; then
showIgnored=true
while read -r composeFile; do
echo
processFile "$action" "$composeFile"
echo
done < <(runComposeFiles)
else
for input in "$@"; do
for ignored in "${ignoreFiles[@]}"; do
if [[ "$input" == "$ignored" ]]; then
showIgnored=true
ignoredFile+=("$input")
break 2
fi
done
while read -r composeFile; do
echo
processFile "$action" "$composeFile"
echo
done < <(runComposeFiles "$input")
done
fi
echo -e "\n===== SUMMARY ====="
if $showIgnored; then
((${#ignoredFile[@]})) && echo -e "\nIgnored:" && printf ' \033[1mℹ\033[0m %s\n' "${ignoredFile[@]}"
fi
case "$action" in
start)
((${#startSkipped[@]})) && echo -e "\nSkipped:" && printf ' \033[1mℹ\033[0m Skipped (already running) %s\n' "${startSkipped[@]}"
((${#startSuccess[@]})) && echo -e "\nStarted:" && printf '✔ Successfully started %s\n' "${startSuccess[@]}"
((${#startFailed[@]})) && echo -e "\nFailed to Start:" && printf '✘ Failed to Start %s\n' "${startFailed[@]}"
((${#startPostStartScriptSuccess[@]})) && echo -e "\nStarted Scripts:" && printf '✔ Successfully Started Script %s\n' "${startPostStartScriptSuccess[@]}"
((${#startPostStartScriptFailed[@]})) && echo -e "\nFailed Script Starts:" && printf ' ✘ %s\n' "${startPostStartScriptFailed[@]}"
;;
stop)
((${#stopSkipped[@]})) && echo -e "\nSkipped:" && printf ' \033[1mℹ\033[0m Skipped (already stopped) %s\n' "${stopSkipped[@]}"
((${#stopSuccess[@]})) && echo -e "\nStopped:" && printf '✔ Successfully stopped %s\n' "${stopSuccess[@]}"
((${#stopFailed[@]})) && echo -e "\nFailed to Stop:" && printf '✘ Failed to stop %s\n' "${stopFailed[@]}"
((${#stopPostStartScriptSuccess[@]})) && echo -e "\nStopped Scripts:" && printf '✔ Successfully Stopped Script %s\n' "${stopPostStartScriptSuccess[@]}"
((${#stopPostStartScriptFailed[@]})) && echo -e "\nFailed Script Stops:" && printf ' ✘ %s\n' "${stopPostStartScriptFailed[@]}"
((${#stopPostStartScriptSkipped[@]})) && echo -e "\nSkipped Script Stops:" && printf ' \033[1mℹ\033[0m %s\n' "${stopPostStartScriptSkipped[@]}"
;;
restart)
((${#restartSuccess[@]})) && echo -e "\nRestarted:" && printf '✔ Successfully Restarted %s\n' "${restartSuccess[@]}"
((${#restartFailed[@]})) && echo -e "\nFailed to Restart:" && printf ' ✘ Failed to Restart %s\n' "${restartFailed[@]}"
;;
update)
((${#updateSuccess[@]})) && echo -e "\nUpdated:" && printf '✔ Successfully Updated %s\n' "${updateSuccess[@]}"
((${#updateFailed[@]})) && echo -e "\nFailed to Update:" && printf '✘ Failed to Update %s\n' "${updateFailed[@]}"
((${#restartSuccess[@]})) && echo -e "\nRestarted:" && printf '✔ Successfully Restarted %s\n' "${restartSuccess[@]}"
((${#restartFailed[@]})) && echo -e "\nFailed to Restart:" && printf ' ✘ Failed to Restart %s\n' "${restartFailed[@]}"
;;
esac
if ((${#startFailed[@]})) || ((${#stopFailed[@]})) || ((${#updateFailed[@]})) || ((${#restartFailed[@]})) || ((${#startPostStartScriptFailed[@]})) || ((${#stopPostStartScriptFailed[@]})); then
exit 2
else
exit 0
fi
}
helpMenu() {
echo -e "$(basename "$0"): A script to start, stop, restart and update docker containers and images through their compose files and view their logs."
echo
echo -e "Example usage:"
echo -e " $(basename "$0") args path/to/docker-compose/.yml/file"
echo -e " $(basename "$0") args containerName"
echo -e
echo -e " Args Subargs Description"
echo -e " start starts the specified compose file"
echo -e " stop stops the specified compose file"
echo -e " restart restarts the specified compose file"
echo -e " update updates all the images of the specified compose file. For individual images use 'docker pull imagename:tag'"
echo -e " status shows the logs of the specified container. Only accepts one container as arguement."
echo -e " -f Used with status arg to follow the container logs."
echo -e " --help/-h print the help menu"
echo
echo -e "NOTE: Needs docker compose .yml files either in current dir or provide the path to docker-compose .yml file as in example"
echo -e "examples:"
echo -e " $(basename "$0") start vaultwarden"
echo -e " $(basename "$0") start /home/${USER}/vaultwarden.yml"
echo
echo -e "status examples:"
echo -e " $(basename "$0") status containerName"
echo -e " $(basename "$0") status containerName -f"
echo
echo -e "NOTE: You can use multiple compose.yml file separated by space (except for status arg. It shows log of one container only)"
echo -e " $(basename "$0") args composefile1 composefile2 composefile3"
}
case "$1" in
"start" | "stop" | "restart" | "update") runMain "$@" ;;
"status") runAction "$@" ;;
"--debug") loadConfig "$@"; debugMain;;
--help | -h) helpMenu ;;
*) helpMenu ;;
esac