ruspet_portal_back/deploy.sh

288 lines
10 KiB
Bash
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
set -e
trap 'echo "🔴 Deploy failed at line $LINENO"; exit 1' ERR
THIS_PATH=$(dirname "$(realpath "$0")")
# ═══════════════════════════════════════════════════════════════
# Цвета для вывода
# ═══════════════════════════════════════════════════════════════
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
NC='\033[0m'
export GOPATH=/home/git/.go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
log_info() { echo -e "${BLUE}ℹ️ $1${NC}"; }
log_success() { echo -e "${GREEN}✅ $1${NC}"; }
log_warning() { echo -e "${YELLOW}⚠️ $1${NC}"; }
log_error() { echo -e "${RED}❌ $1${NC}"; }
log_service() { echo -e "${MAGENTA}📦 $1${NC}"; }
# ═══════════════════════════════════════════════════════════════
# Парсинг аргументов
# ═══════════════════════════════════════════════════════════════
SERVICE_TYPE="${1:-all}"
GENERATE_SWAGGER="${2:-false}"
validate_service_type() {
case "$1" in
bot|telegram|balancer|admin|migrations|all) return 0 ;;
*) return 1 ;;
esac
}
if ! validate_service_type "$SERVICE_TYPE"; then
log_error "Unknown service type: $SERVICE_TYPE"
echo "Usage: $0 [telegram|balancer|admin|migrations|all] [swagger]"
exit 1
fi
# ═══════════════════════════════════════════════════════════════
# Обработка 'all'
# ═══════════════════════════════════════════════════════════════
if [ "$SERVICE_TYPE" = "all" ]; then
log_info "Deploying all services..."
echo ""
# ✅ Используем абсолютный путь к скрипту
SELF="$THIS_PATH/deploy.sh"
log_service "Step 1/4: Database migrations"
bash "$SELF" migrations
echo ""
log_service "Step 2/4: Telegram bot"
bash "$SELF" telegram
echo ""
log_service "Step 3/4: REST balancer"
bash "$SELF" balancer
echo ""
log_service "Step 4/4: REST admin"
bash "$SELF" admin "$GENERATE_SWAGGER"
echo ""
log_success "All services deployed successfully!"
exit 0
fi
# ═══════════════════════════════════════════════════════════════
# Определяем конфигурацию сервиса
# ═══════════════════════════════════════════════════════════════
case "$SERVICE_TYPE" in
telegram|bot)
SERVICE_NAME="telegram_service"
DESCRIPTION="Telegram Bot Service"
SERVICE_KIND="daemon"
;;
balancer)
SERVICE_NAME="rest_balancer_service"
DESCRIPTION="REST Balancer Service"
SERVICE_KIND="daemon"
;;
admin)
SERVICE_NAME="rest_admin_service"
DESCRIPTION="REST Admin Service"
SERVICE_KIND="daemon"
;;
migrations)
SERVICE_NAME="system_service"
DESCRIPTION="Database Migrations"
SERVICE_KIND="oneshot"
;;
esac
SERVICE_PATH="$THIS_PATH/service/$SERVICE_NAME"
BINARY_PATH="/usr/local/bin/$SERVICE_NAME"
echo "════════════════════════════════════════"
log_info "Deploying: $DESCRIPTION"
log_info "Service: $SERVICE_NAME"
log_info "Kind: $SERVICE_KIND"
log_info "Path: $SERVICE_PATH"
log_info "Binary: $BINARY_PATH"
echo "════════════════════════════════════════"
echo ""
if [ ! -d "$SERVICE_PATH" ]; then
log_error "Service directory not found: $SERVICE_PATH"
exit 1
fi
# ═══════════════════════════════════════════════════════════════
# Генерация Swagger (только для админки)
# ═══════════════════════════════════════════════════════════════
if [ "$SERVICE_TYPE" = "admin" ] && [ "$GENERATE_SWAGGER" = "swagger" ]; then
log_info "Generating Swagger documentation..."
if ! command -v swag &> /dev/null; then
log_warning "swag CLI not found. Installing..."
go install github.com/swaggo/swag/cmd/swag@latest
export PATH=$PATH:$(go env GOPATH)/bin
fi
cd "$SERVICE_PATH"
mkdir -p ./docs
swag init -g main.go --parseDependency --parseInternal -o ./docs
log_success "Swagger documentation generated"
cd "$THIS_PATH"
echo ""
fi
# ═══════════════════════════════════════════════════════════════
# Сборка core
# ═══════════════════════════════════════════════════════════════
log_info "Building core module..."
cd "$THIS_PATH/core"
go mod tidy
go vet ./...
log_success "Core built successfully"
echo ""
# ═══════════════════════════════════════════════════════════════
# Сборка сервиса
# ═══════════════════════════════════════════════════════════════
log_info "Building $SERVICE_NAME..."
cd "$SERVICE_PATH"
# Проверяем, лежит ли исходный код в подпапке cmd или в корне сервиса
BUILD_TARGET="."
if [ -d "./cmd" ]; then
log_info "Found 'cmd' directory, building from ./cmd"
BUILD_TARGET="./cmd"
fi
gofmt -w .
go vet ./...
# Передаем BUILD_TARGET вместо точки
go build -ldflags="-s -w" -o "$BINARY_PATH" "$BUILD_TARGET"
log_success "Binary deployed to $BINARY_PATH"
# ═══════════════════════════════════════════════════════════════
# Управление сервисом
# ═══════════════════════════════════════════════════════════════
if [ "$SERVICE_KIND" = "daemon" ]; then
# Проверяем существует ли systemd unit
if [ ! -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
log_warning "Systemd unit not found: /etc/systemd/system/$SERVICE_NAME.service"
log_info "Creating systemd unit..."
sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
[Unit]
Description=$DESCRIPTION
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/workspace/ruspet_portal_back
ExecStart=$BINARY_PATH
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable "$SERVICE_NAME"
log_success "Systemd unit created and enabled"
fi
log_info "Restarting systemd service..."
sudo systemctl restart "$SERVICE_NAME"
sleep 3
if systemctl is-active --quiet "$SERVICE_NAME"; then
log_success "Service is running"
SERVICE_STATUS=$(systemctl is-active "$SERVICE_NAME")
log_info "Status: $SERVICE_STATUS"
else
log_error "Service failed to start"
log_info "Check logs: sudo journalctl -u $SERVICE_NAME -n 50"
exit 1
fi
elif [ "$SERVICE_KIND" = "oneshot" ]; then
# Миграции — проверяем существует ли unit
if [ ! -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
log_warning "Systemd unit not found: /etc/systemd/system/$SERVICE_NAME.service"
log_info "Creating systemd unit for migrations..."
sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
[Unit]
Description=$DESCRIPTION
After=network.target
[Service]
Type=oneshot
User=root
WorkingDirectory=/workspace/ruspet_portal_back
ExecStart=$BINARY_PATH
StandardOutput=journal
StandardError=journal
RemainAfterExit=no
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
log_success "Systemd unit created"
fi
log_info "Running migrations..."
sudo systemctl start "$SERVICE_NAME"
TIMEOUT=300
ELAPSED=0
while systemctl is-active --quiet "$SERVICE_NAME"; do
sleep 2
ELAPSED=$((ELAPSED + 2))
if [ $ELAPSED -ge $TIMEOUT ]; then
log_error "Migrations timed out after ${TIMEOUT}s"
sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager
exit 1
fi
printf "."
done
echo ""
RESULT=$(systemctl show "$SERVICE_NAME" --property=ExecMainStatus --value)
if [ "$RESULT" = "0" ]; then
log_success "Migrations completed successfully"
log_info "Migration log:"
sudo journalctl -u "$SERVICE_NAME" -n 20 --no-pager
else
log_error "Migrations failed with exit code: $RESULT"
sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager
exit 1
fi
fi
echo ""
echo "════════════════════════════════════════"
log_success "Deployment of $SERVICE_NAME completed!"
echo "════════════════════════════════════════"
if [ "$SERVICE_TYPE" = "admin" ]; then
echo ""
log_info "Admin panel info:"
echo " - Swagger UI: https://api.ruspet.tw1.ru/swagger/index.html"
fi