562 lines
18 KiB
Docker
562 lines
18 KiB
Docker
# Phantom TLD System - Децентрализованная система доменов первого уровня
|
||
# Поддерживает миллиарды доменов с высокой производительностью
|
||
|
||
FROM ubuntu:22.04
|
||
|
||
LABEL maintainer="Phantom Protocol Team 2025"
|
||
LABEL description="Phantom TLD System - Decentralized Top-Level Domain System"
|
||
LABEL version="1.0.0"
|
||
|
||
# Установка зависимостей
|
||
RUN apt-get update && apt-get install -y \
|
||
build-essential \
|
||
gcc \
|
||
g++ \
|
||
make \
|
||
cmake \
|
||
pkg-config \
|
||
libssl-dev \
|
||
libxml2-dev \
|
||
libprotobuf-dev \
|
||
protobuf-compiler \
|
||
libsqlite3-dev \
|
||
libevent-dev \
|
||
libcurl4-openssl-dev \
|
||
libjson-c-dev \
|
||
libmicrohttpd-dev \
|
||
python3 \
|
||
python3-pip \
|
||
curl \
|
||
wget \
|
||
htop \
|
||
iotop \
|
||
net-tools \
|
||
tcpdump \
|
||
dnsutils \
|
||
&& rm -rf /var/lib/apt/lists/*
|
||
|
||
# Установка Python зависимостей для мониторинга
|
||
RUN pip3 install \
|
||
psutil \
|
||
requests \
|
||
flask \
|
||
prometheus_client \
|
||
pyyaml
|
||
|
||
# Создание пользователя phantom
|
||
RUN useradd -r -s /bin/false -d /opt/phantom phantom
|
||
|
||
# Создание директорий
|
||
RUN mkdir -p /opt/phantom/bin \
|
||
/opt/phantom/config \
|
||
/opt/phantom/data \
|
||
/opt/phantom/logs \
|
||
/opt/phantom/scripts \
|
||
/opt/phantom/monitoring \
|
||
/var/lib/phantom/domains \
|
||
/var/lib/phantom/consensus \
|
||
/var/lib/phantom/cache
|
||
|
||
# Копирование исходного кода
|
||
COPY src/ /opt/phantom/src/
|
||
COPY protos/ /opt/phantom/protos/
|
||
COPY docker/tld-system/ /opt/phantom/scripts/
|
||
|
||
# Сборка проекта
|
||
WORKDIR /opt/phantom/src
|
||
RUN make clean && make tld-system
|
||
|
||
# Копирование бинарных файлов
|
||
RUN cp phantom-tld-system /opt/phantom/bin/ && \
|
||
cp phantom-dns-resolver /opt/phantom/bin/ && \
|
||
cp phantom-consensus /opt/phantom/bin/ && \
|
||
cp phantom-domain-registry /opt/phantom/bin/
|
||
|
||
# Создание конфигурационных файлов
|
||
RUN cat > /opt/phantom/config/tld-system.conf << 'EOF'
|
||
# Phantom TLD System Configuration
|
||
|
||
[general]
|
||
node_id = auto
|
||
data_directory = /var/lib/phantom
|
||
log_level = info
|
||
log_file = /opt/phantom/logs/tld-system.log
|
||
|
||
[network]
|
||
bind_address = 0.0.0.0
|
||
port = 8053
|
||
max_connections = 10000
|
||
worker_threads = 16
|
||
|
||
[dns]
|
||
dns_port = 53
|
||
cache_size = 1000000
|
||
max_ttl = 86400
|
||
upstream_servers = 8.8.8.8,1.1.1.1
|
||
|
||
[consensus]
|
||
consensus_port = 8054
|
||
min_validators = 3
|
||
block_time = 30
|
||
epoch_length = 100
|
||
|
||
[domains]
|
||
max_domains_per_shard = 10000000
|
||
shard_count = 256
|
||
cache_size = 100000
|
||
index_size = 1000000
|
||
|
||
[monitoring]
|
||
metrics_port = 8055
|
||
health_check_port = 8056
|
||
prometheus_enabled = true
|
||
|
||
[security]
|
||
enable_rate_limiting = true
|
||
max_queries_per_second = 10000
|
||
max_queries_per_ip = 100
|
||
blacklist_file = /opt/phantom/config/blacklist.txt
|
||
EOF
|
||
|
||
# Создание скрипта запуска
|
||
RUN cat > /opt/phantom/scripts/start-tld-system.sh << 'EOF'
|
||
#!/bin/bash
|
||
|
||
set -e
|
||
|
||
echo "Запуск Phantom TLD System..."
|
||
|
||
# Проверка конфигурации
|
||
if [ ! -f /opt/phantom/config/tld-system.conf ]; then
|
||
echo "Ошибка: файл конфигурации не найден"
|
||
exit 1
|
||
fi
|
||
|
||
# Создание директорий данных
|
||
mkdir -p /var/lib/phantom/domains/shards
|
||
mkdir -p /var/lib/phantom/consensus
|
||
mkdir -p /var/lib/phantom/cache
|
||
mkdir -p /opt/phantom/logs
|
||
|
||
# Установка прав доступа
|
||
chown -R phantom:phantom /var/lib/phantom
|
||
chown -R phantom:phantom /opt/phantom/logs
|
||
|
||
# Генерация ключей валидатора если не существуют
|
||
if [ ! -f /var/lib/phantom/consensus/validator.key ]; then
|
||
echo "Генерация ключей валидатора..."
|
||
/opt/phantom/bin/phantom-consensus --generate-keys \
|
||
--output /var/lib/phantom/consensus/validator.key
|
||
chown phantom:phantom /var/lib/phantom/consensus/validator.key
|
||
chmod 600 /var/lib/phantom/consensus/validator.key
|
||
fi
|
||
|
||
# Инициализация базы данных доменов
|
||
if [ ! -f /var/lib/phantom/domains/registry.db ]; then
|
||
echo "Инициализация реестра доменов..."
|
||
/opt/phantom/bin/phantom-domain-registry --init \
|
||
--data-dir /var/lib/phantom/domains \
|
||
--config /opt/phantom/config/tld-system.conf
|
||
fi
|
||
|
||
# Запуск компонентов в фоновом режиме
|
||
echo "Запуск реестра доменов..."
|
||
su phantom -s /bin/bash -c "/opt/phantom/bin/phantom-domain-registry \
|
||
--config /opt/phantom/config/tld-system.conf \
|
||
--daemon" &
|
||
|
||
sleep 2
|
||
|
||
echo "Запуск системы консенсуса..."
|
||
su phantom -s /bin/bash -c "/opt/phantom/bin/phantom-consensus \
|
||
--config /opt/phantom/config/tld-system.conf \
|
||
--validator-key /var/lib/phantom/consensus/validator.key \
|
||
--daemon" &
|
||
|
||
sleep 2
|
||
|
||
echo "Запуск DNS resolver..."
|
||
su phantom -s /bin/bash -c "/opt/phantom/bin/phantom-dns-resolver \
|
||
--config /opt/phantom/config/tld-system.conf \
|
||
--daemon" &
|
||
|
||
sleep 2
|
||
|
||
echo "Запуск основной TLD системы..."
|
||
exec su phantom -s /bin/bash -c "/opt/phantom/bin/phantom-tld-system \
|
||
--config /opt/phantom/config/tld-system.conf"
|
||
EOF
|
||
|
||
# Создание скрипта мониторинга
|
||
RUN cat > /opt/phantom/scripts/monitor.py << 'EOF'
|
||
#!/usr/bin/env python3
|
||
"""
|
||
Phantom TLD System Monitor
|
||
Мониторинг производительности и состояния TLD системы
|
||
"""
|
||
|
||
import time
|
||
import json
|
||
import psutil
|
||
import requests
|
||
from flask import Flask, jsonify, render_template_string
|
||
|
||
app = Flask(__name__)
|
||
|
||
class TLDSystemMonitor:
|
||
def __init__(self):
|
||
self.start_time = time.time()
|
||
|
||
def get_system_stats(self):
|
||
"""Получение системной статистики"""
|
||
return {
|
||
'cpu_percent': psutil.cpu_percent(interval=1),
|
||
'memory_percent': psutil.virtual_memory().percent,
|
||
'disk_usage': psutil.disk_usage('/').percent,
|
||
'network_io': psutil.net_io_counters()._asdict(),
|
||
'uptime': time.time() - self.start_time
|
||
}
|
||
|
||
def get_tld_stats(self):
|
||
"""Получение статистики TLD системы"""
|
||
try:
|
||
response = requests.get('http://localhost:8055/metrics', timeout=5)
|
||
if response.status_code == 200:
|
||
return response.json()
|
||
except:
|
||
pass
|
||
return {}
|
||
|
||
def get_dns_stats(self):
|
||
"""Получение статистики DNS resolver"""
|
||
try:
|
||
response = requests.get('http://localhost:8055/dns/stats', timeout=5)
|
||
if response.status_code == 200:
|
||
return response.json()
|
||
except:
|
||
pass
|
||
return {}
|
||
|
||
def get_consensus_stats(self):
|
||
"""Получение статистики консенсуса"""
|
||
try:
|
||
response = requests.get('http://localhost:8055/consensus/stats', timeout=5)
|
||
if response.status_code == 200:
|
||
return response.json()
|
||
except:
|
||
pass
|
||
return {}
|
||
|
||
monitor = TLDSystemMonitor()
|
||
|
||
@app.route('/')
|
||
def dashboard():
|
||
"""Главная страница мониторинга"""
|
||
template = '''
|
||
<!DOCTYPE html>
|
||
<html>
|
||
<head>
|
||
<title>Phantom TLD System Monitor</title>
|
||
<meta charset="utf-8">
|
||
<meta http-equiv="refresh" content="5">
|
||
<style>
|
||
body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
|
||
.container { max-width: 1200px; margin: 0 auto; }
|
||
.header { background: #2c3e50; color: white; padding: 20px; border-radius: 5px; margin-bottom: 20px; }
|
||
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
|
||
.stat-card { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
|
||
.stat-title { font-size: 18px; font-weight: bold; margin-bottom: 15px; color: #2c3e50; }
|
||
.stat-value { font-size: 24px; font-weight: bold; color: #27ae60; }
|
||
.stat-label { font-size: 14px; color: #7f8c8d; }
|
||
.status-ok { color: #27ae60; }
|
||
.status-warning { color: #f39c12; }
|
||
.status-error { color: #e74c3c; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="container">
|
||
<div class="header">
|
||
<h1>🌐 Phantom TLD System Monitor</h1>
|
||
<p>Мониторинг децентрализованной системы доменов первого уровня</p>
|
||
</div>
|
||
|
||
<div class="stats-grid">
|
||
<div class="stat-card">
|
||
<div class="stat-title">Системные ресурсы</div>
|
||
<div>CPU: <span class="stat-value">{{ system_stats.cpu_percent }}%</span></div>
|
||
<div>Память: <span class="stat-value">{{ system_stats.memory_percent }}%</span></div>
|
||
<div>Диск: <span class="stat-value">{{ system_stats.disk_usage }}%</span></div>
|
||
<div>Время работы: <span class="stat-value">{{ "%.1f"|format(system_stats.uptime/3600) }} ч</span></div>
|
||
</div>
|
||
|
||
<div class="stat-card">
|
||
<div class="stat-title">DNS Resolver</div>
|
||
<div>Запросов: <span class="stat-value">{{ dns_stats.get('total_queries', 0) }}</span></div>
|
||
<div>Успешных: <span class="stat-value">{{ dns_stats.get('successful_queries', 0) }}</span></div>
|
||
<div>Кэш попаданий: <span class="stat-value">{{ dns_stats.get('cache_hits', 0) }}</span></div>
|
||
<div>Phantom запросов: <span class="stat-value">{{ dns_stats.get('phantom_queries', 0) }}</span></div>
|
||
</div>
|
||
|
||
<div class="stat-card">
|
||
<div class="stat-title">Реестр доменов</div>
|
||
<div>Всего доменов: <span class="stat-value">{{ tld_stats.get('total_domains', 0) }}</span></div>
|
||
<div>Активных шардов: <span class="stat-value">{{ tld_stats.get('active_shards', 0) }}</span></div>
|
||
<div>Попаданий кэша: <span class="stat-value">{{ tld_stats.get('cache_hit_rate', 0) }}%</span></div>
|
||
<div>Запросов в секунду: <span class="stat-value">{{ tld_stats.get('queries_per_second', 0) }}</span></div>
|
||
</div>
|
||
|
||
<div class="stat-card">
|
||
<div class="stat-title">Консенсус</div>
|
||
<div>Валидаторов: <span class="stat-value">{{ consensus_stats.get('validator_count', 0) }}</span></div>
|
||
<div>Общий залог: <span class="stat-value">{{ consensus_stats.get('total_stake', 0) }}</span></div>
|
||
<div>Активных предложений: <span class="stat-value">{{ consensus_stats.get('active_proposals', 0) }}</span></div>
|
||
<div>Сообщений отправлено: <span class="stat-value">{{ consensus_stats.get('messages_sent', 0) }}</span></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</body>
|
||
</html>
|
||
'''
|
||
|
||
return render_template_string(template,
|
||
system_stats=monitor.get_system_stats(),
|
||
tld_stats=monitor.get_tld_stats(),
|
||
dns_stats=monitor.get_dns_stats(),
|
||
consensus_stats=monitor.get_consensus_stats()
|
||
)
|
||
|
||
@app.route('/api/stats')
|
||
def api_stats():
|
||
"""API для получения статистики"""
|
||
return jsonify({
|
||
'system': monitor.get_system_stats(),
|
||
'tld': monitor.get_tld_stats(),
|
||
'dns': monitor.get_dns_stats(),
|
||
'consensus': monitor.get_consensus_stats()
|
||
})
|
||
|
||
@app.route('/health')
|
||
def health_check():
|
||
"""Проверка здоровья системы"""
|
||
system_stats = monitor.get_system_stats()
|
||
|
||
status = 'healthy'
|
||
if system_stats['cpu_percent'] > 90 or system_stats['memory_percent'] > 90:
|
||
status = 'warning'
|
||
if system_stats['disk_usage'] > 95:
|
||
status = 'critical'
|
||
|
||
return jsonify({
|
||
'status': status,
|
||
'timestamp': time.time(),
|
||
'uptime': system_stats['uptime']
|
||
})
|
||
|
||
if __name__ == '__main__':
|
||
app.run(host='0.0.0.0', port=8056, debug=False)
|
||
EOF
|
||
|
||
# Создание скрипта тестирования
|
||
RUN cat > /opt/phantom/scripts/test-tld-system.sh << 'EOF'
|
||
#!/bin/bash
|
||
|
||
echo "Тестирование Phantom TLD System..."
|
||
|
||
# Функция для проверки доступности сервиса
|
||
check_service() {
|
||
local service_name=$1
|
||
local port=$2
|
||
local max_attempts=30
|
||
local attempt=1
|
||
|
||
echo "Проверка $service_name на порту $port..."
|
||
|
||
while [ $attempt -le $max_attempts ]; do
|
||
if nc -z localhost $port 2>/dev/null; then
|
||
echo "✓ $service_name доступен"
|
||
return 0
|
||
fi
|
||
echo "Попытка $attempt/$max_attempts: $service_name недоступен"
|
||
sleep 2
|
||
attempt=$((attempt + 1))
|
||
done
|
||
|
||
echo "✗ $service_name недоступен после $max_attempts попыток"
|
||
return 1
|
||
}
|
||
|
||
# Проверка основных сервисов
|
||
check_service "DNS Resolver" 53
|
||
check_service "TLD System" 8053
|
||
check_service "Consensus" 8054
|
||
check_service "Monitoring" 8055
|
||
check_service "Health Check" 8056
|
||
|
||
# Тестирование DNS запросов
|
||
echo "Тестирование DNS запросов..."
|
||
|
||
# Тест 1: Запрос несуществующего домена
|
||
echo "Тест 1: Запрос несуществующего домена"
|
||
dig @localhost test.phantom +short || echo "Ожидаемо: домен не найден"
|
||
|
||
# Тест 2: Регистрация тестового домена
|
||
echo "Тест 2: Регистрация тестового домена"
|
||
curl -X POST http://localhost:8055/api/domains \
|
||
-H "Content-Type: application/json" \
|
||
-d '{
|
||
"domain": "test",
|
||
"tld": "phantom",
|
||
"ipv4": "192.168.1.100",
|
||
"ttl": 3600
|
||
}' || echo "Ошибка регистрации домена"
|
||
|
||
sleep 2
|
||
|
||
# Тест 3: Запрос зарегистрированного домена
|
||
echo "Тест 3: Запрос зарегистрированного домена"
|
||
dig @localhost test.phantom A +short
|
||
|
||
# Тест 4: Проверка статистики
|
||
echo "Тест 4: Проверка статистики"
|
||
curl -s http://localhost:8055/api/stats | python3 -m json.tool
|
||
|
||
# Тест 5: Проверка здоровья системы
|
||
echo "Тест 5: Проверка здоровья системы"
|
||
curl -s http://localhost:8056/health | python3 -m json.tool
|
||
|
||
echo "Тестирование завершено"
|
||
EOF
|
||
|
||
# Создание скрипта производительности
|
||
RUN cat > /opt/phantom/scripts/benchmark.sh << 'EOF'
|
||
#!/bin/bash
|
||
|
||
echo "Бенчмарк Phantom TLD System..."
|
||
|
||
# Установка инструментов для тестирования
|
||
apt-get update && apt-get install -y dnsperf bind9-utils
|
||
|
||
# Создание файла с тестовыми доменами
|
||
cat > /tmp/test-domains.txt << 'DOMAINS'
|
||
test1.phantom A
|
||
test2.phantom A
|
||
test3.phantom A
|
||
test4.phantom A
|
||
test5.phantom A
|
||
example.phantom A
|
||
demo.phantom A
|
||
benchmark.phantom A
|
||
performance.phantom A
|
||
speed.phantom A
|
||
DOMAINS
|
||
|
||
# Регистрация тестовых доменов
|
||
echo "Регистрация тестовых доменов..."
|
||
for i in {1..10}; do
|
||
curl -X POST http://localhost:8055/api/domains \
|
||
-H "Content-Type: application/json" \
|
||
-d "{
|
||
\"domain\": \"test$i\",
|
||
\"tld\": \"phantom\",
|
||
\"ipv4\": \"192.168.1.$((100+i))\",
|
||
\"ttl\": 3600
|
||
}" &
|
||
done
|
||
wait
|
||
|
||
sleep 5
|
||
|
||
# Тест производительности DNS
|
||
echo "Запуск теста производительности DNS..."
|
||
dnsperf -s localhost -d /tmp/test-domains.txt -l 30 -Q 1000
|
||
|
||
# Тест нагрузки
|
||
echo "Запуск теста нагрузки..."
|
||
for i in {1..100}; do
|
||
dig @localhost test$((i%10+1)).phantom A +short &
|
||
done
|
||
wait
|
||
|
||
# Получение финальной статистики
|
||
echo "Финальная статистика:"
|
||
curl -s http://localhost:8055/api/stats | python3 -m json.tool
|
||
|
||
echo "Бенчмарк завершен"
|
||
EOF
|
||
|
||
# Установка прав выполнения
|
||
RUN chmod +x /opt/phantom/scripts/*.sh /opt/phantom/scripts/*.py
|
||
|
||
# Создание systemd сервиса
|
||
RUN cat > /etc/systemd/system/phantom-tld-system.service << 'EOF'
|
||
[Unit]
|
||
Description=Phantom TLD System
|
||
Documentation=https://phantom-protocol.org/docs/tld-system
|
||
After=network.target
|
||
Wants=network.target
|
||
|
||
[Service]
|
||
Type=exec
|
||
User=phantom
|
||
Group=phantom
|
||
ExecStart=/opt/phantom/scripts/start-tld-system.sh
|
||
ExecReload=/bin/kill -HUP $MAINPID
|
||
KillMode=mixed
|
||
Restart=on-failure
|
||
RestartSec=5
|
||
TimeoutStopSec=30
|
||
|
||
# Безопасность
|
||
NoNewPrivileges=true
|
||
PrivateTmp=true
|
||
ProtectSystem=strict
|
||
ProtectHome=true
|
||
ReadWritePaths=/var/lib/phantom /opt/phantom/logs
|
||
|
||
# Ресурсы
|
||
LimitNOFILE=65536
|
||
LimitNPROC=32768
|
||
|
||
[Install]
|
||
WantedBy=multi-user.target
|
||
EOF
|
||
|
||
# Создание logrotate конфигурации
|
||
RUN cat > /etc/logrotate.d/phantom-tld-system << 'EOF'
|
||
/opt/phantom/logs/*.log {
|
||
daily
|
||
missingok
|
||
rotate 30
|
||
compress
|
||
delaycompress
|
||
notifempty
|
||
create 644 phantom phantom
|
||
postrotate
|
||
systemctl reload phantom-tld-system
|
||
endscript
|
||
}
|
||
EOF
|
||
|
||
# Настройка переменных окружения
|
||
ENV PHANTOM_CONFIG_DIR=/opt/phantom/config
|
||
ENV PHANTOM_DATA_DIR=/var/lib/phantom
|
||
ENV PHANTOM_LOG_DIR=/opt/phantom/logs
|
||
ENV PHANTOM_BIN_DIR=/opt/phantom/bin
|
||
|
||
# Открытие портов
|
||
EXPOSE 53/udp 53/tcp 8053 8054 8055 8056
|
||
|
||
# Создание точек монтирования
|
||
VOLUME ["/var/lib/phantom", "/opt/phantom/logs", "/opt/phantom/config"]
|
||
|
||
# Проверка здоровья
|
||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||
CMD curl -f http://localhost:8056/health || exit 1
|
||
|
||
# Установка рабочей директории
|
||
WORKDIR /opt/phantom
|
||
|
||
# Команда по умолчанию
|
||
CMD ["/opt/phantom/scripts/start-tld-system.sh"]
|
||
|