Refactor Docker and configuration files for improved structure and functionality

- Updated `.dockerignore` to include additional development and temporary files, enhancing build efficiency.
- Modified `.gitignore` to remove unnecessary entries and streamline ignored files.
- Enhanced `docker-compose.yml` with health checks, resource limits, and improved environment variable handling for better service management.
- Refactored `Dockerfile.bot` to utilize a multi-stage build for optimized image size and security.
- Improved `Makefile` with new commands for deployment, migration, and backup, along with enhanced help documentation.
- Updated `requirements.txt` to include new dependencies for environment variable management.
- Refactored metrics handling in the bot to ensure proper initialization and collection.
This commit is contained in:
2025-08-29 23:15:06 +03:00
parent f097d69dd4
commit 8f338196b7
27 changed files with 1499 additions and 370 deletions

86
scripts/deploy.sh Normal file
View File

@@ -0,0 +1,86 @@
#!/bin/bash
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Configuration
PROJECT_NAME="telegram-helper-bot"
DOCKER_COMPOSE_FILE="docker-compose.yml"
ENV_FILE=".env"
echo -e "${GREEN}🚀 Starting deployment of $PROJECT_NAME${NC}"
# Check if .env file exists
if [ ! -f "$ENV_FILE" ]; then
echo -e "${RED}❌ Error: $ENV_FILE file not found!${NC}"
echo -e "${YELLOW}Please copy env.example to .env and configure your settings${NC}"
exit 1
fi
# Load environment variables
source "$ENV_FILE"
# Validate required environment variables
required_vars=("BOT_TOKEN" "MAIN_PUBLIC" "GROUP_FOR_POSTS" "GROUP_FOR_MESSAGE" "GROUP_FOR_LOGS")
for var in "${required_vars[@]}"; do
if [ -z "${!var}" ]; then
echo -e "${RED}❌ Error: Required environment variable $var is not set${NC}"
exit 1
fi
done
echo -e "${GREEN}✅ Environment variables validated${NC}"
# Create necessary directories
echo -e "${YELLOW}📁 Creating necessary directories...${NC}"
mkdir -p database logs
# Set proper permissions
echo -e "${YELLOW}🔐 Setting proper permissions...${NC}"
chmod 600 "$ENV_FILE"
chmod 755 database logs
# Stop existing containers
echo -e "${YELLOW}🛑 Stopping existing containers...${NC}"
docker-compose -f "$DOCKER_COMPOSE_FILE" down --remove-orphans || true
# Remove old images
echo -e "${YELLOW}🧹 Cleaning up old images...${NC}"
docker system prune -f
# Build and start services
echo -e "${YELLOW}🔨 Building and starting services...${NC}"
docker-compose -f "$DOCKER_COMPOSE_FILE" up -d --build
# Wait for services to be healthy
echo -e "${YELLOW}⏳ Waiting for services to be healthy...${NC}"
sleep 30
# Check service health
echo -e "${YELLOW}🏥 Checking service health...${NC}"
if docker-compose -f "$DOCKER_COMPOSE_FILE" ps | grep -q "unhealthy"; then
echo -e "${RED}❌ Some services are unhealthy!${NC}"
docker-compose -f "$DOCKER_COMPOSE_FILE" logs
exit 1
fi
# Show service status
echo -e "${GREEN}📊 Service status:${NC}"
docker-compose -f "$DOCKER_COMPOSE_FILE" ps
echo -e "${GREEN}✅ Deployment completed successfully!${NC}"
echo -e "${GREEN}📊 Monitoring URLs:${NC}"
echo -e " Prometheus: http://localhost:9090"
echo -e " Grafana: http://localhost:3000"
echo -e " Bot Metrics: http://localhost:8000/metrics"
echo -e " Bot Health: http://localhost:8000/health"
echo -e ""
echo -e "${YELLOW}📝 Useful commands:${NC}"
echo -e " View logs: docker-compose logs -f"
echo -e " Restart: docker-compose restart"
echo -e " Stop: docker-compose down"

View File

@@ -0,0 +1,104 @@
#!/bin/bash
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${GREEN}🔄 Starting migration from systemctl + cron to Docker${NC}"
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo -e "${RED}❌ This script must be run as root for systemctl operations${NC}"
exit 1
fi
# Configuration
SERVICE_NAME="telegram-helper-bot"
CRON_USER="root"
echo -e "${YELLOW}📋 Migration steps:${NC}"
echo "1. Stop systemctl service"
echo "2. Disable systemctl service"
echo "3. Remove cron jobs"
echo "4. Backup existing data"
echo "5. Deploy Docker version"
# Step 1: Stop systemctl service
echo -e "${YELLOW}🛑 Stopping systemctl service...${NC}"
if systemctl is-active --quiet "$SERVICE_NAME"; then
systemctl stop "$SERVICE_NAME"
echo -e "${GREEN}✅ Service stopped${NC}"
else
echo -e "${YELLOW}⚠️ Service was not running${NC}"
fi
# Step 2: Disable systemctl service
echo -e "${YELLOW}🚫 Disabling systemctl service...${NC}"
if systemctl is-enabled --quiet "$SERVICE_NAME"; then
systemctl disable "$SERVICE_NAME"
echo -e "${GREEN}✅ Service disabled${NC}"
else
echo -e "${YELLOW}⚠️ Service was not enabled${NC}"
fi
# Step 3: Remove cron jobs
echo -e "${YELLOW}🗑️ Removing cron jobs...${NC}"
if crontab -u "$CRON_USER" -l 2>/dev/null | grep -q "telegram-helper-bot"; then
crontab -u "$CRON_USER" -l 2>/dev/null | grep -v "telegram-helper-bot" | crontab -u "$CRON_USER" -
echo -e "${GREEN}✅ Cron jobs removed${NC}"
else
echo -e "${YELLOW}⚠️ No cron jobs found${NC}"
fi
# Step 4: Backup existing data
echo -e "${YELLOW}💾 Creating backup...${NC}"
BACKUP_DIR="/backup/telegram-bot-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"
# Backup database
if [ -f "database/tg-bot-database.db" ]; then
cp -r database "$BACKUP_DIR/"
echo -e "${GREEN}✅ Database backed up to $BACKUP_DIR/database${NC}"
fi
# Backup logs
if [ -d "logs" ]; then
cp -r logs "$BACKUP_DIR/"
echo -e "${GREEN}✅ Logs backed up to $BACKUP_DIR/logs${NC}"
fi
# Backup settings
if [ -f ".env" ]; then
cp .env "$BACKUP_DIR/"
echo -e "${GREEN}✅ Settings backed up to $BACKUP_DIR/.env${NC}"
fi
# Step 5: Deploy Docker version
echo -e "${YELLOW}🐳 Deploying Docker version...${NC}"
# Check if Docker is installed
if ! command -v docker &> /dev/null; then
echo -e "${RED}❌ Docker is not installed. Please install Docker first.${NC}"
exit 1
fi
if ! command -v docker-compose &> /dev/null; then
echo -e "${RED}❌ Docker Compose is not installed. Please install Docker Compose first.${NC}"
exit 1
fi
# Make deploy script executable and run it
chmod +x scripts/deploy.sh
./scripts/deploy.sh
echo -e "${GREEN}✅ Migration completed successfully!${NC}"
echo -e "${GREEN}📁 Backup location: $BACKUP_DIR${NC}"
echo -e "${YELLOW}📝 Next steps:${NC}"
echo "1. Verify the bot is working correctly"
echo "2. Check monitoring dashboards"
echo "3. Remove old systemctl service file if no longer needed"
echo "4. Update any external monitoring/alerting systems"

32
scripts/start_docker.sh Executable file
View File

@@ -0,0 +1,32 @@
#!/bin/bash
echo "🐍 Запуск Telegram Bot с Python 3.9 (стандартная версия)..."
echo ""
echo "🔧 Сборка Docker образа с Python 3.9..."
make build
echo ""
echo "🚀 Запуск сервисов..."
make up
echo ""
echo "🐍 Проверка версии Python в контейнере..."
make check-python
echo ""
echo "📦 Проверка установленных пакетов..."
docker exec telegram-bot .venv/bin/pip list
echo ""
echo "✅ Сервисы успешно запущены!"
echo ""
echo "📝 Полезные команды:"
echo " Логи бота: make logs-bot"
echo " Статус: make status"
echo " Остановка: make stop"
echo " Перезапуск: make restart"
echo ""
echo "📊 Мониторинг:"
echo " Prometheus: http://localhost:9090"
echo " Grafana: http://localhost:3000 (admin/admin)"