### Start Xray Process Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Starts the Xray process with the given configuration. ```go err := tunnel.StartXray(xrayConfigData) if err != nil { // Handle error } ``` -------------------------------- ### Kubernetes ConfigMap Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Example of how to provide configuration to the exporter via a Kubernetes ConfigMap. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: xray-health-exporter-config species: data: config.yaml: | listen_address: ":9273" ``` -------------------------------- ### Configuration File Example - Subscriptions Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Example of the 'subscriptions' section in the configuration file, showing how to specify a subscription URL and update interval. ```yaml # Подписки — автоматическое получение серверов (опционально) subscriptions: - url: "https://provider.example.com/subscribe?token=xxx" update_interval: "1h" # как часто обновлять (по умолчанию 1h) ``` -------------------------------- ### Start Push Metrics Loop Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Starts a background loop to periodically push metrics to the Pushgateway. ```go go metrics.PushLoop(pushCfg, "my_job", 15*time.Second) ``` -------------------------------- ### Configuration File Subscriptions Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Example snippet showing how to configure subscriptions for automatic server fetching, including the URL and update interval. ```yaml # Subscriptions — automatic server fetching (optional) subscriptions: - url: "https://provider.example.com/subscribe?token=xxx" update_interval: "1h" # how often to update (default: 1h) ``` -------------------------------- ### Example Configuration File Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md An example YAML configuration file demonstrating defaults, subscriptions, and tunnel configurations using VLESS URL or Xray JSON. ```yaml defaults: check_url: "https://www.google.com" check_interval: "30s" check_timeout: "30s" # Subscriptions (optional) — automatic server fetching subscriptions: - url: "https://provider.example.com/api/v1/client/subscribe?token=xxx" update_interval: "1h" tunnels: # Option 1: VLESS URL - name: "Server 1" url: "vless://uuid@host1:443?type=tcp&security=reality&pbk=...&sni=google.com" # Option 2: native Xray JSON config (any protocol) - name: "Server 2" xray_config_file: "/etc/xray/server2.json" ``` -------------------------------- ### Basic SOCKS5 Connection Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-socks.md A fundamental example demonstrating how to create a `SOCKS5Dialer` and use its `DialContext` method to establish a raw TCP connection to a remote host through the SOCKS5 proxy. ```go package main import ( "fmt" "net" "time" "github.com/batonogov/xray-health-exporter/internal/socks" "context" ) func main() { dialer := socks.NewSOCKS5Dialer("127.0.0.1:1080", 10*time.Second) conn, err := dialer.DialContext(context.Background(), "tcp", "example.com:443") if err != nil { fmt.Printf("Error: %v\n", err) return } defer conn.Close() fmt.Println("Connected through SOCKS5!") } ``` -------------------------------- ### Install with Helm Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Add the Helm repository and install the xray-health-exporter chart, optionally with a custom values.yaml file. ```bash helm repo add batonogov https://batonogov.github.io/helm-charts helm install xray-health-exporter batonogov/xray-health-exporter -f values.yaml ``` -------------------------------- ### Configuration File Defaults Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Example snippet showing global defaults for check URL, interval, and timeout in the YAML configuration. ```yaml # Global defaults (optional) defaults: check_url: "https://www.google.com" check_interval: "30s" check_timeout: "30s" ``` -------------------------------- ### StartXray Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-tunnel.md Starts an Xray-core instance with the provided configuration. ```APIDOC ## StartXray ### Description Starts an Xray-core instance with the provided configuration. ### Parameters #### Request Body - **configJSON** ([]byte) - Required - JSON configuration for Xray. ### Returns - **core.Instance** - A pointer to the managed Xray instance. - **error** - An error if the instance fails to start. ``` -------------------------------- ### Basic Auth Example with curl Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Example of accessing the /metrics endpoint with Basic Authentication using curl. ```bash curl -u 'user:password' http://localhost:9273/metrics ``` -------------------------------- ### Initialize Prometheus Start Time Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Sets the start time for the exporter, used in uptime metrics. ```go metrics.InitStartTime() ``` -------------------------------- ### Start Xray Instance Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-tunnel.md Initializes an Xray-core instance with a provided JSON configuration. Returns the managed instance or an error if startup fails. ```go func StartXray(configJSON []byte) (*core.Instance, error) ``` -------------------------------- ### Download and Install Linux Binary Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Download pre-built binaries for Linux amd64 and arm64 architectures and make them executable. ```bash # Linux amd64 wget https://github.com/batonogov/xray-health-exporter/releases/latest/download/xray-health-exporter-linux-amd64 chmod +x xray-health-exporter-linux-amd64 # Linux arm64 wget https://github.com/batonogov/xray-health-exporter/releases/latest/download/xray-health-exporter-linux-arm64 chmod +x xray-health-exporter-linux-arm64 ``` -------------------------------- ### Initialize Metrics Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Initializes the start time for xray_exporter_uptime_seconds and sets build information for xray_exporter_build_info. ```go metrics.InitStartTime() metrics.SetBuildInfo(Version, runtime.Version(), Commit) ``` -------------------------------- ### Example PromQL Query Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Example PromQL query to get the status of tunnels. ```promql sum by (name, status) (rate(tunnel_check_total[5m])) ``` -------------------------------- ### Load Configuration from YAML Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Example of loading configuration from a YAML file. This is the primary method for configuring the exporter. ```go cfg, err := config.LoadConfig("./config.yaml") if err != nil { log.Fatalf("Failed to load config: %v", err) } ``` -------------------------------- ### Minimal Configuration Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt A minimal configuration file for xray-health-exporter. ```yaml listen_address: ":9273" ``` -------------------------------- ### Defaults Section Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/configuration.md Provides an example of the 'defaults' section in the YAML configuration, specifying parameters like check URL, interval, and timeout. ```yaml defaults: check_url: "https://api.example.com/health" check_interval: "1m" check_timeout: "45s" max_backoff: "10m" backoff_multiplier: 1.5 check_method: "http" ``` -------------------------------- ### Example Configuration File Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Example YAML configuration file for Xray Health Exporter, including defaults, subscriptions, and tunnels using VLESS URL or Xray JSON config. ```yaml defaults: check_url: "https://www.google.com" check_interval: "30s" check_timeout: "30s" # Подписки (опционально) — автоматическое получение серверов subscriptions: - url: "https://provider.example.com/api/v1/client/subscribe?token=xxx" update_interval: "1h" tunnels: # Вариант 1: VLESS URL - name: "Server 1" url: "vless://uuid@host1:443?type=tcp&security=reality&pbk=...&sni=google.com" # Вариант 2: нативный Xray JSON-конфиг (любой протокол) - name: "Server 2" xray_config_file: "/etc/xray/server2.json" ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Installs pre-commit hooks for the project. This should be run before committing to ensure code quality checks are performed. ```bash task install-hooks ``` -------------------------------- ### Kubernetes Deployment Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Example Kubernetes deployment configuration for the xray-health-exporter. This includes RBAC and ServiceMonitor for Prometheus integration. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: xray-health-exporter namespace: monitoring spec: replicas: 1 selector: matchLabels: app: xray-health-exporter template: metadata: labels: app: xray-health-exporter spec: containers: - name: xray-health-exporter image: ghcr.io/batonogov/xray-health-exporter:latest ports: - containerPort: 9273 volumeMounts: - name: config-volume mountPath: /app/config.yaml subPath: config.yaml volumes: - name: config-volume configMap: name: xray-health-exporter-config --- apiVersion: v1 kind: ConfigMap metadata: name: xray-health-exporter-config namespace: monitoring data: config.yaml: | # Your configuration here # Example: # tunnels: # - name: "tunnel1" # server: "1.2.3.4" # port: 80 --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: xray-health-exporter-role rules: - apiGroups: [""] resources: ["pods", "services", "endpoints"] verbs: ["get", "list", "watch"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: xray-health-exporter-role-binding subjects: - kind: ServiceAccount name: xray-health-exporter-sa namespace: monitoring roleRef: kind: ClusterRole name: xray-health-exporter-role apiGroup: rbac.authorization.k8s.io --- apiVersion: v1 kind: ServiceAccount metadata: name: xray-health-exporter-sa namespace: monitoring --- apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: xray-health-exporter-monitor namespace: monitoring spec: selector: matchLabels: app: xray-health-exporter namespaceSelector: matchNames: - monitoring endpoints: - port: http interval: 30s ``` -------------------------------- ### Build with Version Flags Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Example command to build the exporter, setting the Version and Commit global variables using Go's linker flags. ```bash go build -ldflags="-X main.Version=v1.6.0 -X main.Commit=abc123def" ./cmd/exporter ``` -------------------------------- ### Prometheus Configuration Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Example Prometheus configuration to scrape metrics from xray-health-exporter. Assumes the exporter is running and accessible. ```yaml scrape_configs: - job_name: 'xray-health-exporter' static_configs: - targets: [':9273'] # If using Basic Auth: # basic_auth: # username: 'user' # password: 'password' ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Installs pre-commit hooks for development workflows. Use this command before making code changes. ```bash # Install pre-commit hooks task install-hooks ``` -------------------------------- ### Duration Format Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Examples of duration formats accepted by the exporter (e.g., for timeouts or intervals). ```text 10s 1m30s 2h ``` -------------------------------- ### Run with Kubernetes Leader Election Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Starts the application with Kubernetes lease-based leader election enabled. ```go err := leaderelection.RunWithLeaderElection(ctx, leConfig, func() { // Run your application logic here }) if err != nil { // Handle error } ``` -------------------------------- ### Unauthorized Response Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/endpoints.md This example shows the HTTP response when authentication fails for the /metrics endpoint. ```http HTTP/1.1 401 Unauthorized WWW-Authenticate: Basic realm="metrics" 401 Unauthorized ``` -------------------------------- ### Setup Logger Function Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Initializes structured logging using the 'log/slog' package. Reads environment variables for configuration, supporting different log levels and formats. ```go func setupLogger(){ } ``` -------------------------------- ### Subscriptions Section Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/configuration.md Illustrates the 'subscriptions' section for defining remote server lists, including URL and update interval. ```yaml subscriptions: - url: "https://api.example.com/v1/client/subscribe?token=abc123" update_interval: "2h" - url: "https://mirror.example.com/subscribe?token=xyz789" update_interval: "6h" ``` -------------------------------- ### Run Xray-Health-Exporter with Docker Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Example of running the exporter using Docker. Ensure you have a configuration file or environment variables set up. ```bash docker run --rm -p 9273:9273 -v $(pwd)/config.yaml:/app/config.yaml ghcr.io/batonogov/xray-health-exporter:latest ``` -------------------------------- ### Tunnel Configuration Examples Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Demonstrates different ways to configure tunnels, including VLESS URLs, native Xray JSON configs, and overriding default parameters. ```yaml tunnels: # Option 1: VLESS URL - url: "vless://uuid@host:443?type=tcp&security=reality&pbk=...&sni=google.com" # Option 2: native Xray JSON config (any protocol/transport) - name: "VMess Server" xray_config_file: "/etc/xray/vmess.json" # With overridden parameters - name: "Backup Server" url: "vless://uuid@host:443?..." check_url: "https://1.1.1.1" check_interval: "60s" check_timeout: "45s" # With a custom SOCKS port (optional, auto-assigned by default) - name: "Server 3" url: "vless://uuid@host:443?..." socks_port: 2080 ``` -------------------------------- ### Tunnel Configuration Examples Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Demonstrates various ways to configure tunnels for monitoring, including VLESS URLs, native Xray JSON configs, and overriding parameters like check URLs and intervals. ```yaml tunnels: # Вариант 1: VLESS URL - url: "vless://uuid@host:443?type=tcp&security=reality&pbk=...&sni=google.com" # Вариант 2: нативный Xray JSON-конфиг (любой протокол/транспорт) - name: "VMess Server" xray_config_file: "/etc/xray/vmess.json" # С переопределением параметров - name: "Backup Server" url: "vless://uuid@host:443?..." check_url: "https://1.1.1.1" check_interval: "60s" check_timeout: "45s" # С кастомным SOCKS портом (опционально, по умолчанию — автоназначение) - name: "Server 3" url: "vless://uuid@host:443?..." socks_port: 2080 ``` -------------------------------- ### Kubernetes with Leader Election Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Example command to run the exporter in Kubernetes with leader election enabled. Sets necessary environment variables for leader election. ```bash export LEADER_ELECTION=true export LEADER_ELECTION_NAMESPACE=default export LEADER_ELECTION_IDENTITY=pod-name export CONFIG_FILE=/etc/xray/config.yaml go run ./cmd/exporter ``` -------------------------------- ### Text Log Output Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Example of structured log output in text format, showing timestamp, level, message, and version information. ```text 2026-01-15T10:30:45.123Z INFO xray-health-exporter starting version=v1.6.0 2026-01-15T10:30:45.234Z DEBUG config loaded tunnels=2 ``` -------------------------------- ### JSON Log Output Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Example of structured log output in JSON format, including time, level, message, and version. ```json {"time":"2026-01-15T10:30:45.123Z","level":"INFO","msg":"xray-health-exporter starting","version":"v1.6.0"} ``` -------------------------------- ### Integrate SOCKS5 Dialer with HTTP Client Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Example of using the SOCKS5Dialer with Go's HTTP client. ```go http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { return socks.NewSOCKS5Dialer("localhost:1080", nil).DialContext(ctx, network, addr) } ``` -------------------------------- ### Install Xray Health Exporter with Helm Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Deploy the exporter using the provided Helm chart. Customize deployment with a values.yaml file. ```bash helm repo add batonogov https://batonogov.github.io/helm-charts helm install xray-health-exporter batonogov/xray-health-exporter \ -f values.yaml ``` -------------------------------- ### Prometheus Metrics Exposition Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/endpoints.md This is an example of the Prometheus text-exposition format returned by the /metrics endpoint. It includes various metrics related to tunnels and exporter status. ```text # HELP xray_tunnel_up 1 if tunnel is working, 0 otherwise # TYPE xray_tunnel_up gauge xray_tunnel_up{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 1 xray_tunnel_up{name="Server 2",server="api.example.com:443",security="tls",sni="api.example.com"} 0 # HELP xray_tunnel_latency_seconds Latency of the tunnel check in seconds # TYPE xray_tunnel_latency_seconds gauge xray_tunnel_latency_seconds{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 0.245 # HELP xray_tunnel_latency_histogram_seconds Latency of the tunnel check in seconds (histogram for percentile queries via histogram_quantile) # TYPE xray_tunnel_latency_histogram_seconds histogram xray_tunnel_latency_histogram_seconds_bucket{name="Server 1",server="example.com:443",security="reality",sni="google.com",le="0.01"} 0 xray_tunnel_latency_histogram_seconds_bucket{name="Server 1",server="example.com:443",security="reality",sni="google.com",le="0.025"} 0 ... xray_tunnel_latency_histogram_seconds_bucket{name="Server 1",server="example.com:443",security="reality",sni="google.com",le="+Inf"} 1 # HELP xray_tunnel_check_total Total number of tunnel checks by result # TYPE xray_tunnel_check_total counter xray_tunnel_check_total{name="Server 1",server="example.com:443",security="reality",sni="google.com",result="success"} 42 xray_tunnel_check_total{name="Server 1",server="example.com:443",security="reality",sni="google.com",result="failure"} 2 # HELP xray_tunnel_last_success_timestamp Timestamp of last successful tunnel check # TYPE xray_tunnel_last_success_timestamp gauge xray_tunnel_last_success_timestamp{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 1704117344 # HELP xray_tunnel_http_status HTTP status code from tunnel check # TYPE xray_tunnel_http_status gauge xray_tunnel_http_status{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 200 # HELP xray_tunnel_error_total Total number of tunnel errors categorized by reason # TYPE xray_tunnel_error_total counter xray_tunnel_error_total{name="Server 1",server="example.com:443",security="reality",sni="google.com",reason="timeout"} 1 xray_tunnel_error_total{name="Server 2",server="api.example.com:443",security="tls",sni="api.example.com",reason="connection_refused"} 2 # HELP xray_exporter_build_info Build info (value always 1) # TYPE xray_exporter_build_info gauge xray_exporter_build_info{commit="abc123def",go_version="go1.26",version="v1.6.0"} 1 # HELP xray_exporter_uptime_seconds Time since the process started # TYPE xray_exporter_uptime_seconds gauge xray_exporter_uptime_seconds 3600 # HELP xray_exporter_leader 1 if this instance is actively probing tunnels # TYPE xray_exporter_leader gauge xray_exporter_leader 1 # HELP xray_exporter_config_reload_total Configuration reload attempts # TYPE xray_exporter_config_reload_total counter xray_exporter_config_reload_total 2 # HELP xray_exporter_config_reload_errors_total Configuration reload errors # TYPE xray_exporter_config_reload_errors_total counter xray_exporter_config_reload_errors_total 0 # HELP xray_exporter_tunnels_configured Current number of configured tunnels # TYPE xray_exporter_tunnels_configured gauge xray_exporter_tunnels_configured 2 # HELP go_goroutines Number of goroutines that currently exist. # TYPE go_goroutines gauge go_goroutines 25 # ... остальные go_* и process_* метрики ``` -------------------------------- ### Run-Once Mode for CI/Scripts Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Example command to run the exporter in Run-Once mode for CI or scripting. Outputs metrics to metrics.txt and errors to errors.log. ```bash export RUN_ONCE=true export CONFIG_FILE=./config.yaml go run ./cmd/exporter > metrics.txt 2>errors.log echo "Exit code: $?" ``` -------------------------------- ### Handle Initialization Errors Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/errors.md Logs initialization errors and exits with a non-zero status code. Use when core services fail to start. ```go if err := tunnel.RunProbing(ctx, configFile, checker, metrics); err != nil { slog.Error("probing failed", "error", err) os.Exit(1) } ``` -------------------------------- ### RunProbing Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-tunnel.md The main entry point for daemon mode, initializing tunnels, starting health check goroutines, and config watchers. ```APIDOC ## RunProbing ### Description This is the main entry point for daemon mode. It initializes tunnels, starts goroutines for health checks, and sets up watchers for configuration changes. It loads configuration, initializes tunnels and starts Xray, launches goroutines for checking each tunnel's health, waits for config file changes (fsnotify), waits for subscription changes (periodic polling), supports hot configuration reloads, and blocks until the context is cancelled (e.g., by SIGINT/SIGTERM). This mode is used in daemon mode, with optional leader election. ### Parameters #### Request Body - **ctx** (context.Context) - Required - Context for cancellation (e.g., SIGINT/SIGTERM). - **configFile** (string) - Required - Path to the YAML configuration file. - **checker** (HealthChecker) - Required - Implementation of the health check. - **mu** (MetricsUpdater) - Required - Implementation of metrics update. ### Returns - **error** - Typically nil on normal exit. ``` -------------------------------- ### Curl Example for Basic Auth Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Demonstrates how to use curl to access a protected endpoint using Basic Authentication with a specified username and password. ```bash curl -u metricsUser:secretPassword http://localhost:9273/metrics ``` -------------------------------- ### Tunnel Metrics Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/docs/metrics.md Illustrates the format and labels for various tunnel metrics, including status, latency, checks, and errors. ```text xray_tunnel_up{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 1 xray_tunnel_latency_seconds{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 0.345 xray_tunnel_check_total{name="Server 1",...,result="success"} 42 xray_tunnel_error_total{name="Server 1",...,reason="timeout"} 3 xray_exporter_leader 1 ``` -------------------------------- ### Local Daemon Mode Execution Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Example command to run the exporter in daemon mode locally. Sets configuration file, listen address, and log level. ```bash export CONFIG_FILE=./config.yaml export LISTEN_ADDR=:9273 export LOG_LEVEL=debug go run ./cmd/exporter ``` -------------------------------- ### Run Xray-Health-Exporter in Daemon Mode Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Example of running the exporter as a daemon process. This is suitable for direct execution on a server. ```bash nohup ./xray-health-exporter --config ./config.yaml > exporter.log 2>&1 & ``` -------------------------------- ### Basic Auth Protection Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Example commands to run the exporter with Basic Auth protection enabled and to curl the metrics endpoint with credentials. ```bash export METRICS_PROTECTED=true export METRICS_USERNAME=admin export METRICS_PASSWORD=super_secret_password go run ./cmd/exporter ``` ```bash curl -u admin:super_secret_password http://localhost:9273/metrics ``` -------------------------------- ### HTTP Client with SOCKS5 and Keep-Alives Disabled Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-socks.md Illustrates setting up an `http.Client` with a custom `http.Transport` that utilizes the `SOCKS5Dialer`. This example specifically disables keep-alive connections. ```go dialer := socks.NewSOCKS5Dialer("127.0.0.1:1080", 30*time.Second) transport := &http.Transport{ DialContext: dialer.DialContext, DisableKeepAlives: true, } client := &http.Client{ Timeout: 30*time.Second, Transport: transport, } resp, err := client.Get("https://api.example.com/data") if err != nil { log.Fatal(err) } defer resp.Body.Close() // Обработать ответ... ``` -------------------------------- ### Start Push Metrics Loop Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-metrics.md Periodically pushes metrics to the Pushgateway. This function operates only if 'xray_exporter_leader' is 1 and blocks until the context is cancelled. Errors during pushes are logged but do not interrupt the loop. ```go func PushLoop(ctx context.Context, cfg PushConfig) ``` ```go pushCfg, _ := metrics.ReadPushConfig(30 * time.Second) if pushCfg != nil { go metrics.PushLoop(ctx, *pushCfg) } ``` -------------------------------- ### Daemon Mode (Default) Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Runs the exporter in daemon mode. Sets the leader to true implicitly if leader election is disabled. Optionally starts a Pushgateway loop. ```go if lec == nil { metrics.SetLeader(true) // Implicit leader если leader election отключена } tunnel.RunProbing(ctx, configFile, ...) metrics.PushLoop(ctx, pushCfg) // Optional Pushgateway ``` -------------------------------- ### Run Leader Election Process Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-leaderelection.md Starts the Kubernetes lease-based leader election. The leader replica will run tunnel probing and update metrics. Followers will only serve metrics and health endpoints. ```go func RunWithLeaderElection( ctx context.Context, lec *LeaderElectionConfig, configFile string, checker tunnel.HealthChecker, mu tunnel.MetricsUpdater, ) error ``` ```go lec, err := leaderelection.ReadLeaderElectionConfig() if err != nil { log.Fatal(err) } if lec != nil { err = leaderelection.RunWithLeaderElection( ctx, lec, "./config.yaml", checker.DefaultChecker{}, tunnel.NewPrometheusMetrics(), ) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create TTFB Instrumented Request Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-checker.md Generates a GET request with httptrace instrumentation to measure Time To First Byte (TTFB). It takes a context, start time, and the URL. It returns the prepared request, an atomic integer for TTFB in nanoseconds, and any error during creation. This is an internal function. ```go func ttfbRequest(ctx context.Context, start time.Time, url string) (*http.Request, *atomic.Int64, error) ``` -------------------------------- ### 401 Unauthorized Response Example Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Example of an HTTP response when Basic Authentication fails, returning a 401 Unauthorized status and a WWW-Authenticate header. ```http HTTP/1.1 401 Unauthorized WWW-Authenticate: Basic realm="metrics" ``` -------------------------------- ### Main Application Function Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md The main function orchestrates application startup, mode selection (Run Once, Leader Election, Daemon), and graceful shutdown. It configures logging, initializes metrics, and manages tunnel probing. ```go func main(){ } ``` -------------------------------- ### Run Tests Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Executes the project's tests. Use 'go test -v -cover ./...' for verbose output and coverage information. ```bash task test ``` ```bash go test -v -cover ./... ``` -------------------------------- ### Example Prometheus Metrics Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Example output of Prometheus metrics exposed by the Xray Health Exporter, including tunnel status, latency, and check counts. ```text xray_tunnel_up{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 1 xray_tunnel_latency_seconds{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 0.345 xray_tunnel_check_total{name="Server 1",server="example.com:443",security="reality",sni="google.com",result="success"} 42 xray_tunnel_last_success_timestamp{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 1704117344 xray_tunnel_http_status{name="Server 1",server="example.com:443",security="reality",sni="google.com"} 200 ``` -------------------------------- ### Download and Make Executable for Linux amd64 Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Download the latest binary for Linux amd64 and make it executable. ```bash # Linux amd64 wget https://github.com/batonogov/xray-health-exporter/releases/latest/download/xray-health-exporter-linux-amd64 chmod +x xray-health-exporter-linux-amd64 ``` -------------------------------- ### Initialize Logger Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Sets up the slog handler based on LOG_FORMAT and LOG_LEVEL. All logging output goes to stderr. ```go setupLogger() ``` -------------------------------- ### Download and Make Executable for Linux arm64 Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Download the latest binary for Linux arm64 and make it executable. ```bash # Linux arm64 wget https://github.com/batonogov/xray-health-exporter/releases/latest/download/xray-health-exporter-linux-arm64 chmod +x xray-health-exporter-linux-arm64 ``` -------------------------------- ### RunWithLeaderElection Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-leaderelection.md Starts leader election and runs tunnel probing only on the leader. Requires execution within a pod. ```APIDOC ## RunWithLeaderElection ### Description Starts Kubernetes lease-based leader election and executes `tunnel.RunProbing` only on the leader. This function requires being run inside a pod (uses `InClusterConfig`). ### Method ```go func RunWithLeaderElection( ctx context.Context, lec *LeaderElectionConfig, configFile string, checker tunnel.HealthChecker, mu tunnel.MetricsUpdater, ) error ``` ### Parameters | Parameter | Type | Description | |---|---|---| | `ctx` | `context.Context` | Context for cancellation (SIGINT/SIGTERM) | | `lec` | `*LeaderElectionConfig` | Leader election configuration | | `configFile` | `string` | Path to the tunnels YAML config file | | `checker` | `tunnel.HealthChecker` | Health checking implementation (usually `checker.DefaultChecker`) | | `mu` | `tunnel.MetricsUpdater` | Metrics updating implementation | ### Returns - `error` - Typically nil on normal exit. ### Possible Errors - `InClusterConfig` is not available (not running in a pod). - Error creating Kubernetes client. - Error working with the Lease resource. ### Behavior **Leader:** - Executes `tunnel.RunProbing()` to initialize and check tunnels. - Publishes `xray_tunnel_*` metrics. - Sets `xray_exporter_leader=1`. - Immediately releases the Lease (`ReleaseOnCancel`) on graceful shutdown (SIGTERM). **Follower:** - Responds to `/metrics` and `/health` (HTTP server remains running). - Publishes only `xray_exporter_leader=0`. - Does NOT initialize tunnels. - Does NOT publish `xray_tunnel_*` metrics. - Waits for an opportunity to become the leader. ### Fault Tolerance - **Graceful Shutdown (Leader):** On SIGTERM, the Lease is released immediately, and a follower takes over within approximately 5 seconds. - **Hard Crash (Leader):** The Lease is held for approximately 30 seconds (`LeaseDuration`), after which a new leader takes over. ### Example ```go lec, err := leaderelection.ReadLeaderElectionConfig() if err != nil { log.Fatal(err) } if lec != nil { err = leaderelection.RunWithLeaderElection( ctx, lec, "./config.yaml", checker.DefaultChecker{}, tunnel.NewPrometheusMetrics(), ) if err != nil { log.Fatal(err) } } ``` ``` -------------------------------- ### Download Method Tunnel Check Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-checker.md Illustrates how to set up and execute a tunnel check using the download method, specifying download URL, timeout, and minimum size. ```go ti.CheckMethod = "download" ti.DownloadURL = "https://proof.ovh.net/files/1Mb.dat" ti.DownloadTimeout = 60 * time.Second ti.DownloadMinSize = 51200 result := c.Check(ti) if result.Up { fmt.Printf("Загружено успешно, TTFB: %v\n", result.Latency) } ``` -------------------------------- ### Run Tests with Go Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Executes all tests in the project using the Go testing framework. Use the -v flag for verbose output. ```bash # Run tests task test # or go test -v -cover ./... ``` -------------------------------- ### Tunnels Section - Simple VLESS URL Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/configuration.md Example of a tunnel configuration using a simple VLESS URL. ```yaml tunnels: # Простой VLESS URL - name: "Server 1" url: "vless://550e8400@example.com:443?type=tcp&security=reality&pbk=xxx&sni=google.com" ``` -------------------------------- ### Build Project Locally Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Compiles the project for local development. Use this command to build the executable. ```bash # Local build task build ``` -------------------------------- ### SOCKS5 Connection with Context Timeout Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-socks.md Demonstrates establishing a SOCKS5 connection while using a `context.WithTimeout` to enforce a deadline. If the connection attempt exceeds the specified duration, it will be canceled. ```go ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() dialer := socks.NewSOCKS5Dialer("127.0.0.1:1080", 20*time.Second) conn, err := dialer.DialContext(ctx, "tcp", "example.com:80") if err != nil { fmt.Printf("Timeout or error: %v\n", err) return } defer conn.Close() ``` -------------------------------- ### Build Project with Versioning Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/README.md Use this command to build the exporter and set the version and commit hash during compilation. The version is visible in the `xray_exporter_build_info` metric. ```bash go build -ldflags="-X main.Version=v1.6.0 -X main.Commit=$(git rev-parse --short HEAD)" ./cmd/exporter ``` -------------------------------- ### Run with Docker Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Run the Xray Health Exporter using Docker, mounting a local config.yaml file and exposing the metrics port. ```bash # Docker docker run --rm \ -v $(pwd)/config.yaml:/app/config.yaml:ro \ -p 9273:9273 \ ghcr.io/batonogov/xray-health-exporter:latest ``` -------------------------------- ### Basic HTTP Tunnel Check Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-checker.md Demonstrates how to initialize the checker and perform a basic HTTP health check on a tunnel configuration. ```go import ( "github.com/batonogov/xray-health-exporter/internal/checker" "github.com/batonogov/xray-health-exporter/internal/tunnel" ) // Создать checker c := checker.NewDefaultChecker("") // Создать туннель ti := &tunnel.TunnelInstance{ SocksPort: 1080, CheckURL: "https://www.google.com", CheckMethod: "http", CheckTimeout: 30 * time.Second, } // Выполнить проверку result := c.Check(ti) if result.Up { fmt.Printf("Туннель OK, TTFB: %v\n", result.Latency) } ``` -------------------------------- ### Load Xray Configuration File Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Loads an Xray configuration from a file path. ```go xrayConfigData, err := tunnel.LoadXrayConfigFile("/path/to/xray/config.json") if err != nil { // Handle error } ``` -------------------------------- ### Run Locally Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.md Run the Xray Health Exporter locally by setting the CONFIG_FILE environment variable and executing the binary. Requires Go 1.26+. ```bash # Locally (requires Go 1.26+) export CONFIG_FILE=./config.yaml ./xray-health-exporter-linux-amd64 ``` -------------------------------- ### RBAC Configuration for Leader Election Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-leaderelection.md This YAML defines the Role and RoleBinding necessary for leader election. It grants permissions to get, create, and update Lease objects. ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: xray-health-exporter rules: - apiGroups: ["coordination.k8s.io"] resources: ["leases"] verbs: ["get", "create", "update"] --- aspiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: xray-health-exporter roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: xray-health-exporter subjects: - kind: ServiceAccount name: xray-health-exporter ``` -------------------------------- ### Push Metrics Once Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-metrics.md Sends all current metrics from the registry to the Pushgateway in a single operation. Requires a context for potential timeouts. ```go func PushMetrics(ctx context.Context, cfg PushConfig) error ``` -------------------------------- ### RunOnce Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-tunnel.md Loads configuration, initializes tunnels, performs a single health check per tunnel, and outputs Prometheus metrics. ```APIDOC ## RunOnce ### Description Loads configuration, initializes all tunnels, performs exactly one check per tunnel (in parallel), updates Prometheus metrics, and outputs them in Prometheus text format. This mode does not start an HTTP server, file watcher, or subscription watcher, and does not use leader election. ### Parameters #### Request Body - **configFile** (string) - Required - Path to the YAML configuration file. - **checker** (HealthChecker) - Required - Implementation of the health check (typically checker.DefaultChecker). - **mu** (MetricsUpdater) - Required - Implementation of metrics update. - **w** (io.Writer) - Required - Writer for outputting metrics (typically os.Stdout). ### Returns - **bool** - True if all tunnels are up, false if at least one is down. - **error** - An error during configuration loading or initialization. ### Example ```go allUp, err := tunnel.RunOnce( "./config.yaml", checker.DefaultChecker{}, tunnel.NewPrometheusMetrics(), os.Stdout, ) if err != nil { log.Fatal(err) } if !allUp { os.Exit(1) } ``` ``` -------------------------------- ### Local Build Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Builds the project locally. This command compiles the source code into an executable binary. ```bash task build ``` -------------------------------- ### Prometheus Alerting Rules for Xray Health Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Example Prometheus alerting rules for monitoring Xray tunnel status, latency, and check frequency. Ensure the 'xray' job is correctly configured in Prometheus. ```yaml groups: - name: xray rules: # Туннель не работает - alert: XrayTunnelDown expr: xray_tunnel_up == 0 for: 5m labels: severity: critical annotations: summary: "Туннель {{ $labels.name }} не работает" description: "Туннель {{ $labels.name }} ({{ $labels.server }}, {{ $labels.security }}) не работает более 5 минут" # Высокая задержка - alert: XrayHighLatency expr: xray_tunnel_latency_seconds > 2 for: 10m labels: severity: warning annotations: summary: "Высокая задержка на {{ $labels.name }}" description: "Туннель {{ $labels.name }} имеет задержку {{ $value }}s (порог: 2s)" # Туннель давно не проверялся - alert: XrayNoRecentCheck expr: (time() - xray_tunnel_last_success_timestamp) > 300 for: 5m labels: severity: warning annotations: summary: "{{ $labels.name }} давно не проверялся" description: "Туннель {{ $labels.name }} не проверялся успешно {{ $value }}s" ``` -------------------------------- ### Initialize a Tunnel Instance Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-tunnel.md Use InitTunnel to create and initialize a tunnel from its configuration. Ensure the configuration and SOCKS port are valid. The returned TunnelInstance should be stopped when no longer needed. ```go cfgTunnel := config.Tunnel{ Name: "My Tunnel", URL: "vless://uuid@server:443?security=reality", } ti, err := tunnel.InitTunnel(&cfgTunnel, 1080) if err != nil { log.Fatal(err) } deffer ti.Stop() ``` -------------------------------- ### Kubernetes Deployment with Leader Election Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-leaderelection.md Example Kubernetes Deployment configuration for the X-Ray Health Exporter. It specifies multiple replicas and sets environment variables for leader election, namespace, identity, and configuration file. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: xray-health-exporter spec: replicas: 3 # Несколько реплик template: spec: serviceAccountName: xray-health-exporter containers: - name: exporter image: ghcr.io/batonogov/xray-health-exporter:latest env: - name: LEADER_ELECTION value: "true" - name: LEADER_ELECTION_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: LEADER_ELECTION_IDENTITY valueFrom: fieldRef: fieldPath: metadata.name - name: CONFIG_FILE value: /app/config.yaml ports: - name: metrics containerPort: 9273 livenessProbe: httpGet: path: /health port: 9273 initialDelaySeconds: 10 periodSeconds: 10 readinessProbe: httpGet: path: /health port: 9273 initialDelaySeconds: 5 periodSeconds: 5 ``` -------------------------------- ### Run Xray Health Exporter Once Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-tunnel.md Executes a single health check cycle for all configured tunnels in parallel. It loads configuration, initializes tunnels, updates Prometheus metrics, and outputs them. This mode does not start an HTTP server or watchers and is suitable for one-off checks. ```go func RunOnce(configFile string, checker HealthChecker, mu MetricsUpdater, w io.Writer) (bool, error) ``` ```go allUp, err := tunnel.RunOnce( "./config.yaml", checker.DefaultChecker{}, tunnel.NewPrometheusMetrics(), os.Stdout, ) if err != nil { log.Fatal(err) } if !allUp { os.Exit(1) } ``` -------------------------------- ### Read Pushgateway Configuration Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Reads the Pushgateway configuration from environment variables or a file. ```go pushCfg, err := metrics.ReadPushConfig() if err != nil { // Handle error } ``` -------------------------------- ### Run Xray Health Exporter in Daemon Mode Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-tunnel.md The primary entry point for the Xray health exporter when running as a daemon. It initializes tunnels, starts health check goroutines, and monitors configuration file changes for hot reloading. This function blocks until the provided context is cancelled, typically via SIGINT or SIGTERM. ```go func RunProbing(ctx context.Context, configFile string, checker HealthChecker, mu MetricsUpdater) error ``` -------------------------------- ### Run Locally Source: https://github.com/batonogov/xray-health-exporter/blob/main/README.ru.md Run the Xray Health Exporter locally. Requires Go 1.26+ and the CONFIG_FILE environment variable set. ```bash # Локально (требуется Go 1.26+) export CONFIG_FILE=./config.yaml ./xray-health-exporter-linux-amd64 ``` -------------------------------- ### Set Build Information Metric Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Sets the build info metric, including version and commit hash. ```go metrics.SetBuildInfo("v1.0.0", "abcdef123") ``` -------------------------------- ### Create Xray Configuration Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Creates an Xray configuration object from a TunnelInstance. ```go xrayCfg := tunnel.CreateXrayConfig(&tunnelInstance) ``` -------------------------------- ### Logging Formats Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/types.md Defines the supported logging formats configurable via the LOG_FORMAT environment variable. Defaults to 'text'. ```go // LOG_FORMAT env var: - "text" (по умолчанию) - "json" ``` -------------------------------- ### Run Once Mode Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/api-reference-main.md Executes the exporter once and exits. Sets the leader to true and exits with code 0 if all checks pass, otherwise 1. ```go if os.Getenv("RUN_ONCE") == "true" { metrics.SetLeader(true) allUp, err := tunnel.RunOnce(configFile, ...) os.Exit(allUp ? 0 : 1) } ``` -------------------------------- ### Initialize Tunnel Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/SUMMARY.txt Initializes a tunnel instance based on the provided configuration. ```go tunnelInstance := tunnel.InitTunnel(cfg.Tunnels[0]) ``` -------------------------------- ### Handle Configuration Errors Source: https://github.com/batonogov/xray-health-exporter/blob/main/_autodocs/errors.md Logs configuration errors and exits with a non-zero status code. Use when configuration loading fails. ```go if err := config.LoadConfig(configFile); err != nil { slog.Error("config error", "error", err) os.Exit(1) } ```