-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevcli.sh
More file actions
executable file
·511 lines (436 loc) · 16.4 KB
/
devcli.sh
File metadata and controls
executable file
·511 lines (436 loc) · 16.4 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
#!/bin/bash
#!/bin/zsh
# On bash run it with ./devcli.sh
# Color codes for styling
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# shellcheck disable=SC1091
source .env
# Sets COMPOSE_ARGS array with the right -f flags for the given environment
# Dev merges docker-compose.yml with dev.yml; prod uses docker-compose.yml alone
compose_args_for() {
if [ "$1" = "dev" ]; then
COMPOSE_ARGS=(-f docker-compose.yml -f dev.yml)
else
COMPOSE_ARGS=(-f docker-compose.yml)
fi
}
# Function to display help
help() {
echo -e "${GREEN}Usage:${NC} $0 COMMAND [ARGS]"
echo -e ""
echo -e "${GREEN}Commands:${NC}"
echo -e " start ENV Start docker containers for the specified environment."
echo -e " stop ENV Stop docker containers for the specified environment."
echo -e " remove_volumes ENV Remove docker volumes for the specified environment."
echo -e " export_kc_volume Export Keycloak volume to a tar.gz file."
echo -e " import_kc_volume Import Keycloak volume from a tar.gz file."
echo -e " generate_passwords Generate random passwords."
echo -e " generate_certificates Generate SSL/TLS certificates."
echo -e " reload ENV SERVICE Reload a specific service container."
echo -e " e2e_tests Run the e2e."
echo -e " logs ENV Save docker logs for the specified environment."
echo -e " help Display this help message."
echo -e ""
echo -e "${GREEN}Examples:${NC}"
echo -e " $0 start dev"
echo -e " $0 reload dev backend"
echo -e ""
}
# Function to generate SSL/TLS certificates and convert to JKS
# Might need to run this script with sudo
generate_certificates() {
# Variables
KEYSTORE_PASSWORD="changeit"
ALIAS="myalias"
DAYS_VALID=365
CONFIG_FILE="./config/certs/server.cnf"
OUTPUT_DIR="./config/certs"
GREEN='\033[0;32m'
NC='\033[0m' # No Color
# Crée le répertoire de sortie s'il n'existe pas
mkdir -p $OUTPUT_DIR
# Création du fichier de configuration OpenSSL
cat >$CONFIG_FILE <<EOL
[ req ]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[ req_distinguished_name ]
C = FR
ST = State
L = Paris
O = matithieu
OU = OrganizationalUnit
CN = matithieu.com
[ v3_req ]
subjectAltName = @alt_names
[ alt_names ]
DNS.1 = matithieu.com
DNS.2 = www.matithieu.com
DNS.3 = keycloak
DNS.4 = localhost
EOL
# Private Key And CSR
openssl req -newkey rsa:2048 -nodes -keyout $OUTPUT_DIR/server.key -out $OUTPUT_DIR/server.csr -config $CONFIG_FILE
# CSR -> CRT
openssl x509 -req -days $DAYS_VALID -in $OUTPUT_DIR/server.csr -signkey $OUTPUT_DIR/server.key -out $OUTPUT_DIR/server.crt -extensions v3_req -extfile $CONFIG_FILE
# Key -> PKCS12
openssl pkcs12 -export -in $OUTPUT_DIR/server.crt -inkey $OUTPUT_DIR/server.key -out $OUTPUT_DIR/server.p12 -name $ALIAS -passout pass:$KEYSTORE_PASSWORD
# PKCS12 -> JKS
keytool -importkeystore -deststorepass $KEYSTORE_PASSWORD -destkeypass $KEYSTORE_PASSWORD -destkeystore $OUTPUT_DIR/keystore.jks -srckeystore $OUTPUT_DIR/server.p12 -srcstoretype PKCS12 -srcstorepass $KEYSTORE_PASSWORD -alias $ALIAS
# Combine the CRT and KEY into a PEM file
cat $OUTPUT_DIR/server.crt $OUTPUT_DIR/server.key >$OUTPUT_DIR/server.pem
# Give the correct permissions to the files
chmod 644 $OUTPUT_DIR/server.crt $OUTPUT_DIR/server.key $OUTPUT_DIR/server.pem $OUTPUT_DIR/server.p12
echo -e "${GREEN}SSL/TLS certificates generated successfully!${NC}"
}
# Function to start docker containers
start() {
if [ -z "$1" ]; then
echo -e "${RED}No environment specified. Please use 'dev' or 'prod'.${NC}"
exit 1
fi
echo "Starting docker containers..."
if [ "$1" = "dev" ] || [ "$1" = "prod" ]; then
BUILD_ARG=""
if [ "$1" = "prod" ]; then
echo -e "${YELLOW}Starting in production mode...${NC}"
if [ -z "$API_IMAGE" ] || [ -z "$FRONTEND_IMAGE" ]; then
echo -e "${RED}Error: API_IMAGE and FRONTEND_IMAGE must be set in .env for production mode.${NC}"
exit 1
fi
else
echo -e "${YELLOW}Starting in development mode...${NC}"
BUILD_ARG="--build"
fi
compose_args_for "$1"
if docker compose "${COMPOSE_ARGS[@]}" up -d ${BUILD_ARG} --quiet-pull; then
echo -e "${GREEN}Containers are up!${NC}"
else
echo -e "${RED}Failed to start docker containers.${NC}"
exit 1
fi
fi
}
stop() {
# Check if an environment is provided
if [ -z "$1" ]; then
echo -e "${RED}Error: No environment specified. Please use 'dev' or 'prod'.${NC}"
exit 1
fi
ENVIRONMENT="$1"
FORCE_CONFIRMATION="$2"
# Handle "prod" environment with optional force argument
# Useful for stopping the production environment during CI/CD
if [ "$ENVIRONMENT" = "prod" ]; then
if [ "$FORCE_CONFIRMATION" != "--force" ]; then
read -r -p "$(echo -e "${RED}Are you sure you want to stop the production environment? (yes/no): ${NC}") " confirmation
if [[ "$confirmation" != "yes" ]]; then
echo -e "${RED}Operation aborted by the user.${NC}"
exit 1
fi
else
echo -e "${YELLOW}Force flag detected. Skipping confirmation prompt.${NC}"
fi
fi
compose_args_for "$ENVIRONMENT"
# Stop the Docker containers
echo "Stopping Docker containers for the '$ENVIRONMENT' environment..."
if docker compose "${COMPOSE_ARGS[@]}" down; then
echo -e "${GREEN}Containers for '$ENVIRONMENT' environment are stopped successfully!${NC}"
else
echo -e "${RED}Error: Failed to stop Docker containers for '$ENVIRONMENT'.${NC}"
exit 1
fi
}
# Function to remove specified volumes
remove_volumes() {
echo -e "${YELLOW}WARNING: You are about to remove specific Docker volumes for the $1 environment.${NC}"
echo -e "${YELLOW}This action is irreversible, and the data stored in these volumes will be permanently lost.${NC}"
echo
echo -e "${YELLOW}The following volumes will be deleted:${NC}"
# List of volumes to delete
volumes_to_delete=(
"boilerplate-meta_pgadmin_data"
# "boilerplate-meta_postgres_data"
)
for volume in "${volumes_to_delete[@]}"; do
echo -e "${YELLOW} - $volume${NC}"
done
echo
read -r -p "Are you sure you want to proceed? (yes/no): " confirmation
if [[ "$confirmation" != "yes" ]]; then
echo -e "${RED}Operation aborted by the user.${NC}"
return
fi
echo "Removing specific volumes for $1 environment..."
# Iterate over the list of volumes to delete
for volume in "${volumes_to_delete[@]}"; do
echo -e "${YELLOW}Attempting to remove volume: $volume${NC}"
if docker volume rm "$volume"; then
echo -e "${GREEN}Successfully removed $volume.${NC}"
else
echo -e "${RED}Failed to remove $volume or it may not exist.${NC}"
fi
done
}
export_kc_volume() {
# Check if Docker volume exists
VOLUME_NAME="boilerplate-meta_keycloak-db"
BACKUP_DIR="./backups"
BACKUP_FILE="$BACKUP_DIR/${VOLUME_NAME}_backup_$(date +'%Y%m%d%H%M%S').tar.gz"
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
# Check if volume exists
if ! docker volume inspect "$VOLUME_NAME" > /dev/null 2>&1; then
echo -e "${RED}Error: Volume '$VOLUME_NAME' does not exist.${NC}"
return 1
fi
echo "Exporting volume '$VOLUME_NAME' to '$BACKUP_FILE'..."
# Use a temporary container to create the backup
if docker run --rm \
-v "$VOLUME_NAME:/data" \
-v "$(pwd)/$BACKUP_DIR:/backup" \
busybox \
tar czvf "/backup/$(basename "$BACKUP_FILE")" -C /data .; then
echo -e "${GREEN}Volume '$VOLUME_NAME' has been successfully exported to '$BACKUP_FILE'.${NC}"
else
echo -e "${RED}Failed to export volume '$VOLUME_NAME'.${NC}"
return 1
fi
}
import_kc_volume() {
# Define volume name and backup file paths
VOLUME_NAME="boilerplate-meta_keycloak-db"
BACKUP_DIR="./backups"
BACKUP_FILE="$1"
# Make sure the user wants to proceed
echo -e "${YELLOW}WARNING: You are about to override the existing volume '$VOLUME_NAME'.${NC}"
echo -e "${YELLOW}This action is irreversible, and the data stored in this volume will be permanently lost.${NC}"
echo
read -r -p "$(echo -e "${RED}Are you sure you want to proceed? (yes/no): ${NC}") " confirmation
if [[ "$confirmation" != "yes" ]]; then
echo -e "${RED}Operation aborted by the user.${NC}"
return 1
fi
# Check if the backup file was provided
if [ -z "$BACKUP_FILE" ]; then
echo -e "${RED}Error: No backup file specified. Please provide the path to the backup file.${NC}"
echo "Usage: import_kc_volume <path_to_backup_file>"
return 1
fi
# Check if the backup file exists
if [ ! -f "$BACKUP_FILE" ]; then
echo -e "${RED}Error: Backup file '$BACKUP_FILE' does not exist.${NC}"
return 1
fi
echo "Importing volume '$VOLUME_NAME' from backup file '$BACKUP_FILE'..."
# Check if the volume exists, if not create it
if ! docker volume inspect "$VOLUME_NAME" > /dev/null 2>&1; then
echo "Volume '$VOLUME_NAME' does not exist. Creating it..."
if ! docker volume create "$VOLUME_NAME"; then
echo -e "${RED}Error: Failed to create volume '$VOLUME_NAME'.${NC}"
return 1
fi
fi
# Use a temporary container to restore the backup into the volume
if docker run --rm \
-v "$VOLUME_NAME:/data" \
-v "$(pwd)/$BACKUP_DIR:/backup" \
busybox \
tar xzvf "/backup/$(basename "$BACKUP_FILE")" -C /data; then
echo -e "${GREEN}Volume '$VOLUME_NAME' has been successfully restored from '$BACKUP_FILE'.${NC}"
else
echo -e "${RED}Failed to restore volume '$VOLUME_NAME' from '$BACKUP_FILE'.${NC}"
return 1
fi
}
# Function to generate random passwords
generate_passwords() {
PASSWORD_LENGTH=16
NUMBER_OF_PASSWORDS=$1 # Number of passwords to generate
if [[ -z "$NUMBER_OF_PASSWORDS" || ! "$NUMBER_OF_PASSWORDS" =~ ^[0-9]+$ ]]; then
echo -e "${GREEN}Usage: generate_passwords <number_of_passwords>${NC}"
return 1
fi
for ((i = 1; i <= NUMBER_OF_PASSWORDS; i++)); do
PASSWORD=$(openssl rand -base64 $PASSWORD_LENGTH)
echo -e "${GREEN}Generated Password $i: ${NC}$PASSWORD"
done
}
# Function to reload a specific service container
reload() {
if [ -z "$1" ] || [ -z "$2" ]; then
echo -e "${RED}No environment or service specified. Please use 'dev' or 'prod' and specify a service name.${NC}"
exit 1
fi
ENV=$1
SERVICE=$2
compose_args_for "$ENV"
echo "Building the Docker image for $SERVICE..."
if docker compose "${COMPOSE_ARGS[@]}" build "$SERVICE"; then
echo -e "${GREEN}Docker image built successfully.${NC}"
else
echo -e "${RED}Failed to build Docker image.${NC}"
exit 1
fi
echo "Starting a new instance of $SERVICE container with the updated image..."
if docker compose "${COMPOSE_ARGS[@]}" up -d --scale "$SERVICE"=2 --no-recreate; then
echo -e "${GREEN}New instance of $SERVICE started successfully!${NC}"
else
echo -e "${RED}Failed to start a new instance of $SERVICE.${NC}"
exit 1
fi
echo "Waiting for the new container to stabilize..."
if [ "$ENV" = "prod" ]; then
sleep 30
else
sleep 10
fi
echo "Stopping the old $SERVICE container..."
if docker compose "${COMPOSE_ARGS[@]}" up -d --scale "$SERVICE"=1; then
echo -e "${GREEN}Old instance of $SERVICE stopped successfully.${NC}"
else
echo -e "${RED}Failed to stop the old instance of $SERVICE.${NC}"
exit 1
fi
echo "Reload of $SERVICE completed with zero downtime!"
}
# Start the E2E test environment
run_end2end_tests() {
docker build -f ./apps/e2e/Dockerfile -t e2e-tests .
# Try to detect the actual docker-compose network dynamically
# This works both locally and in CI by finding the network created by docker-compose
NETWORK_NAME=$(docker network ls --format '{{.Name}}' | grep '_default$' | head -n 1)
if [ -z "$NETWORK_NAME" ]; then
# Fallback: try to construct from directory name
COMPOSE_PROJECT_NAME=$(basename "$(pwd)" | tr '[:upper:]' '[:lower:]' | tr -cd '[:alnum:]-')
NETWORK_NAME="${COMPOSE_PROJECT_NAME}_default"
fi
# Verify the network exists
if docker network inspect "$NETWORK_NAME" >/dev/null 2>&1; then
echo -e "${GREEN}Found network: $NETWORK_NAME${NC}"
NETWORK_ARG="--network=$NETWORK_NAME"
# Use BASE_URL from environment or default to https://traefik (production uses HTTPS)
BASE_URL=${BASE_URL:-https://traefik}
else
echo -e "${YELLOW}Warning: Network $NETWORK_NAME not found, using host.docker.internal${NC}"
NETWORK_ARG="--add-host=host.docker.internal:host-gateway"
# When not on docker network, use host network addressing
BASE_URL=${BASE_URL:-http://host.docker.internal}
fi
echo -e "${GREEN}Running E2E tests with BASE_URL=$BASE_URL${NC}"
docker run \
--rm \
--ipc=host \
$NETWORK_ARG \
--env PW_RUN_HEADLESS="1" \
--env CI="1" \
--env BASE_URL="$BASE_URL" \
e2e-tests
}
run_docker_logs() {
mkdir -p logs
compose_args_for "$1"
services=("postgres" "pgadmin4" "keycloak-db" "keycloak" "backend" "redis" "oauth2-proxy" "prometheus" "grafana" "traefik" "frontend")
for service in "${services[@]}"; do
if docker compose "${COMPOSE_ARGS[@]}" logs "$service" &> "logs/${service}_$1.log"; then
echo -e "${GREEN}Logs for $service in $1 environment saved to logs/${service}_$1.log${NC}"
else
echo -e "${RED}Failed to retrieve logs for $service in $1 environment.${NC}"
fi
done
}
# Parse command-line arguments
COMMAND="$1"
shift
case "$COMMAND" in
start)
ENV="$1"
if [[ "$ENV" == "dev" || "$ENV" == "prod" ]]; then
start "$ENV"
else
echo -e "${RED}Error: Environment not specified or invalid. Use 'dev' or 'prod'.${NC}"
help
exit 1
fi
;;
stop)
ENV="$1"
FORCE="$2"
if [[ "$ENV" == "dev" || "$ENV" == "prod" ]]; then
if [[ "$FORCE" == "--force" ]]; then
stop "$ENV" "$FORCE"
else
stop "$ENV"
fi
else
echo -e "${RED}Error: Environment not specified or invalid. Use 'dev' or 'prod'.${NC}"
help
exit 1
fi
;;
remove_volumes)
ENV="$1"
if [[ "$ENV" == "dev" || "$ENV" == "prod" ]]; then
remove_volumes "$ENV"
else
echo -e "${RED}Error: Environment not specified or invalid. Use 'dev' or 'prod'.${NC}"
help
exit 1
fi
;;
export_kc_volume)
export_kc_volume
;;
import_kc_volume)
import_kc_volume "$@"
;;
generate_passwords)
generate_passwords "$@"
;;
generate_certificates)
generate_certificates
;;
reload)
ENV="$1"
SERVICE="$2"
if [[ "$ENV" == "dev" || "$ENV" == "prod" ]]; then
if [[ -n "$SERVICE" ]]; then
reload "$ENV" "$SERVICE"
else
echo -e "${RED}Error: Service name not specified.${NC}"
help
exit 1
fi
else
echo -e "${RED}Error: Environment not specified or invalid. Use 'dev' or 'prod'.${NC}"
help
exit 1
fi
;;
e2e_tests)
run_end2end_tests
;;
logs)
ENV="$1"
if [[ "$ENV" == "dev" || "$ENV" == "prod" ]]; then
run_docker_logs "$ENV"
else
echo -e "${RED}Error: Environment not specified or invalid. Use 'dev' or 'prod'.${NC}"
help
exit 1
fi
;;
help)
help
;;
*)
echo -e "${RED}Error: Invalid command.${NC}"
help
exit 1
;;
esac