DEV Community

Zach S. for Google Cloud

Posted on

Catching sub-minute Cloud Router BGP flaps and silent route withdrawals with gcloud and jq

Alert policies built on router.googleapis.com/bgp/session_up catch hard outages, yet two common hybrid routing failures slip right past them. bgp/session_up is sampled once every 60 seconds and can take up to 180 seconds to appear in Cloud Monitoring (see Google Cloud metrics: P through Z | Cloud Monitoring). A BGP session that drops and recovers within 15 to 20 seconds between samples looks completely flat (1 -> 1 -> 1). Likewise, if an on-premises router withdraws a critical prefix while keeping BGP Established, bgp/session_up never moves.

You can close both gaps by querying live router state directly from Method: routers.getRouterStatus | Compute Engine. Each response includes per-peer uptimeSeconds, BGP state, optional BFD diagnostics, and active learned routes. Comparing uptimeSeconds across polls catches fast resets even after recovery, and checking learned routes against expected prefixes catches silent withdrawals right away.

What get-status exposes beyond Cloud Monitoring

Running gcloud compute routers get-status | Google Cloud SDK with --format=json returns two key arrays: result.bgpPeerStatus[] and result.bestRoutesForRouter[]. Here is a trimmed peer entry from a Cloud Interconnect VLAN attachment with BFD enabled:

{
  "bfdStatus": {
    "bfdSessionInitializationMode": "ACTIVE",
    "localDiagnostic": "NO_DIAGNOSTIC",
    "localState": "UP",
    "negotiatedLocalControlTxIntervalMs": 1000,
    "uptimeMs": "409548112"
  },
  "enableIpv4": true,
  "enableIpv6": false,
  "ipAddress": "169.254.10.1",
  "md5AuthEnabled": false,
  "name": "peer-vlan-0",
  "numLearnedRoutes": 2,
  "peerIpAddress": "169.254.10.2",
  "state": "Established",
  "status": "UP",
  "uptime": "4 days, 17 hours, 45 minutes, 48 seconds",
  "uptimeSeconds": "409548"
}
Enter fullscreen mode Exit fullscreen mode

Two details matter here. First, uptimeSeconds (and bfdStatus.uptimeMs) comes back as a JSON string, so cast it with tonumber in jq. When uptimeSeconds drops below the prior poll's value, the session bounced in between polls - even if state already reads "Established". Second, bfdStatus.localState and bfdStatus.localDiagnostic help separate fault layers. For example, BGP stuck in "Connect" while BFD stays "UP" points to a TCP 179 filter or config mismatch rather than an underlay drop.

For prefix checks, result.bestRoutesForRouter[] lists the best BGP routes learned by this Cloud Router along with each route's destRange and routeStatus:

"bestRoutesForRouter": [
  {
    "asPaths": [
      {
        "asLists": [
          65002
        ],
        "pathSegmentType": "AS_SEQUENCE"
      }
    ],
    "creationTimestamp": "2026-11-21T11:03:24.015-08:00",
    "destRange": "192.168.100.0/24",
    "kind": "compute#route",
    "network": "https://www.googleapis.com/compute/v1/projects/my-gcp-project/global/networks/vpc-a",
    "nextHopIp": "169.254.10.2",
    "nextHopOrigin": "INCOMPLETE",
    "priority": 0,
    "routeStatus": "ACTIVE",
    "routeType": "BGP"
  }
]
Enter fullscreen mode Exit fullscreen mode

Keep bestRoutesForRouter distinct from the sibling bestRoutes array covered in View router details | Cloud Router. bestRoutesForRouter covers routes learned by this router alone, while bestRoutes shows the winning dynamic routes programmed in the region's VPC (including cross-region routes when global dynamic routing is on). Filtering bestRoutesForRouter on routeStatus == "ACTIVE" confirms that this router still holds your required prefixes and that route quotas didn't drop them.

Checking uptime regressions and active routes with gcloud and jq

This script runs gcloud compute routers get-status, compares uptimeSeconds against a small JSON state file from the previous run, and checks bestRoutesForRouter against your required prefixes. It exits with status 1 if any peer flaps, drops out of Established, disappears, or loses an expected prefix.

#!/bin/bash
set -euo pipefail

# --- Configuration (Replace with your details) ---
PROJECT="<YOUR_PROJECT_ID>"
REGION="<YOUR_REGION>"
ROUTER="<YOUR_CLOUD_ROUTER_NAME>"
EXPECTED_PREFIXES="192.168.100.0/24,192.168.101.0/24"
STATE_FILE="/tmp/cr-bgp-state.json"

PREV_STATE="{}"
if [[ -f "$STATE_FILE" ]]; then
  PREV_STATE=$(cat "$STATE_FILE")
fi

STATUS_JSON=$(gcloud compute routers get-status "$ROUTER" \
    --project="$PROJECT" \
    --region="$REGION" \
    --format=json)

# Compare peer uptimes against the previous poll and verify active learned prefixes
REPORT=$(echo "$STATUS_JSON" | jq \
    --argjson prev "$PREV_STATE" \
    --arg expected_csv "$EXPECTED_PREFIXES" '
  ($expected_csv | split(",") | map(gsub("^\\s+|\\s+$"; "")) | map(select(length > 0))) as $expected |
  ([(.result.bestRoutesForRouter // [])[] | select(.routeStatus == "ACTIVE") | .destRange] | unique) as $active |
  ($expected - $active) as $missing_prefixes |
  (($prev | keys) - [(.result.bgpPeerStatus // [])[].name]) as $missing_peers |
  [
    (.result.bgpPeerStatus // [])[] |
    (.uptimeSeconds // "0" | tonumber) as $cur |
    ($prev[.name] // null) as $last |
    ($last != null and $cur < $last) as $flap |
    (if .bfdStatus then "\(.bfdStatus.localState // "UNKNOWN") (\(.bfdStatus.localDiagnostic // "NONE"))" else "n/a" end) as $bfd |
    {
      alert: (.state != "Established" or $flap),
      line: (
        "Peer: \(.name) | State: \(.state) | Uptime: \($cur)s"
        + (if $flap then " (reset from \($last)s)" else "" end)
        + " | Flap: \($flap) | BFD: \($bfd) | Learned: \(.numLearnedRoutes // 0)"
      )
    }
  ] as $peers |
  {
    has_alert: (($peers | any(.alert)) or ($missing_prefixes | length > 0) or ($missing_peers | length > 0)),
    lines: (
      ($peers | map(.line))
      + (if ($missing_peers | length) > 0 then ["Missing peers: \($missing_peers | join(", "))"] else [] end)
      + [
        if ($missing_prefixes | length) > 0 then
          "Missing active prefixes: \($missing_prefixes | join(", "))"
        else
          "Expected prefixes active: \($expected | join(", "))"
        end
      ]
    )
  }
')

# Persist current peer uptimes for the next poll
echo "$STATUS_JSON" | jq '
  [(.result.bgpPeerStatus // [])[] | {(.name): (.uptimeSeconds // "0" | tonumber)}] | add // {}
' > "$STATE_FILE"

echo "$REPORT" | jq -r '.lines[]'

if [[ $(echo "$REPORT" | jq -r '.has_alert') == "true" ]]; then
  exit 1
fi
Enter fullscreen mode Exit fullscreen mode

On the first run against cr-us-south1, the script saves baseline uptimes and confirms both prefixes are active:

~  bash cr-bgp-health-check.sh

Peer: peer-vlan-0 | State: Established | Uptime: 409548s | Flap: false | BFD: UP (NO_DIAGNOSTIC) | Learned: 2
Peer: peer-vlan-1 | State: Established | Uptime: 812925s | Flap: false | BFD: UP (NO_DIAGNOSTIC) | Learned: 2
Expected prefixes active: 192.168.100.0/24, 192.168.101.0/24
Enter fullscreen mode Exit fullscreen mode

On a later run after peer-vlan-0 bounces for 15 seconds and recovers - while 192.168.102.0/24 is withdrawn upstream - both sessions still read Established. The script catches both issues and exits 1:

~  bash cr-bgp-health-check.sh

Peer: peer-vlan-0 | State: Established | Uptime: 14s (reset from 409548s) | Flap: true | BFD: UP (NO_DIAGNOSTIC) | Learned: 2
Peer: peer-vlan-1 | State: Established | Uptime: 812985s | Flap: false | BFD: UP (NO_DIAGNOSTIC) | Learned: 2
Missing active prefixes: 192.168.102.0/24
Enter fullscreen mode Exit fullscreen mode

Things to watch out for in production

  • Cloud Router maintenance restarts: Google Cloud periodically restarts Cloud Router software tasks, which resets uptimeSeconds while BGP Graceful Restart keeps forwarding traffic. Check Cloud Logging (resource.type="gce_router") for "Router task de-activated" and "Router task activated" events before paging on a single short reset (see View logs and metrics | Cloud Router).
  • Disabled and deleted peers: Deleting a peer makes bgp/session_up stop emitting points instead of writing 0, and --no-enabled emits 0 just like an outage. get-status shows state: "Disabled" (documented in BGP session states | Cloud Router), and diffing against saved peer keys catches deletions on the next poll.
  • Active-passive peers on one router: When two peers on the same router advertise the same prefix with different MEDs or AS paths, bestRoutesForRouter only keeps the winning path. Watch per-peer numLearnedRoutes alongside bestRoutesForRouter if you also want to confirm a standby peer is still sending routes.
  • BFD support: Cloud Router BFD works only on Dedicated Interconnect and Partner Interconnect VLAN attachments - not HA VPN or Router appliance peers (see Bidirectional Forwarding Detection (BFD) overview | Cloud Router). The script defaults to n/a when bfdStatus isn't present.

You can run this check on a timer in Cloud Run Jobs or export the same routers.getRouterStatus fields as custom Cloud Monitoring metrics. It's an easy way to spot fast flaps and silent route drops during cutovers or maintenance windows.

Top comments (3)

Collapse
 
dheerajramasahayam profile image
Dheeraj Ramasahayam •

This is the same trap I hit on the floor with a flapping fiber link: at the moment you check it, the session reads Established and the ticket gets closed as no fault found. What caught it for us was the same idea as your uptimeSeconds check — comparing the session uptime and the interface error counters against the previous check, instead of trusting a single snapshot. A link that bounced 15 seconds ago and recovered looks healthy right now, and the only evidence left is the counter that moved.

Collapse
 
kreout profile image
Andrei Ovcharenko •

One edge case for the uptime comparison: a reset does not always make the next counter smaller. Suppose polls are 60 seconds apart and report 5s, then 20s. A second reset 40 seconds after the first poll produces exactly that pair, but 20 < 5 is false, so $flap stays false.

It would help to persist the sample time alongside each uptime and compare the uptime increase with elapsed time, allowing for integer rounding and request latency. Without a reset, the second uptime should be about 65s in this example; 20s indicates a changed session start time. That pair would make a useful regression test alongside the large-counter-to-small-counter example.

The API defines uptimeSeconds as the time the session has been up, which makes this check possible even when both sampled states are Established.

Collapse
 
zachs profile image
Zach S. Google Cloud •

You're right that cur < last alone misses back-to-back resets when the second counter is larger (like 5s -> 20s over 60 seconds). Saving the poll timestamp and previous peer state alongside each uptimeSeconds value closes that gap.

Comparing ($last.uptime + $elapsed) - $cur against a 5-second tolerance catches the shifted start time while absorbing integer rounding and API latency. Gating on Established -> Established also avoids false flap flags when a peer stays down or cleanly recovers:

NOW=$(date +%s)
TOLERANCE_SEC=5

# In the jq filter (passing --argjson now "$NOW" --argjson tol "$TOLERANCE_SEC"):
#   (if $prev.ts != null and $now >= $prev.ts then ($now - $prev.ts) else null end) as $elapsed |
#   ...
#   ($prev.peers[.name] // null) as $last |
#   (if $last != null and $elapsed != null then ($last.uptime + $elapsed) else null end) as $expected_uptime |
#   (
#     .state == "Established"
#     and $last != null
#     and $last.state == "Established"
#     and (
#       $cur < $last.uptime
#       or ($expected_uptime != null and ($expected_uptime - $cur) > $tol)
#     )
#   ) as $flap

# Persist timestamp, state, and uptime for the next poll
echo "$STATUS_JSON" | jq --argjson now "$NOW" '
  {
    ts: $now,
    peers: ([(.result.bgpPeerStatus // [])[] | {(.name): {state: .state, uptime: (.uptimeSeconds // "0" | tonumber)}}] | add // {})
  }
' > "$STATE_FILE"
Enter fullscreen mode Exit fullscreen mode

With that check in place, a 5s -> 20s pair across a 60-second interval flags Flap: true against expected ~65s. Thanks for calling out that edge case.