Compare commits

..

5 Commits

Author SHA1 Message Date
Andreas Christou 2bd1aec8dc Merge branch 'main' into andreas/graphite-alias-fix 2026-01-14 17:16:32 +00:00
Kristina Demeshchik 87f5d5e741 Dashboard: Hide export options in collapsible row (#116155)
* Introduce export options

* Reset keys

* Introduce a new key

* Generate new keys

* Rename the label

* re-generate key

* Fix the spacing

* Remove debuggers

* Add subtitle

* refactor component

* update labels

* faield tests

* Update tooltip

* Linting issue
2026-01-14 12:12:33 -05:00
Andrew Hackmann 5e68b07cac Elasticsearch: Make code editor look more like prometheus (#115461)
* Make code editor look more prometheus

* add warning when switching builders

* address adam's feedback

* yarn
2026-01-14 09:50:35 -07:00
Andreas Christou eaf354088f Ensure we're checking the target correctly 2026-01-14 16:45:39 +00:00
Andreas Christou e99d7da667 Use target as name for aliased queries 2026-01-13 17:53:02 +00:00
23 changed files with 551 additions and 466 deletions
+10
View File
@@ -1392,6 +1392,11 @@
"count": 2
}
},
"public/app/features/alerting/unified/components/mute-timings/MuteTimingForm.tsx": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/components/mute-timings/MuteTimingTimeInterval.tsx": {
"no-restricted-syntax": {
"count": 5
@@ -1516,6 +1521,11 @@
"count": 1
}
},
"public/app/features/alerting/unified/components/rule-editor/alert-rule-form/simplifiedRouting/route-settings/MuteTimingFields.tsx": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/components/rule-editor/alert-rule-form/simplifiedRouting/route-settings/RouteSettings.tsx": {
"no-restricted-syntax": {
"count": 1
+2 -2
View File
@@ -39,7 +39,7 @@ func (s *Service) CheckHealth(ctx context.Context, req *backend.CheckHealthReque
_, span := tracing.DefaultTracer().Start(ctx, "graphite healthcheck")
defer span.End()
graphiteReq, formData, _, err := s.createGraphiteRequest(ctx, healthCheckQuery, dsInfo)
graphiteReq, formData, _, _, err := s.createGraphiteRequest(ctx, healthCheckQuery, dsInfo)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
@@ -81,7 +81,7 @@ func (s *Service) CheckHealth(ctx context.Context, req *backend.CheckHealthReque
}
}()
_, err = s.toDataFrames(res, healthCheckQuery.RefID, false)
_, err = s.toDataFrames(res, healthCheckQuery.RefID, false, targetStr)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
+23 -15
View File
@@ -24,15 +24,16 @@ import (
func (s *Service) RunQuery(ctx context.Context, req *backend.QueryDataRequest, dsInfo *datasourceInfo) (*backend.QueryDataResponse, error) {
emptyQueries := []string{}
graphiteQueries := map[string]struct {
req *http.Request
formData url.Values
req *http.Request
formData url.Values
rawTarget string
}{}
// FromAlert header is defined in pkg/services/ngalert/models/constants.go
fromAlert := req.Headers["FromAlert"] == "true"
result := backend.NewQueryDataResponse()
for _, query := range req.Queries {
graphiteReq, formData, emptyQuery, err := s.createGraphiteRequest(ctx, query, dsInfo)
graphiteReq, formData, emptyQuery, target, err := s.createGraphiteRequest(ctx, query, dsInfo)
if err != nil {
result.Responses[query.RefID] = backend.ErrorResponseWithErrorSource(err)
return result, nil
@@ -44,11 +45,13 @@ func (s *Service) RunQuery(ctx context.Context, req *backend.QueryDataRequest, d
}
graphiteQueries[query.RefID] = struct {
req *http.Request
formData url.Values
req *http.Request
formData url.Values
rawTarget string
}{
req: graphiteReq,
formData: formData,
req: graphiteReq,
formData: formData,
rawTarget: target,
}
}
@@ -99,7 +102,7 @@ func (s *Service) RunQuery(ctx context.Context, req *backend.QueryDataRequest, d
}
}()
queryFrames, err := s.toDataFrames(res, refId, fromAlert)
queryFrames, err := s.toDataFrames(res, refId, fromAlert, graphiteReq.rawTarget)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
@@ -147,7 +150,7 @@ func (s *Service) processQuery(query backend.DataQuery) (string, *GraphiteQuery,
return target, nil, queryJSON.IsMetricTank, nil
}
func (s *Service) createGraphiteRequest(ctx context.Context, query backend.DataQuery, dsInfo *datasourceInfo) (*http.Request, url.Values, *GraphiteQuery, error) {
func (s *Service) createGraphiteRequest(ctx context.Context, query backend.DataQuery, dsInfo *datasourceInfo) (*http.Request, url.Values, *GraphiteQuery, string, error) {
/*
graphite doc about from and until, with sdk we are getting absolute instead of relative time
https://graphite-api.readthedocs.io/en/latest/api.html#from-until
@@ -163,12 +166,12 @@ func (s *Service) createGraphiteRequest(ctx context.Context, query backend.DataQ
target, emptyQuery, isMetricTank, err := s.processQuery(query)
if err != nil {
return nil, formData, nil, err
return nil, formData, nil, "", err
}
if emptyQuery != nil {
s.logger.Debug("Graphite", "empty query target", emptyQuery)
return nil, formData, emptyQuery, nil
return nil, formData, emptyQuery, "", nil
}
formData["target"] = []string{target}
@@ -188,20 +191,23 @@ func (s *Service) createGraphiteRequest(ctx context.Context, query backend.DataQ
QueryParams: params,
})
if err != nil {
return nil, formData, nil, err
return nil, formData, nil, "", err
}
return graphiteReq, formData, emptyQuery, nil
return graphiteReq, formData, emptyQuery, target, nil
}
func (s *Service) toDataFrames(response *http.Response, refId string, fromAlert bool) (frames data.Frames, error error) {
func (s *Service) toDataFrames(response *http.Response, refId string, fromAlert bool, rawTarget string) (frames data.Frames, error error) {
responseData, err := s.parseResponse(response)
if err != nil {
return nil, err
}
aliasRegex := regexp.MustCompile(`(alias\(|aliasByMetric|aliasByNode|aliasByTags|aliasQuery|aliasSub)`)
frames = data.Frames{}
for _, series := range responseData {
aliasMatch := aliasRegex.MatchString(rawTarget)
timeVector := make([]time.Time, 0, len(series.DataPoints))
values := make([]*float64, 0, len(series.DataPoints))
@@ -217,7 +223,9 @@ func (s *Service) toDataFrames(response *http.Response, refId string, fromAlert
tags := make(map[string]string)
for name, value := range series.Tags {
if name == "name" {
if fromAlert {
// Queries with aliases should use the target as the name
// to ensure multi-dimensional queries are distinguishable from each other
if fromAlert || aliasMatch {
value = series.Target
}
}
+124 -11
View File
@@ -182,7 +182,7 @@ func TestConvertResponses(t *testing.T) {
expectedFrames := data.Frames{expectedFrame}
httpResponse := &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}
dataFrames, err := service.toDataFrames(httpResponse, refId, false)
dataFrames, err := service.toDataFrames(httpResponse, refId, false, "target")
require.NoError(t, err)
if !reflect.DeepEqual(expectedFrames, dataFrames) {
@@ -196,7 +196,7 @@ func TestConvertResponses(t *testing.T) {
body := `
[
{
"target": "aliasedTarget(target)",
"target": "alias(target)",
"tags": { "name": "target", "fooTag": "fooValue", "barTag": "barValue", "int": 100, "float": 3.14 },
"datapoints": [[50, 1], [null, 2], [100, 3]]
}
@@ -211,13 +211,13 @@ func TestConvertResponses(t *testing.T) {
"barTag": "barValue",
"int": "100",
"float": "3.14",
"name": "target",
}, []*float64{&a, nil, &b}).SetConfig(&data.FieldConfig{DisplayNameFromDS: "aliasedTarget(target)"}),
"name": "alias(target)",
}, []*float64{&a, nil, &b}).SetConfig(&data.FieldConfig{DisplayNameFromDS: "alias(target)"}),
).SetMeta(&data.FrameMeta{Type: data.FrameTypeTimeSeriesMulti})
expectedFrames := data.Frames{expectedFrame}
httpResponse := &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}
dataFrames, err := service.toDataFrames(httpResponse, refId, false)
dataFrames, err := service.toDataFrames(httpResponse, refId, false, "alias(target)")
require.NoError(t, err)
if !reflect.DeepEqual(expectedFrames, dataFrames) {
@@ -240,7 +240,7 @@ func TestConvertResponses(t *testing.T) {
expectedFrames := data.Frames{}
httpResponse := &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}
dataFrames, err := service.toDataFrames(httpResponse, refId, false)
dataFrames, err := service.toDataFrames(httpResponse, refId, false, "")
require.NoError(t, err)
if !reflect.DeepEqual(expectedFrames, dataFrames) {
@@ -281,7 +281,7 @@ func TestConvertResponses(t *testing.T) {
expectedFrames := data.Frames{expectedFrame}
httpResponse := &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}
dataFrames, err := service.toDataFrames(httpResponse, refId, false)
dataFrames, err := service.toDataFrames(httpResponse, refId, false, "target")
require.NoError(t, err)
if !reflect.DeepEqual(expectedFrames, dataFrames) {
@@ -295,7 +295,7 @@ func TestConvertResponses(t *testing.T) {
body := `
[
{
"target": "aliasedTarget(target)",
"target": "alias(target)",
"tags": { "name": "target", "fooTag": "fooValue", "barTag": "barValue", "int": 100, "float": 3.14 },
"datapoints": [[50, 1], [null, 2], [100, 3]]
}
@@ -310,13 +310,13 @@ func TestConvertResponses(t *testing.T) {
"barTag": "barValue",
"int": "100",
"float": "3.14",
"name": "aliasedTarget(target)",
}, []*float64{&a, nil, &b}).SetConfig(&data.FieldConfig{DisplayNameFromDS: "aliasedTarget(target)"}),
"name": "alias(target)",
}, []*float64{&a, nil, &b}).SetConfig(&data.FieldConfig{DisplayNameFromDS: "alias(target)"}),
).SetMeta(&data.FrameMeta{Type: data.FrameTypeTimeSeriesMulti})
expectedFrames := data.Frames{expectedFrame}
httpResponse := &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}
dataFrames, err := service.toDataFrames(httpResponse, refId, true)
dataFrames, err := service.toDataFrames(httpResponse, refId, true, "alias(target)")
require.NoError(t, err)
if !reflect.DeepEqual(expectedFrames, dataFrames) {
@@ -738,6 +738,119 @@ Error: Target not found
}
}
func TestAliasMatching(t *testing.T) {
service := &Service{
logger: backend.Logger,
}
testCases := []struct {
name string
target string
tagsName string
fromAlert bool
expectedLabelName string
}{
{
name: "alias() function sets name tag to target",
target: "alias(stats.counters.web.hits, 'Web Hits')",
tagsName: "stats.counters.web.hits",
fromAlert: false,
expectedLabelName: "alias(stats.counters.web.hits, 'Web Hits')",
},
{
name: "aliasByNode() function sets name tag to target",
target: "aliasByNode(stats.counters.web.hits, 2)",
tagsName: "stats.counters.web.hits",
fromAlert: false,
expectedLabelName: "aliasByNode(stats.counters.web.hits, 2)",
},
{
name: "aliasByMetric() function sets name tag to target",
target: "aliasByMetric(stats.counters.web.hits)",
tagsName: "stats.counters.web.hits",
fromAlert: false,
expectedLabelName: "aliasByMetric(stats.counters.web.hits)",
},
{
name: "aliasByTags() function sets name tag to target",
target: "aliasByTags(stats.counters.web.hits, 'host')",
tagsName: "stats.counters.web.hits",
fromAlert: false,
expectedLabelName: "aliasByTags(stats.counters.web.hits, 'host')",
},
{
name: "aliasSub() function sets name tag to target",
target: "aliasSub(stats.counters.web.hits, 'stats', 'metrics')",
tagsName: "stats.counters.web.hits",
fromAlert: false,
expectedLabelName: "aliasSub(stats.counters.web.hits, 'stats', 'metrics')",
},
{
name: "aliasQuery() function sets name tag to target",
target: "aliasQuery(stats.counters.web.hits, 'SELECT name FROM hosts')",
tagsName: "stats.counters.web.hits",
fromAlert: false,
expectedLabelName: "aliasQuery(stats.counters.web.hits, 'SELECT name FROM hosts')",
},
{
name: "no alias function keeps original name tag",
target: "stats.counters.web.hits",
tagsName: "stats.counters.web.hits",
fromAlert: false,
expectedLabelName: "stats.counters.web.hits",
},
{
name: "fromAlert overrides name tag even without alias",
target: "stats.counters.web.hits",
tagsName: "original.name",
fromAlert: true,
expectedLabelName: "stats.counters.web.hits",
},
{
name: "nested alias function matches",
target: "sumSeries(alias(stats.counters.*.hits, 'Hits'))",
tagsName: "stats.counters.web.hits",
fromAlert: false,
expectedLabelName: "sumSeries(alias(stats.counters.*.hits, 'Hits'))",
},
{
name: "alias in metric path should not match",
target: "stats.alias.web.hits",
tagsName: "stats.alias.web.hits",
fromAlert: false,
expectedLabelName: "stats.alias.web.hits",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
body := fmt.Sprintf(`[
{
"target": %q,
"tags": { "name": %q, "host": "server1" },
"datapoints": [[100, 1609459200]]
}
]`, tc.target, tc.tagsName)
httpResponse := &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}
dataFrames, err := service.toDataFrames(httpResponse, "A", tc.fromAlert, tc.target)
require.NoError(t, err)
require.Len(t, dataFrames, 1)
frame := dataFrames[0]
require.GreaterOrEqual(t, len(frame.Fields), 2)
valueField := frame.Fields[1]
require.NotNil(t, valueField.Labels)
actualName, ok := valueField.Labels["name"]
require.True(t, ok, "name label should exist")
assert.Equal(t, tc.expectedLabelName, actualName, "name label should match expected value")
})
}
}
func TestParseGraphiteError(t *testing.T) {
tests := []struct {
name string
@@ -56,24 +56,6 @@ export const ImportedContactPointAlert = (props: ExtraAlertProps) => {
);
};
export const ImportedTimeIntervalAlert = (props: ExtraAlertProps) => {
return (
<Alert
title={t(
'alerting.provisioning.title-imported-time-interval',
'This time interval was imported and cannot be edited through the UI'
)}
severity="info"
{...props}
>
<Trans i18nKey="alerting.provisioning.body-imported-time-interval">
This time interval was imported from an external Alertmanager and is currently read-only. The time interval will
become editable after the migration process is complete.
</Trans>
</Alert>
);
};
export const ProvisioningBadge = ({
tooltip,
provenance,
@@ -1,130 +0,0 @@
import { render, screen, userEvent } from 'test/test-utils';
import { setupMswServer } from 'app/features/alerting/unified/mockApi';
import { grantUserPermissions } from 'app/features/alerting/unified/mocks';
import { setTimeIntervalsList } from 'app/features/alerting/unified/mocks/server/configure';
import { AlertmanagerProvider } from 'app/features/alerting/unified/state/AlertmanagerContext';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { AccessControlAction } from 'app/types/accessControl';
import MuteTimingsSelector from './MuteTimingsSelector';
const renderWithProvider = (alertManagerSource = GRAFANA_RULES_SOURCE_NAME) => {
return render(
<AlertmanagerProvider accessType={'notification'} alertmanagerSourceName={alertManagerSource}>
<MuteTimingsSelector
alertmanager={alertManagerSource}
selectProps={{
onChange: () => {},
}}
/>
</AlertmanagerProvider>
);
};
setupMswServer();
describe('MuteTimingsSelector', () => {
beforeEach(() => {
grantUserPermissions([
AccessControlAction.AlertingNotificationsRead,
AccessControlAction.AlertingNotificationsWrite,
]);
});
it('should show all non-imported time intervals', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'regular-interval', provenance: 'none' },
{ name: 'file-provisioned', provenance: 'file' },
{ name: 'another-regular', provenance: 'none' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// All non-imported intervals should be visible
expect(await screen.findByText('regular-interval')).toBeInTheDocument();
expect(screen.getByText('file-provisioned')).toBeInTheDocument();
expect(screen.getByText('another-regular')).toBeInTheDocument();
});
it('should filter out imported time intervals (provenance: converted_prometheus)', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'regular-interval', provenance: 'none' },
{ name: 'imported-interval', provenance: 'converted_prometheus' },
{ name: 'file-provisioned', provenance: 'file' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// Regular and file-provisioned should be visible
expect(await screen.findByText('regular-interval')).toBeInTheDocument();
expect(screen.getByText('file-provisioned')).toBeInTheDocument();
// Imported interval should NOT be in the list
expect(screen.queryByText('imported-interval')).not.toBeInTheDocument();
});
it('should show only non-imported intervals when all types are present', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'normal-1', provenance: 'none' },
{ name: 'imported-1', provenance: 'converted_prometheus' },
{ name: 'normal-2', provenance: 'none' },
{ name: 'imported-2', provenance: 'converted_prometheus' },
{ name: 'file-1', provenance: 'file' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// Non-imported intervals should be visible
expect(await screen.findByText('normal-1')).toBeInTheDocument();
expect(screen.getByText('normal-2')).toBeInTheDocument();
expect(screen.getByText('file-1')).toBeInTheDocument();
// Imported intervals should NOT be visible
expect(screen.queryByText('imported-1')).not.toBeInTheDocument();
expect(screen.queryByText('imported-2')).not.toBeInTheDocument();
});
it('should handle empty list', async () => {
setTimeIntervalsList([]);
renderWithProvider();
// Selector should be present but have no options
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
expect(selector).toBeInTheDocument();
});
it('should handle list with only imported intervals', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'imported-1', provenance: 'converted_prometheus' },
{ name: 'imported-2', provenance: 'converted_prometheus' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// No intervals should be visible
expect(screen.queryByText('imported-1')).not.toBeInTheDocument();
expect(screen.queryByText('imported-2')).not.toBeInTheDocument();
});
});
@@ -1,24 +1,17 @@
import { SelectableValue } from '@grafana/data';
import { t } from '@grafana/i18n';
import { MultiSelect, MultiSelectCommonProps } from '@grafana/ui';
import { MuteTiming, useMuteTimings } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
import { useMuteTimings } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
import { BaseAlertmanagerArgs } from 'app/features/alerting/unified/types/hooks';
import { timeIntervalToString } from 'app/features/alerting/unified/utils/alertmanager';
import { K8sAnnotations } from 'app/features/alerting/unified/utils/k8s/constants';
import { isImportedResource } from 'app/features/alerting/unified/utils/k8s/utils';
import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types';
const mapTimeInterval = ({ name, time_intervals }: MuteTiming): SelectableValue<string> => ({
const mapTimeInterval = ({ name, time_intervals }: MuteTimeInterval): SelectableValue<string> => ({
value: name,
label: name,
description: time_intervals.map((interval) => timeIntervalToString(interval)).join(', AND '),
});
/** Check if a time interval was imported from an external Alertmanager */
const isImportedTimeInterval = (timing: MuteTiming): boolean => {
const provenance = timing.metadata?.annotations?.[K8sAnnotations.Provenance];
return isImportedResource(provenance);
};
/** Provides a MultiSelect with available time intervals for the given alertmanager */
const TimeIntervalSelector = ({
alertmanager,
@@ -26,9 +19,7 @@ const TimeIntervalSelector = ({
}: BaseAlertmanagerArgs & { selectProps: MultiSelectCommonProps<string> }) => {
const { data } = useMuteTimings({ alertmanager, skip: selectProps.disabled });
// Filter out imported time intervals (provenance === 'prometheus_convert')
const availableTimings = data?.filter((timing) => !isImportedTimeInterval(timing)) || [];
const timeIntervalOptions = availableTimings.map((value) => mapTimeInterval(value));
const timeIntervalOptions = data?.map((value) => mapTimeInterval(value)) || [];
return (
<MultiSelect
@@ -3,7 +3,6 @@ import { Navigate } from 'react-router-dom-v5-compat';
import { t } from '@grafana/i18n';
import { useGetMuteTiming } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
import { useURLSearchParams } from 'app/features/alerting/unified/hooks/useURLSearchParams';
import { K8sAnnotations } from 'app/features/alerting/unified/utils/k8s/constants';
import { useAlertmanager } from '../../state/AlertmanagerContext';
import { withPageErrorBoundary } from '../../withPageErrorBoundary';
@@ -29,15 +28,13 @@ const EditTimingRoute = () => {
return <Navigate replace to="/alerting/routes" />;
}
const provenance = timeInterval?.metadata?.annotations?.[K8sAnnotations.Provenance];
return (
<MuteTimingForm
editMode
loading={isLoading}
showError={isError}
muteTiming={timeInterval}
provenance={provenance}
provisioned={timeInterval?.provisioned}
/>
);
};
@@ -1,103 +0,0 @@
import { render, screen } from 'test/test-utils';
import { setupMswServer } from 'app/features/alerting/unified/mockApi';
import { grantUserPermissions } from 'app/features/alerting/unified/mocks';
import { AlertmanagerProvider } from 'app/features/alerting/unified/state/AlertmanagerContext';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { AccessControlAction } from 'app/types/accessControl';
import MuteTimingForm from './MuteTimingForm';
import { muteTimeInterval } from './mocks';
const renderWithProvider = (provenance?: string, editMode = false) => {
return render(
<AlertmanagerProvider accessType={'notification'} alertmanagerSourceName={GRAFANA_RULES_SOURCE_NAME}>
<MuteTimingForm
muteTiming={{ id: 'mock-id', ...muteTimeInterval }}
provenance={provenance}
editMode={editMode}
loading={false}
showError={false}
/>
</AlertmanagerProvider>
);
};
setupMswServer();
describe('MuteTimingForm', () => {
beforeEach(() => {
grantUserPermissions([
AccessControlAction.AlertingNotificationsRead,
AccessControlAction.AlertingNotificationsWrite,
]);
});
it('should not show any alert when provenance is none', async () => {
renderWithProvider('none');
expect(screen.queryByText(/imported and cannot be edited/i)).not.toBeInTheDocument();
expect(screen.queryByText(/provisioned/i)).not.toBeInTheDocument();
});
it('should not show any alert when provenance is undefined', async () => {
renderWithProvider(undefined);
expect(screen.queryByText(/imported and cannot be edited/i)).not.toBeInTheDocument();
expect(screen.queryByText(/provisioned/i)).not.toBeInTheDocument();
});
it('should show imported alert when provenance is converted_prometheus', async () => {
renderWithProvider('converted_prometheus');
expect(
await screen.findByText(/This time interval was imported and cannot be edited through the UI/i)
).toBeInTheDocument();
expect(
screen.getByText(/This time interval was imported from an external Alertmanager and is currently read-only/i)
).toBeInTheDocument();
});
it('should show provisioning alert when provenance is file', async () => {
renderWithProvider('file');
expect(await screen.findByText(/This time interval cannot be edited through the UI/i)).toBeInTheDocument();
expect(
screen.getByText(/This time interval has been provisioned, that means it was created by config/i)
).toBeInTheDocument();
});
it('should show provisioning alert for other provenance types', async () => {
renderWithProvider('api');
expect(await screen.findByText(/This time interval cannot be edited through the UI/i)).toBeInTheDocument();
});
it('should disable form when provenance is converted_prometheus', async () => {
renderWithProvider('converted_prometheus', true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeDisabled();
});
it('should disable form when provenance is file', async () => {
renderWithProvider('file', true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeDisabled();
});
it('should enable form when provenance is none', async () => {
renderWithProvider('none', true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeEnabled();
});
it('should enable form when provenance is undefined', async () => {
renderWithProvider(undefined, true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeEnabled();
});
});
@@ -14,10 +14,9 @@ import {
import { useAlertmanager } from '../../state/AlertmanagerContext';
import { MuteTimingFields } from '../../types/mute-timing-form';
import { isImportedResource, isProvisionedResource } from '../../utils/k8s/utils';
import { makeAMLink } from '../../utils/misc';
import { createMuteTiming, defaultTimeInterval, isTimeIntervalDisabled } from '../../utils/mute-timings';
import { ImportedTimeIntervalAlert, ProvisionedResource, ProvisioningAlert } from '../Provisioning';
import { ProvisionedResource, ProvisioningAlert } from '../Provisioning';
import { MuteTimingTimeInterval } from './MuteTimingTimeInterval';
@@ -25,8 +24,8 @@ interface Props {
muteTiming?: MuteTiming;
showError?: boolean;
loading?: boolean;
/** Provenance of the mute timing - indicates how it was created (e.g., 'file', 'prometheus_convert', 'none') */
provenance?: string;
/** Is the current mute timing provisioned? If so, will disable editing via UI */
provisioned?: boolean;
/** Are we editing an existing time interval? */
editMode?: boolean;
}
@@ -57,7 +56,7 @@ const useDefaultValues = (muteTiming?: MuteTiming): MuteTimingFields => {
};
};
const MuteTimingForm = ({ muteTiming, showError, loading, provenance, editMode }: Props) => {
const MuteTimingForm = ({ muteTiming, showError, loading, provisioned, editMode }: Props) => {
const { selectedAlertmanager } = useAlertmanager();
const hookArgs = { alertmanager: selectedAlertmanager! };
@@ -106,19 +105,14 @@ const MuteTimingForm = ({ muteTiming, showError, loading, provenance, editMode }
);
}
const isProvisioned = isProvisionedResource(provenance);
const isImported = isImportedResource(provenance);
return (
<>
{isProvisioned && isImported && <ImportedTimeIntervalAlert />}
{isProvisioned && !isImported && <ProvisioningAlert resource={ProvisionedResource.MuteTiming} />}
{provisioned && <ProvisioningAlert resource={ProvisionedResource.MuteTiming} />}
<FormProvider {...formApi}>
<form onSubmit={formApi.handleSubmit(onSubmit)} data-testid="mute-timing-form">
<FieldSet disabled={isProvisioned || updating}>
<FieldSet disabled={provisioned || updating}>
<Field
required
noMargin
label={t('alerting.mute-timing-form.label-name', 'Name')}
description={t(
'alerting.time-interval-form.description-unique-time-interval',
@@ -27,7 +27,6 @@ export function MuteTimingFields({ alertmanager }: BaseAlertmanagerArgs) {
)}
className={styles.muteTimingField}
invalid={!!errors.contactPoints?.[alertmanager]?.muteTimeIntervals}
noMargin
>
<Controller
render={({ field: { onChange, ref, ...field } }) => (
@@ -175,36 +175,6 @@ export const setTimeIntervalsListEmpty = () => {
return handler;
};
interface TimeIntervalConfig {
name: string;
provenance?: string;
}
/**
* Makes the mock server respond with custom time intervals
*/
export const setTimeIntervalsList = (intervals: TimeIntervalConfig[]) => {
const listMuteTimingsPath = listNamespacedTimeIntervalHandler().info.path;
const handler = http.get(listMuteTimingsPath, () => {
const items = intervals.map((interval) => ({
metadata: {
annotations: {
'grafana.com/provenance': interval.provenance ?? 'none',
},
name: interval.name,
uid: `uid-${interval.name}`,
namespace: 'default',
resourceVersion: 'e0270bfced786660',
},
spec: { name: interval.name, time_intervals: [] },
}));
return HttpResponse.json(getK8sResponse('TimeIntervalList', items));
});
server.use(handler);
return handler;
};
export function mimirDataSource() {
const dataSource = mockDataSource(
{
@@ -65,7 +65,3 @@ export const stringifyFieldSelector = (fieldSelectors: FieldSelector[]): string
export function isProvisionedResource(provenance?: string): boolean {
return Boolean(provenance && provenance !== KnownProvenance.None);
}
export function isImportedResource(provenance?: string): boolean {
return provenance === KnownProvenance.ConvertedPrometheus;
}
@@ -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;
}
@@ -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}
/>
);
};
@@ -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
+4 -4
View File
@@ -2178,10 +2178,8 @@
"badge-tooltip-provenance": "This resource has been provisioned via {{provenance}} and cannot be edited through the UI",
"badge-tooltip-standard": "This resource has been provisioned and cannot be edited through the UI",
"body-imported": "This contact point contains integrations that were imported from an external Alertmanager and is currently read-only. The integrations will become editable after the migration process is complete.",
"body-imported-time-interval": "This time interval was imported from an external Alertmanager and is currently read-only. The time interval will become editable after the migration process is complete.",
"body-provisioned": "This {{resource}} has been provisioned, that means it was created by config. Please contact your server admin to update this {{resource}}.",
"title-imported": "This contact point was imported and cannot be edited through the UI",
"title-imported-time-interval": "This time interval was imported and cannot be edited through the UI",
"title-provisioned": "This {{resource}} cannot be edited through the UI"
},
"provisioning-badge": {
@@ -6385,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.",
@@ -7844,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"
},