ab ovo
This commit is contained in:
82
docker-tests/Dockerfile
Normal file
82
docker-tests/Dockerfile
Normal file
@@ -0,0 +1,82 @@
|
||||
# Dockerfile for P2P Cross-Machine Testing
|
||||
#
|
||||
# Build context should be the project root (zig-p2p/)
|
||||
# Run: docker build -f docker-tests/Dockerfile -t zig-p2p-peer .
|
||||
|
||||
FROM debian:bookworm-slim AS builder
|
||||
|
||||
# Install dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
curl \
|
||||
xz-utils \
|
||||
ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Zig 0.15.2
|
||||
ARG ZIG_VERSION=0.15.2
|
||||
ARG TARGETARCH
|
||||
|
||||
# Download correct Zig for architecture
|
||||
# URL format: zig-{arch}-linux-{version}.tar.xz
|
||||
RUN set -ex; \
|
||||
case "${TARGETARCH}" in \
|
||||
amd64) ZIG_ARCH="x86_64" ;; \
|
||||
arm64) ZIG_ARCH="aarch64" ;; \
|
||||
*) echo "Unsupported architecture: ${TARGETARCH}"; exit 1 ;; \
|
||||
esac; \
|
||||
echo "Downloading Zig ${ZIG_VERSION} for ${ZIG_ARCH}-linux"; \
|
||||
curl -fsSL "https://ziglang.org/download/${ZIG_VERSION}/zig-${ZIG_ARCH}-linux-${ZIG_VERSION}.tar.xz" -o /tmp/zig.tar.xz && \
|
||||
tar -xJf /tmp/zig.tar.xz -C /opt && \
|
||||
mv /opt/zig-${ZIG_ARCH}-linux-${ZIG_VERSION} /opt/zig && \
|
||||
rm /tmp/zig.tar.xz
|
||||
|
||||
ENV PATH="/opt/zig:${PATH}"
|
||||
|
||||
# Verify Zig installation
|
||||
RUN zig version
|
||||
|
||||
# Copy source code
|
||||
WORKDIR /build
|
||||
COPY src ./src
|
||||
COPY build.zig ./build.zig
|
||||
COPY docker-tests ./docker-tests
|
||||
|
||||
# Build only the docker-peer target (not all targets to avoid needing examples/)
|
||||
RUN zig build docker-peer && \
|
||||
cp zig-out/bin/docker-peer /build/docker-peer && \
|
||||
ls -la /build/docker-peer
|
||||
|
||||
# =============================================================================
|
||||
# Runtime Stage
|
||||
# =============================================================================
|
||||
FROM debian:bookworm-slim AS runtime
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
ca-certificates \
|
||||
iproute2 \
|
||||
iputils-ping \
|
||||
net-tools \
|
||||
procps \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN useradd -m -s /bin/bash p2p
|
||||
|
||||
COPY --from=builder /build/docker-peer /usr/local/bin/docker-peer
|
||||
RUN chmod +x /usr/local/bin/docker-peer
|
||||
|
||||
RUN mkdir -p /data && chown p2p:p2p /data
|
||||
RUN mkdir -p /shared && chown p2p:p2p /shared
|
||||
|
||||
USER p2p
|
||||
WORKDIR /data
|
||||
|
||||
ENV PEER_MODE=seeder
|
||||
ENV PEER_PORT=8080
|
||||
ENV FILE_SIZE_MB=10
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
|
||||
CMD pgrep docker-peer || exit 1
|
||||
|
||||
CMD ["docker-peer"]
|
||||
195
docker-tests/README.md
Normal file
195
docker-tests/README.md
Normal file
@@ -0,0 +1,195 @@
|
||||
# P2P Cross-Machine Testing with Docker
|
||||
|
||||
This directory contains Docker-based testing infrastructure for simulating cross-machine P2P file transfers on a single host.
|
||||
|
||||
## Overview
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ p2p-test-network │
|
||||
│ (172.28.0.0/16) │
|
||||
│ │
|
||||
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
|
||||
│ │ seeder │◄───│leecher-1│ │leecher-2│ ... │
|
||||
│ │172.28.1.│ │ :8081 │ │ :8082 │ │
|
||||
│ │ :8080 │ └─────────┘ └─────────┘ │
|
||||
│ └─────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Run basic test (1 seeder, 3 leechers, 10MB file)
|
||||
./run-tests.sh
|
||||
|
||||
# Run with more leechers
|
||||
./run-tests.sh --leechers 10
|
||||
|
||||
# Run with larger file
|
||||
./run-tests.sh --file-size 100
|
||||
|
||||
# Run with network chaos (requires pumba)
|
||||
./run-tests.sh --chaos
|
||||
|
||||
# Clean up
|
||||
./run-tests.sh --clean
|
||||
```
|
||||
|
||||
## Manual Docker Commands
|
||||
|
||||
```bash
|
||||
# Build the image
|
||||
docker compose build
|
||||
|
||||
# Start services (3 leechers by default)
|
||||
docker compose up -d
|
||||
|
||||
# Scale leechers
|
||||
docker compose up -d --scale leecher=10
|
||||
|
||||
# View logs
|
||||
docker compose logs -f
|
||||
|
||||
# View specific service logs
|
||||
docker compose logs -f seeder
|
||||
docker compose logs -f leecher
|
||||
|
||||
# Stop everything
|
||||
docker compose down -v
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Environment variables (set in shell or `.env` file):
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `LEECHER_COUNT` | 3 | Number of leecher containers |
|
||||
| `FILE_SIZE_MB` | 10 | Test file size in megabytes |
|
||||
| `PIECE_SIZE_KB` | 256 | Piece size in kilobytes |
|
||||
|
||||
## Network Chaos Testing
|
||||
|
||||
For realistic network simulation, install [Pumba](https://github.com/alexei-led/pumba):
|
||||
|
||||
```bash
|
||||
# macOS
|
||||
brew install pumba
|
||||
|
||||
# Linux
|
||||
curl -L https://github.com/alexei-led/pumba/releases/download/0.9.0/pumba_linux_amd64 -o pumba
|
||||
chmod +x pumba
|
||||
sudo mv pumba /usr/local/bin/
|
||||
```
|
||||
|
||||
### Chaos Scenarios
|
||||
|
||||
```bash
|
||||
# Add 100ms latency to all leechers
|
||||
pumba netem --duration 5m delay --time 100 \
|
||||
$(docker ps -q -f "name=leecher")
|
||||
|
||||
# Add 5% packet loss
|
||||
pumba netem --duration 5m loss --percent 5 \
|
||||
$(docker ps -q -f "name=leecher")
|
||||
|
||||
# Add latency + jitter + packet loss
|
||||
pumba netem --duration 5m \
|
||||
delay --time 50 --jitter 20 \
|
||||
loss --percent 2 \
|
||||
$(docker ps -q -f "name=leecher")
|
||||
|
||||
# Bandwidth limit (1 Mbps)
|
||||
pumba netem --duration 5m rate --rate 1mbit \
|
||||
$(docker ps -q -f "name=leecher")
|
||||
```
|
||||
|
||||
## Debug Mode
|
||||
|
||||
Start with a network debugging container:
|
||||
|
||||
```bash
|
||||
# Start with debug profile
|
||||
docker compose --profile debug up -d
|
||||
|
||||
# Access the debug container
|
||||
docker exec -it p2p-monitor bash
|
||||
|
||||
# Inside debug container:
|
||||
ping seeder
|
||||
nslookup seeder
|
||||
tcpdump -i eth0 port 8080
|
||||
iperf3 -c seeder -p 8080
|
||||
```
|
||||
|
||||
## Files
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `Dockerfile` | Multi-stage build for Zig P2P peer |
|
||||
| `docker-compose.yml` | Service definitions |
|
||||
| `peer.zig` | Test peer binary source |
|
||||
| `run-tests.sh` | Test runner script |
|
||||
| `README.md` | This file |
|
||||
|
||||
## Test Scenarios
|
||||
|
||||
### Basic Transfer Test
|
||||
```bash
|
||||
./run-tests.sh --leechers 1 --file-size 10
|
||||
```
|
||||
|
||||
### Multi-Peer Scaling Test
|
||||
```bash
|
||||
./run-tests.sh --leechers 20 --file-size 50
|
||||
```
|
||||
|
||||
### Large File Test
|
||||
```bash
|
||||
./run-tests.sh --leechers 5 --file-size 500
|
||||
```
|
||||
|
||||
### Stress Test with Network Issues
|
||||
```bash
|
||||
# Terminal 1: Start test
|
||||
./run-tests.sh --leechers 10 --file-size 100
|
||||
|
||||
# Terminal 2: Add network chaos
|
||||
pumba netem --duration 10m delay --time 100 --jitter 50 loss --percent 3 \
|
||||
$(docker ps -q -f "name=leecher")
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Build fails
|
||||
```bash
|
||||
# Check Zig version matches (0.15.2)
|
||||
docker compose build --no-cache --progress=plain 2>&1 | tee build.log
|
||||
```
|
||||
|
||||
### Containers not communicating
|
||||
```bash
|
||||
# Check network
|
||||
docker network inspect docker-tests_p2p-network
|
||||
|
||||
# Check DNS resolution
|
||||
docker exec -it p2p-seeder ping leecher
|
||||
```
|
||||
|
||||
### Out of memory
|
||||
```bash
|
||||
# Check resource limits in docker-compose.yml
|
||||
# Increase Docker memory allocation in Docker Desktop settings
|
||||
```
|
||||
|
||||
## Performance Metrics
|
||||
|
||||
Expected results on a typical development machine:
|
||||
|
||||
| Scenario | Throughput | Notes |
|
||||
|----------|------------|-------|
|
||||
| 1 leecher, 10MB | 50-100 MB/s | Loopback overhead |
|
||||
| 5 leechers, 100MB | 30-50 MB/s | Concurrent transfers |
|
||||
| 10 leechers, 100MB | 20-40 MB/s | More contention |
|
||||
| With 50ms latency | 5-15 MB/s | Network delay impact |
|
||||
121
docker-tests/docker-compose.yml
Normal file
121
docker-tests/docker-compose.yml
Normal file
@@ -0,0 +1,121 @@
|
||||
# Docker Compose for P2P Cross-Machine Testing
|
||||
#
|
||||
# This creates a simulated multi-machine P2P network:
|
||||
# - 1 seeder node that shares a test file
|
||||
# - Multiple leecher nodes that download from the seeder
|
||||
# - Isolated network with DNS resolution between containers
|
||||
#
|
||||
# Usage:
|
||||
# docker compose up --build # Start all services
|
||||
# docker compose up --build --scale leecher=5 # Start with 5 leechers
|
||||
# docker compose logs -f # View logs
|
||||
# docker compose down # Stop and cleanup
|
||||
#
|
||||
# Network topology:
|
||||
# ┌─────────────────────────────────────────────────────────────┐
|
||||
# │ p2p-test-network │
|
||||
# │ (172.28.0.0/16) │
|
||||
# │ │
|
||||
# │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
|
||||
# │ │ seeder │◄───│leecher-1│ │leecher-2│ ... │
|
||||
# │ │172.28.1.│ │172.28.2.│ │172.28.3.│ │
|
||||
# │ │ :8080 │ │ :8081 │ │ :8082 │ │
|
||||
# │ └─────────┘ └─────────┘ └─────────┘ │
|
||||
# └─────────────────────────────────────────────────────────────┘
|
||||
|
||||
services:
|
||||
# ==========================================================================
|
||||
# Seeder Node - Shares the test file
|
||||
# ==========================================================================
|
||||
seeder:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker-tests/Dockerfile
|
||||
container_name: p2p-seeder
|
||||
hostname: seeder
|
||||
environment:
|
||||
- PEER_MODE=seeder
|
||||
- PEER_PORT=8080
|
||||
- FILE_SIZE_MB=${FILE_SIZE_MB:-10}
|
||||
- PIECE_SIZE_KB=${PIECE_SIZE_KB:-256}
|
||||
- LEECHER_COUNT=${LEECHER_COUNT:-3}
|
||||
networks:
|
||||
p2p-network:
|
||||
ipv4_address: 172.28.1.10
|
||||
volumes:
|
||||
- seeder-data:/data
|
||||
- shared-metadata:/shared # Shared volume for metadata exchange
|
||||
ports:
|
||||
- "8080:8080" # Expose for debugging
|
||||
healthcheck:
|
||||
test: ["CMD", "pgrep", "docker-peer"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
# ==========================================================================
|
||||
# Leecher Node(s) - Download from seeder
|
||||
# ==========================================================================
|
||||
leecher:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker-tests/Dockerfile
|
||||
hostname: leecher
|
||||
environment:
|
||||
- PEER_MODE=leecher
|
||||
- PEER_PORT=8081
|
||||
- SEEDER_HOST=seeder
|
||||
- SEEDER_PORT=8080
|
||||
- FILE_SIZE_MB=${FILE_SIZE_MB:-10}
|
||||
- PIECE_SIZE_KB=${PIECE_SIZE_KB:-256}
|
||||
networks:
|
||||
- p2p-network
|
||||
volumes:
|
||||
- shared-metadata:/shared # Shared volume for metadata exchange
|
||||
depends_on:
|
||||
seeder:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
replicas: ${LEECHER_COUNT:-3}
|
||||
resources:
|
||||
limits:
|
||||
memory: 256M
|
||||
reservations:
|
||||
memory: 128M
|
||||
|
||||
# ==========================================================================
|
||||
# Network Monitor (optional) - For debugging
|
||||
# ==========================================================================
|
||||
monitor:
|
||||
image: nicolaka/netshoot:latest
|
||||
container_name: p2p-monitor
|
||||
hostname: monitor
|
||||
networks:
|
||||
- p2p-network
|
||||
profiles:
|
||||
- debug
|
||||
command: ["sleep", "infinity"]
|
||||
# Use: docker compose --profile debug up
|
||||
# Then: docker exec -it p2p-monitor bash
|
||||
|
||||
# ==========================================================================
|
||||
# Custom Network with fixed subnet
|
||||
# ==========================================================================
|
||||
networks:
|
||||
p2p-network:
|
||||
driver: bridge
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: 172.28.0.0/16
|
||||
gateway: 172.28.0.1
|
||||
|
||||
# ==========================================================================
|
||||
# Persistent volumes for data
|
||||
# ==========================================================================
|
||||
volumes:
|
||||
seeder-data:
|
||||
driver: local
|
||||
shared-metadata:
|
||||
driver: local
|
||||
267
docker-tests/local-network-test.sh
Normal file
267
docker-tests/local-network-test.sh
Normal file
@@ -0,0 +1,267 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Local Network P2P Test using Loopback Aliases
|
||||
#
|
||||
# This creates multiple "virtual" IP addresses on the loopback interface
|
||||
# to simulate cross-machine P2P testing without Docker.
|
||||
#
|
||||
# Usage:
|
||||
# sudo ./local-network-test.sh # Run test
|
||||
# sudo ./local-network-test.sh --clean # Clean up aliases
|
||||
|
||||
set -e
|
||||
|
||||
# Colors
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m'
|
||||
|
||||
# Configuration
|
||||
SEEDER_IP="127.0.0.2"
|
||||
LEECHER1_IP="127.0.0.3"
|
||||
LEECHER2_IP="127.0.0.4"
|
||||
SEEDER_PORT=9001
|
||||
LEECHER1_PORT=9002
|
||||
LEECHER2_PORT=9003
|
||||
|
||||
print_header() {
|
||||
echo ""
|
||||
echo -e "${BLUE}========================================${NC}"
|
||||
echo -e "${BLUE} $1${NC}"
|
||||
echo -e "${BLUE}========================================${NC}"
|
||||
echo ""
|
||||
}
|
||||
|
||||
print_status() {
|
||||
echo -e "${GREEN}[✓]${NC} $1"
|
||||
}
|
||||
|
||||
print_warning() {
|
||||
echo -e "${YELLOW}[!]${NC} $1"
|
||||
}
|
||||
|
||||
print_error() {
|
||||
echo -e "${RED}[✗]${NC} $1"
|
||||
}
|
||||
|
||||
# Check if running as root
|
||||
check_root() {
|
||||
if [ "$EUID" -ne 0 ]; then
|
||||
print_error "This script requires root privileges for loopback aliases"
|
||||
echo "Please run: sudo $0"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Create loopback aliases
|
||||
setup_aliases() {
|
||||
print_header "Setting Up Loopback Aliases"
|
||||
|
||||
# Check if aliases already exist
|
||||
if ifconfig lo0 | grep -q "$SEEDER_IP"; then
|
||||
print_warning "Aliases already exist"
|
||||
return
|
||||
fi
|
||||
|
||||
# Create aliases
|
||||
ifconfig lo0 alias $SEEDER_IP
|
||||
print_status "Created alias $SEEDER_IP"
|
||||
|
||||
ifconfig lo0 alias $LEECHER1_IP
|
||||
print_status "Created alias $LEECHER1_IP"
|
||||
|
||||
ifconfig lo0 alias $LEECHER2_IP
|
||||
print_status "Created alias $LEECHER2_IP"
|
||||
|
||||
# Verify
|
||||
echo ""
|
||||
echo "Active loopback addresses:"
|
||||
ifconfig lo0 | grep "inet " | awk '{print " " $2}'
|
||||
}
|
||||
|
||||
# Remove loopback aliases
|
||||
cleanup_aliases() {
|
||||
print_header "Cleaning Up Loopback Aliases"
|
||||
|
||||
ifconfig lo0 -alias $SEEDER_IP 2>/dev/null && print_status "Removed $SEEDER_IP" || true
|
||||
ifconfig lo0 -alias $LEECHER1_IP 2>/dev/null && print_status "Removed $LEECHER1_IP" || true
|
||||
ifconfig lo0 -alias $LEECHER2_IP 2>/dev/null && print_status "Removed $LEECHER2_IP" || true
|
||||
}
|
||||
|
||||
# Clean up on exit
|
||||
cleanup() {
|
||||
print_header "Cleaning Up"
|
||||
|
||||
# Kill background processes
|
||||
if [ ! -z "$SEEDER_PID" ]; then
|
||||
kill $SEEDER_PID 2>/dev/null || true
|
||||
print_status "Stopped seeder (PID $SEEDER_PID)"
|
||||
fi
|
||||
|
||||
if [ ! -z "$LEECHER1_PID" ]; then
|
||||
kill $LEECHER1_PID 2>/dev/null || true
|
||||
print_status "Stopped leecher 1 (PID $LEECHER1_PID)"
|
||||
fi
|
||||
|
||||
if [ ! -z "$LEECHER2_PID" ]; then
|
||||
kill $LEECHER2_PID 2>/dev/null || true
|
||||
print_status "Stopped leecher 2 (PID $LEECHER2_PID)"
|
||||
fi
|
||||
|
||||
# Clean up test data
|
||||
rm -rf /tmp/p2p-test-* 2>/dev/null || true
|
||||
|
||||
# Remove aliases
|
||||
cleanup_aliases
|
||||
}
|
||||
|
||||
# Build the test binary
|
||||
build_binary() {
|
||||
print_header "Building Test Binary"
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if ! zig build docker-peer 2>/dev/null; then
|
||||
# docker-peer isn't a separate step, just build all
|
||||
zig build
|
||||
fi
|
||||
|
||||
if [ -f "zig-out/bin/docker-peer" ]; then
|
||||
print_status "Binary built: zig-out/bin/docker-peer"
|
||||
else
|
||||
print_error "Failed to build docker-peer"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Run the test
|
||||
run_test() {
|
||||
print_header "P2P Local Network Test"
|
||||
|
||||
echo "Network topology:"
|
||||
echo " Seeder: $SEEDER_IP:$SEEDER_PORT"
|
||||
echo " Leecher1: $LEECHER1_IP:$LEECHER1_PORT"
|
||||
echo " Leecher2: $LEECHER2_IP:$LEECHER2_PORT"
|
||||
echo ""
|
||||
|
||||
# Create test directories
|
||||
mkdir -p /tmp/p2p-test-seeder
|
||||
mkdir -p /tmp/p2p-test-leecher1
|
||||
mkdir -p /tmp/p2p-test-leecher2
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
BINARY="./zig-out/bin/docker-peer"
|
||||
|
||||
# Start seeder
|
||||
print_status "Starting seeder..."
|
||||
PEER_MODE=seeder \
|
||||
PEER_PORT=$SEEDER_PORT \
|
||||
FILE_SIZE_MB=5 \
|
||||
$BINARY > /tmp/p2p-test-seeder/log.txt 2>&1 &
|
||||
SEEDER_PID=$!
|
||||
print_status "Seeder started (PID $SEEDER_PID)"
|
||||
|
||||
# Wait for seeder to initialize
|
||||
sleep 3
|
||||
|
||||
# Check if seeder is still running
|
||||
if ! kill -0 $SEEDER_PID 2>/dev/null; then
|
||||
print_error "Seeder crashed!"
|
||||
cat /tmp/p2p-test-seeder/log.txt
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Start leecher 1
|
||||
print_status "Starting leecher 1..."
|
||||
PEER_MODE=leecher \
|
||||
PEER_PORT=$LEECHER1_PORT \
|
||||
SEEDER_HOST=$SEEDER_IP \
|
||||
SEEDER_PORT=$SEEDER_PORT \
|
||||
FILE_SIZE_MB=5 \
|
||||
$BINARY > /tmp/p2p-test-leecher1/log.txt 2>&1 &
|
||||
LEECHER1_PID=$!
|
||||
print_status "Leecher 1 started (PID $LEECHER1_PID)"
|
||||
|
||||
# Start leecher 2
|
||||
print_status "Starting leecher 2..."
|
||||
PEER_MODE=leecher \
|
||||
PEER_PORT=$LEECHER2_PORT \
|
||||
SEEDER_HOST=$SEEDER_IP \
|
||||
SEEDER_PORT=$SEEDER_PORT \
|
||||
FILE_SIZE_MB=5 \
|
||||
$BINARY > /tmp/p2p-test-leecher2/log.txt 2>&1 &
|
||||
LEECHER2_PID=$!
|
||||
print_status "Leecher 2 started (PID $LEECHER2_PID)"
|
||||
|
||||
# Monitor for 30 seconds
|
||||
print_header "Monitoring Test (30 seconds)"
|
||||
|
||||
for i in {1..6}; do
|
||||
sleep 5
|
||||
echo "--- Progress at ${i}0 seconds ---"
|
||||
|
||||
# Check if processes are still running
|
||||
if kill -0 $SEEDER_PID 2>/dev/null; then
|
||||
echo "Seeder: Running"
|
||||
tail -3 /tmp/p2p-test-seeder/log.txt 2>/dev/null | sed 's/^/ /'
|
||||
else
|
||||
echo "Seeder: Stopped"
|
||||
fi
|
||||
|
||||
if kill -0 $LEECHER1_PID 2>/dev/null; then
|
||||
echo "Leecher 1: Running"
|
||||
tail -3 /tmp/p2p-test-leecher1/log.txt 2>/dev/null | sed 's/^/ /'
|
||||
else
|
||||
echo "Leecher 1: Stopped"
|
||||
fi
|
||||
|
||||
if kill -0 $LEECHER2_PID 2>/dev/null; then
|
||||
echo "Leecher 2: Running"
|
||||
tail -3 /tmp/p2p-test-leecher2/log.txt 2>/dev/null | sed 's/^/ /'
|
||||
else
|
||||
echo "Leecher 2: Stopped"
|
||||
fi
|
||||
echo ""
|
||||
done
|
||||
|
||||
print_header "Test Complete"
|
||||
|
||||
# Show final logs
|
||||
echo "=== Seeder Final Log ==="
|
||||
tail -20 /tmp/p2p-test-seeder/log.txt 2>/dev/null
|
||||
echo ""
|
||||
echo "=== Leecher 1 Final Log ==="
|
||||
tail -20 /tmp/p2p-test-leecher1/log.txt 2>/dev/null
|
||||
echo ""
|
||||
echo "=== Leecher 2 Final Log ==="
|
||||
tail -20 /tmp/p2p-test-leecher2/log.txt 2>/dev/null
|
||||
}
|
||||
|
||||
# Main
|
||||
case "${1:-}" in
|
||||
--clean)
|
||||
check_root
|
||||
cleanup_aliases
|
||||
;;
|
||||
--help|-h)
|
||||
echo "Local Network P2P Test"
|
||||
echo ""
|
||||
echo "Usage: sudo $0 [OPTIONS]"
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " --clean Remove loopback aliases only"
|
||||
echo " --help Show this help"
|
||||
echo ""
|
||||
echo "This script creates loopback aliases to simulate multiple"
|
||||
echo "machines on a single host for P2P testing."
|
||||
;;
|
||||
*)
|
||||
check_root
|
||||
trap cleanup EXIT
|
||||
build_binary
|
||||
setup_aliases
|
||||
run_test
|
||||
;;
|
||||
esac
|
||||
629
docker-tests/peer.zig
Normal file
629
docker-tests/peer.zig
Normal file
@@ -0,0 +1,629 @@
|
||||
//! Docker P2P Test Peer
|
||||
//!
|
||||
//! A simple peer binary that can act as either a seeder or leecher.
|
||||
//! Controlled via environment variables:
|
||||
//! - PEER_MODE: "seeder" or "leecher"
|
||||
//! - PEER_PORT: Port to listen on (default: 8080)
|
||||
//! - SEEDER_HOST: Host of seeder to connect to (for leecher mode)
|
||||
//! - SEEDER_PORT: Port of seeder (for leecher mode)
|
||||
//! - FILE_SIZE_MB: Size of test file in MB (default: 10)
|
||||
|
||||
const std = @import("std");
|
||||
const p2p = @import("p2p");
|
||||
const files = @import("files");
|
||||
const core = @import("core");
|
||||
|
||||
const P2P = p2p.P2P;
|
||||
const P2PConfig = p2p.P2PConfig;
|
||||
const Address = core.Address;
|
||||
const FileMetadata = files.hash.FileMetadata;
|
||||
|
||||
const METADATA_PATH = "/shared/metadata.bin";
|
||||
const DOWNLOAD_PATH = "/data/downloaded_file.bin";
|
||||
|
||||
pub fn main() !void {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const allocator = gpa.allocator();
|
||||
|
||||
// Parse environment variables
|
||||
const mode = std.posix.getenv("PEER_MODE") orelse "seeder";
|
||||
const port_str = std.posix.getenv("PEER_PORT") orelse "8080";
|
||||
const port = std.fmt.parseInt(u16, port_str, 10) catch 8080;
|
||||
const file_size_str = std.posix.getenv("FILE_SIZE_MB") orelse "10";
|
||||
const file_size_mb = std.fmt.parseInt(u64, file_size_str, 10) catch 10;
|
||||
|
||||
const file_size = file_size_mb * 1024 * 1024;
|
||||
|
||||
std.debug.print("\n", .{});
|
||||
std.debug.print("========================================\n", .{});
|
||||
std.debug.print(" P2P Docker Test Peer\n", .{});
|
||||
std.debug.print("========================================\n", .{});
|
||||
std.debug.print("Mode: {s}\n", .{mode});
|
||||
std.debug.print("Port: {}\n", .{port});
|
||||
std.debug.print("File Size: {} MB\n", .{file_size_mb});
|
||||
std.debug.print("========================================\n\n", .{});
|
||||
|
||||
if (std.mem.eql(u8, mode, "seeder")) {
|
||||
const leecher_count_str = std.posix.getenv("LEECHER_COUNT") orelse "3";
|
||||
const leecher_count = std.fmt.parseInt(u32, leecher_count_str, 10) catch 3;
|
||||
try runSeeder(allocator, port, file_size, leecher_count);
|
||||
} else if (std.mem.eql(u8, mode, "leecher")) {
|
||||
const seeder_host = std.posix.getenv("SEEDER_HOST") orelse "seeder";
|
||||
const seeder_port_str = std.posix.getenv("SEEDER_PORT") orelse "8080";
|
||||
const seeder_port = std.fmt.parseInt(u16, seeder_port_str, 10) catch 8080;
|
||||
try runLeecher(allocator, port, seeder_host, seeder_port, file_size);
|
||||
} else {
|
||||
std.debug.print("ERROR: Unknown mode '{s}'. Use 'seeder' or 'leecher'\n", .{mode});
|
||||
return error.InvalidMode;
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize FileMetadata to a binary format
|
||||
fn serializeMetadata(metadata: FileMetadata, allocator: std.mem.Allocator) ![]u8 {
|
||||
// Format: name_len(4) + name + size(8) + piece_count(4) + created_at(8) + modified_at(8) + piece_hashes
|
||||
const name_len: u32 = @intCast(metadata.name.len);
|
||||
const total_size = 4 + metadata.name.len + 8 + 4 + 8 + 8 + (metadata.piece_count * 32);
|
||||
|
||||
const buffer = try allocator.alloc(u8, total_size);
|
||||
var offset: usize = 0;
|
||||
|
||||
// Name length and name
|
||||
@memcpy(buffer[offset .. offset + 4], std.mem.asBytes(&name_len));
|
||||
offset += 4;
|
||||
@memcpy(buffer[offset .. offset + metadata.name.len], metadata.name);
|
||||
offset += metadata.name.len;
|
||||
|
||||
// Size
|
||||
@memcpy(buffer[offset .. offset + 8], std.mem.asBytes(&metadata.size));
|
||||
offset += 8;
|
||||
|
||||
// Piece count
|
||||
@memcpy(buffer[offset .. offset + 4], std.mem.asBytes(&metadata.piece_count));
|
||||
offset += 4;
|
||||
|
||||
// Created at
|
||||
@memcpy(buffer[offset .. offset + 8], std.mem.asBytes(&metadata.created_at));
|
||||
offset += 8;
|
||||
|
||||
// Modified at
|
||||
@memcpy(buffer[offset .. offset + 8], std.mem.asBytes(&metadata.modified_at));
|
||||
offset += 8;
|
||||
|
||||
// Piece hashes
|
||||
for (metadata.piece_hashes) |hash| {
|
||||
@memcpy(buffer[offset .. offset + 32], &hash);
|
||||
offset += 32;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// Deserialize FileMetadata from binary format
|
||||
fn deserializeMetadata(data: []const u8, allocator: std.mem.Allocator) !FileMetadata {
|
||||
var offset: usize = 0;
|
||||
|
||||
// Name length and name
|
||||
const name_len = std.mem.bytesToValue(u32, data[offset .. offset + 4][0..4]);
|
||||
offset += 4;
|
||||
const name = try allocator.dupe(u8, data[offset .. offset + name_len]);
|
||||
offset += name_len;
|
||||
|
||||
// Size
|
||||
const size = std.mem.bytesToValue(u64, data[offset .. offset + 8][0..8]);
|
||||
offset += 8;
|
||||
|
||||
// Piece count
|
||||
const piece_count = std.mem.bytesToValue(u32, data[offset .. offset + 4][0..4]);
|
||||
offset += 4;
|
||||
|
||||
// Created at
|
||||
const created_at = std.mem.bytesToValue(i64, data[offset .. offset + 8][0..8]);
|
||||
offset += 8;
|
||||
|
||||
// Modified at
|
||||
const modified_at = std.mem.bytesToValue(i64, data[offset .. offset + 8][0..8]);
|
||||
offset += 8;
|
||||
|
||||
// Piece hashes
|
||||
const piece_hashes = try allocator.alloc([32]u8, piece_count);
|
||||
for (0..piece_count) |i| {
|
||||
@memcpy(&piece_hashes[i], data[offset .. offset + 32][0..32]);
|
||||
offset += 32;
|
||||
}
|
||||
|
||||
return FileMetadata{
|
||||
.name = name,
|
||||
.size = size,
|
||||
.piece_count = piece_count,
|
||||
.piece_hashes = piece_hashes,
|
||||
.created_at = created_at,
|
||||
.modified_at = modified_at,
|
||||
};
|
||||
}
|
||||
|
||||
fn runSeeder(allocator: std.mem.Allocator, port: u16, file_size: u64, expected_leechers: u32) !void {
|
||||
std.debug.print("[SEEDER] Starting seeder on port {}...\n", .{port});
|
||||
std.debug.print("[SEEDER] Expecting {} leecher(s) to complete download\n", .{expected_leechers});
|
||||
|
||||
// Create directories
|
||||
std.fs.cwd().makeDir("data") catch |e| switch (e) {
|
||||
error.PathAlreadyExists => {},
|
||||
else => return e,
|
||||
};
|
||||
|
||||
// Ensure /shared exists (Docker volume)
|
||||
std.fs.makeDirAbsolute("/shared") catch |e| switch (e) {
|
||||
error.PathAlreadyExists => {},
|
||||
else => {
|
||||
std.debug.print("[SEEDER] Warning: Could not create /shared: {}\n", .{e});
|
||||
},
|
||||
};
|
||||
|
||||
// Create test file with deterministic content
|
||||
const test_file = "/data/data/test_file.bin";
|
||||
|
||||
// Make parent directory
|
||||
std.fs.makeDirAbsolute("/data/data") catch |e| switch (e) {
|
||||
error.PathAlreadyExists => {},
|
||||
else => return e,
|
||||
};
|
||||
|
||||
std.debug.print("[SEEDER] Creating test file: {} bytes...\n", .{file_size});
|
||||
|
||||
{
|
||||
const file = try std.fs.createFileAbsolute(test_file, .{});
|
||||
defer file.close();
|
||||
|
||||
// Write deterministic pattern
|
||||
var buffer: [4096]u8 = undefined;
|
||||
var written: u64 = 0;
|
||||
var chunk_num: u64 = 0;
|
||||
while (written < file_size) {
|
||||
const remaining = file_size - written;
|
||||
const to_write = @min(buffer.len, remaining);
|
||||
|
||||
// Fill buffer with pattern based on position
|
||||
for (buffer[0..to_write], 0..) |*b, i| {
|
||||
b.* = @truncate((chunk_num * buffer.len + i) % 251);
|
||||
}
|
||||
|
||||
try file.writeAll(buffer[0..to_write]);
|
||||
written += to_write;
|
||||
chunk_num += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate file hash for verification
|
||||
var hasher = std.crypto.hash.sha2.Sha256.init(.{});
|
||||
{
|
||||
const file = try std.fs.openFileAbsolute(test_file, .{});
|
||||
defer file.close();
|
||||
|
||||
var buffer: [8192]u8 = undefined;
|
||||
while (true) {
|
||||
const n = try file.read(&buffer);
|
||||
if (n == 0) break;
|
||||
hasher.update(buffer[0..n]);
|
||||
}
|
||||
}
|
||||
const file_hash = hasher.finalResult();
|
||||
std.debug.print("[SEEDER] File created. Hash: {x}\n", .{file_hash});
|
||||
|
||||
// Initialize P2P library
|
||||
var config = P2PConfig.default();
|
||||
config.network.listen_port = port;
|
||||
config.network.enable_nat_traversal = false;
|
||||
// Allow more simultaneous connections for multi-peer testing
|
||||
config.network.connection_rate_limit = 100;
|
||||
config.network.connection_burst_size = 50;
|
||||
config.file_sharing.allowed_share_directories = &[_][]const u8{ "/data", "/data/data", ".", "data" };
|
||||
config.file_sharing.temp_dir = "/data/temp";
|
||||
|
||||
var p2p_instance = P2P.init(allocator, config) catch |e| {
|
||||
std.debug.print("[SEEDER] Failed to initialize P2P: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
defer p2p_instance.deinit();
|
||||
|
||||
p2p_instance.start() catch |e| {
|
||||
std.debug.print("[SEEDER] Failed to start P2P: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
defer p2p_instance.stop() catch {};
|
||||
|
||||
// Start listening on all interfaces
|
||||
const listen_addr = Address.ipv4(.{ 0, 0, 0, 0 }, port);
|
||||
p2p_instance.startListening(listen_addr) catch |e| {
|
||||
std.debug.print("[SEEDER] Failed to start listening: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
std.debug.print("[SEEDER] Listening on 0.0.0.0:{}\n", .{port});
|
||||
|
||||
// Share the file
|
||||
const session_id = p2p_instance.addFile(test_file) catch |e| {
|
||||
std.debug.print("[SEEDER] Failed to add file: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
std.debug.print("[SEEDER] File shared with session ID: {}\n", .{session_id});
|
||||
|
||||
// Start sharing
|
||||
p2p_instance.startSharing(session_id) catch |e| {
|
||||
std.debug.print("[SEEDER] Failed to start sharing: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
|
||||
// Get file metadata and save to shared volume
|
||||
const metadata = p2p_instance.getFileMetadata(session_id) catch |e| {
|
||||
std.debug.print("[SEEDER] Failed to get metadata: {}\n", .{e});
|
||||
return e;
|
||||
} orelse {
|
||||
std.debug.print("[SEEDER] No metadata found for session\n", .{});
|
||||
return error.MetadataNotFound;
|
||||
};
|
||||
|
||||
std.debug.print("[SEEDER] Got metadata - name: {s}, size: {}, pieces: {}\n", .{
|
||||
metadata.name,
|
||||
metadata.size,
|
||||
metadata.piece_count,
|
||||
});
|
||||
|
||||
// Serialize and save metadata
|
||||
const serialized = try serializeMetadata(metadata, allocator);
|
||||
defer allocator.free(serialized);
|
||||
|
||||
{
|
||||
const meta_file = std.fs.createFileAbsolute(METADATA_PATH, .{}) catch |e| {
|
||||
std.debug.print("[SEEDER] Failed to create metadata file: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
defer meta_file.close();
|
||||
try meta_file.writeAll(serialized);
|
||||
}
|
||||
std.debug.print("[SEEDER] Metadata saved to {s} ({} bytes)\n", .{ METADATA_PATH, serialized.len });
|
||||
|
||||
// Ready to serve
|
||||
std.debug.print("\n[SEEDER] Ready to serve file!\n", .{});
|
||||
std.debug.print("[SEEDER] Expected hash: {x}\n", .{file_hash});
|
||||
|
||||
// Calculate expected total upload (file_size * number of leechers)
|
||||
const expected_upload = file_size * expected_leechers;
|
||||
std.debug.print("[SEEDER] Will exit after uploading {} bytes ({} MB) to {} leecher(s)\n", .{
|
||||
expected_upload,
|
||||
expected_upload / (1024 * 1024),
|
||||
expected_leechers,
|
||||
});
|
||||
|
||||
// Run main loop
|
||||
var stats_timer: u64 = 0;
|
||||
var last_uploaded: u64 = 0;
|
||||
var upload_target_reached = false;
|
||||
var time_since_target: u64 = 0;
|
||||
var had_connections = false;
|
||||
const max_test_duration: u64 = 300; // 5 minute max
|
||||
const max_wait_after_target: u64 = 120; // 2 minutes max after target reached
|
||||
|
||||
var update_counter: u64 = 0;
|
||||
while (stats_timer < max_test_duration) {
|
||||
// Fast update loop - 10ms for high throughput
|
||||
std.Thread.sleep(10 * std.time.ns_per_ms);
|
||||
update_counter += 1;
|
||||
|
||||
// Process events
|
||||
while (p2p_instance.getEventCount() > 0) {
|
||||
if (p2p_instance.getNextEvent()) |event| {
|
||||
std.debug.print("[SEEDER] Event: {}\n", .{event.event_type});
|
||||
}
|
||||
}
|
||||
|
||||
// Call update to process network activity
|
||||
p2p_instance.update() catch {};
|
||||
|
||||
// Increment stats timer every 100 updates (= 1 second)
|
||||
if (update_counter % 100 == 0) {
|
||||
stats_timer += 1;
|
||||
}
|
||||
|
||||
const stats = p2p_instance.getStats();
|
||||
const uploaded = stats.total_uploaded.load(.acquire);
|
||||
const connections = stats.active_connections.load(.acquire);
|
||||
|
||||
// Track if we ever had connections
|
||||
if (connections > 0) {
|
||||
had_connections = true;
|
||||
}
|
||||
|
||||
// Print stats every 5 seconds (500 updates)
|
||||
if (update_counter % 500 == 0) {
|
||||
const speed = (uploaded - last_uploaded) / 5;
|
||||
last_uploaded = uploaded;
|
||||
const progress: f32 = if (expected_upload > 0)
|
||||
@as(f32, @floatFromInt(uploaded)) / @as(f32, @floatFromInt(expected_upload)) * 100.0
|
||||
else
|
||||
0.0;
|
||||
std.debug.print("[SEEDER] Stats - Connections: {}, Uploaded: {} / {} bytes ({d:.1}%), {} KB/s, Uptime: {}s\n", .{
|
||||
connections,
|
||||
uploaded,
|
||||
expected_upload,
|
||||
progress,
|
||||
speed / 1024,
|
||||
stats_timer,
|
||||
});
|
||||
}
|
||||
|
||||
// Check if we've uploaded enough data (queued)
|
||||
if (uploaded >= expected_upload and !upload_target_reached) {
|
||||
upload_target_reached = true;
|
||||
std.debug.print("\n[SEEDER] Upload target reached! Waiting for all leechers to complete...\n", .{});
|
||||
}
|
||||
|
||||
if (upload_target_reached) {
|
||||
time_since_target += 1;
|
||||
|
||||
// Success: All peers disconnected after we had connections
|
||||
if (had_connections and connections == 0) {
|
||||
std.debug.print("[SEEDER] All leechers disconnected. Test PASSED!\n", .{});
|
||||
std.debug.print("[SEEDER] Successfully uploaded {} bytes to {} leecher(s)\n", .{
|
||||
uploaded,
|
||||
expected_leechers,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
// Timeout waiting for peers to disconnect
|
||||
if (time_since_target >= max_wait_after_target) {
|
||||
std.debug.print("[SEEDER] Timeout waiting for leechers to complete. {} connections still active.\n", .{connections});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (stats_timer >= max_test_duration) {
|
||||
const stats = p2p_instance.getStats();
|
||||
const uploaded = stats.total_uploaded.load(.acquire);
|
||||
std.debug.print("[SEEDER] Test TIMEOUT after {} seconds. Uploaded {} / {} bytes\n", .{
|
||||
stats_timer,
|
||||
uploaded,
|
||||
expected_upload,
|
||||
});
|
||||
}
|
||||
|
||||
std.debug.print("\n[SEEDER] Shutting down...\n", .{});
|
||||
}
|
||||
|
||||
fn runLeecher(
|
||||
allocator: std.mem.Allocator,
|
||||
port: u16,
|
||||
seeder_host: []const u8,
|
||||
seeder_port: u16,
|
||||
file_size: u64,
|
||||
) !void {
|
||||
std.debug.print("[LEECHER] Starting leecher on port {}...\n", .{port});
|
||||
std.debug.print("[LEECHER] Will connect to seeder at {s}:{}\n", .{ seeder_host, seeder_port });
|
||||
|
||||
// Create directories
|
||||
std.fs.makeDirAbsolute("/data/data") catch |e| switch (e) {
|
||||
error.PathAlreadyExists => {},
|
||||
else => return e,
|
||||
};
|
||||
|
||||
// Wait for metadata file from seeder
|
||||
std.debug.print("[LEECHER] Waiting for metadata file...\n", .{});
|
||||
var wait_count: u32 = 0;
|
||||
while (wait_count < 30) {
|
||||
if (std.fs.openFileAbsolute(METADATA_PATH, .{})) |file| {
|
||||
file.close();
|
||||
break;
|
||||
} else |_| {
|
||||
std.Thread.sleep(1 * std.time.ns_per_s);
|
||||
wait_count += 1;
|
||||
if (wait_count % 5 == 0) {
|
||||
std.debug.print("[LEECHER] Still waiting for metadata... ({} seconds)\n", .{wait_count});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (wait_count >= 30) {
|
||||
std.debug.print("[LEECHER] Timeout waiting for metadata file\n", .{});
|
||||
return error.MetadataTimeout;
|
||||
}
|
||||
|
||||
// Read and deserialize metadata
|
||||
std.debug.print("[LEECHER] Reading metadata...\n", .{});
|
||||
const metadata_data = blk: {
|
||||
const file = try std.fs.openFileAbsolute(METADATA_PATH, .{});
|
||||
defer file.close();
|
||||
const stat = try file.stat();
|
||||
const data = try allocator.alloc(u8, stat.size);
|
||||
_ = try file.readAll(data);
|
||||
break :blk data;
|
||||
};
|
||||
defer allocator.free(metadata_data);
|
||||
|
||||
const metadata = try deserializeMetadata(metadata_data, allocator);
|
||||
std.debug.print("[LEECHER] Got metadata - name: {s}, size: {}, pieces: {}\n", .{
|
||||
metadata.name,
|
||||
metadata.size,
|
||||
metadata.piece_count,
|
||||
});
|
||||
|
||||
// Initialize P2P library
|
||||
var config = P2PConfig.default();
|
||||
config.network.listen_port = port;
|
||||
config.network.enable_nat_traversal = false;
|
||||
config.file_sharing.allowed_share_directories = &[_][]const u8{ "/data", "/data/data", ".", "data" };
|
||||
config.file_sharing.temp_dir = "/data/temp";
|
||||
|
||||
var p2p_instance = P2P.init(allocator, config) catch |e| {
|
||||
std.debug.print("[LEECHER] Failed to initialize P2P: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
defer p2p_instance.deinit();
|
||||
|
||||
p2p_instance.start() catch |e| {
|
||||
std.debug.print("[LEECHER] Failed to start P2P: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
defer p2p_instance.stop() catch {};
|
||||
|
||||
std.debug.print("[LEECHER] P2P library started\n", .{});
|
||||
|
||||
// Start download BEFORE connecting (so we can receive bitfield)
|
||||
std.debug.print("[LEECHER] Starting download to {s}...\n", .{DOWNLOAD_PATH});
|
||||
const download_session_id = p2p_instance.downloadFile(metadata, DOWNLOAD_PATH) catch |e| {
|
||||
std.debug.print("[LEECHER] Failed to start download: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
std.debug.print("[LEECHER] Download session created: {}\n", .{download_session_id});
|
||||
|
||||
// Resolve and connect to seeder
|
||||
std.debug.print("[LEECHER] Resolving seeder address...\n", .{});
|
||||
const seeder_addr = blk: {
|
||||
const addr_list = std.net.getAddressList(allocator, seeder_host, seeder_port) catch |e| {
|
||||
std.debug.print("[LEECHER] DNS lookup failed: {}\n", .{e});
|
||||
const addr = std.net.Address.parseIp4(seeder_host, seeder_port) catch |e2| {
|
||||
std.debug.print("[LEECHER] IP parse failed: {}\n", .{e2});
|
||||
return e;
|
||||
};
|
||||
break :blk addr;
|
||||
};
|
||||
defer addr_list.deinit();
|
||||
|
||||
if (addr_list.addrs.len == 0) {
|
||||
std.debug.print("[LEECHER] No addresses found\n", .{});
|
||||
return error.AddressNotFound;
|
||||
}
|
||||
break :blk addr_list.addrs[0];
|
||||
};
|
||||
|
||||
const core_addr = Address.ipv4(
|
||||
@bitCast(seeder_addr.in.sa.addr),
|
||||
seeder_addr.getPort(),
|
||||
);
|
||||
|
||||
std.debug.print("[LEECHER] Connecting to seeder...\n", .{});
|
||||
const peer_id = p2p_instance.connectToPeer(core_addr) catch |e| {
|
||||
std.debug.print("[LEECHER] Failed to connect: {}\n", .{e});
|
||||
return e;
|
||||
};
|
||||
std.debug.print("[LEECHER] Connected! Peer ID: {x}\n", .{peer_id.bytes[0..8].*});
|
||||
|
||||
// Monitor download progress
|
||||
const start_time = std.time.milliTimestamp();
|
||||
var download_complete = false;
|
||||
var last_downloaded: u64 = 0;
|
||||
|
||||
var last_progress_time: i64 = 0;
|
||||
while (!download_complete) {
|
||||
// Fast update loop - 10ms for high throughput
|
||||
std.Thread.sleep(10 * std.time.ns_per_ms);
|
||||
|
||||
// Process events
|
||||
while (p2p_instance.getNextEvent()) |event| {
|
||||
std.debug.print("[LEECHER] Event: {}\n", .{event.event_type});
|
||||
if (event.event_type == .file_download_completed) {
|
||||
download_complete = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Call update to process network activity
|
||||
p2p_instance.update() catch {};
|
||||
|
||||
const elapsed = std.time.milliTimestamp() - start_time;
|
||||
// Print progress every 2 seconds
|
||||
if (elapsed - last_progress_time >= 2000) {
|
||||
last_progress_time = elapsed;
|
||||
const stats = p2p_instance.getStats();
|
||||
const downloaded = stats.total_downloaded.load(.acquire);
|
||||
const speed = if (elapsed > 0) @as(u64, @intCast(downloaded)) * 1000 / @as(u64, @intCast(elapsed)) else 0;
|
||||
|
||||
// Calculate progress
|
||||
const progress = if (file_size > 0)
|
||||
@as(f32, @floatFromInt(downloaded)) / @as(f32, @floatFromInt(file_size)) * 100.0
|
||||
else
|
||||
0.0;
|
||||
|
||||
std.debug.print("[LEECHER] Progress: {d:.1}% ({} / {} bytes) - {} KB/s\n", .{
|
||||
progress,
|
||||
downloaded,
|
||||
file_size,
|
||||
speed / 1024,
|
||||
});
|
||||
|
||||
// Check if download is complete by bytes
|
||||
if (downloaded >= file_size) {
|
||||
std.debug.print("[LEECHER] Download appears complete by size!\n", .{});
|
||||
download_complete = true;
|
||||
}
|
||||
|
||||
last_downloaded = downloaded;
|
||||
}
|
||||
|
||||
// Timeout after 120 seconds
|
||||
if (elapsed > 120000) {
|
||||
std.debug.print("[LEECHER] Download timeout after 120 seconds\n", .{});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Verify downloaded file
|
||||
if (download_complete) {
|
||||
std.debug.print("\n[LEECHER] Verifying downloaded file...\n", .{});
|
||||
|
||||
var hasher = std.crypto.hash.sha2.Sha256.init(.{});
|
||||
{
|
||||
const file = std.fs.openFileAbsolute(DOWNLOAD_PATH, .{}) catch |e| {
|
||||
std.debug.print("[LEECHER] Could not open downloaded file: {}\n", .{e});
|
||||
return;
|
||||
};
|
||||
defer file.close();
|
||||
|
||||
var buffer: [8192]u8 = undefined;
|
||||
while (true) {
|
||||
const n = file.read(&buffer) catch break;
|
||||
if (n == 0) break;
|
||||
hasher.update(buffer[0..n]);
|
||||
}
|
||||
}
|
||||
const downloaded_hash = hasher.finalResult();
|
||||
|
||||
// Compare with expected (generate expected hash same way as seeder)
|
||||
var expected_hasher = std.crypto.hash.sha2.Sha256.init(.{});
|
||||
{
|
||||
var buffer: [4096]u8 = undefined;
|
||||
var written: u64 = 0;
|
||||
var chunk_num: u64 = 0;
|
||||
while (written < file_size) {
|
||||
const remaining = file_size - written;
|
||||
const to_write = @min(buffer.len, remaining);
|
||||
|
||||
for (buffer[0..to_write], 0..) |*b, i| {
|
||||
b.* = @truncate((chunk_num * buffer.len + i) % 251);
|
||||
}
|
||||
|
||||
expected_hasher.update(buffer[0..to_write]);
|
||||
written += to_write;
|
||||
chunk_num += 1;
|
||||
}
|
||||
}
|
||||
const expected_hash = expected_hasher.finalResult();
|
||||
|
||||
std.debug.print("[LEECHER] Downloaded hash: {x}\n", .{downloaded_hash});
|
||||
std.debug.print("[LEECHER] Expected hash: {x}\n", .{expected_hash});
|
||||
|
||||
if (std.mem.eql(u8, &downloaded_hash, &expected_hash)) {
|
||||
std.debug.print("\n[LEECHER] SUCCESS! File verified correctly!\n", .{});
|
||||
} else {
|
||||
std.debug.print("\n[LEECHER] FAILED! Hash mismatch!\n", .{});
|
||||
}
|
||||
}
|
||||
|
||||
const total_time = std.time.milliTimestamp() - start_time;
|
||||
const stats = p2p_instance.getStats();
|
||||
const total_downloaded = stats.total_downloaded.load(.acquire);
|
||||
const avg_speed = if (total_time > 0) total_downloaded * 1000 / @as(u64, @intCast(total_time)) else 0;
|
||||
|
||||
std.debug.print("\n[LEECHER] Test complete.\n", .{});
|
||||
std.debug.print("[LEECHER] Total downloaded: {} bytes in {} ms\n", .{ total_downloaded, total_time });
|
||||
std.debug.print("[LEECHER] Average speed: {} KB/s ({} MB/s)\n", .{ avg_speed / 1024, avg_speed / (1024 * 1024) });
|
||||
}
|
||||
216
docker-tests/run-tests.sh
Executable file
216
docker-tests/run-tests.sh
Executable file
@@ -0,0 +1,216 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# P2P Cross-Machine Test Runner
|
||||
#
|
||||
# This script builds and runs the Docker-based P2P tests with various configurations.
|
||||
#
|
||||
# Usage:
|
||||
# ./run-tests.sh # Run basic test (1 seeder, 3 leechers)
|
||||
# ./run-tests.sh --leechers 10 # Run with 10 leechers
|
||||
# ./run-tests.sh --file-size 100 # Run with 100MB file
|
||||
# ./run-tests.sh --chaos # Run with network chaos (requires pumba)
|
||||
# ./run-tests.sh --clean # Clean up everything
|
||||
|
||||
set -e
|
||||
|
||||
# Colors for output
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Default values
|
||||
LEECHER_COUNT=3
|
||||
FILE_SIZE_MB=10
|
||||
PIECE_SIZE_KB=256
|
||||
ENABLE_CHAOS=false
|
||||
CLEAN_ONLY=false
|
||||
DEBUG_MODE=false
|
||||
|
||||
# Parse arguments
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--leechers|-l)
|
||||
LEECHER_COUNT="$2"
|
||||
shift 2
|
||||
;;
|
||||
--file-size|-f)
|
||||
FILE_SIZE_MB="$2"
|
||||
shift 2
|
||||
;;
|
||||
--piece-size|-p)
|
||||
PIECE_SIZE_KB="$2"
|
||||
shift 2
|
||||
;;
|
||||
--chaos|-c)
|
||||
ENABLE_CHAOS=true
|
||||
shift
|
||||
;;
|
||||
--clean)
|
||||
CLEAN_ONLY=true
|
||||
shift
|
||||
;;
|
||||
--debug|-d)
|
||||
DEBUG_MODE=true
|
||||
shift
|
||||
;;
|
||||
--help|-h)
|
||||
echo "P2P Cross-Machine Test Runner"
|
||||
echo ""
|
||||
echo "Usage: $0 [OPTIONS]"
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " --leechers, -l NUM Number of leecher nodes (default: 3)"
|
||||
echo " --file-size, -f MB Test file size in MB (default: 10)"
|
||||
echo " --piece-size, -p KB Piece size in KB (default: 256)"
|
||||
echo " --chaos, -c Enable network chaos testing"
|
||||
echo " --debug, -d Start debug monitor container"
|
||||
echo " --clean Clean up containers and volumes"
|
||||
echo " --help, -h Show this help"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo -e "${RED}Unknown option: $1${NC}"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Change to docker-tests directory
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
# Export environment variables for docker-compose
|
||||
export LEECHER_COUNT
|
||||
export FILE_SIZE_MB
|
||||
export PIECE_SIZE_KB
|
||||
|
||||
print_header() {
|
||||
echo ""
|
||||
echo -e "${BLUE}========================================${NC}"
|
||||
echo -e "${BLUE} $1${NC}"
|
||||
echo -e "${BLUE}========================================${NC}"
|
||||
echo ""
|
||||
}
|
||||
|
||||
print_status() {
|
||||
echo -e "${GREEN}[✓]${NC} $1"
|
||||
}
|
||||
|
||||
print_warning() {
|
||||
echo -e "${YELLOW}[!]${NC} $1"
|
||||
}
|
||||
|
||||
print_error() {
|
||||
echo -e "${RED}[✗]${NC} $1"
|
||||
}
|
||||
|
||||
# Clean up function
|
||||
cleanup() {
|
||||
print_header "Cleaning Up"
|
||||
docker compose down -v --remove-orphans 2>/dev/null || true
|
||||
docker compose --profile debug down -v 2>/dev/null || true
|
||||
print_status "Containers stopped and removed"
|
||||
print_status "Volumes cleaned"
|
||||
}
|
||||
|
||||
# If clean only, just cleanup and exit
|
||||
if [ "$CLEAN_ONLY" = true ]; then
|
||||
cleanup
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Check Docker is available
|
||||
if ! command -v docker &> /dev/null; then
|
||||
print_error "Docker is not installed or not in PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! docker info &> /dev/null; then
|
||||
print_error "Docker daemon is not running"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
print_header "P2P Cross-Machine Test"
|
||||
|
||||
echo "Configuration:"
|
||||
echo " - Leecher count: $LEECHER_COUNT"
|
||||
echo " - File size: ${FILE_SIZE_MB}MB"
|
||||
echo " - Piece size: ${PIECE_SIZE_KB}KB"
|
||||
echo " - Network chaos: $ENABLE_CHAOS"
|
||||
echo " - Debug mode: $DEBUG_MODE"
|
||||
echo ""
|
||||
|
||||
# Clean up any previous runs
|
||||
print_status "Cleaning up previous runs..."
|
||||
docker compose down -v --remove-orphans 2>/dev/null || true
|
||||
|
||||
# Build the images
|
||||
print_header "Building Docker Images"
|
||||
docker compose build --progress=plain
|
||||
|
||||
print_status "Docker images built successfully"
|
||||
|
||||
# Start the network
|
||||
print_header "Starting P2P Network"
|
||||
|
||||
if [ "$DEBUG_MODE" = true ]; then
|
||||
docker compose --profile debug up -d
|
||||
print_status "Started with debug monitor"
|
||||
print_warning "Debug: docker exec -it p2p-monitor bash"
|
||||
else
|
||||
docker compose up -d --scale leecher=$LEECHER_COUNT
|
||||
fi
|
||||
|
||||
print_status "Seeder started"
|
||||
print_status "$LEECHER_COUNT leecher(s) started"
|
||||
|
||||
# Wait for services to be healthy
|
||||
print_header "Waiting for Services"
|
||||
|
||||
echo "Waiting for seeder to be healthy..."
|
||||
timeout=60
|
||||
while [ $timeout -gt 0 ]; do
|
||||
if docker compose ps seeder | grep -q "healthy"; then
|
||||
print_status "Seeder is healthy"
|
||||
break
|
||||
fi
|
||||
echo -n "."
|
||||
sleep 2
|
||||
timeout=$((timeout - 2))
|
||||
done
|
||||
|
||||
if [ $timeout -le 0 ]; then
|
||||
print_error "Seeder failed to become healthy"
|
||||
docker compose logs seeder
|
||||
cleanup
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Follow logs
|
||||
print_header "Test Logs"
|
||||
echo "Following container logs (Ctrl+C to stop)..."
|
||||
echo ""
|
||||
|
||||
# If chaos mode, add network delays
|
||||
if [ "$ENABLE_CHAOS" = true ]; then
|
||||
print_warning "Chaos mode enabled - this requires pumba to be installed"
|
||||
|
||||
if command -v pumba &> /dev/null; then
|
||||
# Add 50ms delay with 10ms jitter to leechers
|
||||
echo "Adding network chaos to leechers..."
|
||||
pumba netem --duration 5m delay --time 50 --jitter 10 \
|
||||
$(docker ps -q -f "name=leecher") &
|
||||
else
|
||||
print_warning "Pumba not found. Install with: brew install pumba"
|
||||
print_warning "Continuing without network chaos..."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Stream logs
|
||||
docker compose logs -f --tail=100
|
||||
|
||||
# This won't be reached unless user Ctrl+C
|
||||
echo ""
|
||||
print_header "Test Complete"
|
||||
echo "Run './run-tests.sh --clean' to clean up"
|
||||
Reference in New Issue
Block a user