Skip to content

better handling of restarts during initialisation - #287

Merged
scott-cotton merged 1 commit into
mainfrom
tp-monitor-add-init-timeout
Dec 11, 2025
Merged

scott-cotton merged 1 commit into
mainfrom
tp-monitor-add-init-timeout

Conversation

@scott-cotton

@scott-cotton scott-cotton commented Dec 11, 2025 •

Copy link
Copy Markdown
Member

There was a class of unrecoverable errors that occurred frequently when using the CLI:

✗ Local connection not healthy!
* failed to configure hosts in /etc/hosts ("rpc error: code = Unavailable desc = connection error: desc = \"transport: Error while dialing: socks connect tcp :59350->tunnel-api.signadot.svc:9070: dial tcp :59350: connect: connection refused\"")

This error state was unrecoverable and required manual disconnect/reconnect to resolve.

The tunnel proxy monitor (tpMonitor) was detecting when localnetSVC and etcHostsSVC became unhealthy, but never actually restarting them to recover. The old code would:

  1. Detect unhealthy service status
  2. Return false from checkTunnelProxyAccess()
  3. Continue checking every second
  4. Never trigger a restart (except in very specific cases like tunnel proxy address changes or agent-metrics failures)

This meant that when services encountered connection errors (like "connection refused" to the tunnel proxy), they would remain in an unhealthy state indefinitely, requiring manual intervention.

This change implements automatic recovery by:

  1. Adding a startup grace period: Introduces a 30-second grace period during initial startup to allow services time to become healthy before restarting them.

  2. Implementing automatic restart logic: After the startup period, when services become unhealthy, the monitor now automatically restarts them to recover.

  3. Improving state management: Tracks the starting phase with beginStarting timestamp and properly manages state transitions between starting and running states.

  4. Refactoring for maintainability: Extracts the restart decision logic into a shouldRestartDueToUnhealthy() helper function to reduce code duplication.

  5. Added maxStartingTime constant (10 seconds): Defines the grace period for services to become healthy during startup.

  6. Added beginStarting field: Tracks when the starting phase began to implement the timeout logic.

  7. Modified run() method:

    • Initializes starting and beginStarting at the start of the monitoring loop
    • Properly manages state transitions, resetting beginStarting when transitioning from not-starting to starting
    • Sets starting = false when checks succeed
  8. Modified checkTunnelProxyAccess() method:

    • Separates nil checks from health checks for better clarity
    • Critical fix: When services are unhealthy after startup, sets restartSvcs = true to trigger automatic restart
    • During startup: waits up to maxStartingTime before restarting (prevents restart loops during initial startup)
  9. Added shouldRestartDueToUnhealthy() helper: Centralizes the logic for determining when to restart unhealthy services, reducing duplication.

Before (Old Code):

if rootMgr.localnetSVC == nil || !rootMgr.localnetSVC.Status().Healthy {
    return false  // ❌ Never restarts!
}

After (New Code):

if !rootMgr.localnetSVC.Status().Healthy {
    if shouldRestart := mon.shouldRestartDueToUnhealthy(); shouldRestart {
        restartSvcs = true  // ✅ Triggers restart!
    } else {
        return false  // Wait during startup grace period
    }
}

When the etcHostsSVC service encounters a connection error (like "connection refused" to the tunnel proxy):

  1. Detection: The monitor detects that etcHostsSVC.Status().Healthy is false
  2. Decision: After the startup grace period, shouldRestartDueToUnhealthy() returns true
  3. Recovery: restartSvcs is set to true, triggering:
    • stopLocalnetService() and runLocalnetService()
    • stopEtcHostsService() and runEtcHostsService()
  4. Reconnection: Services restart with fresh connections to the tunnel proxy
  5. Automatic Recovery: The system recovers automatically without manual intervention
  • ✅ Automatic recovery: Services automatically restart when they become unhealthy

  • ✅ Prevents restart loops: Grace period during startup prevents premature restarts

  • ✅ Better maintainability: Extracted helper function reduces code duplication

  • ✅ No breaking changes: Maintains backward compatibility with existing behavior

  • ✅ Improved reliability: Eliminates the need for manual disconnect/reconnect cycles

  • Verify that services recover automatically after connection errors

  • Ensure startup grace period prevents restart loops during initial startup

  • Confirm that services restart appropriately when they become unhealthy after startup

  • Test that the monitor continues to work correctly for tunnel proxy address changes

There was a class of unrecoverable errors that occurred frequently when using the CLI:

```
✗ Local connection not healthy!
* failed to configure hosts in /etc/hosts ("rpc error: code = Unavailable desc = connection error: desc = \"transport: Error while dialing: socks connect tcp :59350->tunnel-api.signadot.svc:9070: dial tcp :59350: connect: connection refused\"")
```

This error state was unrecoverable and required manual disconnect/reconnect to resolve.

The tunnel proxy monitor (`tpMonitor`) was detecting when `localnetSVC` and `etcHostsSVC` became unhealthy, but **never actually restarting them** to recover. The old code would:

1. Detect unhealthy service status
2. Return `false` from `checkTunnelProxyAccess()`
3. Continue checking every second
4. **Never trigger a restart** (except in very specific cases like tunnel proxy address changes or agent-metrics failures)

This meant that when services encountered connection errors (like "connection refused" to the tunnel proxy), they would remain in an unhealthy state indefinitely, requiring manual intervention.

This change implements automatic recovery by:

1. **Adding a startup grace period**: Introduces a 10-second grace period during initial startup to allow services time to become healthy before restarting them.

2. **Implementing automatic restart logic**: After the startup period, when services become unhealthy, the monitor now automatically restarts them to recover.

3. **Improving state management**: Tracks the starting phase with `beginStarting` timestamp and properly manages state transitions between starting and running states.

4. **Refactoring for maintainability**: Extracts the restart decision logic into a `shouldRestartDueToUnhealthy()` helper function to reduce code duplication.

1. **Added `maxStartingTime` constant** (10 seconds): Defines the grace period for services to become healthy during startup.

2. **Added `beginStarting` field**: Tracks when the starting phase began to implement the timeout logic.

3. **Modified `run()` method**:
   - Initializes `starting` and `beginStarting` at the start of the monitoring loop
   - Properly manages state transitions, resetting `beginStarting` when transitioning from not-starting to starting
   - Sets `starting = false` when checks succeed

4. **Modified `checkTunnelProxyAccess()` method**:
   - Separates nil checks from health checks for better clarity
   - **Critical fix**: When services are unhealthy after startup, sets `restartSvcs = true` to trigger automatic restart
   - During startup: waits up to `maxStartingTime` before restarting (prevents restart loops during initial startup)

5. **Added `shouldRestartDueToUnhealthy()` helper**: Centralizes the logic for determining when to restart unhealthy services, reducing duplication.

**Before (Old Code):**
```go
if rootMgr.localnetSVC == nil || !rootMgr.localnetSVC.Status().Healthy {
    return false  // ❌ Never restarts!
}
```

**After (New Code):**
```go
if !rootMgr.localnetSVC.Status().Healthy {
    if shouldRestart := mon.shouldRestartDueToUnhealthy(); shouldRestart {
        restartSvcs = true  // ✅ Triggers restart!
    } else {
        return false  // Wait during startup grace period
    }
}
```

When the `etcHostsSVC` service encounters a connection error (like "connection refused" to the tunnel proxy):

1. **Detection**: The monitor detects that `etcHostsSVC.Status().Healthy` is `false`
2. **Decision**: After the startup grace period, `shouldRestartDueToUnhealthy()` returns `true`
3. **Recovery**: `restartSvcs` is set to `true`, triggering:
   - `stopLocalnetService()` and `runLocalnetService()`
   - `stopEtcHostsService()` and `runEtcHostsService()`
4. **Reconnection**: Services restart with fresh connections to the tunnel proxy
5. **Automatic Recovery**: The system recovers automatically without manual intervention

- ✅ **Automatic recovery**: Services automatically restart when they become unhealthy
- ✅ **Prevents restart loops**: Grace period during startup prevents premature restarts
- ✅ **Better maintainability**: Extracted helper function reduces code duplication
- ✅ **No breaking changes**: Maintains backward compatibility with existing behavior
- ✅ **Improved reliability**: Eliminates the need for manual disconnect/reconnect cycles

- Verify that services recover automatically after connection errors
- Ensure startup grace period prevents restart loops during initial startup
- Confirm that services restart appropriately when they become unhealthy after startup
- Test that the monitor continues to work correctly for tunnel proxy address changes

@daniel-de-vera daniel-de-vera left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@scott-cotton
scott-cotton merged commit ec1f3b3 into main Dec 11, 2025
@scott-cotton
scott-cotton deleted the tp-monitor-add-init-timeout branch December 11, 2025 13:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants