Skip to content

[Bug]: If 3 volume snapshots fail in a row, the instance manager stops functioning (connection pool exhausted) #6761

Closed

Description

@jmealo

Is there an existing issue already for this bug?

  • I have searched for an existing issue, and could not find anything. I believe this is a new bug.

I have read the troubleshooting guide

  • I have read the troubleshooting guide and I think this is a new bug.

I am running a supported version of CloudNativePG

  • I have read the troubleshooting guide and I think this is a new bug.

Contact Details

[email protected]

Version

1.25 (latest patch)

What version of Kubernetes are you using?

1.29

What is your Kubernetes environment?

Cloud: Azure AKS

How did you install the operator?

YAML manifest

What happened?

When 3 scheduled volume snapshots fail in a row. The super user connection pool becomes exhausted in the instance manger. This causes all endpoints except /healthz to fail. This causes a near total failure of CNPG.

Impact:

  • All scheduled backups start to fail (due to endpoints hanging)
  • You run out of WAL space
  • Metrics are no longer collected
  • Hibernate fails
  • cnpg status hangs
  • All HTTP endpoints except /healthz hang
  • Instance manager can no longer be updated in-place

Depending on when you catch it, the real reason for the volume snapshot failure will be buried by context cancelled: deadline exceeded (because only the first 2-3 attempts can start a backup, the other ones hang getting the cluster status).

This PR has the beginnings of a fix, but there's more to be done:
jmealo#1

Big shout outs to the Gophers in the Go Slack:

@farhaven and nbraun

Cluster resource

Not relevant

Relevant log output

postgres=# SELECT pid, age(clock_timestamp(), query_start), usename, query 
FROM pg_stat_activity 
WHERE query != '<IDLE>' AND query NOT ILIKE '%pg_stat_activity%' 
ORDER BY query_start desc;
 pid  |       age       | usename  |                      query                       
------+-----------------+----------+--------------------------------------------------
   26 |                 |          | 
   27 |                 |          | 
   28 |                 |          | 
  204 |                 |          | 
 3886 | 00:03:55.430776 | postgres | SELECT pg_backup_start(label => $1, fast => $2);
 2518 | 01:04:35.711006 | postgres | SELECT pg_backup_start(label => $1, fast => $2);
 1112 | 02:06:57.669102 | postgres | SELECT pg_backup_start(label => $1, fast => $2);
(7 rows)

postgres=# 

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. added
    triage
    on Feb 4, 2025
  2. jmealo commented on Feb 5, 2025

    @jmealo
    ContributorAuthor

    Is there a reason that the connection is held until the backup completes (never being released if it fails)? The Postgres docs make it sound like this is unnecessary.

  3. added this to the 1.25.1 milestone on Feb 7, 2025
  4. added
    bug 🐛
    backport-requested ◀️
    and removed
    triage
    on Feb 7, 2025
  5. mnencia commented on Feb 7, 2025

    @mnencia
    Member

    Thank you for reporting this issue; this is important and needs to be fixed.

    Is there a reason that the connection is held until the backup completes (never being released if it fails)? The Postgres docs make it sound like this is unnecessary.

    Concurrent backups are aborted if the controlling connection is terminated.

  6. armru commented on Feb 13, 2025

    @armru
    Member

    Hello @jmealo, could you please post the cnpg.backup and volumesnapshot resources yaml with their respective status connected to those stuck backups?

  7. jmealo commented on Feb 13, 2025

    @jmealo
    ContributorAuthor

    @armru: I have a fix for the issue and the bug is easy to reproduce (takes 1-3 minutes).

    Set a scheduled backup to minute or second intervals. Two volume snapshots against the same volume can't be in progress at once on most clouds. That will cause the connection exhaustion in 4x backup interval.

    What needs to be fixed/addressed or documented:

    • CNPG allows multiple failed backups to keep connections open indefinitely
    • CNPG shares a single 3 connection pool for backups, status, and metrics*
    • CNPG allows multiple in-flight /pg/status calls to queue indefinitely for a connection*
    • CNPG does not pass around context to queries to allow for timeout or cancellation
    • CNPG does not have query or http response timeouts
    • CNPG requires a connection to do an in-place upgrade*

    * My PR fixes these. I need to rebase it over main, most of it is on my fork.

    Azure has been giving us 502s for volume snapshots. I can try to get you some backup or volume snapshots but the work is all outlined above.

  8. jmealo commented on Feb 13, 2025

    @jmealo
    ContributorAuthor

    @armru cnpg.backup:

    {
        "apiVersion": "postgresql.cnpg.io/v1",
        "kind": "Backup",
        "metadata": {
            "annotations": {
                "cnpg.io/operatorVersion": "1.25.0"
            },
            "creationTimestamp": "2025-02-13T13:00:00Z",
            "generation": 1,
            "labels": {
                "cnpg.io/cluster": "production-pg-etl",
                "cnpg.io/immediateBackup": "false",
                "cnpg.io/scheduled-backup": "production-pg-etl-hourly-volume-snapshot"
            },
            "name": "production-pg-etl-hourly-volume-snapshot-20250213130000",
            "namespace": "db",
            "ownerReferences": [
                {
                    "apiVersion": "postgresql.cnpg.io/v1",
                    "controller": true,
                    "kind": "Cluster",
                    "name": "production-pg-etl",
                    "uid": "80ca9a97-5203-48f2-959b-679cad4ec3db"
                }
            ],
            "resourceVersion": "940404148",
            "uid": "7a852fee-8d6a-42c3-827d-8d874c9f53d1"
        },
        "spec": {
            "cluster": {
                "name": "production-pg-etl"
            },
            "method": "volumeSnapshot"
        },
        "status": {
            "backupId": "production-pg-etl-hourly-volume-snapshot-20250213130000",
            "backupName": "production-pg-etl-hourly-volume-snapshot-20250213130000",
            "error": "can't execute snapshot backup: while trying to start the backup: while executing http request: Post \"https://10.130.1.165:8000/pg/mode/backup\": context deadline exceeded (Client.Timeout exceeded while awaiting headers)",
            "instanceID": {
                "ContainerID": "containerd://33fd08ac359d9fc9c0a4b3494d3d20a3f460ee9dbcd1fdc57c923424dc61e4b5",
                "podName": "production-pg-etl-1"
            },
            "method": "volumeSnapshot",
            "phase": "failed",
            "startedAt": "2025-02-13T13:00:00Z"
        }
    }
    

    @armru As you can see, no underlying volume snapshot here, because the backup connection pool is exhausted, it never gets that far.
    This behavior can ONLY be seen on my fork. CNPG as-is would have timed out on /pg/status not /pg/mode/backup.

  9. 48 remaining items

  10. jmealo commented on Feb 19, 2025

    @jmealo
    ContributorAuthor

    @mnencia: Building now. I have this deployed in staging. I'll let three hours pass and see where we're at. (I have hourly volume snapshots)

  11. jmealo commented on Feb 20, 2025

    @jmealo
    ContributorAuthor

    @mnencia: Tests look good overnight in staging. 👍 No not ready pods. We'll deploy to production shortly.

  12. jmealo commented on Feb 20, 2025

    @jmealo
    ContributorAuthor

    @mnencia: my operator manager briefly entered a crash loop (for about a minute)... I only noticed because this release requires a reload of the cluster to clear the old stuck backups. I don't know if that's all we need to add to the release notes or if we should share queries to run against each instance to check for stuck backups? @gbartolini

    In terms of release notes:
    Do we think we want to provide a query and instructions on how to run it against each instance to check for the presence of stuck backups, or should folks just check for failed backups via k8s?

    Simplest approach:
    Should we simply suggest folks do a reload if they have any failed backups?

    Reasoning:
    The presence of failed backups (via k8s) is easier to check for than the stuck backups.

  13. jmealo commented on Feb 20, 2025

    @jmealo
    ContributorAuthor

    @mnencia: these timed out in as little as 40 seconds, and did not provide helpful error information.

    When I describe the volumesnapshot (in the one case they were created, despite the timeout):

    ❯ kubectl describe -n db volumesnapshot production-pg-common1-20250220131634
    Name:         production-pg-common1-20250220131634
    Namespace:    db
    Labels:       cnpg.io/backupDate=20250220
                  cnpg.io/backupMonth=202502
                  cnpg.io/backupName=production-pg-common1-20250220131634
                  cnpg.io/backupTimeline=1
                  cnpg.io/backupYear=2025
                  cnpg.io/cluster=production-pg-common1
    Annotations:  cnpg.io/backupEndWAL: 00000001000000260000000D
                  cnpg.io/backupStartWAL: 00000001000000260000000D
                  cnpg.io/clusterManifest:
                    {"kind":"Cluster","apiVersion":"postgresql.cnpg.io/v1","metadata":{"name":"production-pg-common1","namespace":"db","uid":"028c3449-3387-48...
                  cnpg.io/instanceName: production-pg-common1-2
                  cnpg.io/instanceRole: replica
                  cnpg.io/nodeSerial: 2
                  cnpg.io/onlineBackup: false
                  cnpg.io/operatorVersion: 1.25.0
                  cnpg.io/pgControldata:
                    pg_control version number:            1700
                    Catalog version number:               202406281
                    Database system identifier:           7472873182127792153
                    Database cluster state:               in archive recovery
                    pg_control last modified:             Thu 20 Feb 2025 06:17:09 PM UTC
                    Latest checkpoint location:           26/85AE64F0
                    Latest checkpoint's REDO location:    26/D0FF8D0
                    Latest checkpoint's REDO WAL file:    00000001000000260000000D
                    Latest checkpoint's TimeLineID:       1
                    Latest checkpoint's PrevTimeLineID:   1
                    Latest checkpoint's full_page_writes: on
                    Latest checkpoint's NextXID:          0:52283592
                    Latest checkpoint's NextOID:          23456
                    Latest checkpoint's NextMultiXactId:  2735841
                    Latest checkpoint's NextMultiOffset:  9644680
                    Latest checkpoint's oldestXID:        730
                    Latest checkpoint's oldestXID's DB:   1
                    Latest checkpoint's oldestActiveXID:  52283587
                    Latest checkpoint's oldestMultiXid:   1
                    Latest checkpoint's oldestMulti's DB: 1
                    Latest checkpoint's oldestCommitTsXid:0
                    Latest checkpoint's newestCommitTsXid:0
                    Time of latest checkpoint:            Thu 20 Feb 2025 05:59:35 PM UTC
                    Fake LSN counter for unlogged rels:   0/3E8
                    Minimum recovery ending location:     27/7BD0A0
                    Min recovery ending loc's timeline:   1
                    Backup start location:                0/0
                    Backup end location:                  0/0
                    End-of-backup record required:        no
                    wal_level setting:                    logical
                    wal_log_hints setting:                on
                    max_connections setting:              200
                    max_worker_processes setting:         8
                    max_wal_senders setting:              16
                    max_prepared_xacts setting:           0
                    max_locks_per_xact setting:           64
                    track_commit_timestamp setting:       off
                    Maximum data alignment:               8
                    Database block size:                  8192
                    Blocks per segment of large relation: 131072
                    WAL block size:                       8192
                    Bytes per WAL segment:                16777216
                    Maximum length of identifiers:        64
                    Maximum columns in an index:          32
                    Maximum size of a TOAST chunk:        1996
                    Size of a large-object chunk:         2048
                    Date/time type storage:               64-bit integers
                    Float8 argument passing:              by value
                    Data page checksum version:           0
                    Mock authentication nonce:            abce64f8dba59c2765144399a0a8cd00e78a4e6b9b883c3fd223e88b15a56e5b
                  cnpg.io/pvcRole: PG_DATA
                  cnpg.io/pvcStatus: ready
                  pv.kubernetes.io/bind-completed: yes
                  pv.kubernetes.io/bound-by-controller: yes
                  role: replica
                  volume.beta.kubernetes.io/storage-provisioner: disk.csi.azure.com
                  volume.kubernetes.io/selected-node: aks-pgcommon1-36874012-vmss000003
                  volume.kubernetes.io/storage-provisioner: disk.csi.azure.com
    API Version:  snapshot.storage.k8s.io/v1
    Kind:         VolumeSnapshot
    Metadata:
      Creation Timestamp:             2025-02-20T18:17:09Z
      Deletion Grace Period Seconds:  0
      Deletion Timestamp:             2025-02-20T18:22:00Z
      Finalizers:
        snapshot.storage.kubernetes.io/volumesnapshot-bound-protection
      Generation:  2
      Owner References:
        API Version:     postgresql.cnpg.io/v1
        Controller:      true
        Kind:            Backup
        Name:            production-pg-common1-20250220131634
        UID:             6c2b6c22-79a8-4887-8147-4702db97eeeb
      Resource Version:  952947094
      UID:               ee912eed-04f1-4710-b287-f90c363f5981
    Spec:
      Source:
        Persistent Volume Claim Name:  production-pg-common1-2
      Volume Snapshot Class Name:      csi-azure-disk
    Status:
      Bound Volume Snapshot Content Name:  snapcontent-ee912eed-04f1-4710-b287-f90c363f5981
      Error:
        Message:     Failed to create snapshot: failed to take snapshot of the volume /subscriptions/19ea338e-67f7-4a2f-a165-6ccdb9c1aecb/resourceGroups/mc_application_production-app-cluster_eastus/providers/Microsoft.Compute/disks/pvc-1f002cd0-da26-4cda-a994-a47894ae2485: "rpc error: code = Internal desc = waitForSnapshotReady(, mc_application_production-app-cluster_eastus, snapshot-ee912eed-04f1-4710-b287-f90c363f5981) failed with Retriable: true, RetryAfter: 0s, HTTPStatusCode: 502, RawError: Internal Server Error"
        Time:        2025-02-20T18:19:12Z
      Ready To Use:  false
    Events:
      Type    Reason            Age   From                 Message
      ----    ------            ----  ----                 -------
      Normal  CreatingSnapshot  14m   snapshot-controller  Waiting for a snapshot db/production-pg-common1-20250220131634 to be created by the CSI driver.
    
    production-pg-common1-20250220131010                             2m19s   production-pg-common1   volumeSnapshot      failed      can't execute snapshot backup: while trying to start the backup: while executing http request: Post "https://10.130.10.156:8000/pg/mode/backup": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
    production-pg-common1-daily-object-store-backup-20250219000000   42h     production-pg-common1   barmanObjectStore   completed   
    production-pg-common1-daily-object-store-backup-20250220000000   18h     production-pg-common1   barmanObjectStore   completed   
    production-pg-etl-20250220131014                                 2m16s   production-pg-etl       volumeSnapshot      failed      can't execute snapshot backup: while trying to start the backup: while executing http request: Post "https://10.130.1.164:8000/pg/mode/backup": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
    
  14. added a commit that references this issue on Feb 25, 2025
    d4a0166
  15. added a commit that references this issue on Feb 25, 2025
    e2bcca8
  16. added 2 commits that reference this issue on Feb 25, 2025
    eebed3b
    b5c211a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

backport-requested ◀️bug 🐛

Type

Projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions