delete stale correlations when datasources are deleted

This commit is contained in:
Elfo404 2022-07-12 18:03:56 +02:00
parent 1f3307637e
commit cb6bef1a44
No known key found for this signature in database
GPG Key ID: 586539D9491F0726
4 changed files with 30 additions and 4 deletions

View File

@ -4,12 +4,14 @@ import (
"context"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/sqlstore"
)
func ProvideService(sqlStore *sqlstore.SQLStore, routeRegister routing.RouteRegister, datasourceService datasources.DataSourceService) *CorrelationsService {
func ProvideService(sqlStore *sqlstore.SQLStore, routeRegister routing.RouteRegister, datasourceService datasources.DataSourceService, bus bus.Bus) *CorrelationsService {
s := &CorrelationsService{
SQLStore: sqlStore,
RouteRegister: routeRegister,
@ -19,6 +21,8 @@ func ProvideService(sqlStore *sqlstore.SQLStore, routeRegister routing.RouteRegi
s.registerAPIEndpoints()
bus.AddEventListener(s.handleDatasourceDeletion)
return s
}
@ -41,3 +45,15 @@ func (s CorrelationsService) CreateCorrelation(ctx context.Context, cmd CreateCo
func (s CorrelationsService) DeleteCorrelationsBySourceUID(ctx context.Context, cmd DeleteCorrelationsBySourceUIDCommand) error {
return s.deleteCorrelationsBySourceUID(ctx, cmd)
}
func (s CorrelationsService) handleDatasourceDeletion(ctx context.Context, event *events.DataSourceDeleted) error {
s.deleteCorrelationsBySourceUID(ctx, DeleteCorrelationsBySourceUIDCommand{
SourceUID: event.UID,
})
s.deleteCorrelationsByTargetUID(ctx, DeleteCorrelationsByTargetUIDCommand{
TargetUID: event.UID,
})
return nil
}

View File

@ -70,5 +70,13 @@ func (s CorrelationsService) deleteCorrelationsBySourceUID(ctx context.Context,
return err
})
})
}
func (s CorrelationsService) deleteCorrelationsByTargetUID(ctx context.Context, cmd DeleteCorrelationsByTargetUIDCommand) error {
return s.SQLStore.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
return s.SQLStore.InTransaction(ctx, func(ctx context.Context) error {
_, err := session.Delete(&Correlation{TargetUID: cmd.TargetUID})
return err
})
})
}

View File

@ -51,3 +51,7 @@ type CreateCorrelationCommand struct {
type DeleteCorrelationsBySourceUIDCommand struct {
SourceUID string
}
type DeleteCorrelationsByTargetUIDCommand struct {
TargetUID string
}

View File

@ -123,8 +123,6 @@ func (ss *SQLStore) DeleteDataSource(ctx context.Context, cmd *datasources.Delet
}
}
// TODO: delete correlations having sourceUID or targetUID = cmd.UID
// Publish data source deletion event
sess.publishAfterCommit(&events.DataSourceDeleted{
Timestamp: time.Now(),