From 193e0c7d6f6613f15b5ac991cb3f32c17751a1cd Mon Sep 17 00:00:00 2001 From: andres-portainer <91705312+andres-portainer@users.noreply.github.com> Date: Mon, 7 Nov 2022 20:28:18 -0300 Subject: [PATCH] fix(snapshots): remove snapshots when removing endpoints EE-4527 (#7973) * fix(snapshots): remove snapshots when removing endpoints EE-4527 * Fix nil pointer dereference. Co-authored-by: andres-portainer --- api/datastore/migrator/migrate_ce.go | 3 ++ api/datastore/migrator/migrate_dbversion71.go | 36 +++++++++++++++++++ api/http/handler/endpoints/endpoint_delete.go | 5 +++ 3 files changed, 44 insertions(+) create mode 100644 api/datastore/migrator/migrate_dbversion71.go diff --git a/api/datastore/migrator/migrate_ce.go b/api/datastore/migrator/migrate_ce.go index a767dfee0..82671ba18 100644 --- a/api/datastore/migrator/migrate_ce.go +++ b/api/datastore/migrator/migrate_ce.go @@ -110,6 +110,9 @@ func (m *Migrator) Migrate() error { // Portainer 2.16 newMigration(70, m.migrateDBVersionToDB70), + + // Portainer 2.16.1 + newMigration(71, m.migrateDBVersionToDB71), } var lastDbVersion int diff --git a/api/datastore/migrator/migrate_dbversion71.go b/api/datastore/migrator/migrate_dbversion71.go new file mode 100644 index 000000000..d860adf8d --- /dev/null +++ b/api/datastore/migrator/migrate_dbversion71.go @@ -0,0 +1,36 @@ +package migrator + +import ( + "github.com/portainer/portainer/api/dataservices/errors" + + "github.com/rs/zerolog/log" +) + +func (m *Migrator) migrateDBVersionToDB71() error { + log.Info().Msg("removing orphaned snapshots") + + snapshots, err := m.snapshotService.Snapshots() + if err != nil { + return err + } + + for _, s := range snapshots { + _, err := m.endpointService.Endpoint(s.EndpointID) + if err == nil { + log.Debug().Int("endpoint_id", int(s.EndpointID)).Msg("keeping snapshot") + continue + } else if err != errors.ErrObjectNotFound { + log.Debug().Int("endpoint_id", int(s.EndpointID)).Err(err).Msg("database error") + return err + } + + log.Debug().Int("endpoint_id", int(s.EndpointID)).Msg("removing snapshot") + + err = m.snapshotService.DeleteSnapshot(s.EndpointID) + if err != nil { + return err + } + } + + return nil +} diff --git a/api/http/handler/endpoints/endpoint_delete.go b/api/http/handler/endpoints/endpoint_delete.go index 45a840970..ac4e967fd 100644 --- a/api/http/handler/endpoints/endpoint_delete.go +++ b/api/http/handler/endpoints/endpoint_delete.go @@ -49,6 +49,11 @@ func (handler *Handler) endpointDelete(w http.ResponseWriter, r *http.Request) * } } + err = handler.DataStore.Snapshot().DeleteSnapshot(portainer.EndpointID(endpointID)) + if err != nil { + return httperror.InternalServerError("Unable to remove the snapshot from the database", err) + } + err = handler.DataStore.Endpoint().DeleteEndpoint(portainer.EndpointID(endpointID)) if err != nil { return httperror.InternalServerError("Unable to remove environment from the database", err)