Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f218122ae5 | |||
| 7b91acbaeb | |||
| 450eaba447 | |||
| 87f5d5e741 | |||
| 5e68b07cac | |||
| 99acd3766d | |||
| ea5b39cd9f | |||
| ba79a2bbd6 | |||
| 3175275c25 | |||
| 4a3cf7abaf | |||
| 1cbbce160d | |||
| 47fbff6136 | |||
| d98dd3e952 |
@@ -15,7 +15,9 @@ import (
|
||||
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/client-go/dynamic"
|
||||
"k8s.io/client-go/rest"
|
||||
|
||||
"github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v0alpha1"
|
||||
"github.com/grafana/grafana/apps/shorturl/pkg/apis/shorturl/v1beta1"
|
||||
"github.com/grafana/grafana/pkg/apimachinery/identity"
|
||||
"github.com/grafana/grafana/pkg/infra/db"
|
||||
@@ -61,6 +63,7 @@ type CleanUpService struct {
|
||||
orgService org.Service
|
||||
teamService team.Service
|
||||
dataSourceService datasources.DataSourceService
|
||||
dynamicClientFactory func(*rest.Config) (dynamic.Interface, error)
|
||||
}
|
||||
|
||||
func ProvideService(cfg *setting.Cfg, Features featuremgmt.FeatureToggles, serverLockService *serverlock.ServerLockService,
|
||||
@@ -86,6 +89,9 @@ func ProvideService(cfg *setting.Cfg, Features featuremgmt.FeatureToggles, serve
|
||||
orgService: orgService,
|
||||
teamService: teamService,
|
||||
dataSourceService: dataSourceService,
|
||||
dynamicClientFactory: func(c *rest.Config) (dynamic.Interface, error) {
|
||||
return dynamic.NewForConfig(c)
|
||||
},
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -230,14 +236,93 @@ func (srv *CleanUpService) shouldCleanupTempFile(filemtime time.Time, now time.T
|
||||
|
||||
func (srv *CleanUpService) deleteExpiredSnapshots(ctx context.Context) {
|
||||
logger := srv.log.FromContext(ctx)
|
||||
cmd := dashboardsnapshots.DeleteExpiredSnapshotsCommand{}
|
||||
if err := srv.dashboardSnapshotService.DeleteExpiredSnapshots(ctx, &cmd); err != nil {
|
||||
logger.Error("Failed to delete expired snapshots", "error", err.Error())
|
||||
//nolint:staticcheck // not yet migrated to OpenFeature
|
||||
if srv.Features.IsEnabledGlobally(featuremgmt.FlagKubernetesSnapshots) {
|
||||
srv.deleteKubernetesExpiredSnapshots(ctx)
|
||||
} else {
|
||||
logger.Debug("Deleted expired snapshots", "rows affected", cmd.DeletedRows)
|
||||
cmd := dashboardsnapshots.DeleteExpiredSnapshotsCommand{}
|
||||
if err := srv.dashboardSnapshotService.DeleteExpiredSnapshots(ctx, &cmd); err != nil {
|
||||
logger.Error("Failed to delete expired snapshots", "error", err.Error())
|
||||
} else {
|
||||
logger.Debug("Deleted expired snapshots", "rows affected", cmd.DeletedRows)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (srv *CleanUpService) deleteKubernetesExpiredSnapshots(ctx context.Context) {
|
||||
logger := srv.log.FromContext(ctx)
|
||||
logger.Debug("Starting deleting expired Kubernetes snapshots")
|
||||
|
||||
// Create the dynamic client for Kubernetes API
|
||||
restConfig, err := srv.clientConfigProvider.GetRestConfig(ctx)
|
||||
if err != nil {
|
||||
logger.Error("Failed to get REST config for Kubernetes client", "error", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
client, err := srv.dynamicClientFactory(restConfig)
|
||||
if err != nil {
|
||||
logger.Error("Failed to create Kubernetes client", "error", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Set up the GroupVersionResource for snapshots
|
||||
gvr := v0alpha1.SnapshotKind().GroupVersionResource()
|
||||
|
||||
// Expiration time is now
|
||||
expirationTime := time.Now()
|
||||
expirationTimestamp := expirationTime.UnixMilli()
|
||||
deletedCount := 0
|
||||
|
||||
// List and delete expired snapshots across all namespaces
|
||||
orgs, err := srv.orgService.Search(ctx, &org.SearchOrgsQuery{})
|
||||
if err != nil {
|
||||
logger.Error("Failed to list organizations", "error", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
for _, o := range orgs {
|
||||
ctx, _ := identity.WithServiceIdentity(ctx, o.ID)
|
||||
namespaceMapper := request.GetNamespaceMapper(srv.Cfg)
|
||||
snapshots, err := client.Resource(gvr).Namespace(namespaceMapper(o.ID)).List(ctx, v1.ListOptions{})
|
||||
if err != nil {
|
||||
logger.Error("Failed to list snapshots for org", "orgID", o.ID, "error", err.Error())
|
||||
continue
|
||||
}
|
||||
// Check each snapshot for expiration
|
||||
for _, item := range snapshots.Items {
|
||||
// Convert unstructured object to Snapshot struct
|
||||
var snapshot v0alpha1.Snapshot
|
||||
err := runtime.DefaultUnstructuredConverter.FromUnstructured(item.Object, &snapshot)
|
||||
if err != nil {
|
||||
logger.Error("Failed to convert unstructured object to snapshot", "name", item.GetName(), "namespace", item.GetNamespace(), "error", err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
// Only delete expired snapshots
|
||||
if snapshot.Spec.Expires != nil && *snapshot.Spec.Expires < expirationTimestamp {
|
||||
namespace := snapshot.Namespace
|
||||
name := snapshot.Name
|
||||
|
||||
err := client.Resource(gvr).Namespace(namespace).Delete(ctx, name, v1.DeleteOptions{})
|
||||
if err != nil {
|
||||
// Check if it's a "not found" error, which is expected if the resource was already deleted
|
||||
if k8serrors.IsNotFound(err) {
|
||||
logger.Debug("Snapshot already deleted", "name", name, "namespace", namespace)
|
||||
} else {
|
||||
logger.Error("Failed to delete expired snapshot", "name", name, "namespace", namespace, "error", err.Error())
|
||||
}
|
||||
} else {
|
||||
deletedCount++
|
||||
logger.Debug("Successfully deleted expired snapshot", "name", name, "namespace", namespace, "creationTime", snapshot.CreationTimestamp.Unix(), "expirationTime", expirationTimestamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.Debug("Deleted expired Kubernetes snapshots", "count", deletedCount)
|
||||
}
|
||||
|
||||
func (srv *CleanUpService) deleteExpiredDashboardVersions(ctx context.Context) {
|
||||
logger := srv.log.FromContext(ctx)
|
||||
cmd := dashver.DeleteExpiredVersionsCommand{}
|
||||
@@ -318,7 +403,7 @@ func (srv *CleanUpService) deleteStaleKubernetesShortURLs(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
client, err := dynamic.NewForConfig(restConfig)
|
||||
client, err := srv.dynamicClientFactory(restConfig)
|
||||
if err != nil {
|
||||
logger.Error("Failed to create Kubernetes client", "error", err.Error())
|
||||
return
|
||||
|
||||
@@ -1,11 +1,28 @@
|
||||
package cleanup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
k8serrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/client-go/dynamic"
|
||||
"k8s.io/client-go/rest"
|
||||
|
||||
"github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v0alpha1"
|
||||
"github.com/grafana/grafana/pkg/infra/log"
|
||||
"github.com/grafana/grafana/pkg/services/apiserver"
|
||||
"github.com/grafana/grafana/pkg/services/dashboardsnapshots"
|
||||
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||
"github.com/grafana/grafana/pkg/services/org"
|
||||
"github.com/grafana/grafana/pkg/services/org/orgtest"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
)
|
||||
|
||||
@@ -36,3 +53,247 @@ func TestCleanUpTmpFiles(t *testing.T) {
|
||||
require.False(t, service.shouldCleanupTempFile(weekAgo, now))
|
||||
})
|
||||
}
|
||||
|
||||
func TestDeleteExpiredSnapshots_LegacyMode(t *testing.T) {
|
||||
t.Run("calls DeleteExpiredSnapshots on success", func(t *testing.T) {
|
||||
mockSnapService := dashboardsnapshots.NewMockService(t)
|
||||
mockSnapService.On("DeleteExpiredSnapshots", mock.Anything, mock.Anything).Return(nil)
|
||||
|
||||
service := &CleanUpService{
|
||||
log: log.New("cleanup"),
|
||||
Features: featuremgmt.WithFeatures(),
|
||||
dashboardSnapshotService: mockSnapService,
|
||||
}
|
||||
|
||||
service.deleteExpiredSnapshots(context.Background())
|
||||
|
||||
mockSnapService.AssertCalled(t, "DeleteExpiredSnapshots", mock.Anything, mock.Anything)
|
||||
})
|
||||
|
||||
t.Run("handles error gracefully", func(t *testing.T) {
|
||||
mockSnapService := dashboardsnapshots.NewMockService(t)
|
||||
mockSnapService.On("DeleteExpiredSnapshots", mock.Anything, mock.Anything).Return(errors.New("db error"))
|
||||
|
||||
service := &CleanUpService{
|
||||
log: log.New("cleanup"),
|
||||
Features: featuremgmt.WithFeatures(),
|
||||
dashboardSnapshotService: mockSnapService,
|
||||
}
|
||||
|
||||
// Should not panic
|
||||
service.deleteExpiredSnapshots(context.Background())
|
||||
})
|
||||
}
|
||||
|
||||
func TestDeleteExpiredSnapshots_KubernetesMode(t *testing.T) {
|
||||
t.Run("deletes expired snapshots across multiple orgs", func(t *testing.T) {
|
||||
// Create expired snapshots - one per org
|
||||
expiredTime := time.Now().Add(-time.Hour).UnixMilli()
|
||||
expiredSnapshot1 := createUnstructuredSnapshot("expired-snap-1", "org-1", expiredTime)
|
||||
expiredSnapshot2 := createUnstructuredSnapshot("expired-snap-2", "org-2", expiredTime)
|
||||
|
||||
// Track which namespaces were queried
|
||||
namespacesQueried := make(map[string]bool)
|
||||
|
||||
mockResource := new(mockResourceInterface)
|
||||
mockResource.On("Namespace", mock.Anything).Run(func(args mock.Arguments) {
|
||||
ns := args.Get(0).(string)
|
||||
namespacesQueried[ns] = true
|
||||
}).Return(mockResource)
|
||||
mockResource.On("List", mock.Anything, mock.Anything).Return(&unstructured.UnstructuredList{
|
||||
Items: []unstructured.Unstructured{*expiredSnapshot1, *expiredSnapshot2},
|
||||
}, nil)
|
||||
mockResource.On("Delete", mock.Anything, "expired-snap-1", mock.Anything, mock.Anything).Return(nil)
|
||||
mockResource.On("Delete", mock.Anything, "expired-snap-2", mock.Anything, mock.Anything).Return(nil)
|
||||
|
||||
mockDynClient := new(mockDynamicClient)
|
||||
mockDynClient.On("Resource", mock.Anything).Return(mockResource)
|
||||
|
||||
service := createK8sCleanupService(t, mockDynClient)
|
||||
service.deleteExpiredSnapshots(context.Background())
|
||||
|
||||
// Verify multiple namespaces were queried (one per org)
|
||||
require.GreaterOrEqual(t, len(namespacesQueried), 2, "expected at least 2 namespaces to be queried")
|
||||
// Verify both snapshots were deleted
|
||||
mockResource.AssertCalled(t, "Delete", mock.Anything, "expired-snap-1", mock.Anything, mock.Anything)
|
||||
mockResource.AssertCalled(t, "Delete", mock.Anything, "expired-snap-2", mock.Anything, mock.Anything)
|
||||
})
|
||||
|
||||
t.Run("skips non-expired snapshots", func(t *testing.T) {
|
||||
// Setup with future timestamp
|
||||
futureTime := time.Now().Add(time.Hour).UnixMilli()
|
||||
futureSnapshot := createUnstructuredSnapshot("future-snap", "org-1", futureTime)
|
||||
|
||||
mockResource := new(mockResourceInterface)
|
||||
mockResource.On("Namespace", mock.Anything).Return(mockResource)
|
||||
mockResource.On("List", mock.Anything, mock.Anything).Return(&unstructured.UnstructuredList{
|
||||
Items: []unstructured.Unstructured{*futureSnapshot},
|
||||
}, nil)
|
||||
|
||||
mockDynClient := new(mockDynamicClient)
|
||||
mockDynClient.On("Resource", mock.Anything).Return(mockResource)
|
||||
|
||||
service := createK8sCleanupService(t, mockDynClient)
|
||||
service.deleteExpiredSnapshots(context.Background())
|
||||
|
||||
mockResource.AssertNotCalled(t, "Delete", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
})
|
||||
|
||||
t.Run("handles REST config error", func(t *testing.T) {
|
||||
service := &CleanUpService{
|
||||
log: log.New("cleanup"),
|
||||
Cfg: &setting.Cfg{},
|
||||
Features: featuremgmt.WithFeatures(featuremgmt.FlagKubernetesSnapshots),
|
||||
clientConfigProvider: apiserver.WithoutRestConfig,
|
||||
}
|
||||
|
||||
// Should not panic
|
||||
service.deleteExpiredSnapshots(context.Background())
|
||||
})
|
||||
|
||||
t.Run("handles not found error gracefully", func(t *testing.T) {
|
||||
expiredTime := time.Now().Add(-time.Hour).UnixMilli()
|
||||
expiredSnapshot := createUnstructuredSnapshot("expired-snap", "org-1", expiredTime)
|
||||
|
||||
notFoundErr := k8serrors.NewNotFound(schema.GroupResource{}, "expired-snap")
|
||||
|
||||
mockResource := new(mockResourceInterface)
|
||||
mockResource.On("Namespace", mock.Anything).Return(mockResource)
|
||||
mockResource.On("List", mock.Anything, mock.Anything).Return(&unstructured.UnstructuredList{
|
||||
Items: []unstructured.Unstructured{*expiredSnapshot},
|
||||
}, nil)
|
||||
mockResource.On("Delete", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(notFoundErr)
|
||||
|
||||
mockDynClient := new(mockDynamicClient)
|
||||
mockDynClient.On("Resource", mock.Anything).Return(mockResource)
|
||||
|
||||
service := createK8sCleanupService(t, mockDynClient)
|
||||
|
||||
// Should not panic - not found is expected
|
||||
service.deleteExpiredSnapshots(context.Background())
|
||||
mockResource.AssertExpectations(t)
|
||||
})
|
||||
|
||||
t.Run("continues processing other orgs when one org fails to list snapshots", func(t *testing.T) {
|
||||
// Create an expired snapshot for the second org
|
||||
expiredTime := time.Now().Add(-time.Hour).UnixMilli()
|
||||
expiredSnapshot := createUnstructuredSnapshot("expired-snap-org2", "org-2", expiredTime)
|
||||
|
||||
// Use namespace-aware mock that returns error for first namespace, success for second
|
||||
mockResource := &namespaceAwareMockResource{
|
||||
expiredSnapshot: expiredSnapshot,
|
||||
deletedNames: make(map[string]bool),
|
||||
}
|
||||
|
||||
mockDynClient := new(mockDynamicClient)
|
||||
mockDynClient.On("Resource", mock.Anything).Return(mockResource)
|
||||
|
||||
service := createK8sCleanupService(t, mockDynClient)
|
||||
service.deleteExpiredSnapshots(context.Background())
|
||||
|
||||
// Verify that the snapshot from the second org was still deleted despite the first org failing
|
||||
require.True(t, mockResource.deletedNames["expired-snap-org2"], "expected snapshot from second org to be deleted")
|
||||
})
|
||||
}
|
||||
|
||||
// Helper function to create unstructured snapshots for testing
|
||||
func createUnstructuredSnapshot(name, namespace string, expiresMillis int64) *unstructured.Unstructured {
|
||||
snapshot := &v0alpha1.Snapshot{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
},
|
||||
Spec: v0alpha1.SnapshotSpec{
|
||||
Expires: &expiresMillis,
|
||||
},
|
||||
}
|
||||
obj, _ := runtime.DefaultUnstructuredConverter.ToUnstructured(snapshot)
|
||||
return &unstructured.Unstructured{Object: obj}
|
||||
}
|
||||
|
||||
// Helper to create CleanUpService configured for Kubernetes mode with standard two-org setup
|
||||
func createK8sCleanupService(t *testing.T, mockDynClient *mockDynamicClient) *CleanUpService {
|
||||
mockOrgSvc := orgtest.NewMockService(t)
|
||||
mockOrgSvc.On("Search", mock.Anything, mock.Anything).Return([]*org.OrgDTO{
|
||||
{ID: 1, Name: "org1"},
|
||||
{ID: 2, Name: "org2"},
|
||||
}, nil)
|
||||
|
||||
return &CleanUpService{
|
||||
log: log.New("cleanup"),
|
||||
Cfg: &setting.Cfg{},
|
||||
Features: featuremgmt.WithFeatures(featuremgmt.FlagKubernetesSnapshots),
|
||||
clientConfigProvider: apiserver.RestConfigProviderFunc(func(ctx context.Context) (*rest.Config, error) {
|
||||
return &rest.Config{}, nil
|
||||
}),
|
||||
orgService: mockOrgSvc,
|
||||
dynamicClientFactory: func(cfg *rest.Config) (dynamic.Interface, error) {
|
||||
return mockDynClient, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// mockDynamicClient is a minimal mock for dynamic.Interface
|
||||
type mockDynamicClient struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *mockDynamicClient) Resource(resource schema.GroupVersionResource) dynamic.NamespaceableResourceInterface {
|
||||
args := m.Called(resource)
|
||||
return args.Get(0).(dynamic.NamespaceableResourceInterface)
|
||||
}
|
||||
|
||||
// mockResourceInterface is a minimal mock for dynamic.ResourceInterface.
|
||||
// Embeds dynamic.ResourceInterface to avoid implementing unused methods.
|
||||
type mockResourceInterface struct {
|
||||
mock.Mock
|
||||
dynamic.ResourceInterface
|
||||
}
|
||||
|
||||
func (m *mockResourceInterface) Namespace(ns string) dynamic.ResourceInterface {
|
||||
args := m.Called(ns)
|
||||
return args.Get(0).(dynamic.ResourceInterface)
|
||||
}
|
||||
|
||||
func (m *mockResourceInterface) List(ctx context.Context, opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {
|
||||
args := m.Called(ctx, opts)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*unstructured.UnstructuredList), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *mockResourceInterface) Delete(ctx context.Context, name string, opts metav1.DeleteOptions, subresources ...string) error {
|
||||
args := m.Called(ctx, name, opts, subresources)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
// namespaceAwareMockResource is a mock that returns different results based on namespace.
|
||||
// Used to test that processing continues when one org fails.
|
||||
// Embeds dynamic.ResourceInterface to avoid implementing unused methods.
|
||||
type namespaceAwareMockResource struct {
|
||||
dynamic.ResourceInterface
|
||||
currentNamespace string
|
||||
expiredSnapshot *unstructured.Unstructured
|
||||
deletedNames map[string]bool
|
||||
}
|
||||
|
||||
func (m *namespaceAwareMockResource) Namespace(ns string) dynamic.ResourceInterface {
|
||||
m.currentNamespace = ns
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *namespaceAwareMockResource) List(ctx context.Context, opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {
|
||||
// Fail for the first org namespace (org ID 1 maps to "default"), succeed for the second (org ID 2 maps to "org-2")
|
||||
if m.currentNamespace == "default" {
|
||||
return nil, errors.New("simulated list error for org-1")
|
||||
}
|
||||
return &unstructured.UnstructuredList{
|
||||
Items: []unstructured.Unstructured{*m.expiredSnapshot},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *namespaceAwareMockResource) Delete(ctx context.Context, name string, opts metav1.DeleteOptions, subresources ...string) error {
|
||||
m.deletedNames[name] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/grafana/grafana/pkg/storage/unified/resource"
|
||||
"github.com/grafana/grafana/pkg/util/testutil"
|
||||
)
|
||||
|
||||
func TestBadgerKVStorageBackend(t *testing.T) {
|
||||
@@ -36,7 +37,9 @@ func TestBadgerKVStorageBackend(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestSQLKVStorageBackend(t *testing.T) {
|
||||
func TestIntegrationSQLKVStorageBackend(t *testing.T) {
|
||||
testutil.SkipIntegrationTestInShortMode(t)
|
||||
|
||||
skipTests := map[string]bool{
|
||||
TestWatchWriteEvents: true,
|
||||
TestList: true,
|
||||
|
||||
@@ -25,6 +25,10 @@ export class ExportAsCode extends ShareExportTab {
|
||||
public getTabLabel(): string {
|
||||
return t('export.json.title', 'Export dashboard');
|
||||
}
|
||||
|
||||
public getSubtitle(): string | undefined {
|
||||
return t('export.json.info-text', 'Copy or download a file containing the definition of your dashboard');
|
||||
}
|
||||
}
|
||||
|
||||
function ExportAsCodeRenderer({ model }: SceneComponentProps<ExportAsCode>) {
|
||||
@@ -53,12 +57,6 @@ function ExportAsCodeRenderer({ model }: SceneComponentProps<ExportAsCode>) {
|
||||
|
||||
return (
|
||||
<div data-testid={selector.container} className={styles.container}>
|
||||
<p>
|
||||
<Trans i18nKey="export.json.info-text">
|
||||
Copy or download a file containing the definition of your dashboard
|
||||
</Trans>
|
||||
</p>
|
||||
|
||||
{config.featureToggles.kubernetesDashboards ? (
|
||||
<ResourceExport
|
||||
dashboardJson={dashboardJson}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { render, screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { AsyncState } from 'react-use/lib/useAsync';
|
||||
|
||||
import { selectors as e2eSelectors } from '@grafana/e2e-selectors';
|
||||
import { Dashboard } from '@grafana/schema';
|
||||
import { Spec as DashboardV2Spec } from '@grafana/schema/dist/esm/schema/dashboard/v2';
|
||||
|
||||
import { ExportMode, ResourceExport } from './ResourceExport';
|
||||
|
||||
type DashboardJsonState = AsyncState<{
|
||||
json: Dashboard | DashboardV2Spec | { error: unknown };
|
||||
hasLibraryPanels?: boolean;
|
||||
initialSaveModelVersion: 'v1' | 'v2';
|
||||
}>;
|
||||
|
||||
const selector = e2eSelectors.pages.ExportDashboardDrawer.ExportAsJson;
|
||||
|
||||
const createDefaultProps = (overrides?: Partial<Parameters<typeof ResourceExport>[0]>) => {
|
||||
const defaultProps: Parameters<typeof ResourceExport>[0] = {
|
||||
dashboardJson: {
|
||||
loading: false,
|
||||
value: {
|
||||
json: { title: 'Test Dashboard' } as Dashboard,
|
||||
hasLibraryPanels: false,
|
||||
initialSaveModelVersion: 'v1',
|
||||
},
|
||||
} as DashboardJsonState,
|
||||
isSharingExternally: false,
|
||||
exportMode: ExportMode.Classic,
|
||||
isViewingYAML: false,
|
||||
onExportModeChange: jest.fn(),
|
||||
onShareExternallyChange: jest.fn(),
|
||||
onViewYAML: jest.fn(),
|
||||
};
|
||||
|
||||
return { ...defaultProps, ...overrides };
|
||||
};
|
||||
|
||||
const createV2DashboardJson = (hasLibraryPanels = false): DashboardJsonState => ({
|
||||
loading: false,
|
||||
value: {
|
||||
json: {
|
||||
title: 'Test V2 Dashboard',
|
||||
spec: {
|
||||
elements: {},
|
||||
},
|
||||
} as unknown as DashboardV2Spec,
|
||||
hasLibraryPanels,
|
||||
initialSaveModelVersion: 'v2',
|
||||
},
|
||||
});
|
||||
|
||||
const expandOptions = async () => {
|
||||
const button = screen.getByRole('button', { expanded: false });
|
||||
await userEvent.click(button);
|
||||
};
|
||||
|
||||
describe('ResourceExport', () => {
|
||||
describe('export mode options for v1 dashboard', () => {
|
||||
it('should show three export mode options in correct order: Classic, V1 Resource, V2 Resource', async () => {
|
||||
render(<ResourceExport {...createDefaultProps()} />);
|
||||
await expandOptions();
|
||||
|
||||
const radioGroup = screen.getByRole('radiogroup', { name: /model/i });
|
||||
const labels = within(radioGroup)
|
||||
.getAllByRole('radio')
|
||||
.map((radio) => radio.parentElement?.textContent?.trim());
|
||||
|
||||
expect(labels).toHaveLength(3);
|
||||
expect(labels).toEqual(['Classic', 'V1 Resource', 'V2 Resource']);
|
||||
});
|
||||
|
||||
it('should have first option selected by default when exportMode is Classic', async () => {
|
||||
render(<ResourceExport {...createDefaultProps({ exportMode: ExportMode.Classic })} />);
|
||||
await expandOptions();
|
||||
|
||||
const radioGroup = screen.getByRole('radiogroup', { name: /model/i });
|
||||
const radios = within(radioGroup).getAllByRole('radio');
|
||||
expect(radios[0]).toBeChecked();
|
||||
});
|
||||
|
||||
it('should call onExportModeChange when export mode is changed', async () => {
|
||||
const onExportModeChange = jest.fn();
|
||||
render(<ResourceExport {...createDefaultProps({ onExportModeChange })} />);
|
||||
await expandOptions();
|
||||
|
||||
const radioGroup = screen.getByRole('radiogroup', { name: /model/i });
|
||||
const radios = within(radioGroup).getAllByRole('radio');
|
||||
await userEvent.click(radios[1]); // V1 Resource
|
||||
expect(onExportModeChange).toHaveBeenCalledWith(ExportMode.V1Resource);
|
||||
});
|
||||
});
|
||||
|
||||
describe('export mode options for v2 dashboard', () => {
|
||||
it('should not show export mode options', async () => {
|
||||
render(<ResourceExport {...createDefaultProps({ dashboardJson: createV2DashboardJson() })} />);
|
||||
await expandOptions();
|
||||
|
||||
expect(screen.queryByRole('radiogroup', { name: /model/i })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('format options', () => {
|
||||
it('should not show format options when export mode is Classic', async () => {
|
||||
render(<ResourceExport {...createDefaultProps({ exportMode: ExportMode.Classic })} />);
|
||||
await expandOptions();
|
||||
|
||||
expect(screen.getByRole('radiogroup', { name: /model/i })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('radiogroup', { name: /format/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([ExportMode.V1Resource, ExportMode.V2Resource])(
|
||||
'should show format options when export mode is %s',
|
||||
async (exportMode) => {
|
||||
render(<ResourceExport {...createDefaultProps({ exportMode })} />);
|
||||
await expandOptions();
|
||||
|
||||
expect(screen.getByRole('radiogroup', { name: /model/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('radiogroup', { name: /format/i })).toBeInTheDocument();
|
||||
}
|
||||
);
|
||||
|
||||
it('should have first format option selected when isViewingYAML is false', async () => {
|
||||
render(<ResourceExport {...createDefaultProps({ exportMode: ExportMode.V1Resource, isViewingYAML: false })} />);
|
||||
await expandOptions();
|
||||
|
||||
const formatGroup = screen.getByRole('radiogroup', { name: /format/i });
|
||||
const formatRadios = within(formatGroup).getAllByRole('radio');
|
||||
expect(formatRadios[0]).toBeChecked(); // JSON
|
||||
});
|
||||
|
||||
it('should have second format option selected when isViewingYAML is true', async () => {
|
||||
render(<ResourceExport {...createDefaultProps({ exportMode: ExportMode.V1Resource, isViewingYAML: true })} />);
|
||||
await expandOptions();
|
||||
|
||||
const formatGroup = screen.getByRole('radiogroup', { name: /format/i });
|
||||
const formatRadios = within(formatGroup).getAllByRole('radio');
|
||||
expect(formatRadios[1]).toBeChecked(); // YAML
|
||||
});
|
||||
|
||||
it('should call onViewYAML when format is changed', async () => {
|
||||
const onViewYAML = jest.fn();
|
||||
render(<ResourceExport {...createDefaultProps({ exportMode: ExportMode.V1Resource, onViewYAML })} />);
|
||||
await expandOptions();
|
||||
|
||||
const formatGroup = screen.getByRole('radiogroup', { name: /format/i });
|
||||
const formatRadios = within(formatGroup).getAllByRole('radio');
|
||||
await userEvent.click(formatRadios[1]); // YAML
|
||||
expect(onViewYAML).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('share externally switch', () => {
|
||||
it('should show share externally switch for Classic mode', () => {
|
||||
render(<ResourceExport {...createDefaultProps({ exportMode: ExportMode.Classic })} />);
|
||||
|
||||
expect(screen.getByTestId(selector.exportExternallyToggle)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show share externally switch for V2Resource mode with V2 dashboard', () => {
|
||||
render(
|
||||
<ResourceExport
|
||||
{...createDefaultProps({
|
||||
dashboardJson: createV2DashboardJson(),
|
||||
exportMode: ExportMode.V2Resource,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId(selector.exportExternallyToggle)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call onShareExternallyChange when switch is toggled', async () => {
|
||||
const onShareExternallyChange = jest.fn();
|
||||
render(<ResourceExport {...createDefaultProps({ exportMode: ExportMode.Classic, onShareExternallyChange })} />);
|
||||
|
||||
const switchElement = screen.getByTestId(selector.exportExternallyToggle);
|
||||
await userEvent.click(switchElement);
|
||||
expect(onShareExternallyChange).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should reflect isSharingExternally value in switch', () => {
|
||||
render(<ResourceExport {...createDefaultProps({ exportMode: ExportMode.Classic, isSharingExternally: true })} />);
|
||||
|
||||
expect(screen.getByTestId(selector.exportExternallyToggle)).toBeChecked();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,8 @@ import { selectors as e2eSelectors } from '@grafana/e2e-selectors';
|
||||
import { Trans, t } from '@grafana/i18n';
|
||||
import { Dashboard } from '@grafana/schema';
|
||||
import { Spec as DashboardV2Spec } from '@grafana/schema/dist/esm/schema/dashboard/v2';
|
||||
import { Alert, Label, RadioButtonGroup, Stack, Switch } from '@grafana/ui';
|
||||
import { Alert, Icon, Label, RadioButtonGroup, Stack, Switch, Box, Tooltip } from '@grafana/ui';
|
||||
import { QueryOperationRow } from 'app/core/components/QueryOperationRow/QueryOperationRow';
|
||||
import { DashboardJson } from 'app/features/manage-dashboards/types';
|
||||
|
||||
import { ExportableResource } from '../ShareExportTab';
|
||||
@@ -48,80 +49,90 @@ export function ResourceExport({
|
||||
|
||||
const switchExportLabel =
|
||||
exportMode === ExportMode.V2Resource
|
||||
? t('export.json.export-remove-ds-refs', 'Remove deployment details')
|
||||
: t('share-modal.export.share-externally-label', `Export for sharing externally`);
|
||||
? t('dashboard-scene.resource-export.share-externally', 'Share dashboard with another instance')
|
||||
: t('share-modal.export.share-externally-label', 'Export for sharing externally');
|
||||
const switchExportTooltip = t(
|
||||
'dashboard-scene.resource-export.share-externally-tooltip',
|
||||
'Removes all instance-specific metadata and data source references from the resource before export.'
|
||||
);
|
||||
const switchExportModeLabel = t('export.json.export-mode', 'Model');
|
||||
const switchExportFormatLabel = t('export.json.export-format', 'Format');
|
||||
|
||||
const exportResourceOptions = [
|
||||
{
|
||||
label: t('dashboard-scene.resource-export.label.classic', 'Classic'),
|
||||
value: ExportMode.Classic,
|
||||
},
|
||||
{
|
||||
label: t('dashboard-scene.resource-export.label.v1-resource', 'V1 Resource'),
|
||||
value: ExportMode.V1Resource,
|
||||
},
|
||||
{
|
||||
label: t('dashboard-scene.resource-export.label.v2-resource', 'V2 Resource'),
|
||||
value: ExportMode.V2Resource,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Stack gap={2} direction="column">
|
||||
<Stack gap={1} direction="column">
|
||||
{initialSaveModelVersion === 'v1' && (
|
||||
<Stack alignItems="center">
|
||||
<Label>{switchExportModeLabel}</Label>
|
||||
<RadioButtonGroup
|
||||
options={[
|
||||
{ label: t('dashboard-scene.resource-export.label.classic', 'Classic'), value: ExportMode.Classic },
|
||||
{
|
||||
label: t('dashboard-scene.resource-export.label.v1-resource', 'V1 Resource'),
|
||||
value: ExportMode.V1Resource,
|
||||
},
|
||||
{
|
||||
label: t('dashboard-scene.resource-export.label.v2-resource', 'V2 Resource'),
|
||||
value: ExportMode.V2Resource,
|
||||
},
|
||||
]}
|
||||
value={exportMode}
|
||||
onChange={(value) => onExportModeChange(value)}
|
||||
/>
|
||||
<>
|
||||
<QueryOperationRow
|
||||
id="Advanced options"
|
||||
index={0}
|
||||
title={t('dashboard-scene.resource-export.label.advanced-options', 'Advanced options')}
|
||||
isOpen={false}
|
||||
>
|
||||
<Box marginTop={2}>
|
||||
<Stack gap={1} direction="column">
|
||||
{initialSaveModelVersion === 'v1' && (
|
||||
<Stack gap={1} alignItems="center">
|
||||
<Label>{switchExportModeLabel}</Label>
|
||||
<RadioButtonGroup
|
||||
options={exportResourceOptions}
|
||||
value={exportMode}
|
||||
onChange={(value) => onExportModeChange(value)}
|
||||
aria-label={switchExportModeLabel}
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{exportMode !== ExportMode.Classic && (
|
||||
<Stack gap={1} alignItems="center">
|
||||
<Label>{switchExportFormatLabel}</Label>
|
||||
<RadioButtonGroup
|
||||
options={[
|
||||
{ label: t('dashboard-scene.resource-export.label.json', 'JSON'), value: 'json' },
|
||||
{ label: t('dashboard-scene.resource-export.label.yaml', 'YAML'), value: 'yaml' },
|
||||
]}
|
||||
value={isViewingYAML ? 'yaml' : 'json'}
|
||||
onChange={onViewYAML}
|
||||
aria-label={switchExportFormatLabel}
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
{initialSaveModelVersion === 'v2' && (
|
||||
<Stack alignItems="center">
|
||||
<Label>{switchExportModeLabel}</Label>
|
||||
<RadioButtonGroup
|
||||
options={[
|
||||
{
|
||||
label: t('dashboard-scene.resource-export.label.v2-resource', 'V2 Resource'),
|
||||
value: ExportMode.V2Resource,
|
||||
},
|
||||
{
|
||||
label: t('dashboard-scene.resource-export.label.v1-resource', 'V1 Resource'),
|
||||
value: ExportMode.V1Resource,
|
||||
},
|
||||
]}
|
||||
value={exportMode}
|
||||
onChange={(value) => onExportModeChange(value)}
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
{exportMode !== ExportMode.Classic && (
|
||||
<Stack gap={1} alignItems="center">
|
||||
<Label>{switchExportFormatLabel}</Label>
|
||||
<RadioButtonGroup
|
||||
options={[
|
||||
{ label: t('dashboard-scene.resource-export.label.json', 'JSON'), value: 'json' },
|
||||
{ label: t('dashboard-scene.resource-export.label.yaml', 'YAML'), value: 'yaml' },
|
||||
]}
|
||||
value={isViewingYAML ? 'yaml' : 'json'}
|
||||
onChange={onViewYAML}
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
{(isV2Dashboard ||
|
||||
exportMode === ExportMode.Classic ||
|
||||
(initialSaveModelVersion === 'v2' && exportMode === ExportMode.V1Resource)) && (
|
||||
<Stack gap={1} alignItems="start">
|
||||
<Label>{switchExportLabel}</Label>
|
||||
<Switch
|
||||
label={switchExportLabel}
|
||||
value={isSharingExternally}
|
||||
onChange={onShareExternallyChange}
|
||||
data-testid={selector.exportExternallyToggle}
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
</Box>
|
||||
</QueryOperationRow>
|
||||
|
||||
{(isV2Dashboard ||
|
||||
exportMode === ExportMode.Classic ||
|
||||
(initialSaveModelVersion === 'v2' && exportMode === ExportMode.V1Resource)) && (
|
||||
<Stack gap={1} alignItems="start">
|
||||
<Label>
|
||||
<Stack gap={0.5} alignItems="center">
|
||||
<Tooltip content={switchExportTooltip} placement="bottom">
|
||||
<Icon name="info-circle" size="sm" />
|
||||
</Tooltip>
|
||||
{switchExportLabel}
|
||||
</Stack>
|
||||
</Label>
|
||||
<Switch
|
||||
label={switchExportLabel}
|
||||
value={isSharingExternally}
|
||||
onChange={onShareExternallyChange}
|
||||
data-testid={selector.exportExternallyToggle}
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{showV2LibPanelAlert && (
|
||||
<Alert
|
||||
@@ -130,6 +141,7 @@ export function ResourceExport({
|
||||
'Library panels will be converted to regular panels'
|
||||
)}
|
||||
severity="warning"
|
||||
topSpacing={2}
|
||||
>
|
||||
<Trans i18nKey="dashboard-scene.save-dashboard-form.schema-v2-library-panels-export">
|
||||
Due to limitations in the new dashboard schema (V2), library panels will be converted to regular panels with
|
||||
@@ -137,6 +149,6 @@ export function ResourceExport({
|
||||
</Trans>
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -66,7 +66,12 @@ function ShareDrawerRenderer({ model }: SceneComponentProps<ShareDrawer>) {
|
||||
const dashboard = getDashboardSceneFor(model);
|
||||
|
||||
return (
|
||||
<Drawer title={activeShare?.getTabLabel()} onClose={model.onDismiss} size="md">
|
||||
<Drawer
|
||||
title={activeShare?.getTabLabel()}
|
||||
subtitle={activeShare?.getSubtitle?.()}
|
||||
onClose={model.onDismiss}
|
||||
size="md"
|
||||
>
|
||||
<ShareDrawerContext.Provider value={{ dashboard, onDismiss: model.onDismiss }}>
|
||||
{activeShare && <activeShare.Component model={activeShare} />}
|
||||
</ShareDrawerContext.Provider>
|
||||
|
||||
@@ -66,6 +66,10 @@ export class ShareExportTab extends SceneObjectBase<ShareExportTabState> impleme
|
||||
return t('share-modal.tab-title.export', 'Export');
|
||||
}
|
||||
|
||||
public getSubtitle(): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
public onShareExternallyChange = () => {
|
||||
this.setState({
|
||||
isSharingExternally: !this.state.isSharingExternally,
|
||||
|
||||
@@ -15,5 +15,6 @@ export interface SceneShareTab<T extends SceneShareTabState = SceneShareTabState
|
||||
|
||||
export interface ShareView extends SceneObject {
|
||||
getTabLabel(): string;
|
||||
getSubtitle?(): string | undefined;
|
||||
onDismiss?: () => void;
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ import { render, screen } from '@testing-library/react';
|
||||
import { defaultsDeep } from 'lodash';
|
||||
import { Provider } from 'react-redux';
|
||||
|
||||
import { FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
|
||||
import { PanelDataErrorViewProps } from '@grafana/runtime';
|
||||
import { CoreApp, EventBusSrv, FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
|
||||
import { config, PanelDataErrorViewProps } from '@grafana/runtime';
|
||||
import { usePanelContext } from '@grafana/ui';
|
||||
import { configureStore } from 'app/store/configureStore';
|
||||
|
||||
import { PanelDataErrorView } from './PanelDataErrorView';
|
||||
@@ -16,7 +17,24 @@ jest.mock('app/features/dashboard/services/DashboardSrv', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('@grafana/ui', () => ({
|
||||
...jest.requireActual('@grafana/ui'),
|
||||
usePanelContext: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockUsePanelContext = jest.mocked(usePanelContext);
|
||||
const RUN_QUERY_MESSAGE = 'Run a query to visualize it here or go to all visualizations to add other panel types';
|
||||
const panelContextRoot = {
|
||||
app: CoreApp.Dashboard,
|
||||
eventsScope: 'global',
|
||||
eventBus: new EventBusSrv(),
|
||||
};
|
||||
|
||||
describe('PanelDataErrorView', () => {
|
||||
beforeEach(() => {
|
||||
mockUsePanelContext.mockReturnValue(panelContextRoot);
|
||||
});
|
||||
|
||||
it('show No data when there is no data', () => {
|
||||
renderWithProps();
|
||||
|
||||
@@ -70,6 +88,45 @@ describe('PanelDataErrorView', () => {
|
||||
|
||||
expect(screen.getByText('Query returned nothing')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show "Run a query..." message when no query is configured and feature toggle is enabled', () => {
|
||||
mockUsePanelContext.mockReturnValue(panelContextRoot);
|
||||
|
||||
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
|
||||
config.featureToggles.newVizSuggestions = true;
|
||||
|
||||
renderWithProps({
|
||||
data: {
|
||||
state: LoadingState.Done,
|
||||
series: [],
|
||||
timeRange: getDefaultTimeRange(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(screen.getByText(RUN_QUERY_MESSAGE)).toBeInTheDocument();
|
||||
|
||||
config.featureToggles.newVizSuggestions = originalFeatureToggle;
|
||||
});
|
||||
|
||||
it('should show "No data" message when feature toggle is disabled even without queries', () => {
|
||||
mockUsePanelContext.mockReturnValue(panelContextRoot);
|
||||
|
||||
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
|
||||
config.featureToggles.newVizSuggestions = false;
|
||||
|
||||
renderWithProps({
|
||||
data: {
|
||||
state: LoadingState.Done,
|
||||
series: [],
|
||||
timeRange: getDefaultTimeRange(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(screen.getByText('No data')).toBeInTheDocument();
|
||||
expect(screen.queryByText(RUN_QUERY_MESSAGE)).not.toBeInTheDocument();
|
||||
|
||||
config.featureToggles.newVizSuggestions = originalFeatureToggle;
|
||||
});
|
||||
});
|
||||
|
||||
function renderWithProps(overrides?: Partial<PanelDataErrorViewProps>) {
|
||||
|
||||
@@ -5,14 +5,15 @@ import {
|
||||
FieldType,
|
||||
getPanelDataSummary,
|
||||
GrafanaTheme2,
|
||||
PanelData,
|
||||
PanelDataSummary,
|
||||
PanelPluginVisualizationSuggestion,
|
||||
} from '@grafana/data';
|
||||
import { selectors } from '@grafana/e2e-selectors';
|
||||
import { t, Trans } from '@grafana/i18n';
|
||||
import { PanelDataErrorViewProps, locationService } from '@grafana/runtime';
|
||||
import { PanelDataErrorViewProps, locationService, config } from '@grafana/runtime';
|
||||
import { VizPanel } from '@grafana/scenes';
|
||||
import { usePanelContext, useStyles2 } from '@grafana/ui';
|
||||
import { Icon, usePanelContext, useStyles2 } from '@grafana/ui';
|
||||
import { CardButton } from 'app/core/components/CardButton';
|
||||
import { LS_VISUALIZATION_SELECT_TAB_KEY } from 'app/core/constants';
|
||||
import store from 'app/core/store';
|
||||
@@ -24,6 +25,11 @@ import { findVizPanelByKey, getVizPanelKeyForPanelId } from 'app/features/dashbo
|
||||
import { useDispatch } from 'app/types/store';
|
||||
|
||||
import { changePanelPlugin } from '../state/actions';
|
||||
import { hasData } from '../suggestions/utils';
|
||||
|
||||
function hasNoQueryConfigured(data: PanelData): boolean {
|
||||
return !data.request?.targets || data.request.targets.length === 0;
|
||||
}
|
||||
|
||||
export function PanelDataErrorView(props: PanelDataErrorViewProps) {
|
||||
const styles = useStyles2(getStyles);
|
||||
@@ -93,8 +99,14 @@ export function PanelDataErrorView(props: PanelDataErrorViewProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const noData = !hasData(props.data);
|
||||
const noQueryConfigured = hasNoQueryConfigured(props.data);
|
||||
const showEmptyState =
|
||||
config.featureToggles.newVizSuggestions && context.app === CoreApp.PanelEditor && noQueryConfigured && noData;
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
{showEmptyState && <Icon name="chart-line" size="xxxl" className={styles.emptyStateIcon} />}
|
||||
<div className={styles.message} data-testid={selectors.components.Panels.Panel.PanelDataErrorMessage}>
|
||||
{message}
|
||||
</div>
|
||||
@@ -131,7 +143,17 @@ function getMessageFor(
|
||||
return message;
|
||||
}
|
||||
|
||||
if (!data.series || data.series.length === 0 || data.series.every((frame) => frame.length === 0)) {
|
||||
const noData = !hasData(data);
|
||||
const noQueryConfigured = hasNoQueryConfigured(data);
|
||||
|
||||
if (config.featureToggles.newVizSuggestions && noQueryConfigured && noData) {
|
||||
return t(
|
||||
'dashboard.new-panel.empty-state-message',
|
||||
'Run a query to visualize it here or go to all visualizations to add other panel types'
|
||||
);
|
||||
}
|
||||
|
||||
if (noData) {
|
||||
return fieldConfig?.defaults.noValue ?? t('panel.panel-data-error-view.no-value.default', 'No data');
|
||||
}
|
||||
|
||||
@@ -176,5 +198,9 @@ const getStyles = (theme: GrafanaTheme2) => {
|
||||
width: '100%',
|
||||
maxWidth: '600px',
|
||||
}),
|
||||
emptyStateIcon: css({
|
||||
color: theme.colors.text.secondary,
|
||||
marginBottom: theme.spacing(2),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
+12
-15
@@ -1,29 +1,26 @@
|
||||
import { SelectableValue } from '@grafana/data';
|
||||
import { RadioButtonGroup } from '@grafana/ui';
|
||||
|
||||
import { useDispatch } from '../../hooks/useStatelessReducer';
|
||||
import { EditorType } from '../../types';
|
||||
|
||||
import { useQuery } from './ElasticsearchQueryContext';
|
||||
import { changeEditorTypeAndResetQuery } from './state';
|
||||
|
||||
const BASE_OPTIONS: Array<SelectableValue<EditorType>> = [
|
||||
{ value: 'builder', label: 'Builder' },
|
||||
{ value: 'code', label: 'Code' },
|
||||
];
|
||||
|
||||
export const EditorTypeSelector = () => {
|
||||
const query = useQuery();
|
||||
const dispatch = useDispatch();
|
||||
|
||||
// Default to 'builder' if editorType is empty
|
||||
const editorType: EditorType = query.editorType === 'code' ? 'code' : 'builder';
|
||||
|
||||
const onChange = (newEditorType: EditorType) => {
|
||||
dispatch(changeEditorTypeAndResetQuery(newEditorType));
|
||||
};
|
||||
interface Props {
|
||||
value: EditorType;
|
||||
onChange: (editorType: EditorType) => void;
|
||||
}
|
||||
|
||||
export const EditorTypeSelector = ({ value, onChange }: Props) => {
|
||||
return (
|
||||
<RadioButtonGroup<EditorType> fullWidth={false} options={BASE_OPTIONS} value={editorType} onChange={onChange} />
|
||||
<RadioButtonGroup<EditorType>
|
||||
data-testid="elasticsearch-editor-type-toggle"
|
||||
size="sm"
|
||||
options={BASE_OPTIONS}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
+36
-14
@@ -10,9 +10,13 @@ interface Props {
|
||||
onRunQuery: () => void;
|
||||
}
|
||||
|
||||
// This offset was chosen by testing to match Prometheus behavior
|
||||
const EDITOR_HEIGHT_OFFSET = 2;
|
||||
|
||||
export function RawQueryEditor({ value, onChange, onRunQuery }: Props) {
|
||||
const styles = useStyles2(getStyles);
|
||||
const editorRef = useRef<monacoTypes.editor.IStandaloneCodeEditor | null>(null);
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const handleEditorDidMount = useCallback(
|
||||
(editor: monacoTypes.editor.IStandaloneCodeEditor, monaco: Monaco) => {
|
||||
@@ -22,6 +26,22 @@ export function RawQueryEditor({ value, onChange, onRunQuery }: Props) {
|
||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, () => {
|
||||
onRunQuery();
|
||||
});
|
||||
|
||||
// Make the editor resize itself so that the content fits (grows taller when necessary)
|
||||
// this code comes from the Prometheus query editor.
|
||||
// We may wish to consider abstracting it into the grafana/ui repo in the future
|
||||
const updateElementHeight = () => {
|
||||
const containerDiv = containerRef.current;
|
||||
if (containerDiv !== null) {
|
||||
const pixelHeight = editor.getContentHeight();
|
||||
containerDiv.style.height = `${pixelHeight + EDITOR_HEIGHT_OFFSET}px`;
|
||||
const pixelWidth = containerDiv.clientWidth;
|
||||
editor.layout({ width: pixelWidth, height: pixelHeight });
|
||||
}
|
||||
};
|
||||
|
||||
editor.onDidContentSizeChange(updateElementHeight);
|
||||
updateElementHeight();
|
||||
},
|
||||
[onRunQuery]
|
||||
);
|
||||
@@ -65,7 +85,17 @@ export function RawQueryEditor({ value, onChange, onRunQuery }: Props) {
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<div className={styles.header}>
|
||||
<div ref={containerRef} className={styles.editorContainer}>
|
||||
<CodeEditor
|
||||
value={value ?? ''}
|
||||
language="json"
|
||||
width="100%"
|
||||
onBlur={handleQueryChange}
|
||||
monacoOptions={monacoOptions}
|
||||
onEditorDidMount={handleEditorDidMount}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.footer}>
|
||||
<Stack gap={1}>
|
||||
<Button
|
||||
size="sm"
|
||||
@@ -76,20 +106,8 @@ export function RawQueryEditor({ value, onChange, onRunQuery }: Props) {
|
||||
>
|
||||
Format
|
||||
</Button>
|
||||
<Button size="sm" variant="primary" icon="play" onClick={onRunQuery} tooltip="Run query (Ctrl/Cmd+Enter)">
|
||||
Run
|
||||
</Button>
|
||||
</Stack>
|
||||
</div>
|
||||
<CodeEditor
|
||||
value={value ?? ''}
|
||||
language="json"
|
||||
height={200}
|
||||
width="100%"
|
||||
onBlur={handleQueryChange}
|
||||
monacoOptions={monacoOptions}
|
||||
onEditorDidMount={handleEditorDidMount}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -100,7 +118,11 @@ const getStyles = (theme: GrafanaTheme2) => ({
|
||||
flexDirection: 'column',
|
||||
gap: theme.spacing(1),
|
||||
}),
|
||||
header: css({
|
||||
editorContainer: css({
|
||||
width: '100%',
|
||||
overflow: 'hidden',
|
||||
}),
|
||||
footer: css({
|
||||
display: 'flex',
|
||||
justifyContent: 'flex-end',
|
||||
padding: theme.spacing(0.5, 0),
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { css } from '@emotion/css';
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import { useCallback, useEffect, useId, useState } from 'react';
|
||||
import { SemVer } from 'semver';
|
||||
|
||||
import { getDefaultTimeRange, GrafanaTheme2, QueryEditorProps } from '@grafana/data';
|
||||
import { config } from '@grafana/runtime';
|
||||
import { Alert, InlineField, InlineLabel, Input, QueryField, useStyles2 } from '@grafana/ui';
|
||||
import { Alert, ConfirmModal, InlineField, InlineLabel, Input, QueryField, useStyles2 } from '@grafana/ui';
|
||||
|
||||
import { ElasticsearchDataQuery } from '../../dataquery.gen';
|
||||
import { ElasticDatasource } from '../../datasource';
|
||||
import { useNextId } from '../../hooks/useNextId';
|
||||
import { useDispatch } from '../../hooks/useStatelessReducer';
|
||||
import { ElasticsearchOptions } from '../../types';
|
||||
import { EditorType, ElasticsearchOptions } from '../../types';
|
||||
import { isSupportedVersion, isTimeSeriesQuery, unsupportedVersionMessage } from '../../utils';
|
||||
|
||||
import { BucketAggregationsEditor } from './BucketAggregationsEditor';
|
||||
@@ -20,7 +20,7 @@ import { MetricAggregationsEditor } from './MetricAggregationsEditor';
|
||||
import { metricAggregationConfig } from './MetricAggregationsEditor/utils';
|
||||
import { QueryTypeSelector } from './QueryTypeSelector';
|
||||
import { RawQueryEditor } from './RawQueryEditor';
|
||||
import { changeAliasPattern, changeQuery, changeRawDSLQuery } from './state';
|
||||
import { changeAliasPattern, changeEditorTypeAndResetQuery, changeQuery, changeRawDSLQuery } from './state';
|
||||
|
||||
export type ElasticQueryEditorProps = QueryEditorProps<ElasticDatasource, ElasticsearchDataQuery, ElasticsearchOptions>;
|
||||
|
||||
@@ -97,31 +97,61 @@ const QueryEditorForm = ({ value, onRunQuery }: Props & { onRunQuery: () => void
|
||||
const inputId = useId();
|
||||
const styles = useStyles2(getStyles);
|
||||
|
||||
const [switchModalOpen, setSwitchModalOpen] = useState(false);
|
||||
const [pendingEditorType, setPendingEditorType] = useState<EditorType | null>(null);
|
||||
|
||||
const isTimeSeries = isTimeSeriesQuery(value);
|
||||
|
||||
const isCodeEditor = value.editorType === 'code';
|
||||
const rawDSLFeatureEnabled = config.featureToggles.elasticsearchRawDSLQuery;
|
||||
|
||||
// Default to 'builder' if editorType is empty
|
||||
const currentEditorType: EditorType = value.editorType === 'code' ? 'code' : 'builder';
|
||||
|
||||
const showBucketAggregationsEditor = value.metrics?.every(
|
||||
(metric) => metricAggregationConfig[metric.type].impliedQueryType === 'metrics'
|
||||
);
|
||||
|
||||
const onEditorTypeChange = useCallback((newEditorType: EditorType) => {
|
||||
// Show warning modal when switching modes
|
||||
setPendingEditorType(newEditorType);
|
||||
setSwitchModalOpen(true);
|
||||
}, []);
|
||||
|
||||
const confirmEditorTypeChange = useCallback(() => {
|
||||
if (pendingEditorType) {
|
||||
dispatch(changeEditorTypeAndResetQuery(pendingEditorType));
|
||||
}
|
||||
setSwitchModalOpen(false);
|
||||
setPendingEditorType(null);
|
||||
}, [dispatch, pendingEditorType]);
|
||||
|
||||
const cancelEditorTypeChange = useCallback(() => {
|
||||
setSwitchModalOpen(false);
|
||||
setPendingEditorType(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ConfirmModal
|
||||
isOpen={switchModalOpen}
|
||||
title="Switch editor"
|
||||
body="Switching between editors will reset your query. Are you sure you want to continue?"
|
||||
confirmText="Continue"
|
||||
onConfirm={confirmEditorTypeChange}
|
||||
onDismiss={cancelEditorTypeChange}
|
||||
/>
|
||||
<div className={styles.root}>
|
||||
<InlineLabel width={17}>Query type</InlineLabel>
|
||||
<div className={styles.queryItem}>
|
||||
<QueryTypeSelector />
|
||||
</div>
|
||||
</div>
|
||||
{rawDSLFeatureEnabled && (
|
||||
<div className={styles.root}>
|
||||
<InlineLabel width={17}>Editor type</InlineLabel>
|
||||
<div className={styles.queryItem}>
|
||||
<EditorTypeSelector />
|
||||
{rawDSLFeatureEnabled && (
|
||||
<div style={{ marginLeft: 'auto' }}>
|
||||
<EditorTypeSelector value={currentEditorType} onChange={onEditorTypeChange} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isCodeEditor && rawDSLFeatureEnabled && (
|
||||
<RawQueryEditor
|
||||
|
||||
@@ -6383,12 +6383,15 @@
|
||||
},
|
||||
"resource-export": {
|
||||
"label": {
|
||||
"advanced-options": "Advanced options",
|
||||
"classic": "Classic",
|
||||
"json": "JSON",
|
||||
"v1-resource": "V1 Resource",
|
||||
"v2-resource": "V2 Resource",
|
||||
"yaml": "YAML"
|
||||
}
|
||||
},
|
||||
"share-externally": "Share dashboard with another instance",
|
||||
"share-externally-tooltip": "Removes all instance-specific metadata and data source references from the resource before export."
|
||||
},
|
||||
"revert-dashboard-modal": {
|
||||
"body-restore-version": "Are you sure you want to restore the dashboard to version {{version}}? All unsaved changes will be lost.",
|
||||
@@ -7842,7 +7845,6 @@
|
||||
"export-externally-label": "Export the dashboard to use in another instance",
|
||||
"export-format": "Format",
|
||||
"export-mode": "Model",
|
||||
"export-remove-ds-refs": "Remove deployment details",
|
||||
"info-text": "Copy or download a file containing the definition of your dashboard",
|
||||
"title": "Export dashboard"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user