Compare commits

..

7 Commits

Author SHA1 Message Date
Jatinderjit Singh
829ecd01a0 refactor(rules): source external URL via alertmanager.Config() instead of plumbing through main
Address PR feedback (therealpandey): expose a Config() accessor on the
alertmanager.Alertmanager interface and consume the external URL from it
inside signozruler.NewFactory. This drops the *url.URL parameter that
was previously threaded through cmd/community/server.go,
cmd/enterprise/server.go, and pkg/signoz/signoz.go.

Also switch BaseRule.GeneratorURL to *url.URL.JoinPath + Query so the
URL is composed correctly when the external URL carries a base path
(e.g. https://signoz.example.com/signoz) and ruleId is properly
query-encoded, as suggested in review.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 20:49:54 +05:30
Srikanth Chekuri
93e92be231 Merge branch 'main' into host-url 2026-05-26 18:04:55 +05:30
Jatinderjit Singh
5011246bc9 Merge branch 'main' into host-url 2026-05-25 23:14:40 +05:30
Jatinderjit Singh
f88af61a7c chore: use alert overview url for generator url 2026-05-25 23:01:47 +05:30
Jatinderjit Singh
6935748fd3 refactor: simplify ExternalURLHost 2026-05-25 19:11:52 +05:30
Jatinderjit Singh
16fc710518 feat(rules)!: drop frontend source URL fallback for related logs/traces and generator URL
Always derive the host portion of the rule generator URL and the
related_logs / related_traces annotations from SIGNOZ_ALERTMANAGER_SIGNOZ_EXTERNAL__URL.
Self-hosted deployments that have not set the env var will see the
default (http://localhost:8080) in alert notifications, which makes the
need to configure it surface clearly. Revert this commit to restore the
prior fallback behavior.

Refs SigNoz/engineering-pod#5055

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 18:07:14 +05:30
Jatinderjit Singh
745d3bc772 feat(rules): use alertmanager external URL for related logs/traces and generator URL
Plumbs SIGNOZ_ALERTMANAGER_SIGNOZ_EXTERNAL__URL through the rule manager so
the host portion of related_logs / related_traces come from configured
external URL instead of the frontend window.location captured at
rule-creation time. Frontend-supplied source URL is retained
as a fallback when the env var has not been set so existing self-hosted
deployments keep working.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 18:06:07 +05:30
12 changed files with 202 additions and 176 deletions

View File

@@ -39,6 +39,7 @@ func PrepareTaskFunc(opts baserules.PrepareTaskOptions) (baserules.Task, error)
baserules.WithQueryParser(opts.ManagerOpts.QueryParser),
baserules.WithMetadataStore(opts.ManagerOpts.MetadataStore),
baserules.WithRuleStateHistoryModule(opts.ManagerOpts.RuleStateHistoryModule),
baserules.WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {
@@ -63,6 +64,7 @@ func PrepareTaskFunc(opts baserules.PrepareTaskOptions) (baserules.Task, error)
baserules.WithQueryParser(opts.ManagerOpts.QueryParser),
baserules.WithMetadataStore(opts.ManagerOpts.MetadataStore),
baserules.WithRuleStateHistoryModule(opts.ManagerOpts.RuleStateHistoryModule),
baserules.WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {
@@ -87,6 +89,7 @@ func PrepareTaskFunc(opts baserules.PrepareTaskOptions) (baserules.Task, error)
baserules.WithQueryParser(opts.ManagerOpts.QueryParser),
baserules.WithMetadataStore(opts.ManagerOpts.MetadataStore),
baserules.WithRuleStateHistoryModule(opts.ManagerOpts.RuleStateHistoryModule),
baserules.WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {
return task, err
@@ -146,6 +149,7 @@ func TestNotification(opts baserules.PrepareTestRuleOptions) (int, error) {
baserules.WithSQLStore(opts.SQLStore),
baserules.WithQueryParser(opts.ManagerOpts.QueryParser),
baserules.WithMetadataStore(opts.ManagerOpts.MetadataStore),
baserules.WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {
@@ -167,6 +171,7 @@ func TestNotification(opts baserules.PrepareTestRuleOptions) (int, error) {
baserules.WithSQLStore(opts.SQLStore),
baserules.WithQueryParser(opts.ManagerOpts.QueryParser),
baserules.WithMetadataStore(opts.ManagerOpts.MetadataStore),
baserules.WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {
@@ -186,6 +191,7 @@ func TestNotification(opts baserules.PrepareTestRuleOptions) (int, error) {
baserules.WithSQLStore(opts.SQLStore),
baserules.WithQueryParser(opts.ManagerOpts.QueryParser),
baserules.WithMetadataStore(opts.ManagerOpts.MetadataStore),
baserules.WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {
slog.Error("failed to prepare a new anomaly rule for test", "name", alertname, errors.Attr(err))

View File

@@ -48,6 +48,11 @@ type Alertmanager interface {
// DeleteChannelByID deletes a channel for the organization.
DeleteChannelByID(context.Context, string, valuer.UUID) error
// Config returns the alertmanager provider configuration. It exposes
// global settings (e.g. the external URL) to consumers like the rule
// manager so they do not need the value to be wired through main.
Config() Config
// SetConfig sets the config for the organization.
SetConfig(context.Context, *alertmanagertypes.Config) error

View File

@@ -8,6 +8,7 @@ import (
"context"
"net/http"
"github.com/SigNoz/signoz/pkg/alertmanager"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/prometheus/alertmanager/config"
@@ -109,6 +110,50 @@ func (_c *MockAlertmanager_Collect_Call) RunAndReturn(run func(context1 context.
return _c
}
// Config provides a mock function for the type MockAlertmanager
func (_mock *MockAlertmanager) Config() alertmanager.Config {
ret := _mock.Called()
if len(ret) == 0 {
panic("no return value specified for Config")
}
var r0 alertmanager.Config
if returnFunc, ok := ret.Get(0).(func() alertmanager.Config); ok {
r0 = returnFunc()
} else {
r0 = ret.Get(0).(alertmanager.Config)
}
return r0
}
// MockAlertmanager_Config_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Config'
type MockAlertmanager_Config_Call struct {
*mock.Call
}
// Config is a helper method to define mock.On call
func (_e *MockAlertmanager_Expecter) Config() *MockAlertmanager_Config_Call {
return &MockAlertmanager_Config_Call{Call: _e.mock.On("Config")}
}
func (_c *MockAlertmanager_Config_Call) Run(run func()) *MockAlertmanager_Config_Call {
_c.Call.Run(func(args mock.Arguments) {
run()
})
return _c
}
func (_c *MockAlertmanager_Config_Call) Return(config alertmanager.Config) *MockAlertmanager_Config_Call {
_c.Call.Return(config)
return _c
}
func (_c *MockAlertmanager_Config_Call) RunAndReturn(run func() alertmanager.Config) *MockAlertmanager_Config_Call {
_c.Call.Return(run)
return _c
}
// CreateChannel provides a mock function for the type MockAlertmanager
func (_mock *MockAlertmanager) CreateChannel(context1 context.Context, s string, v alertmanagertypes.Receiver) (*alertmanagertypes.Channel, error) {
ret := _mock.Called(context1, s, v)

View File

@@ -235,6 +235,10 @@ func (provider *provider) CreateChannel(ctx context.Context, orgID string, recei
return channel, nil
}
func (provider *provider) Config() alertmanager.Config {
return provider.config
}
func (provider *provider) SetConfig(ctx context.Context, config *alertmanagertypes.Config) error {
return provider.configStore.Set(ctx, config)
}

View File

@@ -219,25 +219,19 @@ func (m *module) GetStats(ctx context.Context, orgID valuer.UUID, req *metricsex
return nil, err
}
var (
metricStats []metricsexplorertypes.Stat
total uint64
err error
)
hasFilter := req.Filter != nil && strings.TrimSpace(req.Filter.Expression) != ""
if hasFilter {
var filterWhereClause *sqlbuilder.WhereClause
filterWhereClause, err = m.buildFilterClause(ctx, req.Filter, req.Start, req.End)
if err != nil {
return nil, err
}
metricStats, total, err = m.fetchMetricsStatsWithSamples(ctx, req, filterWhereClause, false, req.OrderBy)
} else {
metricStats, total, err = m.fetchMetricsStatsWithSamplesFastPath(ctx, req, false, req.OrderBy)
filterWhereClause, err := m.buildFilterClause(ctx, req.Filter, req.Start, req.End)
if err != nil {
return nil, err
}
// Single query to get stats with samples, timeseries counts in required sorting order
metricStats, total, err := m.fetchMetricsStatsWithSamples(
ctx,
req,
filterWhereClause,
false,
req.OrderBy,
)
if err != nil {
return nil, err
}
@@ -1091,109 +1085,6 @@ func (m *module) fetchMetricsStatsWithSamples(
return metricStats, total, nil
}
func (m *module) fetchMetricsStatsWithSamplesFastPath(
ctx context.Context,
req *metricsexplorertypes.StatsRequest,
normalized bool,
orderBy *qbtypes.OrderBy,
) ([]metricsexplorertypes.Stat, uint64, error) {
ctx = m.withMetricsExplorerContext(ctx, "fetchMetricsStatsWithSamplesFastPath")
start, end, distributedTsTable, localTsTable := telemetrymetrics.WhichTSTableToUse(uint64(req.Start), uint64(req.End), nil)
samplesTable := telemetrymetrics.WhichSamplesTableToUse(uint64(req.Start), uint64(req.End), metrictypes.UnspecifiedType, metrictypes.TimeAggregationUnspecified, nil)
countExp := telemetrymetrics.CountExpressionForSamplesTable(samplesTable)
// Timeseries counts per metric
tsSB := sqlbuilder.NewSelectBuilder()
tsSB.Select(
"metric_name",
"uniq(fingerprint) AS timeseries",
)
tsSB.From(fmt.Sprintf("%s.%s", telemetrymetrics.DBName, distributedTsTable))
tsSB.Where(tsSB.Between("unix_milli", start, end))
tsSB.Where("NOT startsWith(metric_name, 'signoz')")
tsSB.Where(tsSB.E("__normalized", normalized))
tsSB.GroupBy("metric_name")
// Distinct metric_names from local TS table — narrows samples scan on its leading sort key
metricNamesSB := sqlbuilder.NewSelectBuilder()
metricNamesSB.Select("DISTINCT metric_name")
metricNamesSB.From(fmt.Sprintf("%s.%s", telemetrymetrics.DBName, localTsTable))
metricNamesSB.Where(metricNamesSB.Between("unix_milli", start, end))
metricNamesSB.Where("NOT startsWith(metric_name, 'signoz')")
metricNamesSB.Where(metricNamesSB.E("__normalized", normalized))
// Samples counts per metric
samplesSB := sqlbuilder.NewSelectBuilder()
samplesSB.Select(
"metric_name",
fmt.Sprintf("%s AS samples", countExp),
)
samplesSB.From(fmt.Sprintf("%s.%s", telemetrymetrics.DBName, samplesTable))
samplesSB.Where(samplesSB.Between("unix_milli", req.Start, req.End))
samplesSB.Where("NOT startsWith(metric_name, 'signoz')")
samplesSB.Where(fmt.Sprintf("metric_name IN (%s)", samplesSB.Var(metricNamesSB)))
samplesSB.GroupBy("metric_name")
cteBuilder := sqlbuilder.With(
sqlbuilder.CTEQuery("__time_series_counts").As(tsSB),
sqlbuilder.CTEQuery("__sample_counts").As(samplesSB),
)
finalSB := cteBuilder.Select(
"COALESCE(ts.metric_name, s.metric_name) AS metric_name",
"COALESCE(ts.timeseries, 0) AS timeseries",
"COALESCE(s.samples, 0) AS samples",
"COUNT(*) OVER() AS total",
)
finalSB.From("__time_series_counts ts")
finalSB.JoinWithOption(sqlbuilder.FullOuterJoin, "__sample_counts s", "ts.metric_name = s.metric_name")
finalSB.Where("(COALESCE(ts.timeseries, 0) > 0 OR COALESCE(s.samples, 0) > 0)")
orderByColumn, orderDirection, err := getStatsOrderByColumn(orderBy)
if err != nil {
return nil, 0, err
}
finalSB.OrderBy(
fmt.Sprintf("%s %s", orderByColumn, strings.ToUpper(orderDirection)),
"metric_name ASC",
)
finalSB.Limit(req.Limit)
finalSB.Offset(req.Offset)
query, args := finalSB.BuildWithFlavor(sqlbuilder.ClickHouse)
valueCtx := ctxtypes.SetClickhouseMaxThreads(ctx, m.config.TelemetryStore.Threads)
db := m.telemetryStore.ClickhouseDB()
rows, err := db.Query(valueCtx, query, args...)
if err != nil {
return nil, 0, errors.WrapInternalf(err, errors.CodeInternal, "failed to execute metrics stats with samples fastpath query")
}
defer rows.Close()
metricStats := make([]metricsexplorertypes.Stat, 0)
var total uint64
for rows.Next() {
var (
metricStat metricsexplorertypes.Stat
rowTotal uint64
)
if err := rows.Scan(&metricStat.MetricName, &metricStat.TimeSeries, &metricStat.Samples, &rowTotal); err != nil {
return nil, 0, errors.WrapInternalf(err, errors.CodeInternal, "failed to scan metrics stats row")
}
metricStats = append(metricStats, metricStat)
total = rowTotal
}
if err := rows.Err(); err != nil {
return nil, 0, errors.WrapInternalf(err, errors.CodeInternal, "error iterating metrics stats rows")
}
return metricStats, total, nil
}
func (m *module) computeTimeseriesTreemap(ctx context.Context, req *metricsexplorertypes.TreemapRequest, filterWhereClause *sqlbuilder.WhereClause) ([]metricsexplorertypes.TreemapEntry, error) {
ctx = m.withMetricsExplorerContext(ctx, "computeTimeseriesTreemap")

View File

@@ -4,6 +4,8 @@ import (
"context"
"fmt"
"log/slog"
"net/url"
"strings"
"sync"
"time"
@@ -23,7 +25,7 @@ type BaseRule struct {
id string
name string
orgID valuer.UUID
source string
externalURL *url.URL
handledRestart bool
// Type of the rule
@@ -138,6 +140,16 @@ func WithRuleStateHistoryModule(module rulestatehistory.Module) RuleOption {
}
}
// WithExternalURL injects the alertmanager external URL. It is sourced from
// SIGNOZ_ALERTMANAGER_SIGNOZ_EXTERNAL__URL via [alertmanager.Alertmanager.Config]
// and used as the base for rule-related URLs (generator URL and related
// logs/traces links) in alert notifications.
func WithExternalURL(externalURL *url.URL) RuleOption {
return func(r *BaseRule) {
r.externalURL = externalURL
}
}
func NewBaseRule(id string, orgID valuer.UUID, p *ruletypes.PostableRule, opts ...RuleOption) (*BaseRule, error) {
threshold, err := p.RuleCondition.Thresholds.GetRuleThreshold()
if err != nil {
@@ -152,7 +164,6 @@ func NewBaseRule(id string, orgID valuer.UUID, p *ruletypes.PostableRule, opts .
id: id,
orgID: orgID,
name: p.AlertName,
source: p.Source,
typ: p.AlertType,
ruleCondition: p.RuleCondition,
evalWindow: p.EvalWindow,
@@ -241,7 +252,24 @@ func (r *BaseRule) Annotations() ruletypes.Labels { return r.annotations }
func (r *BaseRule) PreferredChannels() []string { return r.preferredChannels }
func (r *BaseRule) GeneratorURL() string {
return ruletypes.PrepareRuleGeneratorURL(r.ID(), r.source)
if r.externalURL == nil {
return ""
}
u := r.externalURL.JoinPath("alerts", "overview")
q := u.Query()
q.Set("ruleId", r.ID())
u.RawQuery = q.Encode()
return u.String()
}
// ExternalURLHost returns the configured alertmanager external URL as a string
// (trailing slash trimmed). It is used as the host portion of rule-related URLs
// (e.g. related logs/traces links) in alert notifications.
func (r *BaseRule) ExternalURLHost() string {
if r.externalURL == nil {
return ""
}
return strings.TrimRight(r.externalURL.String(), "/")
}
func (r *BaseRule) SelectedQuery(ctx context.Context) string {

View File

@@ -3,6 +3,7 @@ package rules
import (
"context"
"fmt"
"net/url"
"testing"
"time"
@@ -723,6 +724,88 @@ func TestBaseRule_FilterNewSeries(t *testing.T) {
}
}
func TestBaseRule_ExternalURLHost(t *testing.T) {
mustParse := func(raw string) *url.URL {
u, err := url.Parse(raw)
require.NoError(t, err)
return u
}
tests := []struct {
name string
externalURL *url.URL
want string
}{
{name: "nil URL returns empty", externalURL: nil, want: ""},
{name: "default value returned as-is", externalURL: mustParse("http://localhost:8080"), want: "http://localhost:8080"},
{name: "configured https host", externalURL: mustParse("https://signoz.example.com"), want: "https://signoz.example.com"},
{name: "configured host with port", externalURL: mustParse("http://signoz.internal:3301"), want: "http://signoz.internal:3301"},
{name: "trailing slash is trimmed", externalURL: mustParse("https://signoz.example.com/"), want: "https://signoz.example.com"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
p := createPostableRule(&ruletypes.AlertCompositeQuery{})
r, err := NewBaseRule("some-id", valuer.GenerateUUID(), &p, WithExternalURL(tc.externalURL))
if err != nil {
t.Errorf("unexpected error: %v", err)
}
require.Equal(t, tc.want, r.ExternalURLHost())
})
}
}
func TestBaseRule_GeneratorURL(t *testing.T) {
mustParse := func(raw string) *url.URL {
u, err := url.Parse(raw)
require.NoError(t, err)
return u
}
tests := []struct {
name string
ruleID string
externalURL *url.URL
want string
}{
{
name: "nil URL returns empty",
ruleID: "abc",
externalURL: nil,
want: "",
},
{
name: "configured external URL",
ruleID: "abc",
externalURL: mustParse("https://signoz.example.com"),
want: "https://signoz.example.com/alerts/overview?ruleId=abc",
},
{
name: "default external URL is used as-is",
ruleID: "abc",
externalURL: mustParse("http://localhost:8080"),
want: "http://localhost:8080/alerts/overview?ruleId=abc",
},
{
name: "external URL with base path is preserved",
ruleID: "abc",
externalURL: mustParse("https://signoz.example.com/signoz"),
want: "https://signoz.example.com/signoz/alerts/overview?ruleId=abc",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
p := createPostableRule(&ruletypes.AlertCompositeQuery{})
r, err := NewBaseRule(tc.ruleID, valuer.GenerateUUID(), &p, WithExternalURL(tc.externalURL))
if err != nil {
t.Errorf("unexpected error: %v", err)
}
require.Equal(t, tc.want, r.GeneratorURL())
})
}
}
// labelsKey creates a deterministic string key from a labels map
// This is used to group series by their unique label combinations
func labelsKey(lbls []*qbtypes.Label) string {

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net/url"
"sort"
"strings"
"sync"
@@ -80,6 +81,11 @@ type ManagerOptions struct {
EvalDelay valuer.TextDuration
// ExternalURL is the alertmanager external URL.
// Rules use it as the host for generator URLs and related logs/traces
// links in alert notifications.
ExternalURL *url.URL
RuleStateHistoryModule rulestatehistory.Module
PrepareTaskFunc func(opts PrepareTaskOptions) (Task, error)
@@ -155,6 +161,7 @@ func defaultPrepareTaskFunc(opts PrepareTaskOptions) (Task, error) {
WithQueryParser(opts.ManagerOpts.QueryParser),
WithMetadataStore(opts.ManagerOpts.MetadataStore),
WithRuleStateHistoryModule(opts.ManagerOpts.RuleStateHistoryModule),
WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {
return task, err
@@ -178,6 +185,7 @@ func defaultPrepareTaskFunc(opts PrepareTaskOptions) (Task, error) {
WithQueryParser(opts.ManagerOpts.QueryParser),
WithMetadataStore(opts.ManagerOpts.MetadataStore),
WithRuleStateHistoryModule(opts.ManagerOpts.RuleStateHistoryModule),
WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {
return task, err

View File

@@ -54,6 +54,7 @@ func defaultTestNotification(opts PrepareTestRuleOptions) (int, error) {
WithSQLStore(opts.SQLStore),
WithQueryParser(opts.ManagerOpts.QueryParser),
WithMetadataStore(opts.ManagerOpts.MetadataStore),
WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {
@@ -75,6 +76,7 @@ func defaultTestNotification(opts PrepareTestRuleOptions) (int, error) {
WithSQLStore(opts.SQLStore),
WithQueryParser(opts.ManagerOpts.QueryParser),
WithMetadataStore(opts.ManagerOpts.MetadataStore),
WithExternalURL(opts.ManagerOpts.ExternalURL),
)
if err != nil {

View File

@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net/url"
"reflect"
"time"
@@ -55,17 +54,6 @@ func NewThresholdRule(
}, nil
}
func (r *ThresholdRule) hostFromSource() string {
parsedURL, err := url.Parse(r.source)
if err != nil {
return ""
}
if parsedURL.Port() != "" {
return fmt.Sprintf("%s://%s:%s", parsedURL.Scheme, parsedURL.Hostname(), parsedURL.Port())
}
return fmt.Sprintf("%s://%s", parsedURL.Scheme, parsedURL.Hostname())
}
func (r *ThresholdRule) Type() ruletypes.RuleType {
return ruletypes.RuleTypeThreshold
}
@@ -350,15 +338,15 @@ func (r *ThresholdRule) Eval(ctx context.Context, ts time.Time) (int, error) {
switch r.typ {
case ruletypes.AlertTypeTraces:
link := r.prepareLinksToTraces(ctx, ts, smpl.Metric)
if link != "" && r.hostFromSource() != "" {
r.logger.InfoContext(ctx, "adding traces link to annotations", slog.String("annotation.link", fmt.Sprintf("%s/traces-explorer?%s", r.hostFromSource(), link)))
annotations = append(annotations, ruletypes.Label{Name: ruletypes.AnnotationRelatedTraces, Value: fmt.Sprintf("%s/traces-explorer?%s", r.hostFromSource(), link)})
if link != "" && r.ExternalURLHost() != "" {
r.logger.InfoContext(ctx, "adding traces link to annotations", slog.String("annotation.link", fmt.Sprintf("%s/traces-explorer?%s", r.ExternalURLHost(), link)))
annotations = append(annotations, ruletypes.Label{Name: ruletypes.AnnotationRelatedTraces, Value: fmt.Sprintf("%s/traces-explorer?%s", r.ExternalURLHost(), link)})
}
case ruletypes.AlertTypeLogs:
link := r.prepareLinksToLogs(ctx, ts, smpl.Metric)
if link != "" && r.hostFromSource() != "" {
r.logger.InfoContext(ctx, "adding logs link to annotations", slog.String("annotation.link", fmt.Sprintf("%s/logs/logs-explorer?%s", r.hostFromSource(), link)))
annotations = append(annotations, ruletypes.Label{Name: ruletypes.AnnotationRelatedLogs, Value: fmt.Sprintf("%s/logs/logs-explorer?%s", r.hostFromSource(), link)})
if link != "" && r.ExternalURLHost() != "" {
r.logger.InfoContext(ctx, "adding logs link to annotations", slog.String("annotation.link", fmt.Sprintf("%s/logs/logs-explorer?%s", r.ExternalURLHost(), link)))
annotations = append(annotations, ruletypes.Label{Name: ruletypes.AnnotationRelatedLogs, Value: fmt.Sprintf("%s/logs/logs-explorer?%s", r.ExternalURLHost(), link)})
}
}

View File

@@ -57,6 +57,7 @@ func NewFactory(
Logger: providerSettings.Logger,
Cache: cache,
EvalDelay: valuer.MustParseTextDuration(config.EvalDelay.String()),
ExternalURL: alertmanager.Config().Signoz.ExternalURL,
PrepareTaskFunc: prepareTaskFunc,
PrepareTestRuleFunc: prepareTestRuleFunc,
Alertmanager: alertmanager,

View File

@@ -2,10 +2,7 @@ package ruletypes
import (
"encoding/json"
"fmt"
"net/url"
"sort"
"strings"
"time"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
@@ -191,35 +188,3 @@ func (rc *RuleCondition) String() string {
return string(data)
}
// PrepareRuleGeneratorURL creates an appropriate url for the rule. The URL is
// sent in Slack messages as well as to other systems and allows backtracking
// to the rule definition from the third party systems.
func PrepareRuleGeneratorURL(ruleID string, source string) string {
if source == "" {
return source
}
// check if source is a valid url
parsedSource, err := url.Parse(source)
if err != nil {
return ""
}
// since we capture window.location when a new rule is created
// we end up with rulesource host:port/alerts/new. in this case
// we want to replace new with rule id parameter
hasNew := strings.LastIndex(source, "new")
if hasNew > -1 {
ruleURL := fmt.Sprintf("%sedit?ruleId=%s", source[0:hasNew], ruleID)
return ruleURL
}
// The source contains the encoded query, start and end time
// and other parameters. We don't want to include them in the generator URL
// mainly to keep the URL short and lower the alert body contents
// The generator URL with /alerts/edit?ruleId= is enough
if parsedSource.Port() != "" {
return fmt.Sprintf("%s://%s:%s/alerts/edit?ruleId=%s", parsedSource.Scheme, parsedSource.Hostname(), parsedSource.Port(), ruleID)
}
return fmt.Sprintf("%s://%s/alerts/edit?ruleId=%s", parsedSource.Scheme, parsedSource.Hostname(), ruleID)
}