-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.sh
executable file
·76 lines (67 loc) · 2.29 KB
/
shell.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
#!/bin/bash
set -e
# Check if a service name was provided
if [ -z "$1" ]; then
echo "Usage: shell.sh <service_name> [optional] <command> [optional] <command_argument>"
echo "Commands:"
echo " shell: Start an interactive bash shell in the container (default)"
echo " run <command>: Run a command in the container"
echo " logs: Show logs for the container"
echo " restart: Restart the container"
exit 1
fi
SERVICE_NAME="$1"
COMMAND="$2"
if [ -z "$COMMAND" ]; then
COMMAND="shell"
fi
# Find all running containers for services ending with the given service name
CONTAINER_IDS=($(docker ps --filter "name=_${SERVICE_NAME}\." --format "{{.ID}}"))
if [ ${#CONTAINER_IDS[@]} -eq 0 ]; then
echo "No running containers found for service ending with '${SERVICE_NAME}'."
exit 1
fi
# If multiple containers are found, let the user select one
if [ ${#CONTAINER_IDS[@]} -gt 1 ]; then
echo "Multiple containers found for service '${SERVICE_NAME}'. Select one:"
PS3="Enter the number of the container to connect to: "
select CONTAINER_ID in "${CONTAINER_IDS[@]}"; do
if [ -n "$CONTAINER_ID" ]; then
break
else
echo "Invalid selection."
fi
done
else
CONTAINER_ID=${CONTAINER_IDS[0]}
fi
# Get stack name from container label
STACK_NAME=$(docker inspect "$CONTAINER_ID" --format "{{ index .Config.Labels \"com.docker.stack.namespace\" }}")
FULL_SERVICE_NAME="${STACK_NAME}_${SERVICE_NAME}"
if [ "$COMMAND" == "shell" ]; then
# Start an interactive bash shell in the container
docker exec -it "$CONTAINER_ID" /bin/bash
elif [ "$COMMAND" == "run" ]; then
if [ -z "$3" ]; then
echo "Usage: shell <service_name> run <command>"
exit 1
fi
docker exec "$CONTAINER_ID" "${@:3}"
elif [ "$COMMAND" == "logs" ]; then
# Show logs for the container
docker logs -f "$CONTAINER_ID"
elif [ "$COMMAND" == "restart" ]; then
# Restart the container by scaling it down to 0 and then back to 1
echo "Stopping container..."
docker service scale "${FULL_SERVICE_NAME}=0"
# Wait for the container to stop, and print a dot every second
while docker ps --filter "name=${FULL_SERVICE_NAME}\." --format "{{.ID}}" | grep -q .; do
echo -n "."
sleep 1
done
echo "Starting container..."
docker service scale "${FULL_SERVICE_NAME}=1"
else
echo "Invalid command: $COMMAND"
exit 1
fi