Skip to content

About

VPNOrchestra transforms a collection of .ovpn files into a unified, load-balanced networking gateway.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

VPNOrchestra

CI Coverage

VPNOrchestra runs multiple OpenVPN connections in Docker, each with a SOCKS5 proxy. A FastAPI controller manages their lifecycle through a Docker socket proxy, and HAProxy distributes new connections across available VPN backends.

flowchart TB
    Client[Application / User]
    Internet((Internet))

    subgraph Stack[VPNOrchestra Stack]
        Controller[FastAPI Controller]
        DockerProxy[Docker Socket Proxy]
        Gateway[HAProxy Gateway]

        subgraph VPNs[VPN Containers]
            VPN_0[VPN Container 1]
            VPN_1[VPN Container 2]
            VPN_N[VPN Container N]
        end
    end

    Client -->|SOCKS5 request| Gateway
    Controller -->|Docker API| DockerProxy
    DockerProxy -->|Manage| VPNs
    DockerProxy -->|Manage| Gateway
    Gateway -->|Round robin| VPN_0 & VPN_1 & VPN_N
    VPN_0 & VPN_1 & VPN_N -->|OpenVPN tunnel| Internet
Loading

Requirements

  • Docker Engine with Compose, or Docker Desktop using Linux containers.
  • TUN support, NET_ADMIN, and IPv4/IPv6 firewall support for VPN containers.
  • Python 3.14+ for local scripts and tests.
  • OpenVPN profiles and your provider's VPN credentials.

Quick start

Run commands from the repository root. The examples below use Bash.

git clone https://github.com/giabb/VPNOrchestra.git
cd VPNOrchestra
python -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
cp ovpn_configs/vpn.auth.sample ovpn_configs/vpn.auth

On PowerShell, activate the environment with .\.venv\Scripts\Activate.ps1 and set $env:PWD = (Get-Location).Path before running Compose. The Compose file uses PWD to construct host paths for volume mounts.

Edit ovpn_configs/vpn.auth to contain your VPN username and password on two lines:

your_vpn_username
your_vpn_password

Place your .ovpn profiles in ovpn_configs/, or download the default Surfshark TCP profiles:

python scripts/update_configs.py

Start the controller and Docker socket proxy:

docker compose up --build -d

Compose waits for the Docker socket proxy's healthcheck before starting the controller. The controller healthcheck verifies its API and Docker access.

Once the API is available at http://localhost:8000/docs, start the VPNs and gateway:

python scripts/restart_vpn.py

The script stops existing VPN containers, builds the VPN image, and starts up to four randomly selected profiles by default. Each VPN's SOCKS5 proxy opens only after its tunnel and startup connectivity checks succeed.

Verify a request through the gateway:

curl --socks5-hostname localhost:1080 https://api.ipify.org
Service Default address
Controller API and Swagger UI http://localhost:8000/docs
ReDoc http://localhost:8000/redoc
SOCKS5 gateway localhost:1080
HAProxy statistics http://localhost:8080/stats
HAProxy HTTP health endpoint http://localhost:8080/health

The HTTP health endpoint reports that HAProxy is responding; it does not establish that a VPN backend is usable. Use a SOCKS5 request to check VPN connectivity.

To stop the VPNs and gateway, then shut down the controller:

curl -X DELETE http://localhost:8000/stop-vpns/
docker compose down

Run docker compose down after the API confirms a successful stop. VPN containers are created through the Docker API and are not managed by docker compose down.

API

Method Endpoint Purpose
POST /start-vpns/ Start the selected profiles and create the gateway
DELETE /stop-vpns/ Remove VPN containers and the gateway
GET /vpns/ List managed containers, Docker health and published proxy ports
GET /vpns/traffic/ Read per-VPN health, traffic totals and transfer rates
GET /vpns/traffic/{container_id}/history/ Read retained samples; accepts since (Unix seconds) and limit (1–10000)
GET /gateway-status/ Read the gateway's Docker state

To select profiles explicitly, build the VPN image and send their filenames:

docker build -t vpnorchestra ./proxy_files
curl -X POST http://localhost:8000/start-vpns/ \
  -H 'Content-Type: application/json' \
  -d '{"filenames": ["us-nyc.ovpn", "uk-lon.ovpn"]}'

Use filenames that exist in ovpn_configs/. Names must start with a letter or digit, contain only letters, digits, dots, underscores or hyphens, and end in .ovpn. Empty selections, duplicates, invalid paths and missing profiles return HTTP 422.

Start and stop operations are serialized: overlapping requests return HTTP 409. A partial shutdown returns HTTP 500 and identifies containers that could not be removed. Stop the current stack before starting a new selection of profiles.

Health and traffic monitoring

Each VPN checks connectivity through SOCKS5 every 15 seconds. Three consecutive failures trigger recovery; an exited OpenVPN/proxy process or missing tun0 triggers it immediately. Docker also runs the connectivity probe as a healthcheck. The supervisor restarts OpenVPN and SOCKS5 inside the same container, preserving its published port and the gateway configuration. Existing connections are lost.

Recovery allows three retries per container start, with increasing delays of 5, 10 and 20 seconds. Invalid configuration and rejected credentials stop without retrying. After the retry budget is exhausted, the container exits and needs manual intervention. Firewall rules remain active throughout recovery and block the proxy from falling back to the ordinary network.

Unsupported options pushed by a provider, such as block-outside-dns on Linux, may produce an Options error log entry without preventing connection. The supervisor tolerates these messages; actual fatal exits and local configuration errors still stop the VPN.

The controller samples tun0 every 15 seconds and retains 24 hours of history in SQLite. Compose stores it in the traffic-data volume, surviving controller restarts. Local runs use .data/traffic.sqlite3. Only VPN containers created with the new role label are sampled; rebuild the VPN image and recreate existing VPNs when upgrading.

curl http://localhost:8000/vpns/traffic/
curl 'http://localhost:8000/vpns/traffic/CONTAINER_ID/history/?limit=100'

Samples include runtime state, failure reason, restart count, raw received/sent bytes and download/upload rates in bytes per second. observed_received_bytes and observed_sent_bytes accumulate observed tunnel counters across reconnects for the same container ID. Rates are null on the first sample, counter resets or long sampling gaps; stale marks current data older than three intervals. Collection failures appear in error per container or last_error for the poll.

Counters measure tunnel IP traffic, including health probes, rather than only application payload or encrypted transport overhead. Bytes transferred between the last sample and a lost interface cannot be recovered. Historical samples remain available after container removal until retention expires; observed totals are retained while the container remains tracked. Controller workers must share the same statistics database directory to coordinate sampling.

Configuration

Controller settings are defined in docker-compose.yml.

Variable Compose value / default Purpose
DOCKER_HOST tcp://docker-proxy:2375 Docker API endpoint
VPN_DIR /ovpn_configs Profiles directory inside the controller
HOST_VPN_DIR ${PWD}/ovpn_configs Absolute host path used for profile mounts
GATEWAY_PORT 8080 HAProxy HTTP health and statistics port; SOCKS5 uses 1080
VPN_OPERATION_LOCK vpnorchestra.lock in the system temporary directory Lock shared by controller workers
VPN_STATS_DB /data/traffic.sqlite3 in Compose Statistics database and adjacent collector lock
VPN_STATS_INTERVAL 15 seconds Sampling interval, at least 1 second
VPN_STATS_RETENTION_HOURS 24 History retention, at least 1 hour
VPN_STATS_ENABLED 1 Set to 0 on the controller to disable sampling
BASE_URI http://localhost:8000 Controller URL used by restart_vpn.py
MAX_VPN 4 Maximum profiles selected by restart_vpn.py
OVPN_DOWNLOAD_URL Surfshark configuration ZIP endpoint Download source used by update_configs.py

Keep ovpn_configs/ and proxy_files/ as sibling directories: the gateway mount path is derived from HOST_VPN_DIR. Multiple controller containers must share the same lock file through a volume to serialize operations across instances.

The profile updater installs *_tcp.ovpn files from the downloaded ZIP. It preserves credentials and unrelated files and restores previous profiles if installation fails. If restoration also fails, it reports the retained backup. See update_configs.py for the default download URL.

The controller forwards these settings to newly created VPN containers. Recovery settings are also exposed through Compose environment substitution; add other overrides to the controller's environment section as needed.

Variable Default
VPN_START_TIMEOUT 25 seconds
VPN_POLL_INTERVAL 1 second
VPN_MAX_RESTARTS 3; 0 disables recovery
VPN_RETRY_DELAY 5 seconds, doubled after each retry
VPN_RETRY_MAX_DELAY 60 seconds
VPN_HEALTH_INTERVAL 15 seconds between runtime probes
VPN_HEALTH_FAILURES 3 consecutive failed probes
VPN_HEALTHCHECK_IP 1.1.1.1
VPN_HEALTHCHECK_URL https://api.ipify.org
VPN_DNS_SERVERS 1.1.1.1 1.0.0.1

The proxy runs under a dedicated user whose outbound connections must use tun0. Use a stable, reachable healthcheck URL: an outage of that endpoint can trigger recovery even if other destinations remain reachable. The Docker healthcheck schedule is defined separately in proxy_files/Dockerfile.

Tests and CI

Install development dependencies and run the default suite:

python -m pip install -r requirements-dev.txt
python -m pytest

Alternatively, python -m pip install -e '.[test]' installs the application and test extras from pyproject.toml. Both installation methods use the same dependency constraints.

The default suite uses temporary files and simulated Docker/HTTP calls. It covers API validation, lifecycle operations, rollback, concurrency, configuration updates, statistics persistence, retention and counter resets without a Docker daemon, VPN credentials or Internet access.

Run the complete suite with the same coverage threshold as CI:

python -m pytest --run-integration --cov --cov-report=term-missing --cov-fail-under=85

Integration tests require a running local Docker daemon with Linux containers, TUN, NET_ADMIN, IPv4/IPv6 firewall support and IPv6 Docker networks. They use a local TLS OpenVPN server with temporary credentials and verify HAProxy failover, tunnel traffic, blocked traffic after tunnel loss, automatic recovery, retry limits, connectivity failures with the interface still present, traffic counters, shutdown and restart behavior. Test containers and networks are cleaned up after each scenario. Image downloads and builds require Internet access; the full suite takes several minutes.

The VPN Dockerfile compiles a pinned microsocks revision in a separate build stage. Default builds contain the runtime only; integration tests select the test-tools stage, which adds Perl and OpenSSL for their helpers. The Docker socket proxy is pinned to a release and digest in Compose. Both build contexts use .dockerignore allowlists to exclude credentials, caches and unrelated files.

For an HTML coverage report, add --cov-report=html and open htmlcov/index.html. Coverage measures Python code in src/ and scripts/, excluding the manual probe scripts/test_gateway.py; shell behavior is exercised by integration tests. The manual probe requires the running stack and Internet access and can be run with python scripts/test_gateway.py.

GitHub Actions runs the complete suite on every push, pull request and manual dispatch using Python 3.14 on Ubuntu 24.04. It checks dependency compatibility, enforces 85% minimum coverage, and builds the controller image after successful tests. Coverage is shown in the logs and job summary. The workflow builds images for validation and does not deploy them.

The coverage badge shows the percentage from the last successful CI run on the default branch. Pushes and manual runs on that branch publish the badge data to the dedicated coverage-badge branch using GITHUB_TOKEN; only that publishing job requests contents: write. Pull requests do not update the badge. It becomes available after the first successful run with this workflow.

Contributing and license

Report bugs or propose changes through the issue tracker. Include reproduction steps and relevant logs with bug reports, and run the test suite before submitting a pull request.

Created by Giovanbattista Abbate. Licensed under GPL-3.0-or-later.

About

VPNOrchestra transforms a collection of .ovpn files into a unified, load-balanced networking gateway.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages