mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-16 13:21:15 +00:00
Compare commits
1 Commits
nv/exec-st
...
nv/disable
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e490676aaf |
@@ -28226,6 +28226,62 @@ paths:
|
||||
tags:
|
||||
- rules
|
||||
x-signoz-stability: alpha
|
||||
/api/v2/rules/{id}/disable:
|
||||
post:
|
||||
deprecated: false
|
||||
description: This endpoint disables an alert rule by ID without validating its
|
||||
stored definition, so a rule that no longer passes validation can still be
|
||||
stopped. Enabling goes through the patch endpoint, which validates the whole
|
||||
rule.
|
||||
operationId: DisableRuleByID
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"404":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Not Found
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- rule:update
|
||||
- tokenizer:
|
||||
- rule:update
|
||||
summary: Disable alert rule
|
||||
tags:
|
||||
- rules
|
||||
x-signoz-stability: alpha
|
||||
/api/v2/rules/{id}/history/filter_keys:
|
||||
get:
|
||||
deprecated: false
|
||||
|
||||
@@ -24,6 +24,7 @@ import type {
|
||||
CreateRuleView201,
|
||||
DeleteRuleByIDPathParameters,
|
||||
DeleteRuleViewPathParameters,
|
||||
DisableRuleByIDPathParameters,
|
||||
GetRuleByID200,
|
||||
GetRuleByIDPathParameters,
|
||||
GetRuleHistoryFilterKeys200,
|
||||
@@ -964,6 +965,85 @@ export const useCloneRuleByID = <
|
||||
> => {
|
||||
return useMutation(getCloneRuleByIDMutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* This endpoint disables an alert rule by ID without validating its stored definition, so a rule that no longer passes validation can still be stopped. Enabling goes through the patch endpoint, which validates the whole rule.
|
||||
* @summary Disable alert rule
|
||||
*/
|
||||
export const disableRuleByID = (
|
||||
{ id }: DisableRuleByIDPathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<void>({
|
||||
url: `/api/v2/rules/${id}/disable`,
|
||||
method: 'POST',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getDisableRuleByIDMutationOptions = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof disableRuleByID>>,
|
||||
TError,
|
||||
{ pathParams: DisableRuleByIDPathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof disableRuleByID>>,
|
||||
TError,
|
||||
{ pathParams: DisableRuleByIDPathParameters },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ['disableRuleByID'];
|
||||
const { mutation: mutationOptions } = options
|
||||
? options.mutation &&
|
||||
'mutationKey' in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey } };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof disableRuleByID>>,
|
||||
{ pathParams: DisableRuleByIDPathParameters }
|
||||
> = (props) => {
|
||||
const { pathParams } = props ?? {};
|
||||
|
||||
return disableRuleByID(pathParams);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type DisableRuleByIDMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof disableRuleByID>>
|
||||
>;
|
||||
|
||||
export type DisableRuleByIDMutationError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Disable alert rule
|
||||
*/
|
||||
export const useDisableRuleByID = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof disableRuleByID>>,
|
||||
TError,
|
||||
{ pathParams: DisableRuleByIDPathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationResult<
|
||||
Awaited<ReturnType<typeof disableRuleByID>>,
|
||||
TError,
|
||||
{ pathParams: DisableRuleByIDPathParameters },
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getDisableRuleByIDMutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* Returns distinct label keys from rule history entries for the selected range.
|
||||
* @summary Get rule history filter keys
|
||||
|
||||
@@ -16750,6 +16750,9 @@ export type CloneRuleByID201 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type DisableRuleByIDPathParameters = {
|
||||
id: string;
|
||||
};
|
||||
export type GetRuleHistoryFilterKeysPathParameters = {
|
||||
id: string;
|
||||
};
|
||||
|
||||
@@ -62,7 +62,31 @@ describe('ListAlertRules — actions menu', () => {
|
||||
expect(labels).not.toContain('Disable');
|
||||
});
|
||||
|
||||
it('toggle action: clicking Disable sends PATCH with disabled:true', async () => {
|
||||
it('toggle action: clicking Disable posts to the disable endpoint', async () => {
|
||||
let disabledId: string | null = null;
|
||||
server.use(
|
||||
rest.post('http://localhost/api/v2/rules/:id/disable', (req, res, ctx) => {
|
||||
disabledId = req.params.id as string;
|
||||
return res(ctx.status(204));
|
||||
}),
|
||||
);
|
||||
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('High CPU Alert');
|
||||
await openActionsMenu(row);
|
||||
await clickMenuItem('Disable');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(disabledId).toBe('rule-1');
|
||||
});
|
||||
|
||||
expect(logEventMock).toHaveBeenCalledWith(
|
||||
'Alert: Action',
|
||||
expect.objectContaining({ action: 'Enable/Disable', ruleId: 'rule-1' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('toggle action: clicking Enable sends PATCH with disabled:false', async () => {
|
||||
let capturedBody: unknown = null;
|
||||
let capturedPath: string | null = null;
|
||||
server.use(
|
||||
@@ -74,21 +98,14 @@ describe('ListAlertRules — actions menu', () => {
|
||||
);
|
||||
|
||||
renderListAlertRules();
|
||||
const row = await findAlertRow('High CPU Alert');
|
||||
const row = await findAlertRow('Disabled Alert');
|
||||
await openActionsMenu(row);
|
||||
await clickMenuItem('Disable');
|
||||
await clickMenuItem('Enable');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(capturedBody).toStrictEqual(
|
||||
expect.objectContaining({ disabled: true }),
|
||||
);
|
||||
expect(capturedBody).toStrictEqual({ disabled: false });
|
||||
});
|
||||
expect(capturedPath).toBe('rule-1');
|
||||
|
||||
expect(logEventMock).toHaveBeenCalledWith(
|
||||
'Alert: Action',
|
||||
expect.objectContaining({ action: 'Enable/Disable', ruleId: 'rule-1' }),
|
||||
);
|
||||
expect(capturedPath).toBe('rule-4');
|
||||
});
|
||||
|
||||
it('edit action: clicking Edit navigates via safeNavigate and logs event', async () => {
|
||||
@@ -192,11 +209,11 @@ describe('ListAlertRules — actions menu', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('error path: PATCH is still attempted when server returns 500', async () => {
|
||||
let patchAttempted = false;
|
||||
it('error path: disable is still attempted when server returns 500', async () => {
|
||||
let disableAttempted = false;
|
||||
server.use(
|
||||
rest.patch('http://localhost/api/v2/rules/:id', (_, res, ctx) => {
|
||||
patchAttempted = true;
|
||||
rest.post('http://localhost/api/v2/rules/:id/disable', (_, res, ctx) => {
|
||||
disableAttempted = true;
|
||||
return res(ctx.status(500), ctx.json({ status: 'error' }));
|
||||
}),
|
||||
);
|
||||
@@ -207,7 +224,7 @@ describe('ListAlertRules — actions menu', () => {
|
||||
await clickMenuItem('Disable');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(patchAttempted).toBe(true);
|
||||
expect(disableAttempted).toBe(true);
|
||||
});
|
||||
|
||||
expect(logEventMock).toHaveBeenCalledWith(
|
||||
|
||||
@@ -4,17 +4,15 @@ import { Ellipsis } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { patchRulePartial } from 'api/alerts/patchRulePartial';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import {
|
||||
deleteRuleByID,
|
||||
disableRuleByID,
|
||||
invalidateListRulesV3,
|
||||
patchRuleByID,
|
||||
cloneRuleByID,
|
||||
} from 'api/generated/services/rules';
|
||||
import type {
|
||||
RenderErrorResponseDTO,
|
||||
RuletypesPostableRuleDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { AxiosError } from 'axios';
|
||||
|
||||
import type { AlertRule } from '../types';
|
||||
@@ -31,12 +29,12 @@ function ActionsMenu({ rule, onEdit }: ActionsMenuProps): JSX.Element {
|
||||
const handleToggle = useCallback((): void => {
|
||||
alertActionLogEvent(ALERT_ACTIONS.TOGGLE, rule);
|
||||
const newDisabled = !rule.disabled;
|
||||
const id = rule.id ?? '';
|
||||
const toggleRequest: Promise<unknown> = newDisabled
|
||||
? disableRuleByID({ id })
|
||||
: patchRulePartial(id, { disabled: false });
|
||||
toast.promise(
|
||||
patchRuleByID({ id: rule.id ?? '' }, {
|
||||
disabled: newDisabled,
|
||||
} as RuletypesPostableRuleDTO).then(() =>
|
||||
invalidateListRulesV3(queryClient),
|
||||
),
|
||||
toggleRequest.then(() => invalidateListRulesV3(queryClient)),
|
||||
{
|
||||
loading: newDisabled ? 'Disabling alert...' : 'Enabling alert...',
|
||||
success: newDisabled ? 'Alert disabled' : 'Alert enabled',
|
||||
|
||||
@@ -290,6 +290,9 @@ export const handlers = [
|
||||
rest.patch('http://localhost/api/v2/rules/:id', (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success' })),
|
||||
),
|
||||
rest.post('http://localhost/api/v2/rules/:id/disable', (_, res, ctx) =>
|
||||
res(ctx.status(204)),
|
||||
),
|
||||
rest.delete('http://localhost/api/v2/rules/:id', (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success' })),
|
||||
),
|
||||
|
||||
@@ -7,6 +7,7 @@ import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import {
|
||||
cloneRuleByID,
|
||||
deleteRuleByID,
|
||||
disableRuleByID,
|
||||
getGetRuleHistoryTimelineQueryOptions,
|
||||
invalidateGetRuleByID,
|
||||
invalidateListRulesV3,
|
||||
@@ -24,7 +25,6 @@ import {
|
||||
type GetRuleHistoryTimeline200,
|
||||
type GetRuleHistoryTopContributors200,
|
||||
type RenderErrorResponseDTO,
|
||||
type RuletypesPostableRuleDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { AxiosError } from 'axios';
|
||||
import { QueryParams } from 'constants/query';
|
||||
@@ -378,11 +378,17 @@ export const useAlertRuleStatusToggle = ({
|
||||
|
||||
const { mutate: toggleAlertState } = useMutation(
|
||||
[REACT_QUERY_KEY.TOGGLE_ALERT_STATE, ruleId],
|
||||
(args: { id: string; data: Partial<RuletypesPostableRuleDTO> }) =>
|
||||
patchRulePartial(args.id, args.data),
|
||||
async (args: { id: string; disabled: boolean }) => {
|
||||
if (args.disabled) {
|
||||
await disableRuleByID({ id: args.id });
|
||||
return RuletypesAlertStateDTO.disabled;
|
||||
}
|
||||
const response = await patchRulePartial(args.id, { disabled: false });
|
||||
return response.data.state;
|
||||
},
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
setAlertRuleState(data.data.state);
|
||||
onSuccess: (state) => {
|
||||
setAlertRuleState(state);
|
||||
void invalidateGetRuleByID(queryClient, { id: ruleId });
|
||||
void queryClient.refetchQueries([
|
||||
REACT_QUERY_KEY.ALERT_RULE_DETAILS,
|
||||
@@ -390,7 +396,7 @@ export const useAlertRuleStatusToggle = ({
|
||||
]);
|
||||
notifications.success({
|
||||
message: `Alert has been ${
|
||||
data.data.state === 'disabled' ? 'disabled' : 'enabled'
|
||||
state === RuletypesAlertStateDTO.disabled ? 'disabled' : 'enabled'
|
||||
}.`,
|
||||
});
|
||||
},
|
||||
@@ -408,11 +414,10 @@ export const useAlertRuleStatusToggle = ({
|
||||
);
|
||||
|
||||
const handleAlertStateToggle = (): void => {
|
||||
const args = {
|
||||
toggleAlertState({
|
||||
id: ruleId,
|
||||
data: { disabled: alertRuleState !== 'disabled' },
|
||||
};
|
||||
toggleAlertState(args);
|
||||
disabled: alertRuleState !== RuletypesAlertStateDTO.disabled,
|
||||
});
|
||||
};
|
||||
|
||||
return { handleAlertStateToggle };
|
||||
|
||||
@@ -98,6 +98,10 @@ export const alertOverviewMocks = defineStoryMocks({
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: null })),
|
||||
),
|
||||
|
||||
rest.post('http://localhost/api/v2/rules/:id/disable', (_req, res, ctx) =>
|
||||
res(ctx.status(204)),
|
||||
),
|
||||
|
||||
rest.delete('http://localhost/api/v2/rules/:id', (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: null })),
|
||||
),
|
||||
|
||||
@@ -246,6 +246,12 @@ export const alertRulesMocks = defineStoryMocks({
|
||||
})),
|
||||
),
|
||||
|
||||
rest.post('http://localhost/api/v2/rules/:id/disable', (_req, res, ctx) =>
|
||||
values.toggleState === 'success'
|
||||
? res(ctx.status(204))
|
||||
: actionResponse(values.toggleState, res, ctx, () => null),
|
||||
),
|
||||
|
||||
rest.post('http://localhost/api/v2/rules/:id/clone', (_req, res, ctx) =>
|
||||
actionResponse(values.cloneState, res, ctx, () => ({
|
||||
status: 'success',
|
||||
|
||||
@@ -307,6 +307,28 @@ func (provider *provider) addRulerRoutes(router *mux.Router) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/{id}/disable", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.DisableRuleByID, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "DisableRuleByID",
|
||||
Tags: []string{"rules"},
|
||||
Summary: "Disable alert rule",
|
||||
Description: "This endpoint disables an alert rule by ID without validating its stored definition, so a rule that no longer passes validation can still be stopped. Enabling goes through the patch endpoint, which validates the whole rule.",
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceRule.Scope(coretypes.VerbUpdate)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceRule,
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("id"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/rules/test", handler.New(
|
||||
provider.authzMiddleware.CheckResources(provider.rulerHandler.TestRule, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),
|
||||
handler.OpenAPIDef{
|
||||
|
||||
@@ -1107,6 +1107,29 @@ func (m *Manager) PatchRule(ctx context.Context, ruleStr string, id valuer.UUID)
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
func (m *Manager) DisableRule(ctx context.Context, id valuer.UUID) error {
|
||||
claims, err := authtypes.ClaimsFromContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
storedRule, err := m.ruleStore.GetStoredRule(ctx, valuer.MustNewUUID(claims.OrgID), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := storedRule.Disable(); err != nil {
|
||||
return err
|
||||
}
|
||||
storedRule.UpdatedBy = claims.Email
|
||||
storedRule.UpdatedAt = time.Now()
|
||||
|
||||
return m.ruleStore.EditRule(ctx, storedRule, func(context.Context) error {
|
||||
m.deleteTask(prepareTaskName(id.StringValue()))
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// TestNotification prepares a dummy rule for given rule parameters and
|
||||
// sends a test notification. returns alert count and error (if any)
|
||||
func (m *Manager) TestNotification(ctx context.Context, orgID valuer.UUID, ruleStr string) (int, error) {
|
||||
|
||||
@@ -10,6 +10,7 @@ type Handler interface {
|
||||
UpdateRuleByID(http.ResponseWriter, *http.Request)
|
||||
DeleteRuleByID(http.ResponseWriter, *http.Request)
|
||||
PatchRuleByID(http.ResponseWriter, *http.Request)
|
||||
DisableRuleByID(http.ResponseWriter, *http.Request)
|
||||
TestRule(http.ResponseWriter, *http.Request)
|
||||
|
||||
ListRuleViews(http.ResponseWriter, *http.Request)
|
||||
|
||||
@@ -44,6 +44,9 @@ type Ruler interface {
|
||||
// TODO: same as CreateRule — accept PostableRule instead of raw string.
|
||||
PatchRule(ctx context.Context, ruleStr string, id valuer.UUID) (*ruletypes.GettableRule, error)
|
||||
|
||||
// DisableRule stops the rule identified by id without decoding or validating its stored definition.
|
||||
DisableRule(ctx context.Context, id valuer.UUID) error
|
||||
|
||||
// TestNotification fires a test alert for the rule defined in ruleStr.
|
||||
// TODO: same as CreateRule — accept PostableRule instead of raw string.
|
||||
TestNotification(ctx context.Context, orgID valuer.UUID, ruleStr string) (int, error)
|
||||
|
||||
@@ -177,6 +177,24 @@ func (handler *handler) PatchRuleByID(rw http.ResponseWriter, req *http.Request)
|
||||
render.Success(rw, http.StatusOK, ruletypes.NewRule(rule))
|
||||
}
|
||||
|
||||
func (handler *handler) DisableRuleByID(rw http.ResponseWriter, req *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
id, err := valuer.NewUUID(mux.Vars(req)["id"])
|
||||
if err != nil {
|
||||
render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is not a valid uuid"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := handler.ruler.DisableRule(ctx, id); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusNoContent, nil)
|
||||
}
|
||||
|
||||
func (handler *handler) TestRule(rw http.ResponseWriter, req *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
@@ -165,6 +165,10 @@ func (provider *provider) PatchRule(ctx context.Context, ruleStr string, id valu
|
||||
return provider.manager.PatchRule(ctx, ruleStr, id)
|
||||
}
|
||||
|
||||
func (provider *provider) DisableRule(ctx context.Context, id valuer.UUID) error {
|
||||
return provider.manager.DisableRule(ctx, id)
|
||||
}
|
||||
|
||||
func (provider *provider) TestNotification(ctx context.Context, orgID valuer.UUID, ruleStr string) (int, error) {
|
||||
return provider.manager.TestNotification(ctx, orgID, ruleStr)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/uptrace/bun"
|
||||
@@ -57,6 +58,22 @@ func (rule *StorableRule) ToPostableRuleForCloning() (*PostableRule, error) {
|
||||
return postable, nil
|
||||
}
|
||||
|
||||
func (rule *StorableRule) Disable() error {
|
||||
// only the disabled key is touched, so a rule whose data no longer decodes into PostableRule can still be disabled
|
||||
data := map[string]json.RawMessage{}
|
||||
if err := json.Unmarshal([]byte(rule.Data), &data); err != nil {
|
||||
return errors.WrapInternalf(err, errors.CodeInternal, "stored rule data is not a json object")
|
||||
}
|
||||
data["disabled"] = json.RawMessage("true")
|
||||
|
||||
encoded, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rule.Data = string(encoded)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RuleAlert represents an alert associated with a rule, used when filtering by metric name.
|
||||
type RuleAlert struct {
|
||||
AlertName string
|
||||
|
||||
@@ -508,6 +508,7 @@ def test_viewer_forbidden_on_rule_writes(
|
||||
("patch", f"{V2_RULES_URL}/{target_id}", {"description": "viewer patch"}),
|
||||
("delete", f"{V2_RULES_URL}/{target_id}", None),
|
||||
("post", f"{V2_RULES_URL}/{target_id}/clone", None),
|
||||
("post", f"{V2_RULES_URL}/{target_id}/disable", None),
|
||||
("post", f"{V2_RULES_URL}/test", body),
|
||||
):
|
||||
response = getattr(requests, method)(
|
||||
|
||||
74
tests/integration/tests/ruler/10_disable_rule.py
Normal file
74
tests/integration/tests/ruler/10_disable_rule.py
Normal file
@@ -0,0 +1,74 @@
|
||||
import json
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from http import HTTPStatus
|
||||
|
||||
import requests
|
||||
from sqlalchemy import sql
|
||||
|
||||
from fixtures.alerts import get_rule
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.types import Operation, SigNoz
|
||||
|
||||
BASE_URL = "/api/v2/rules"
|
||||
|
||||
ENABLED_RULE_PATH = "ruler/test_scenarios/threshold_above_at_least_once/rule.json"
|
||||
|
||||
|
||||
def test_disable_rule(
|
||||
signoz: SigNoz,
|
||||
create_alert_rule_with_channel: Callable[[str], str],
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
rule_id = create_alert_rule_with_channel(ENABLED_RULE_PATH)
|
||||
|
||||
response = requests.post(signoz.self.host_configs["8080"].get(f"{BASE_URL}/{rule_id}/disable"), headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
rule = get_rule(signoz, token, rule_id)
|
||||
assert rule["disabled"] is True
|
||||
assert rule["state"] == "disabled"
|
||||
assert rule["updatedBy"] == USER_ADMIN_EMAIL
|
||||
|
||||
# disabling an already disabled rule succeeds
|
||||
response = requests.post(signoz.self.host_configs["8080"].get(f"{BASE_URL}/{rule_id}/disable"), headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
|
||||
def test_disable_rule_with_unknown_id(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = requests.post(signoz.self.host_configs["8080"].get(f"{BASE_URL}/{uuid.uuid4()}/disable"), headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND, response.text
|
||||
|
||||
response = requests.post(signoz.self.host_configs["8080"].get(f"{BASE_URL}/not-a-uuid/disable"), headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
|
||||
|
||||
|
||||
def test_disable_rule_with_undecodable_stored_data(
|
||||
signoz: SigNoz,
|
||||
create_alert_rule_with_channel: Callable[[str], str],
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
rule_id = create_alert_rule_with_channel(ENABLED_RULE_PATH)
|
||||
|
||||
with signoz.sqlstore.conn.begin() as conn:
|
||||
conn.execute(
|
||||
sql.text("UPDATE rule SET data = :data WHERE id = :id"),
|
||||
{"data": json.dumps({"alert": "undecodable", "condition": "not an object", "disabled": False}), "id": rule_id},
|
||||
)
|
||||
|
||||
response = requests.post(signoz.self.host_configs["8080"].get(f"{BASE_URL}/{rule_id}/disable"), headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
# every key other than disabled stays as stored
|
||||
with signoz.sqlstore.conn.connect() as conn:
|
||||
stored = conn.execute(sql.text("SELECT data FROM rule WHERE id = :id"), {"id": rule_id}).fetchone()
|
||||
assert stored is not None
|
||||
assert json.loads(stored[0]) == {"alert": "undecodable", "condition": "not an object", "disabled": True}
|
||||
Reference in New Issue
Block a user