Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

refactor(planned-maintenance): remove time bounds from recurrence (#11500)

Jatinderjit Singh3e51b9556ea4
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index e8195b5b1c..4c6f017413 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -409,10 +409,6 @@ components:
properties:
duration:
type: string
- endTime:
- format: date-time
- nullable: true
- type: string
repeatOn:
items:
$ref: '#/components/schemas/AlertmanagertypesRepeatOn'
@@ -420,11 +416,7 @@ components:
type: array
repeatType:
$ref: '#/components/schemas/AlertmanagertypesRepeatType'
- startTime:
- format: date-time
- type: string
required:
- - startTime
- duration
- repeatType
type: object
@@ -458,6 +450,7 @@ components:
type: string
required:
- timezone
+ - startTime
type: object
AuthtypesAttributeMapping:
properties:
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index 9bccab4694..6e43885c88 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -413,21 +413,11 @@ export interface AlertmanagertypesRecurrenceDTO {
* @type string
*/
duration: string;
- /**
- * @type string,null
- * @format date-time
- */
- endTime?: string | null;
/**
* @type array,null
*/
repeatOn?: AlertmanagertypesRepeatOnDTO[] | null;
repeatType: AlertmanagertypesRepeatTypeDTO;
- /**
- * @type string
- * @format date-time
- */
- startTime: string;
}
export interface AlertmanagertypesScheduleDTO {
@@ -441,7 +431,7 @@ export interface AlertmanagertypesScheduleDTO {
* @type string
* @format date-time
*/
- startTime?: string;
+ startTime: string;
/**
* @type string
*/
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx
index 60556188ca..9ec7ce7cdb 100644
--- a/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx
@@ -151,6 +151,11 @@ export function PlannedDowntimeForm(
const saveHandler = useCallback(
async (values: PlannedDowntimeFormData) => {
+ const { startTime, timezone } = values;
+ if (!startTime || !timezone) {
+ // unreachable: required fields should always be present on submitting.
+ return;
+ }
const data: AlertmanagertypesPostablePlannedMaintenanceDTO = {
alertIds:
values.alertRuleScope === 'all'
@@ -161,9 +166,9 @@ export function PlannedDowntimeForm(
name: values.name,
scope: values.scope,
schedule: {
- startTime: values.startTime?.format(),
+ startTime: startTime.format(),
endTime: values.endTime?.format(),
- timezone: values.timezone!,
+ timezone,
recurrence: values.recurrence,
},
};
@@ -200,25 +205,17 @@ export function PlannedDowntimeForm(
],
);
const onFinish = async (values: PlannedDowntimeFormData): Promise<void> => {
- const { recurrence } = values;
- const recurrenceData =
- !recurrence ||
- recurrence.repeatType === recurrenceOptions.doesNotRepeat.value
- ? undefined
- : {
- duration: recurrence.duration
- ? `${recurrence.duration}${durationUnit}`
- : '',
- startTime: values.startTime!.format(),
- endTime: values.endTime?.format(),
- repeatOn: recurrence.repeatOn,
- repeatType: recurrence.repeatType,
- };
-
- await saveHandler({
- ...values,
- recurrence: recurrenceData,
- });
+ const rec = values.recurrence;
+ const recurrence =
+ rec && rec.repeatType !== recurrenceOptions.doesNotRepeat.value
+ ? {
+ duration: `${rec.duration}${durationUnit}`,
+ repeatOn: rec.repeatOn,
+ repeatType: rec.repeatType,
+ }
+ : undefined;
+
+ await saveHandler({ ...values, recurrence });
};
const handleFormData = (data: Partial<PlannedDowntimeFormData>): void => {
@@ -275,9 +272,6 @@ export function PlannedDowntimeForm(
const formattedInitialValues = useMemo((): PlannedDowntimeFormData => {
const { schedule } = initialValues;
- const startTime = schedule?.recurrence?.startTime || schedule?.startTime;
- const endTime = schedule?.recurrence?.endTime || schedule?.endTime;
-
const initialAlertIds = initialValues.alertIds || [];
return {
@@ -285,8 +279,12 @@ export function PlannedDowntimeForm(
alertRuleScope:
isEditMode && initialAlertIds.length === 0 ? 'all' : 'specific',
alertRules: getAlertOptionsFromIds(initialAlertIds, alertOptions),
- startTime: startTime ? dayjs(startTime).tz(schedule.timezone) : null,
- endTime: endTime ? dayjs(endTime).tz(schedule.timezone) : null,
+ startTime: schedule?.startTime
+ ? dayjs(schedule.startTime).tz(schedule.timezone)
+ : null,
+ endTime: schedule?.endTime
+ ? dayjs(schedule.endTime).tz(schedule.timezone)
+ : null,
recurrence: {
...schedule?.recurrence,
repeatType: !isScheduleRecurring(schedule)
@@ -297,7 +295,7 @@ export function PlannedDowntimeForm(
timezone: schedule?.timezone as string,
scope: initialValues.scope || '',
};
- }, [initialValues, alertOptions]);
+ }, [initialValues, isEditMode, alertOptions]);
useEffect(() => {
setSelectedTags(formattedInitialValues.alertRules);
@@ -341,7 +339,7 @@ export function PlannedDowntimeForm(
const formattedEndTime = endTime.format(TIME_FORMAT);
const formattedEndDate = endTime.format(DATE_FORMAT);
return `Scheduled to end maintenance on ${formattedEndDate} at ${formattedEndTime}.`;
- }, [formData, recurrenceType]);
+ }, [formData]);
return (
<Modal
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntimeList.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntimeList.tsx
index de97f6c7a6..fd46d06410 100644
--- a/frontend/src/container/PlannedDowntime/PlannedDowntimeList.tsx
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntimeList.tsx
@@ -142,7 +142,6 @@ export function CollapseListContent({
updated_by_name?: string;
alertOptions?: DefaultOptionType[];
}): JSX.Element {
- const repeats = schedule?.recurrence;
const renderItems = (title: string, value: ReactNode): JSX.Element => (
<div className="render-item-collapse-list">
<Typography>{title}</Typography>
@@ -193,10 +192,7 @@ export function CollapseListContent({
'Timezone',
<Typography>{schedule?.timezone || '-'}</Typography>,
)}
- {renderItems(
- 'Repeats',
- <Typography>{recurrenceInfo(repeats, schedule?.timezone)}</Typography>,
- )}
+ {renderItems('Repeats', <Typography>{recurrenceInfo(schedule)}</Typography>)}
{renderItems(
'Alerts silenced',
alertOptions?.length ? (
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntimeutils.ts b/frontend/src/container/PlannedDowntime/PlannedDowntimeutils.ts
index c9231ca249..5e53ae7802 100644
--- a/frontend/src/container/PlannedDowntime/PlannedDowntimeutils.ts
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntimeutils.ts
@@ -6,7 +6,7 @@ import type {
DeleteDowntimeScheduleByIDPathParameters,
RenderErrorResponseDTO,
AlertmanagertypesPlannedMaintenanceDTO,
- AlertmanagertypesRecurrenceDTO,
+ AlertmanagertypesScheduleDTO,
} from 'api/generated/services/sigNoz.schemas';
import type { ErrorType } from 'api/generatedAPIInstance';
import { AxiosError } from 'axios';
@@ -66,14 +66,17 @@ export const getAlertOptionsFromIds = (
);
export const recurrenceInfo = (
- recurrence?: AlertmanagertypesRecurrenceDTO | null,
- timezone?: string,
+ schedule?: AlertmanagertypesScheduleDTO | null,
): string => {
+ if (!schedule) {
+ return 'No';
+ }
+ const { startTime, endTime, timezone, recurrence } = schedule;
if (!recurrence) {
return 'No';
}
- const { startTime, duration, repeatOn, repeatType, endTime } = recurrence;
+ const { duration, repeatOn, repeatType } = recurrence;
const formattedStartTime = startTime
? formatDateTime(startTime, timezone)
@@ -95,7 +98,7 @@ export const defaultInitialValues: Partial<AlertmanagertypesPlannedMaintenanceDT
timezone: '',
endTime: undefined,
recurrence: undefined,
- startTime: undefined,
+ startTime: '',
},
alertIds: [],
createdAt: undefined,
diff --git a/frontend/src/container/PlannedDowntime/__test__/testUtils.ts b/frontend/src/container/PlannedDowntime/__test__/testUtils.ts
index 085f56c497..d460e40598 100644
--- a/frontend/src/container/PlannedDowntime/__test__/testUtils.ts
+++ b/frontend/src/container/PlannedDowntime/__test__/testUtils.ts
@@ -11,7 +11,7 @@ export const buildSchedule = (
schedule: Partial<AlertmanagertypesScheduleDTO>,
): AlertmanagertypesScheduleDTO => ({
timezone: schedule?.timezone ?? '',
- startTime: schedule?.startTime,
+ startTime: schedule?.startTime ?? '',
endTime: schedule?.endTime,
recurrence: schedule?.recurrence,
});
diff --git a/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance.go b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance.go
index 328106ef0b..09abf48bb5 100644
--- a/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance.go
+++ b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance.go
@@ -2,6 +2,7 @@ package sqlalertmanagerstore
import (
"context"
+ "encoding/json"
"log/slog"
"time"
@@ -39,16 +40,20 @@ func (r *maintenance) ListPlannedMaintenance(ctx context.Context, orgID string)
return nil, err
}
- gettablePlannedMaintenance := make([]*alertmanagertypes.PlannedMaintenance, 0)
+ plannedMaintenances := make([]*alertmanagertypes.PlannedMaintenance, 0, len(gettableMaintenancesRules))
for _, gettableMaintenancesRule := range gettableMaintenancesRules {
- m := gettableMaintenancesRule.ToPlannedMaintenance()
- gettablePlannedMaintenance = append(gettablePlannedMaintenance, m)
- if m.HasScheduleRecurrenceBoundsMismatch() {
- r.logger.WarnContext(ctx, "planned_downtime_recurrence_schedule_mismatch", slog.String("maintenance_id", m.ID.StringValue()))
+ pm, err := gettableMaintenancesRule.ToPlannedMaintenance()
+ if err != nil {
+ // Don't return an error because we want to process all the valid records.
+ // Log and skip instead.
+ r.logger.WarnContext(ctx, "skipping planned maintenance", slog.String("maintenance_id", gettableMaintenancesRule.ID.StringValue()), errors.Attr(err))
+ continue
}
+
+ plannedMaintenances = append(plannedMaintenances, pm)
}
- return gettablePlannedMaintenance, nil
+ return plannedMaintenances, nil
}
func (r *maintenance) GetPlannedMaintenanceByID(ctx context.Context, id valuer.UUID) (*alertmanagertypes.PlannedMaintenance, error) {
@@ -64,7 +69,7 @@ func (r *maintenance) GetPlannedMaintenanceByID(ctx context.Context, id valuer.U
return nil, r.sqlstore.WrapNotFoundErrf(err, errors.CodeNotFound, "planned maintenance with ID: %s does not exist", id.StringValue())
}
- return storableMaintenanceRule.ToPlannedMaintenance(), nil
+ return storableMaintenanceRule.ToPlannedMaintenance()
}
func (r *maintenance) CreatePlannedMaintenance(ctx context.Context, maintenance *alertmanagertypes.PostablePlannedMaintenance) (*alertmanagertypes.PlannedMaintenance, error) {
@@ -73,6 +78,11 @@ func (r *maintenance) CreatePlannedMaintenance(ctx context.Context, maintenance
return nil, err
}
+ schedule, err := json.Marshal(maintenance.Schedule)
+ if err != nil {
+ return nil, err
+ }
+
storablePlannedMaintenance := alertmanagertypes.StorablePlannedMaintenance{
Identifiable: types.Identifiable{
ID: valuer.GenerateUUID(),
@@ -87,7 +97,7 @@ func (r *maintenance) CreatePlannedMaintenance(ctx context.Context, maintenance
},
Name: maintenance.Name,
Description: maintenance.Description,
- Schedule: maintenance.Schedule,
+ Schedule: string(schedule),
OrgID: claims.OrgID,
Scope: maintenance.Scope,
}
@@ -135,18 +145,21 @@ func (r *maintenance) CreatePlannedMaintenance(ctx context.Context, maintenance
return nil, err
}
- return &alertmanagertypes.PlannedMaintenance{
+ pm := &alertmanagertypes.PlannedMaintenance{
ID: storablePlannedMaintenance.ID,
Name: storablePlannedMaintenance.Name,
Description: storablePlannedMaintenance.Description,
- Schedule: storablePlannedMaintenance.Schedule,
RuleIDs: maintenance.AlertIds,
Scope: maintenance.Scope,
CreatedAt: storablePlannedMaintenance.CreatedAt,
CreatedBy: storablePlannedMaintenance.CreatedBy,
UpdatedAt: storablePlannedMaintenance.UpdatedAt,
UpdatedBy: storablePlannedMaintenance.UpdatedBy,
- }, nil
+ }
+ if err = json.Unmarshal([]byte(storablePlannedMaintenance.Schedule), &pm.Schedule); err != nil {
+ return nil, err
+ }
+ return pm, nil
}
func (r *maintenance) DeletePlannedMaintenance(ctx context.Context, id valuer.UUID) error {
@@ -174,6 +187,11 @@ func (r *maintenance) UpdatePlannedMaintenance(ctx context.Context, maintenance
return err
}
+ schedule, err := json.Marshal(maintenance.Schedule)
+ if err != nil {
+ return err
+ }
+
storablePlannedMaintenance := alertmanagertypes.StorablePlannedMaintenance{
Identifiable: types.Identifiable{
ID: id,
@@ -188,7 +206,7 @@ func (r *maintenance) UpdatePlannedMaintenance(ctx context.Context, maintenance
},
Name: maintenance.Name,
Description: maintenance.Description,
- Schedule: maintenance.Schedule,
+ Schedule: string(schedule),
OrgID: claims.OrgID,
Scope: maintenance.Scope,
}
diff --git a/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance_test.go b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance_test.go
new file mode 100644
index 0000000000..58fe314d84
--- /dev/null
+++ b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/maintenance_test.go
@@ -0,0 +1,94 @@
+package sqlalertmanagerstore
+
+import (
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/SigNoz/signoz/pkg/factory/factorytest"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/sqlstore/sqlitesqlstore"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+func newTestStore(t *testing.T) sqlstore.SQLStore {
+ t.Helper()
+ store, err := sqlitesqlstore.New(t.Context(), factorytest.NewSettings(), sqlstore.Config{
+ Provider: "sqlite",
+ Connection: sqlstore.ConnectionConfig{
+ MaxOpenConns: 1,
+ MaxConnLifetime: 0,
+ },
+ Sqlite: sqlstore.SqliteConfig{
+ Path: filepath.Join(t.TempDir(), "test.db"),
+ Mode: "wal",
+ BusyTimeout: 5 * time.Second,
+ TransactionMode: "deferred",
+ },
+ })
+ require.NoError(t, err)
+
+ _, err = store.BunDB().NewCreateTable().
+ Model((*alertmanagertypes.StorablePlannedMaintenance)(nil)).
+ IfNotExists().
+ Exec(t.Context())
+ require.NoError(t, err)
+
+ _, err = store.BunDB().NewCreateTable().
+ Model((*alertmanagertypes.StorablePlannedMaintenanceRule)(nil)).
+ IfNotExists().
+ Exec(t.Context())
+ require.NoError(t, err)
+
+ return store
+}
+
+// TestListPlannedMaintenanceSkipsInvalid asserts that a single corrupt record
+// (here, an unloadable timezone) is skipped rather than failing the whole list.
+func TestListPlannedMaintenanceSkipsInvalid(t *testing.T) {
+ store := newTestStore(t)
+ orgID := valuer.GenerateUUID().StringValue()
+ now := time.Now().UTC()
+
+ valid := &alertmanagertypes.StorablePlannedMaintenance{
+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},
+ TimeAuditable: types.TimeAuditable{CreatedAt: now, UpdatedAt: now},
+ Name: "valid",
+ Schedule: `{"timezone":"UTC","startTime":"2024-01-01T12:00:00Z","recurrence":{"duration":"2h","repeatType":"daily"}}`,
+ OrgID: orgID,
+ }
+ result, err := store.BunDB().NewInsert().Model(valid).Exec(t.Context())
+ require.NoError(t, err)
+ rowsAffected, err := result.RowsAffected()
+ require.NoError(t, err)
+ require.Equal(t, int64(1), rowsAffected)
+
+ // A schedule with "zero" startTime
+ invalid := &alertmanagertypes.StorablePlannedMaintenance{
+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},
+ TimeAuditable: types.TimeAuditable{
+ CreatedAt: now,
+ UpdatedAt: now,
+ },
+ Name: "invalid",
+ Schedule: `{"timezone":"UTC","recurrence":{"duration":"2h","repeatType":"daily"}}`,
+ OrgID: orgID,
+ }
+ result, err = store.BunDB().NewInsert().Model(invalid).Exec(t.Context())
+ require.NoError(t, err)
+ rowsAffected, err = result.RowsAffected()
+ require.NoError(t, err)
+ require.Equal(t, int64(1), rowsAffected)
+
+ maintenanceStore := NewMaintenanceStore(store, factorytest.NewSettings())
+
+ list, err := maintenanceStore.ListPlannedMaintenance(t.Context(), orgID)
+ require.NoError(t, err)
+ require.Len(t, list, 1)
+ assert.Equal(t, valid.ID, list[0].ID)
+}
diff --git a/pkg/alertmanager/config_test.go b/pkg/alertmanager/config_test.go
index 4ea9033c62..34435201dd 100644
--- a/pkg/alertmanager/config_test.go
+++ b/pkg/alertmanager/config_test.go
@@ -3,6 +3,8 @@ package alertmanager
import (
"context"
"net/url"
+ "os"
+ "strings"
"testing"
"time"
@@ -14,7 +16,23 @@ import (
"github.com/stretchr/testify/require"
)
+const prefix = "SIGNOZ_"
+
+// clearSignozEnv unsets all existing SIGNOZ_* env vars for the duration of the test.
+func clearSignozEnv(t *testing.T) {
+ t.Helper()
+ for _, kv := range os.Environ() {
+ if strings.HasPrefix(kv, prefix) {
+ key := strings.SplitN(kv, "=", 2)[0]
+ orig, _ := os.LookupEnv(key)
+ _ = os.Unsetenv(key)
+ t.Cleanup(func() { _ = os.Setenv(key, orig) })
+ }
+ }
+}
+
func TestNewWithEnvProvider(t *testing.T) {
+ clearSignozEnv(t)
t.Setenv("SIGNOZ_ALERTMANAGER_PROVIDER", "signoz")
t.Setenv("SIGNOZ_ALERTMANAGER_LEGACY_API__URL", "http://localhost:9093/api")
t.Setenv("SIGNOZ_ALERTMANAGER_SIGNOZ_ROUTE_REPEAT__INTERVAL", "5m")
diff --git a/pkg/config/envprovider/provider_test.go b/pkg/config/envprovider/provider_test.go
index 4906a3765c..bd01a244be 100644
--- a/pkg/config/envprovider/provider_test.go
+++ b/pkg/config/envprovider/provider_test.go
@@ -18,8 +18,8 @@ func clearSignozEnv(t *testing.T) {
if strings.HasPrefix(kv, prefix) {
key := strings.SplitN(kv, "=", 2)[0]
orig, _ := os.LookupEnv(key)
- os.Unsetenv(key)
- t.Cleanup(func() { os.Setenv(key, orig) })
+ _ = os.Unsetenv(key)
+ t.Cleanup(func() { _ = os.Setenv(key, orig) })
}
}
}
diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.go
index 08498bffc7..10932bb9ff 100644
--- a/pkg/signoz/provider.go
+++ b/pkg/signoz/provider.go
@@ -213,6 +213,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewCloudIntegrationRemoveCascadeDeleteFactory(sqlschema),
sqlmigration.NewAddUserDashboardPreferenceFactory(sqlstore, sqlschema),
sqlmigration.NewRecreateUserDashboardPreferenceFactory(sqlstore, sqlschema),
+ sqlmigration.NewMigrateRecurrenceBoundsFactory(sqlstore),
)
}
diff --git a/pkg/sqlmigration/027_update_rules.go b/pkg/sqlmigration/027_update_rules.go
index 55f253daee..43201a8e47 100644
--- a/pkg/sqlmigration/027_update_rules.go
+++ b/pkg/sqlmigration/027_update_rules.go
@@ -11,7 +11,6 @@ import (
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types"
- "github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/uptrace/bun"
"github.com/uptrace/bun/migrate"
@@ -57,15 +56,15 @@ type newRule struct {
type existingMaintenance struct {
bun.BaseModel `bun:"table:planned_maintenance"`
- ID int `bun:"id,pk,autoincrement"`
- Name string `bun:"name,type:text,notnull"`
- Description string `bun:"description,type:text"`
- AlertIDs *AlertIds `bun:"alert_ids,type:text"`
- Schedule *alertmanagertypes.Schedule `bun:"schedule,type:text,notnull"`
- CreatedAt time.Time `bun:"created_at,type:datetime,notnull"`
- CreatedBy string `bun:"created_by,type:text,notnull"`
- UpdatedAt time.Time `bun:"updated_at,type:datetime,notnull"`
- UpdatedBy string `bun:"updated_by,type:text,notnull"`
+ ID int `bun:"id,pk,autoincrement"`
+ Name string `bun:"name,type:text,notnull"`
+ Description string `bun:"description,type:text"`
+ AlertIDs *AlertIds `bun:"alert_ids,type:text"`
+ Schedule *schedule `bun:"schedule,type:text,notnull"`
+ CreatedAt time.Time `bun:"created_at,type:datetime,notnull"`
+ CreatedBy string `bun:"created_by,type:text,notnull"`
+ UpdatedAt time.Time `bun:"updated_at,type:datetime,notnull"`
+ UpdatedBy string `bun:"updated_by,type:text,notnull"`
}
type newMaintenance struct {
@@ -73,10 +72,10 @@ type newMaintenance struct {
types.Identifiable
types.TimeAuditable
types.UserAuditable
- Name string `bun:"name,type:text,notnull"`
- Description string `bun:"description,type:text"`
- Schedule *alertmanagertypes.Schedule `bun:"schedule,type:text,notnull"`
- OrgID string `bun:"org_id,type:text"`
+ Name string `bun:"name,type:text,notnull"`
+ Description string `bun:"description,type:text"`
+ Schedule *schedule `bun:"schedule,type:text,notnull"`
+ OrgID string `bun:"org_id,type:text"`
}
type storablePlannedMaintenanceRule struct {
@@ -92,6 +91,21 @@ type ruleHistory struct {
RuleUUID valuer.UUID `bun:"rule_uuid"`
}
+type schedule struct {
+ Timezone string `json:"timezone"`
+ StartTime time.Time `json:"startTime"`
+ EndTime time.Time `json:"endTime,omitzero"`
+ Recurrence *recurrence `json:"recurrence"`
+}
+
+type recurrence struct {
+ StartTime time.Time `json:"startTime"`
+ EndTime time.Time `json:"endTime,omitzero"`
+ Duration valuer.TextDuration `json:"duration"`
+ RepeatType string `json:"repeatType"`
+ RepeatOn []string `json:"repeatOn"`
+}
+
func NewUpdateRulesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
return factory.NewProviderFactory(factory.MustNewName("update_rules"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
return newUpdateRules(ctx, ps, c, sqlstore)
diff --git a/pkg/sqlmigration/094_migrate_recurrence_bounds.go b/pkg/sqlmigration/094_migrate_recurrence_bounds.go
new file mode 100644
index 0000000000..e83e5ca71f
--- /dev/null
+++ b/pkg/sqlmigration/094_migrate_recurrence_bounds.go
@@ -0,0 +1,128 @@
+package sqlmigration
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/migrate"
+)
+
+type migrateRecurrenceBounds struct {
+ sqlstore sqlstore.SQLStore
+ logger *slog.Logger
+}
+
+type plannedMaintenanceScheduleRow struct {
+ bun.BaseModel `bun:"table:planned_maintenance"`
+
+ ID string `bun:"id"`
+ Schedule string `bun:"schedule"`
+}
+
+func NewMigrateRecurrenceBoundsFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
+ return factory.NewProviderFactory(
+ factory.MustNewName("migrate_recurrence_bounds"),
+ func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
+ return &migrateRecurrenceBounds{sqlstore: sqlstore, logger: ps.Logger}, nil
+ },
+ )
+}
+
+func (migration *migrateRecurrenceBounds) Register(migrations *migrate.Migrations) error {
+ if err := migrations.Register(migration.Up, migration.Down); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Up moves the start/end bounds of a recurring planned maintenance from the
+// nested recurrence object up to the schedule level. Until now both the
+// schedule and its recurrence carried their own startTime/endTime, with the
+// recurrence values taking precedence when a recurrence was present. The
+// recurrence fields are being dropped, so the recurrence bounds (the source of
+// truth for recurring maintenances) are promoted to the schedule before the
+// struct loses those fields.
+//
+// We deliberately operate on the raw JSON instead of the Recurrence struct:
+// that struct loses its StartTime/EndTime fields in the same change set, so it
+// can no longer read the values this migration needs to move.
+func (migration *migrateRecurrenceBounds) Up(ctx context.Context, db *bun.DB) error {
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+
+ defer func() {
+ _ = tx.Rollback()
+ }()
+
+ rows := make([]*plannedMaintenanceScheduleRow, 0)
+ if err := tx.NewSelect().Model(&rows).Scan(ctx); err != nil {
+ return err
+ }
+
+ for _, row := range rows {
+ schedule := make(map[string]json.RawMessage)
+ if err := json.Unmarshal([]byte(row.Schedule), &schedule); err != nil {
+ // A single corrupt row must not abort the whole migration (which would block startup).
+ migration.logger.WarnContext(ctx, "skipping planned maintenance with unreadable schedule", slog.String("maintenance_id", row.ID), errors.Attr(err))
+ continue
+ }
+
+ recurrenceRaw, ok := schedule["recurrence"]
+ if !ok || string(recurrenceRaw) == "null" {
+ continue
+ }
+
+ recurrence := make(map[string]json.RawMessage)
+ if err := json.Unmarshal(recurrenceRaw, &recurrence); err != nil {
+ migration.logger.WarnContext(ctx, "skipping planned maintenance with unreadable recurrence", slog.String("maintenance_id", row.ID), errors.Attr(err))
+ continue
+ }
+
+ // Promote the recurrence bounds (source of truth) to the schedule
+ // level, then drop them from the recurrence.
+ if startTime, ok := recurrence["startTime"]; ok {
+ schedule["startTime"] = startTime
+ delete(recurrence, "startTime")
+ }
+ if endTime, ok := recurrence["endTime"]; ok && string(endTime) != "null" {
+ schedule["endTime"] = endTime
+ } else {
+ // The recurrence had no end time, so the schedule must not carry
+ // a stale one duplicated by the UI.
+ delete(schedule, "endTime")
+ }
+ delete(recurrence, "endTime")
+
+ newRecurrence, err := json.Marshal(recurrence)
+ if err != nil {
+ return err
+ }
+ schedule["recurrence"] = newRecurrence
+
+ newSchedule, err := json.Marshal(schedule)
+ if err != nil {
+ return err
+ }
+
+ if _, err := tx.NewUpdate().
+ Model((*plannedMaintenanceScheduleRow)(nil)).
+ Set("schedule = ?", string(newSchedule)).
+ Where("id = ?", row.ID).
+ Exec(ctx); err != nil {
+ return err
+ }
+ }
+
+ return tx.Commit()
+}
+
+func (migration *migrateRecurrenceBounds) Down(context.Context, *bun.DB) error {
+ return nil
+}
diff --git a/pkg/types/alertmanagertypes/maintenance.go b/pkg/types/alertmanagertypes/maintenance.go
index 8592417a3e..bebad257f9 100644
--- a/pkg/types/alertmanagertypes/maintenance.go
+++ b/pkg/types/alertmanagertypes/maintenance.go
@@ -3,6 +3,7 @@ package alertmanagertypes
import (
"context"
"encoding/json"
+ "slices"
"time"
"github.com/expr-lang/expr"
@@ -59,11 +60,11 @@ type StorablePlannedMaintenance struct {
types.Identifiable
types.TimeAuditable
types.UserAuditable
- Name string `bun:"name,type:text,notnull"`
- Description string `bun:"description,type:text"`
- Schedule *Schedule `bun:"schedule,type:text,notnull"`
- OrgID string `bun:"org_id,type:text"`
- Scope string `bun:"scope,type:text"`
+ Name string `bun:"name,type:text,notnull"`
+ Description string `bun:"description,type:text"`
+ Schedule string `bun:"schedule,type:text,notnull"`
+ OrgID string `bun:"org_id,type:text"`
+ Scope string `bun:"scope,type:text"`
}
type PlannedMaintenance struct {
@@ -99,18 +100,9 @@ func (p *PostablePlannedMaintenance) Validate() error {
if p.Schedule == nil {
return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "missing schedule in the payload")
}
- if p.Schedule.Timezone == "" {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "missing timezone in the payload")
- }
-
- if _, err := time.LoadLocation(p.Schedule.Timezone); err != nil {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "invalid timezone in the payload")
- }
- if !p.Schedule.StartTime.IsZero() && !p.Schedule.EndTime.IsZero() {
- if p.Schedule.StartTime.After(p.Schedule.EndTime) {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "start time cannot be after end time")
- }
+ if !p.Schedule.EndTime.IsZero() && p.Schedule.StartTime.After(p.Schedule.EndTime) {
+ return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "start time cannot be after end time")
}
if p.Schedule.Recurrence != nil {
@@ -120,9 +112,6 @@ func (p *PostablePlannedMaintenance) Validate() error {
if p.Schedule.Recurrence.Duration.IsZero() {
return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "missing duration in the payload")
}
- if p.Schedule.Recurrence.EndTime != nil && p.Schedule.Recurrence.EndTime.Before(p.Schedule.Recurrence.StartTime) {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "end time cannot be before start time")
- }
}
if p.Scope != "" {
if _, err := expr.Compile(p.Scope, expr.AllowUndefinedVariables(), expr.AsBool()); err != nil {
@@ -148,134 +137,85 @@ type PlannedMaintenanceWithRules struct {
Rules []*StorablePlannedMaintenanceRule `bun:"rel:has-many,join:id=planned_maintenance_id"`
}
-// HasScheduleRecurrenceBoundsMismatch reports whether a recurring maintenance
-// has different start/end bounds in Schedule and Schedule.Recurrence.
-//
-// This is used to detect if there are any entries with recurrence that don't
-// have the same timestamps stored at the schedule-level.
-// UI payloads duplicated those values in both places, but direct API users may
-// have stored bounds that are missing from, or different than, the schedule-level bounds.
-// We need to observe these before we can safely drop Recurrence.StartTime and
-// Recurrence.EndTime.
-func (m *PlannedMaintenance) HasScheduleRecurrenceBoundsMismatch() bool {
- recurrence := m.Schedule.Recurrence
- if recurrence == nil {
- return false
- }
-
- return !recurrence.StartTime.Equal(m.Schedule.StartTime) ||
- (recurrence.EndTime == nil && !m.Schedule.EndTime.IsZero()) ||
- (recurrence.EndTime != nil && !recurrence.EndTime.Equal(m.Schedule.EndTime))
+// AppliesTo reports whether this maintenance applies to the given rule.
+// An empty RuleIDs set means the maintenance applies to all rules.
+func (m *PlannedMaintenance) AppliesTo(ruleID string) bool {
+ return len(m.RuleIDs) == 0 || slices.Contains(m.RuleIDs, ruleID)
}
func (m *PlannedMaintenance) ShouldSkip(ruleID string, now time.Time, lset model.LabelSet) (bool, error) {
- // Check if the alert ID is in the maintenance window
- found := false
- if len(m.RuleIDs) > 0 {
- for _, alertID := range m.RuleIDs {
- if alertID == ruleID {
- found = true
- break
- }
- }
- }
- // If no alert ids, then skip all alerts
- if len(m.RuleIDs) == 0 {
- found = true
- }
-
- if !found {
- return false, nil
- }
-
- if !m.IsActive(now) {
+ if !m.AppliesTo(ruleID) || !m.IsActive(now) {
return false, nil
}
if m.Scope != "" {
- result, err := EvalScopeExpression(m.Scope, lset)
- if err != nil {
+ skip, err := EvalScopeExpression(m.Scope, lset)
+ if err != nil || !skip {
return false, err
}
- if !result {
- return false, nil
- }
}
return true, nil
}
// IsActive reports whether [now] falls inside the maintenance window's schedule.
func (m *PlannedMaintenance) IsActive(now time.Time) bool {
- // If alert is found, we check if it should be skipped based on the schedule
- loc, err := time.LoadLocation(m.Schedule.Timezone)
- if err != nil {
+ // Check if maintenance window has not started yet
+ if now.Before(m.Schedule.StartTime) {
return false
}
- startTime := m.Schedule.StartTime
- endTime := m.Schedule.EndTime
- recurrence := m.Schedule.Recurrence
-
- // fixed schedule — only when no recurrence is configured.
- // When recurrence is set, the recurring check below handles everything;
- // falling through here would cause the window to match the absolute
- // StartTime–EndTime range instead of the daily/weekly/monthly pattern.
- if recurrence == nil && !startTime.IsZero() && !endTime.IsZero() {
- if now.Equal(startTime) || now.Equal(endTime) ||
- (now.After(startTime) && now.Before(endTime)) {
- return true
- }
+ // Check if maintenance window has expired
+ if !m.Schedule.EndTime.IsZero() && now.After(m.Schedule.EndTime) {
+ return false
}
- // recurring schedule
- if recurrence != nil {
- // Make sure the recurrence has started
- if now.Before(recurrence.StartTime) {
- return false
- }
-
- // Check if recurrence has expired
- if recurrence.EndTime != nil {
- if !recurrence.EndTime.IsZero() && now.After(*recurrence.EndTime) {
- return false
- }
- }
+ // Fixed schedule
+ if m.Schedule.Recurrence == nil {
+ return true
+ }
- currentTime := now.In(loc)
- switch recurrence.RepeatType {
- case RepeatTypeDaily:
- return m.checkDaily(currentTime, recurrence, loc)
- case RepeatTypeWeekly:
- return m.checkWeekly(currentTime, recurrence, loc)
- case RepeatTypeMonthly:
- return m.checkMonthly(currentTime, recurrence, loc)
- }
+ loc, err := time.LoadLocation(m.Schedule.Timezone)
+ if err != nil {
+ return false
}
- return false
+ switch m.Schedule.Recurrence.RepeatType {
+ case RepeatTypeDaily:
+ return m.checkDaily(now, loc)
+ case RepeatTypeWeekly:
+ return m.checkWeekly(now, loc)
+ case RepeatTypeMonthly:
+ return m.checkMonthly(now, loc)
+ default:
+ return false
+ }
}
// checkDaily rebases the recurrence start to today (or yesterday if needed)
// and returns true if currentTime is within [candidate, candidate+Duration].
-func (m *PlannedMaintenance) checkDaily(currentTime time.Time, rec *Recurrence, loc *time.Location) bool {
+func (m *PlannedMaintenance) checkDaily(currentTime time.Time, loc *time.Location) bool {
+ currentTime = currentTime.In(loc)
candidate := time.Date(
currentTime.Year(), currentTime.Month(), currentTime.Day(),
- rec.StartTime.Hour(), rec.StartTime.Minute(), 0, 0,
+ m.Schedule.StartTime.Hour(), m.Schedule.StartTime.Minute(), 0, 0,
loc,
)
if candidate.After(currentTime) {
candidate = candidate.AddDate(0, 0, -1)
}
- return currentTime.Sub(candidate) <= rec.Duration.Duration()
+ return currentTime.Sub(candidate) <= m.Schedule.Recurrence.Duration.Duration()
}
// checkWeekly finds the most recent allowed occurrence by rebasing the recurrence’s
// time-of-day onto the allowed weekday. It does this for each allowed day and returns true
// if the current time falls within the candidate window.
-func (m *PlannedMaintenance) checkWeekly(currentTime time.Time, rec *Recurrence, loc *time.Location) bool {
+func (m *PlannedMaintenance) checkWeekly(currentTime time.Time, loc *time.Location) bool {
+ currentTime = currentTime.In(loc)
+ rec := m.Schedule.Recurrence
+
// If no days specified, treat as every day (like daily).
if len(rec.RepeatOn) == 0 {
- return m.checkDaily(currentTime, rec, loc)
+ return m.checkDaily(currentTime, loc)
}
for _, day := range rec.RepeatOn {
@@ -288,7 +228,7 @@ func (m *PlannedMaintenance) checkWeekly(currentTime time.Time, rec *Recurrence,
// Build a candidate occurrence by rebasing today's date to the allowed weekday.
candidate := time.Date(
currentTime.Year(), currentTime.Month(), currentTime.Day(),
- rec.StartTime.Hour(), rec.StartTime.Minute(), 0, 0,
+ m.Schedule.StartTime.Hour(), m.Schedule.StartTime.Minute(), 0, 0,
loc,
).AddDate(0, 0, delta)
// If the candidate is in the future, subtract 7 days.
@@ -304,8 +244,10 @@ func (m *PlannedMaintenance) checkWeekly(currentTime time.Time, rec *Recurrence,
// checkMonthly rebases the candidate occurrence using the recurrence's day-of-month.
// If the candidate for the current month is in the future, it uses the previous month.
-func (m *PlannedMaintenance) checkMonthly(currentTime time.Time, rec *Recurrence, loc *time.Location) bool {
- refDay := rec.StartTime.Day()
+func (m *PlannedMaintenance) checkMonthly(currentTime time.Time, loc *time.Location) bool {
+ currentTime = currentTime.In(loc)
+ startTime := m.Schedule.StartTime
+ refDay := startTime.Day()
year, month, _ := currentTime.Date()
lastDay := time.Date(year, month+1, 0, 0, 0, 0, 0, loc).Day()
day := refDay
@@ -313,7 +255,7 @@ func (m *PlannedMaintenance) checkMonthly(currentTime time.Time, rec *Recurrence
day = lastDay
}
candidate := time.Date(year, month, day,
- rec.StartTime.Hour(), rec.StartTime.Minute(), rec.StartTime.Second(), rec.StartTime.Nanosecond(),
+ startTime.Hour(), startTime.Minute(), startTime.Second(), startTime.Nanosecond(),
loc,
)
if candidate.After(currentTime) {
@@ -323,33 +265,30 @@ func (m *PlannedMaintenance) checkMonthly(currentTime time.Time, rec *Recurrence
lastDayPrev := time.Date(y, m+1, 0, 0, 0, 0, 0, loc).Day()
if refDay > lastDayPrev {
candidate = time.Date(y, m, lastDayPrev,
- rec.StartTime.Hour(), rec.StartTime.Minute(), rec.StartTime.Second(), rec.StartTime.Nanosecond(),
+ startTime.Hour(), startTime.Minute(), startTime.Second(), startTime.Nanosecond(),
loc,
)
} else {
candidate = time.Date(y, m, refDay,
- rec.StartTime.Hour(), rec.StartTime.Minute(), rec.StartTime.Second(), rec.StartTime.Nanosecond(),
+ startTime.Hour(), startTime.Minute(), startTime.Second(), startTime.Nanosecond(),
loc,
)
}
}
- return currentTime.Sub(candidate) <= rec.Duration.Duration()
+ return currentTime.Sub(candidate) <= m.Schedule.Recurrence.Duration.Duration()
}
func (m *PlannedMaintenance) IsUpcoming() bool {
- loc, err := time.LoadLocation(m.Schedule.Timezone)
- if err != nil {
- return false
- }
- now := time.Now().In(loc)
+ now := time.Now()
- if !m.Schedule.StartTime.IsZero() && !m.Schedule.EndTime.IsZero() {
- return now.Before(m.Schedule.StartTime)
- }
- if m.Schedule.Recurrence != nil {
- return now.Before(m.Schedule.Recurrence.StartTime)
+ if m.IsRecurring() {
+ // Note: this would return true even if the maintenance is active.
+ // This isn't an issue right now because the only usage happens after the `IsActive` check.
+ return m.Schedule.EndTime.IsZero() || now.Before(m.Schedule.EndTime)
}
- return false
+
+ // Fixed schedule
+ return now.Before(m.Schedule.StartTime)
}
func (m *PlannedMaintenance) IsRecurring() bool {
@@ -363,19 +302,8 @@ func (m *PlannedMaintenance) Validate() error {
if m.Schedule == nil {
return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "missing schedule in the payload")
}
- if m.Schedule.Timezone == "" {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "missing timezone in the payload")
- }
-
- _, err := time.LoadLocation(m.Schedule.Timezone)
- if err != nil {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "invalid timezone in the payload")
- }
-
- if !m.Schedule.StartTime.IsZero() && !m.Schedule.EndTime.IsZero() {
- if m.Schedule.StartTime.After(m.Schedule.EndTime) {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "start time cannot be after end time")
- }
+ if !m.Schedule.EndTime.IsZero() && m.Schedule.StartTime.After(m.Schedule.EndTime) {
+ return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "start time cannot be after end time")
}
if m.Schedule.Recurrence != nil {
@@ -385,28 +313,31 @@ func (m *PlannedMaintenance) Validate() error {
if m.Schedule.Recurrence.Duration.IsZero() {
return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "missing duration in the payload")
}
- if m.Schedule.Recurrence.EndTime != nil && m.Schedule.Recurrence.EndTime.Before(m.Schedule.Recurrence.StartTime) {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload, "end time cannot be before start time")
+ }
+ if m.Scope != "" {
+ if _, err := expr.Compile(m.Scope, expr.AllowUndefinedVariables(), expr.AsBool()); err != nil {
+ err := errors.Newf(
+ errors.TypeInvalidInput, ErrCodeInvalidPlannedMaintenancePayload,
+ "invalid scope: %s", err.Error(),
+ )
+ return err.WithUrl(scopeDocUrl)
}
}
return nil
}
func (m PlannedMaintenance) MarshalJSON() ([]byte, error) {
- now := time.Now().In(time.FixedZone(m.Schedule.Timezone, 0))
var status MaintenanceStatus
- if m.IsActive(now) {
+ if m.IsActive(time.Now()) {
status = MaintenanceStatusActive
} else if m.IsUpcoming() {
status = MaintenanceStatusUpcoming
} else {
status = MaintenanceStatusExpired
}
- var kind MaintenanceKind
- if !m.Schedule.StartTime.IsZero() && !m.Schedule.EndTime.IsZero() && m.Schedule.EndTime.After(m.Schedule.StartTime) {
- kind = MaintenanceKindFixed
- } else {
+ kind := MaintenanceKindFixed
+ if m.Schedule.Recurrence != nil {
kind = MaintenanceKindRecurring
}
@@ -439,26 +370,29 @@ func (m PlannedMaintenance) MarshalJSON() ([]byte, error) {
})
}
-func (m *PlannedMaintenanceWithRules) ToPlannedMaintenance() *PlannedMaintenance {
- ruleIDs := []string{}
- if m.Rules != nil {
- for _, storableMaintenanceRule := range m.Rules {
- ruleIDs = append(ruleIDs, storableMaintenanceRule.RuleID.StringValue())
- }
+func (m *PlannedMaintenanceWithRules) ToPlannedMaintenance() (*PlannedMaintenance, error) {
+ schedule := &Schedule{}
+ if err := json.Unmarshal([]byte(m.Schedule), &schedule); err != nil {
+ return nil, err
+ }
+
+ ruleIDs := make([]string, 0, len(m.Rules))
+ for _, storableMaintenanceRule := range m.Rules {
+ ruleIDs = append(ruleIDs, storableMaintenanceRule.RuleID.StringValue())
}
return &PlannedMaintenance{
ID: m.ID,
Name: m.Name,
Description: m.Description,
- Schedule: m.Schedule,
+ Schedule: schedule,
RuleIDs: ruleIDs,
Scope: m.Scope,
CreatedAt: m.CreatedAt,
UpdatedAt: m.UpdatedAt,
CreatedBy: m.CreatedBy,
UpdatedBy: m.UpdatedBy,
- }
+ }, nil
}
type ListPlannedMaintenanceParams struct {
diff --git a/pkg/types/alertmanagertypes/maintenance_test.go b/pkg/types/alertmanagertypes/maintenance_test.go
index 4940af7f78..b875fb351b 100644
--- a/pkg/types/alertmanagertypes/maintenance_test.go
+++ b/pkg/types/alertmanagertypes/maintenance_test.go
@@ -8,11 +8,6 @@ import (
"github.com/prometheus/common/model"
)
-// Helper function to create a time pointer.
-func timePtr(t time.Time) *time.Time {
- return &t
-}
-
func TestShouldSkipMaintenance(t *testing.T) {
cases := []struct {
name string
@@ -24,9 +19,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "only-on-saturday",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "Europe/London",
+ Timezone: "Europe/London",
+ StartTime: time.Date(2025, 3, 1, 0, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2025, 3, 1, 0, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("24h"),
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday, RepeatOnTuesday, RepeatOnWednesday, RepeatOnThursday, RepeatOnFriday, RepeatOnSunday},
@@ -41,10 +36,10 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "weekly-across-midnight-previous-day",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 22, 0, 0, 0, time.UTC), // Monday 22:00
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 22, 0, 0, 0, time.UTC), // Monday 22:00
- Duration: valuer.MustParseTextDuration("4h"), // Until Tuesday 02:00
+ Duration: valuer.MustParseTextDuration("4h"), // Until Tuesday 02:00
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday}, // Only Monday
},
@@ -58,10 +53,10 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "weekly-across-midnight-previous-day",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 22, 0, 0, 0, time.UTC), // Monday 22:00
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 22, 0, 0, 0, time.UTC), // Monday 22:00
- Duration: valuer.MustParseTextDuration("4h"), // Until Tuesday 02:00
+ Duration: valuer.MustParseTextDuration("4h"), // Until Tuesday 02:00
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday}, // Only Monday
},
@@ -75,10 +70,10 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "weekly-across-midnight-previous-day",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 22, 0, 0, 0, time.UTC), // Monday 22:00
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 22, 0, 0, 0, time.UTC), // Monday 22:00
- Duration: valuer.MustParseTextDuration("52h"), // Until Thursday 02:00
+ Duration: valuer.MustParseTextDuration("52h"), // Until Thursday 02:00
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday}, // Only Monday
},
@@ -92,10 +87,10 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "weekly-across-midnight-previous-day-not-in-repeaton",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 2, 22, 0, 0, 0, time.UTC), // Tuesday 22:00
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 2, 22, 0, 0, 0, time.UTC), // Tuesday 22:00
- Duration: valuer.MustParseTextDuration("4h"), // Until Wednesday 02:00
+ Duration: valuer.MustParseTextDuration("4h"), // Until Wednesday 02:00
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnTuesday}, // Only Tuesday
},
@@ -109,10 +104,10 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "daily-maintenance-across-midnight",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 23, 0, 0, 0, time.UTC), // 23:00
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 23, 0, 0, 0, time.UTC), // 23:00
- Duration: valuer.MustParseTextDuration("2h"), // Until 01:00 next day
+ Duration: valuer.MustParseTextDuration("2h"), // Until 01:00 next day
RepeatType: RepeatTypeDaily,
},
},
@@ -125,9 +120,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "at-start-time-boundary",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeDaily,
},
@@ -141,9 +136,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "at-end-time-boundary",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeDaily,
},
@@ -157,9 +152,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "monthly-multi-day-duration",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 28, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 28, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("72h"), // 3 days
RepeatType: RepeatTypeMonthly,
},
@@ -173,9 +168,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "weekly-multi-day-duration",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 28, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 28, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("72h"), // 3 days
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnSunday},
@@ -190,9 +185,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "monthly-crosses-to-next-month",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 30, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 30, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("48h"), // 2 days, crosses to Feb 1
RepeatType: RepeatTypeMonthly,
},
@@ -206,9 +201,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "timezone-offset-test",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "America/New_York", // UTC-5 or UTC-4 depending on DST
+ Timezone: "America/New_York", // UTC-5 or UTC-4 depending on DST
+ StartTime: time.Date(2024, 1, 1, 22, 0, 0, 0, time.FixedZone("America/New_York", -5*3600)),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 22, 0, 0, 0, time.FixedZone("America/New_York", -5*3600)),
Duration: valuer.MustParseTextDuration("4h"),
RepeatType: RepeatTypeDaily,
},
@@ -222,9 +217,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "daily-maintenance-time-outside-window",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeDaily,
},
@@ -238,10 +233,10 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "recurring-maintenance-with-past-end-date",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
+ EndTime: time.Date(2024, 1, 10, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
- EndTime: timePtr(time.Date(2024, 1, 10, 12, 0, 0, 0, time.UTC)),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeDaily,
},
@@ -255,10 +250,10 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "monthly-maintenance-spans-month-end",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 3, 31, 22, 0, 0, 0, time.UTC), // March 31, 22:00
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 3, 31, 22, 0, 0, 0, time.UTC), // March 31, 22:00
- Duration: valuer.MustParseTextDuration("6h"), // Until April 1, 04:00
+ Duration: valuer.MustParseTextDuration("6h"), // Until April 1, 04:00
RepeatType: RepeatTypeMonthly,
},
},
@@ -271,9 +266,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "weekly-empty-repeaton",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{}, // Empty - should apply to all days
@@ -288,9 +283,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "monthly-maintenance-february-fewer-days",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 31, 12, 0, 0, 0, time.UTC), // January 31st
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 31, 12, 0, 0, 0, time.UTC), // January 31st
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeMonthly,
},
@@ -303,9 +298,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "daily-maintenance-crosses-midnight",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 23, 30, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 23, 30, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("1h"), // Crosses to 00:30 next day
RepeatType: RepeatTypeDaily,
},
@@ -318,9 +313,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "monthly-maintenance-crosses-month-end",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 31, 12, 0, 0, 0, time.UTC), // January 31st
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 31, 12, 0, 0, 0, time.UTC), // January 31st
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeMonthly,
},
@@ -333,9 +328,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "monthly-maintenance-crosses-month-end-and-duration-is-2-days",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 30, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 30, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("48h"), // 2 days duration
RepeatType: RepeatTypeMonthly,
},
@@ -348,10 +343,10 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "weekly-maintenance-crosses-midnight",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 23, 0, 0, 0, time.UTC), // Monday 23:00
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 23, 0, 0, 0, time.UTC), // Monday 23:00
- Duration: valuer.MustParseTextDuration("2h"), // Until Tuesday 01:00
+ Duration: valuer.MustParseTextDuration("2h"), // Until Tuesday 01:00
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday}, // Only Monday
},
@@ -364,9 +359,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "monthly-maintenance-crosses-month-end-and-duration-is-2-days",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 31, 12, 0, 0, 0, time.UTC), // January 31st
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 31, 12, 0, 0, 0, time.UTC), // January 31st
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeMonthly,
},
@@ -379,9 +374,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "daily-maintenance-crosses-midnight",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 22, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 22, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("4h"), // Until 02:00 next day
RepeatType: RepeatTypeDaily,
},
@@ -394,9 +389,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "monthly-maintenance-crosses-month-end-and-duration-is-2-hours",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 31, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 31, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeMonthly,
},
@@ -445,9 +440,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "recurring maintenance, repeat sunday, saturday, weekly for 24 hours, in Us/Eastern timezone",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "US/Eastern",
+ Timezone: "US/Eastern",
+ StartTime: time.Date(2025, 3, 29, 20, 0, 0, 0, time.FixedZone("US/Eastern", -4*3600)),
Recurrence: &Recurrence{
- StartTime: time.Date(2025, 3, 29, 20, 0, 0, 0, time.FixedZone("US/Eastern", -4*3600)),
Duration: valuer.MustParseTextDuration("24h"),
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnSunday, RepeatOnSaturday},
@@ -458,57 +453,57 @@ func TestShouldSkipMaintenance(t *testing.T) {
skip: true,
},
{
- name: "recurring maintenance, repeat daily from 12:00 to 14:00",
+ name: "recurring maintenance, repeat daily from 12:00 to 14:00, ts < start",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeDaily,
},
},
},
- ts: time.Date(2024, 1, 1, 12, 10, 0, 0, time.UTC),
- skip: true,
+ ts: time.Date(2024, 1, 10, 11, 0, 0, 0, time.UTC),
+ skip: false,
},
{
- name: "recurring maintenance, repeat daily from 12:00 to 14:00",
+ name: "recurring maintenance, repeat daily from 12:00 to 14:00, start <= ts <= end",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeDaily,
},
},
},
- ts: time.Date(2024, 1, 1, 14, 0, 0, 0, time.UTC),
+ ts: time.Date(2024, 1, 10, 13, 0, 0, 0, time.UTC),
skip: true,
},
{
- name: "recurring maintenance, repeat daily from 12:00 to 14:00",
+ name: "recurring maintenance, repeat daily from 12:00 to 14:00, start > end",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeDaily,
},
},
},
- ts: time.Date(2024, 4, 1, 12, 10, 0, 0, time.UTC),
- skip: true,
+ ts: time.Date(2024, 1, 10, 15, 0, 0, 0, time.UTC),
+ skip: false,
},
{
name: "recurring maintenance, repeat weekly on monday from 12:00 to 14:00",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday},
@@ -522,9 +517,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "recurring maintenance, repeat weekly on monday from 12:00 to 14:00",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday},
@@ -538,9 +533,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "recurring maintenance, repeat weekly on monday from 12:00 to 14:00",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday},
@@ -554,9 +549,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "recurring maintenance, repeat weekly on monday from 12:00 to 14:00",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday},
@@ -570,9 +565,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "recurring maintenance, repeat weekly on monday from 12:00 to 14:00",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 1, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeWeekly,
RepeatOn: []RepeatOn{RepeatOnMonday},
@@ -586,9 +581,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "recurring maintenance, repeat monthly on 4th from 12:00 to 14:00",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 4, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 4, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeMonthly,
},
@@ -601,9 +596,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "recurring maintenance, repeat monthly on 4th from 12:00 to 14:00",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 4, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 4, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeMonthly,
},
@@ -616,9 +611,9 @@ func TestShouldSkipMaintenance(t *testing.T) {
name: "recurring maintenance, repeat monthly on 4th from 12:00 to 14:00",
maintenance: &PlannedMaintenance{
Schedule: &Schedule{
- Timezone: "UTC",
+ Timezone: "UTC",
+ StartTime: time.Date(2024, 4, 4, 12, 0, 0, 0, time.UTC),
Recurrence: &Recurrence{
- StartTime: time.Date(2024, 4, 4, 12, 0, 0, 0, time.UTC),
Duration: valuer.MustParseTextDuration("2h"),
RepeatType: RepeatTypeMonthly,
},
@@ -627,45 +622,6 @@ func TestShouldSkipMaintenance(t *testing.T) {
ts: time.Date(2024, 5, 4, 12, 10, 0, 0, time.UTC),
skip: true,
},
- // The recurrence should govern, when set. Not the fixed range.
- {
- name: "recurring-daily-with-fixed-times-outside-daily-window",
- maintenance: &PlannedMaintenance{
- Schedule: &Schedule{
- Timezone: "UTC",
- // These fixed fields should be ignored when Recurrence is set.
- StartTime: time.Date(2026, 4, 1, 14, 0, 0, 0, time.UTC),
- EndTime: time.Date(2026, 4, 30, 18, 0, 0, 0, time.UTC),
- Recurrence: &Recurrence{
- StartTime: time.Date(2026, 4, 1, 14, 0, 0, 0, time.UTC), // daily at 14:00
- Duration: valuer.MustParseTextDuration("2h"), // until 16:00
- RepeatType: RepeatTypeDaily,
- },
- },
- },
- // 2026-04-15 11:00 is inside the fixed range but outside the daily 14:00-16:00 window.
- ts: time.Date(2026, 4, 15, 11, 0, 0, 0, time.UTC),
- skip: false,
- },
- {
- name: "recurring-daily-with-fixed-times-inside-daily-window",
- maintenance: &PlannedMaintenance{
- Schedule: &Schedule{
- Timezone: "UTC",
- StartTime: time.Date(2026, 4, 1, 14, 0, 0, 0, time.UTC),
- EndTime: time.Date(2026, 4, 30, 18, 0, 0, 0, time.UTC),
- Recurrence: &Recurrence{
- StartTime: time.Date(2026, 4, 1, 14, 0, 0, 0, time.UTC),
- EndTime: timePtr(time.Date(2026, 4, 30, 18, 0, 0, 0, time.UTC)),
- Duration: valuer.MustParseTextDuration("2h"),
- RepeatType: RepeatTypeDaily,
- },
- },
- },
- // 15:00 is inside the daily 14:00-16:00 window. Should skip.
- ts: time.Date(2026, 4, 15, 15, 0, 0, 0, time.UTC),
- skip: true,
- },
}
for idx, c := range cases {
@@ -679,13 +635,211 @@ func TestShouldSkipMaintenance(t *testing.T) {
}
}
+func TestIsActiveFixedSchedule(t *testing.T) {
+ start := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
+ end := time.Date(2024, 1, 10, 12, 0, 0, 0, time.UTC)
+
+ cases := []struct {
+ name string
+ startTime time.Time
+ endTime time.Time
+ now time.Time
+ active bool
+ }{
+ {
+ name: "no end, t < start",
+ startTime: start,
+ now: start.Add(-time.Hour),
+ active: false,
+ },
+ {
+ name: "no end, start == t",
+ startTime: start,
+ now: start,
+ active: true,
+ },
+ {
+ // A fixed schedule with no end time stays active indefinitely.
+ name: "no end, start << t",
+ startTime: start,
+ now: start.AddDate(10, 0, 0),
+ active: true,
+ },
+ {
+ name: "with end, start < t < end",
+ startTime: start,
+ endTime: end,
+ now: start.Add(24 * time.Hour),
+ active: true,
+ },
+ {
+ name: "with end, t == end",
+ startTime: start,
+ endTime: end,
+ now: end,
+ active: true,
+ },
+ {
+ name: "with end, end < t",
+ startTime: start,
+ endTime: end,
+ now: end.Add(time.Hour),
+ active: false,
+ },
+ }
+
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ m := &PlannedMaintenance{
+ Schedule: &Schedule{
+ Timezone: "UTC",
+ StartTime: c.startTime,
+ EndTime: c.endTime,
+ },
+ }
+ if got := m.IsActive(c.now); got != c.active {
+ t.Errorf("IsActive() = %v, want %v", got, c.active)
+ }
+ })
+ }
+}
+
+func TestIsActiveRecurringSchedule(t *testing.T) {
+ // Daily window 12:00-14:00, starting 2024-01-01 (a Monday).
+ start := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
+
+ daily := &Recurrence{
+ Duration: valuer.MustParseTextDuration("2h"),
+ RepeatType: RepeatTypeDaily,
+ }
+
+ cases := []struct {
+ name string
+ startTime time.Time
+ endTime time.Time
+ recurrence *Recurrence
+ now time.Time
+ active bool
+ }{
+ {
+ // The recurrence has not begun yet, even though the time-of-day matches.
+ name: "daily: t < recurrence start",
+ startTime: start,
+ recurrence: daily,
+ now: time.Date(2023, 12, 31, 13, 0, 0, 0, time.UTC),
+ active: false,
+ },
+ {
+ name: "daily: no end, within window",
+ startTime: start,
+ recurrence: daily,
+ now: time.Date(2024, 6, 15, 13, 0, 0, 0, time.UTC),
+ active: true,
+ },
+ {
+ name: "daily: no end, outside window",
+ startTime: start,
+ recurrence: daily,
+ now: time.Date(2024, 6, 15, 15, 0, 0, 0, time.UTC),
+ active: false,
+ },
+ {
+ name: "daily: at window start boundary",
+ startTime: start,
+ recurrence: daily,
+ now: time.Date(2024, 6, 15, 12, 0, 0, 0, time.UTC),
+ active: true,
+ },
+ {
+ name: "daily: at window end boundary",
+ startTime: start,
+ recurrence: daily,
+ now: time.Date(2024, 6, 15, 14, 0, 0, 0, time.UTC),
+ active: true,
+ },
+ {
+ // Past the recurrence end, the time-of-day match no longer applies.
+ name: "daily: t > recurrence end",
+ startTime: start,
+ endTime: time.Date(2024, 1, 10, 12, 0, 0, 0, time.UTC),
+ recurrence: daily,
+ now: time.Date(2024, 1, 15, 13, 0, 0, 0, time.UTC),
+ active: false,
+ },
+ {
+ name: "daily: before recurrence end, within window",
+ startTime: start,
+ endTime: time.Date(2024, 1, 10, 23, 0, 0, 0, time.UTC),
+ recurrence: daily,
+ now: time.Date(2024, 1, 10, 13, 0, 0, 0, time.UTC),
+ active: true,
+ },
+ {
+ name: "weekly: on allowed day, within window",
+ startTime: start, // Monday
+ recurrence: &Recurrence{
+ Duration: valuer.MustParseTextDuration("2h"),
+ RepeatType: RepeatTypeWeekly,
+ RepeatOn: []RepeatOn{RepeatOnMonday},
+ },
+ now: time.Date(2024, 4, 15, 13, 0, 0, 0, time.UTC), // a Monday
+ active: true,
+ },
+ {
+ name: "weekly: on non-allowed day",
+ startTime: start,
+ recurrence: &Recurrence{
+ Duration: valuer.MustParseTextDuration("2h"),
+ RepeatType: RepeatTypeWeekly,
+ RepeatOn: []RepeatOn{RepeatOnMonday},
+ },
+ now: time.Date(2024, 4, 16, 13, 0, 0, 0, time.UTC), // a Tuesday
+ active: false,
+ },
+ {
+ name: "monthly: on day-of-month, within window",
+ startTime: time.Date(2024, 1, 4, 12, 0, 0, 0, time.UTC),
+ recurrence: &Recurrence{
+ Duration: valuer.MustParseTextDuration("2h"),
+ RepeatType: RepeatTypeMonthly,
+ },
+ now: time.Date(2024, 5, 4, 13, 0, 0, 0, time.UTC),
+ active: true,
+ },
+ {
+ name: "monthly: on different day-of-month",
+ startTime: time.Date(2024, 1, 4, 12, 0, 0, 0, time.UTC),
+ recurrence: &Recurrence{
+ Duration: valuer.MustParseTextDuration("2h"),
+ RepeatType: RepeatTypeMonthly,
+ },
+ now: time.Date(2024, 5, 5, 13, 0, 0, 0, time.UTC),
+ active: false,
+ },
+ }
+
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ m := &PlannedMaintenance{
+ Schedule: &Schedule{
+ Timezone: "UTC",
+ StartTime: c.startTime,
+ EndTime: c.endTime,
+ Recurrence: c.recurrence,
+ },
+ }
+ if got := m.IsActive(c.now); got != c.active {
+ t.Errorf("IsActive() = %v, want %v", got, c.active)
+ }
+ })
+ }
+}
+
func TestShouldSkip_Scope(t *testing.T) {
- activeSchedule := func() *Schedule {
- return &Schedule{
- Timezone: "UTC",
- StartTime: time.Now().UTC().Add(-time.Hour),
- EndTime: time.Now().UTC().Add(time.Hour),
- }
+ activeSchedule := &Schedule{
+ Timezone: "UTC",
+ StartTime: time.Now().UTC().Add(-time.Hour),
+ EndTime: time.Now().UTC().Add(time.Hour),
}
now := time.Now().UTC()
@@ -699,7 +853,7 @@ func TestShouldSkip_Scope(t *testing.T) {
}{
{
name: "empty scope - no label filtering applied",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule()},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "production"},
@@ -707,7 +861,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "scope matches labels",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env = "production"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "production"},
@@ -715,7 +869,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "scope does not match labels",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env = "production"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "staging"},
@@ -723,7 +877,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "AND expression - both conditions match",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" AND service = "api"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env = "production" AND service = "api"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "production", "service": "api"},
@@ -731,7 +885,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "AND expression - one condition does not match",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" AND service = "api"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env = "production" AND service = "api"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "production", "service": "worker"},
@@ -739,7 +893,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "OR expression - first alternative matches",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" OR env = "staging"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env = "production" OR env = "staging"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "production"},
@@ -747,7 +901,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "OR expression - second alternative matches",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" OR env = "staging"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env = "production" OR env = "staging"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "staging"},
@@ -755,7 +909,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "OR expression - neither alternative matches",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production" OR env = "staging"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env = "production" OR env = "staging"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "development"},
@@ -763,7 +917,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "scope references label absent from lset",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env = "production"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env = "production"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"service": "api"},
@@ -771,7 +925,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "in expression - value is in list",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env in ["production", "staging"]`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env in ["production", "staging"]`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "staging"},
@@ -779,7 +933,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "in expression - value not in list",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), Scope: `env in ["production", "staging"]`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, Scope: `env in ["production", "staging"]`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "development"},
@@ -787,7 +941,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "ruleID in list and scope matches - should skip",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), RuleIDs: []string{"rule-1", "rule-2"}, Scope: `env = "production"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, RuleIDs: []string{"rule-1", "rule-2"}, Scope: `env = "production"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "production"},
@@ -795,7 +949,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "ruleID not in list and scope matches - ruleID gate prevents skip",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), RuleIDs: []string{"rule-2"}, Scope: `env = "production"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, RuleIDs: []string{"rule-2"}, Scope: `env = "production"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "production"},
@@ -803,7 +957,7 @@ func TestShouldSkip_Scope(t *testing.T) {
},
{
name: "ruleID in list but scope does not match - should not skip",
- maintenance: &PlannedMaintenance{Schedule: activeSchedule(), RuleIDs: []string{"rule-1"}, Scope: `env = "production"`},
+ maintenance: &PlannedMaintenance{Schedule: activeSchedule, RuleIDs: []string{"rule-1"}, Scope: `env = "production"`},
ruleID: "rule-1",
ts: now,
lset: model.LabelSet{"env": "staging"},
diff --git a/pkg/types/alertmanagertypes/recurrence.go b/pkg/types/alertmanagertypes/recurrence.go
index 3ef5461299..2f2900410d 100644
--- a/pkg/types/alertmanagertypes/recurrence.go
+++ b/pkg/types/alertmanagertypes/recurrence.go
@@ -66,9 +66,9 @@ var RepeatOnAllMap = map[RepeatOn]time.Weekday{
RepeatOnSaturday: time.Saturday,
}
+// Recurrence describes the repeat pattern of a planned maintenance.
+// The window bounds (start/end) live on the enclosing Schedule.
type Recurrence struct {
- StartTime time.Time `json:"startTime" required:"true"`
- EndTime *time.Time `json:"endTime,omitempty"`
Duration valuer.TextDuration `json:"duration" required:"true"`
RepeatType RepeatType `json:"repeatType" required:"true"`
RepeatOn []RepeatOn `json:"repeatOn"`
diff --git a/pkg/types/alertmanagertypes/schedule.go b/pkg/types/alertmanagertypes/schedule.go
index bec275d2cc..0224aae27d 100644
--- a/pkg/types/alertmanagertypes/schedule.go
+++ b/pkg/types/alertmanagertypes/schedule.go
@@ -11,7 +11,7 @@ import (
type Schedule struct {
Timezone string `json:"timezone" required:"true"`
- StartTime time.Time `json:"startTime,omitempty"`
+ StartTime time.Time `json:"startTime" required:"true"`
EndTime time.Time `json:"endTime,omitzero"`
Recurrence *Recurrence `json:"recurrence"`
}
@@ -39,29 +39,12 @@ func (s Schedule) MarshalJSON() ([]byte, error) {
return nil, err
}
- var startTime, endTime time.Time
- if !s.StartTime.IsZero() {
- startTime = time.Date(s.StartTime.Year(), s.StartTime.Month(), s.StartTime.Day(), s.StartTime.Hour(), s.StartTime.Minute(), s.StartTime.Second(), s.StartTime.Nanosecond(), loc)
- }
+ // Marshal times in the selected timezone.
+ // This ensures that recurring events are handled correctly when DST is involved.
+ startTime := s.StartTime.In(loc)
+ var endTime time.Time
if !s.EndTime.IsZero() {
- endTime = time.Date(s.EndTime.Year(), s.EndTime.Month(), s.EndTime.Day(), s.EndTime.Hour(), s.EndTime.Minute(), s.EndTime.Second(), s.EndTime.Nanosecond(), loc)
- }
-
- var recurrence *Recurrence
- if s.Recurrence != nil {
- recStartTime := time.Date(s.Recurrence.StartTime.Year(), s.Recurrence.StartTime.Month(), s.Recurrence.StartTime.Day(), s.Recurrence.StartTime.Hour(), s.Recurrence.StartTime.Minute(), s.Recurrence.StartTime.Second(), s.Recurrence.StartTime.Nanosecond(), loc)
- var recEndTime *time.Time
- if s.Recurrence.EndTime != nil {
- end := time.Date(s.Recurrence.EndTime.Year(), s.Recurrence.EndTime.Month(), s.Recurrence.EndTime.Day(), s.Recurrence.EndTime.Hour(), s.Recurrence.EndTime.Minute(), s.Recurrence.EndTime.Second(), s.Recurrence.EndTime.Nanosecond(), loc)
- recEndTime = &end
- }
- recurrence = &Recurrence{
- StartTime: recStartTime,
- EndTime: recEndTime,
- Duration: s.Recurrence.Duration,
- RepeatType: s.Recurrence.RepeatType,
- RepeatOn: s.Recurrence.RepeatOn,
- }
+ endTime = s.EndTime.In(loc)
}
return json.Marshal(&struct {
@@ -73,7 +56,7 @@ func (s Schedule) MarshalJSON() ([]byte, error) {
Timezone: s.Timezone,
StartTime: startTime,
EndTime: endTime,
- Recurrence: recurrence,
+ Recurrence: s.Recurrence,
})
}
@@ -88,55 +71,35 @@ func (s *Schedule) UnmarshalJSON(data []byte) error {
return err
}
+ if aux.Timezone == "" {
+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "missing timezone")
+ }
+
loc, err := time.LoadLocation(aux.Timezone)
if err != nil {
- return err
+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, `invalid timezone "%s"`, aux.Timezone)
}
- var startTime time.Time
- if aux.StartTime != "" {
- startTime, err = time.Parse(time.RFC3339, aux.StartTime)
- if err != nil {
- return err
- }
- s.StartTime = time.Date(startTime.Year(), startTime.Month(), startTime.Day(), startTime.Hour(), startTime.Minute(), startTime.Second(), startTime.Nanosecond(), loc)
+ startTime, err := time.Parse(time.RFC3339, aux.StartTime)
+ if err != nil {
+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, `invalid start time "%s"`, aux.StartTime)
}
+ startTime = startTime.In(loc)
var endTime time.Time
if aux.EndTime != "" {
endTime, err = time.Parse(time.RFC3339, aux.EndTime)
if err != nil {
- return err
+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, `invalid end time "%s"`, aux.EndTime)
+ }
+ if !endTime.IsZero() {
+ endTime = endTime.In(loc)
}
- // TODO(jatinderjit): if endTime.IsZero() then we should not set the endTime
- s.EndTime = time.Date(endTime.Year(), endTime.Month(), endTime.Day(), endTime.Hour(), endTime.Minute(), endTime.Second(), endTime.Nanosecond(), loc)
}
s.Timezone = aux.Timezone
-
- if aux.Recurrence != nil {
- recStartTime, err := time.Parse(time.RFC3339, aux.Recurrence.StartTime.Format(time.RFC3339))
- if err != nil {
- return err
- }
-
- var recEndTime *time.Time
- if aux.Recurrence.EndTime != nil {
- end, err := time.Parse(time.RFC3339, aux.Recurrence.EndTime.Format(time.RFC3339))
- if err != nil {
- return err
- }
- endConverted := time.Date(end.Year(), end.Month(), end.Day(), end.Hour(), end.Minute(), end.Second(), end.Nanosecond(), loc)
- recEndTime = &endConverted
- }
-
- s.Recurrence = &Recurrence{
- StartTime: time.Date(recStartTime.Year(), recStartTime.Month(), recStartTime.Day(), recStartTime.Hour(), recStartTime.Minute(), recStartTime.Second(), recStartTime.Nanosecond(), loc),
- EndTime: recEndTime,
- Duration: aux.Recurrence.Duration,
- RepeatType: aux.Recurrence.RepeatType,
- RepeatOn: aux.Recurrence.RepeatOn,
- }
- }
+ s.StartTime = startTime
+ s.EndTime = endTime
+ s.Recurrence = aux.Recurrence
return nil
}