* feat: add automatic port detection and fallback for mini command
- Added port availability detection using TCP binding tests
- Implemented port fallback mechanism searching for available ports
- Support for both HTTP and gRPC port handling
- IP-aware port checking using actual service bind address
- Dual-interface verification (specific IP and wildcard 0.0.0.0)
- All services (Master, Volume, Filer, S3, WebDAV, Admin) auto-reallocate to available ports
- Enables multiple mini instances to run simultaneously without conflicts
* fix: use actual bind IP for service health checks
- Previously health checks were hardcoded to localhost (127.0.0.1)
- This caused failures when services bind to actual IP (e.g., 10.21.153.8)
- Now health checks use the same IP that services are binding to
- Fixes Volume and other service health check failures on non-localhost IPs
* refactor: improve port detection logic and remove gRPC handling duplication
- findAvailablePortOnIP now returns 0 on failure instead of unavailable port
Allows callers to detect when port finding fails and handle appropriately
- Remove duplicate gRPC port handling from ensureAllPortsAvailableOnIP
All gRPC port logic is now centralized in initializeGrpcPortsOnIP
- Log final port configuration only after all ports are finalized
Both HTTP and gRPC ports are now correctly initialized before logging
- Add error logging when port allocation fails
Makes debugging easier when ports can't be found
* refactor: fix race condition and clean up port detection code
- Convert parallel HTTP port checks to sequential to prevent race conditions
where multiple goroutines could allocate the same available port
- Remove unused 'sync' import since WaitGroup is no longer used
- Add documentation to localhost wrapper functions explaining they are
kept for backwards compatibility and future use
- All gRPC port logic is now exclusively handled in initializeGrpcPortsOnIP
eliminating any duplication in ensureAllPortsAvailableOnIP
* refactor: address code review comments - constants, helper function, and cleanup
- Define GrpcPortOffset constant (10000) to replace magic numbers throughout
the code for better maintainability and consistency
- Extract bindIp determination logic into getBindIp() helper function
to eliminate code duplication between runMini and startMiniServices
- Remove redundant 'calculatedPort = calculatedPort' assignment that had no effect
- Update all gRPC port calculations to use GrpcPortOffset constant
(lines 489, 886 and the error logging at line 501)
* refactor: remove unused wrapper functions and update documentation
- Remove unused localhost wrapper functions that were never called:
- isPortOpen() - wrapper around isPortOpenOnIP with hardcoded 127.0.0.1
- findAvailablePort() - wrapper around findAvailablePortOnIP with hardcoded 127.0.0.1
- ensurePortAvailable() - wrapper around ensurePortAvailableOnIP with hardcoded 127.0.0.1
- ensureAllPortsAvailable() - wrapper around ensureAllPortsAvailableOnIP with hardcoded 127.0.0.1
Since this is new functionality with no backwards compatibility concerns,
these wrapper functions were not needed. The comments claiming they were
'kept for future use or backwards compatibility' are no longer valid.
- Update documentation to reference GrpcPortOffset constant instead of hardcoded 10000:
- Update comment in ensureAllPortsAvailableOnIP to use GrpcPortOffset
- Update admin.port.grpc flag help text to reference GrpcPortOffset
Note: getBindIp() is actually being used and should be retained (contrary to
the review comment suggesting it was unused - it's called in both runMini
and startMiniServices functions)
* refactor: prevent HTTP/gRPC port collisions and improve error handling
- Add upfront reservation of all calculated gRPC ports before allocating HTTP ports
to prevent collisions where an HTTP port allocation could use a port that will
later be needed for a gRPC port calculation.
Example scenario that is now prevented:
- Master HTTP reallocated from 9333 to 9334 (original in use)
- Filer HTTP search finds 19334 available and assigns it
- Master gRPC calculated as 9334 + GrpcPortOffset = 19334 → collision!
Now: reserved gRPC ports are tracked upfront and HTTP port search skips them.
- Improve admin server gRPC port fallback error handling:
- Change from silent V(1) verbose log to Warningf to make the error visible
- Update comment to clarify this indicates a problem in the port initialization sequence
- Add explanation that the fallback calculation may cause bind failure
- Update ensureAllPortsAvailableOnIP comment to clarify it avoids reserved ports
* fix: enforce reserved ports in HTTP allocation and improve admin gRPC fallback
Critical fixes for port allocation safety:
1. Make findAvailablePortOnIP and ensurePortAvailableOnIP aware of reservedPorts:
- Add reservedPorts map parameter to both functions
- findAvailablePortOnIP now skips reserved ports when searching for alternatives
- ensurePortAvailableOnIP passes reservedPorts through to findAvailablePortOnIP
- This prevents HTTP ports from being allocated to ports reserved for gRPC
2. Update ensureAllPortsAvailableOnIP to pass reservedPorts:
- Pass the reservedPorts map to ensurePortAvailableOnIP calls
- Maintains the map updates (delete/add) for accuracy as ports change
3. Replace blind admin gRPC port fallback with proper availability checks:
- Previous code just calculated *miniAdminOptions.port + GrpcPortOffset
- New code checks both the calculated port and finds alternatives if needed
- Uses the same availability checking logic as initializeGrpcPortsOnIP
- Properly logs the fallback process and any port changes
- Will fail gracefully if no available ports found (consistent with other services)
These changes eliminate two critical vulnerabilities:
- HTTP port allocation can no longer accidentally claim gRPC ports
- Admin gRPC port fallback no longer blindly uses an unchecked port
* fix: prevent gRPC port collisions during multi-service fallback allocation
Critical fix for gRPC port allocation safety across multiple services:
Problem: When multiple services need gRPC port fallback allocation in sequence
(e.g., Master gRPC unavailable → finds alternative, then Filer gRPC unavailable
→ searches from calculated port), there was no tracking of previously allocated
gRPC ports. This could allow two services to claim the same port.
Scenario that is now prevented:
- Master gRPC: calculated 19333 unavailable → finds 19334 → assigns 19334
- Filer gRPC: calculated 18888 unavailable → searches from 18889, might land on
19334 if consecutive ports in range are unavailable (especially with custom
port configurations or in high-port-contention environments)
Solution:
- Add allocatedGrpcPorts map to track gRPC ports allocated within the function
- Check allocatedGrpcPorts before using calculated port for each service
- Pass allocatedGrpcPorts to findAvailablePortOnIP when finding fallback ports
- Add allocatedGrpcPorts[port] = true after each successful allocation
- This ensures no two services can allocate the same gRPC port
The fix handles both:
1. Calculated gRPC ports (when grpcPort == 0)
2. Explicitly set gRPC ports (when user provides -service.port.grpc value)
While default port spacing makes collision unlikely, this fix is essential for:
- Custom port configurations
- High-contention environments
- Edge cases with many unavailable consecutive ports
- Correctness and safety guarantees
* feat: enforce hard-fail behavior for explicitly specified ports
When users explicitly specify a port via command-line flags (e.g., -s3.port=8333),
the server should fail immediately if the port is unavailable, rather than silently
falling back to an alternative port. This prevents user confusion and makes misconfiguration
failures obvious.
Changes:
- Modified ensurePortAvailableOnIP() to check if a port was explicitly passed via isFlagPassed()
- If an explicit port is unavailable, return error instead of silently allocating alternative
- Updated ensureAllPortsAvailableOnIP() to handle the returned error and fail startup
- Modified runMini() to check error from ensureAllPortsAvailableOnIP() and return false on failure
- Default ports (not explicitly specified) continue to fallback to available alternatives
This ensures:
- Explicit ports: fail if unavailable (e.g., -s3.port=8333 fails if 8333 is taken)
- Default ports: fallback to alternatives (e.g., s3.port without flag falls back to 8334 if 8333 taken)
* fix: accurate error messages for explicitly specified unavailable ports
When a port is explicitly specified via CLI flags but is unavailable, the error message
now correctly reports the originally requested port instead of reporting a fallback port
that was calculated internally.
The issue was that the config file applied after CLI flag parsing caused isFlagPassed()
to return true for ports loaded from the config file (since flag.Visit() was called during
config file application), incorrectly marking them as explicitly specified.
Solution: Capture which port flags were explicitly passed on the CLI BEFORE the config file
is applied, storing them in the explicitPortFlags map. This preserves the accurate
distinction between user-specified ports and defaults/config-file ports.
Example:
- User runs: weed mini -dir=. -s3.port=22
- Now correctly shows: 'port 22 for S3 (specified by flag s3.port) is not available'
- Previously incorrectly showed: 'port 8334 for S3...' (some calculated fallback)
* fix: respect explicitly specified ports and prevent config file override
When a port is explicitly specified via CLI flags (e.g., -s3.port=8333),
the config file options should NOT override it. Previously, config file
options would be applied if the flag value differed from default, but
this check wasn't sufficient to prevent override in all cases.
Solution: Check the explicitPortFlags map before applying any config file
port options. If a port was explicitly passed on the CLI, skip applying
the config file option for that port.
This ensures:
- Explicit ports take absolute precedence over config file ports
- Config file ports are only used if port wasn't specified on CLI
- Example: 'weed mini -s3.port=8333' will use 8333, never the config file value
* fix: don't print usage on port allocation error
When a port allocation fails (e.g., explicit port is unavailable), exit
immediately without showing the usage example. This provides cleaner
error output when the error is expected (port conflict).
* refactor: clean up code quality issues
Remove no-op assignment (calculatedPort = calculatedPort) that had no effect.
The variable already holds the correct value when no alternative port is
found.
Improve documentation for the defensive gRPC port initialization fallback
in startAdminServer. While this code shouldn't execute in normal flow
because ensureAllPortsAvailableOnIP is called earlier in runMini, the
fallback handles edge cases where port initialization may have been skipped
or failed silently due to configuration changes or error handling paths.
* fix: improve worker reconnection robustness and prevent handleOutgoing hang
- Add dedicated streamFailed signaling channel to abort registration waits early when stream dies
- Add per-connection regWait channel to route RegistrationResponse separately from shared incoming channel, avoiding race where other consumers steal the response
- Refactor handleOutgoing() loop to use select on streamExit/errCh, ensuring old handlers exit cleanly on reconnect (prevents stale senders competing with new stream)
- Buffer msgCh to reduce shutdown edge cases
- Add cleanup of streamFailed and regWait channels on reconnect/disconnect
- Fixes registration timeout and potential stream lifecycle hangs on aggressive server max_age recycling
* fix: prevent deadlock when stream error occurs - make cmds send non-blocking
If managerLoop is blocked (e.g., waiting on regWait), a blocking send to cmds
will deadlock handleIncoming. Make the send non-blocking to prevent this.
* fix: address code review comments on mini.go port allocation
- Remove flawed fallback gRPC port initialization and convert to fatal error
(ensures port initialization issues are caught immediately instead of silently
failing with an empty reserved ports map)
- Extract common port validation logic to eliminate duplication between
calculated and explicitly set gRPC port handling
* Fix critical race condition and improve error handling in worker client
- Capture channel pointers before checking for nil (prevents TOCTOU race with reconnect)
- Use async fallback goroutine for cmds send to prevent error loss when manager is busy
- Consistently close regWait channel on disconnect (matches streamFailed behavior)
- Complete cleanup of channels on failed registration
- Improve error messages for clarity (replace 'timeout' with 'failed' where appropriate)
* Add debug logging for registration response routing
Add glog.V(3) and glog.V(2) logs to track successful and dropped registration
responses in handleIncoming, helping diagnose registration issues in production.
* Update weed/worker/client.go
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Ensure stream errors are never lost by using async fallback
When handleIncoming detects a stream error, queue ActionStreamError to managerLoop
with non-blocking send. If managerLoop is busy and cmds channel is full, spawn an
async goroutine to queue the error asynchronously. This ensures the manager is
always notified of stream failures, preventing the connection from remaining in an
inconsistent state (connected=true while stream is dead).
* Refactor handleOutgoing to eliminate duplicate error handling code
Extract error handling and cleanup logic into helper functions to avoid duplication
in nested select statements. This improves maintainability and reduces the risk of
inconsistencies when updating error handling logic.
* Prevent goroutine leaks by adding timeouts to blocking cmds sends
Add 2-second timeouts to both handleStreamError and the async fallback goroutine
when sending ActionStreamError to cmds channel. This prevents the handleOutgoing
and handleIncoming goroutines from blocking indefinitely if the managerLoop is
no longer receiving (e.g., during shutdown), preventing resource leaks.
* Properly close regWait channel in reconnect to prevent resource leaks
Close the regWait channel before setting it to nil in reconnect(), matching the
pattern used in handleDisconnect(). This ensures any goroutines waiting on this
channel during reconnection are properly signaled, preventing them from hanging.
* Use non-blocking async pattern in handleOutgoing error reporting
Refactor handleStreamError to use non-blocking send with async fallback goroutine,
matching the pattern used in handleIncoming. This allows handleOutgoing to exit
immediately when errors occur rather than blocking for up to 2 seconds, improving
responsiveness and consistency across handlers.
* fix: drain regWait channel before closing to prevent message loss
- Add drain loop before closing regWait in reconnect() cleanup
- Add drain loop before closing regWait in handleDisconnect() cleanup
- Ensures no pending RegistrationResponse messages are lost during channel closure
* docs: add comments explaining regWait buffered channel design
- Document that regWait buffer size 1 prevents race conditions
- Explain non-blocking send pattern between sendRegistration and handleIncoming
- Clarify timing of registration response handling in handleIncoming
* fix: improve error messages and channel handling in sendRegistration
- Clarify error message when stream fails before registration sent
- Use two-value receive form to properly detect closed channels
- Better distinguish between closed channel and nil value scenarios
* refactor: extract drain and close channel logic into helper function
- Create drainAndCloseRegWaitChannel() helper to eliminate code duplication
- Replace 3 copies of drain-and-close logic with single function call
- Improves maintainability and consistency across cleanup paths
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>