Repository navigation
feat(Jira Integration): use grouplabels to calculate hash - #4677
holger-waschke wants to merge 1 commit into
Conversation
36a4f47 to
fbd25c2
Compare
I'm not sure this is true when you use |
Good point — but that shouldn’t be an issue, since the JQL search is always scoped to a single Jira project when looking for existing issues.
If two routes with different label matchers target the same Jira project and produce the same hash, that means they share the same group labels — so reusing the existing issue is the expected and desired behavior. |
The hash is derived from the GroupKey I understand? What happens to the Jira issue when there are two groups two the same GroupKey, but different alerts? Won't they overwrite each other on the same issue? That's why the RouteKey is important iirc. |
Just to clarify — Alertmanager still uses the groupKey to deliver alerts to its integrations. Once the Jira integration receives the alert, it only uses the hash to search for existing issues. |
Sorry I'm getting very confused. In this PR, you replaced the GroupKey with GroupLabels? But GroupLabels are not globally unique, so I believe with this change you will have hash collisions. |
there are two different layers here. one is the global alertmanager dispatch pipeline to it´s integrations. this is unchanged. this still uses the GroupKey to create the aggrGroup (route matchers + grouping labels). second layer is the jira integration itself. here i changed the groupkey to grouplabels for calculating its hash. but it´s only being used to search for existingissues over the jira api to reuse existing issues for deduplication. (and this api search is scoped to the configured jira project in the route config anyway). this means there are no updates on existing issues other than the configured jira project in the route config itself right now. imho the hash shouldnt differ just because they arrived using different routes. if the group labels are the same is logical the same issue. |
Yep agree.
Here I think is the potential issue. Suppose you have the following configuration: route:
- matchers:
- severity=warning
continue: true
receiver: jira
group_by:
- service
- matchers:
- team=ops
continue: true
receiver: jira
group_by:
- serviceYou can have different aggregation groups with the same Group 1 Group 2 However because they have the same |
At first glance, it might seem like they should map to different issues, but this behavior is actually intentional. Deduplication between alerts and Jira issues is a desired feature. You don’t want a new Jira issue every time the repeat_interval triggers; instead, you want related alerts to update or reopen the same Jira issue. That’s why the choice of group_by labels is critical. In real-world configurations, you’ll almost always have multiple grouping labels to ensure alerts are grouped meaningfully. Taking your example: When an alert fires through the first route, it generates a Jira issue with a summary like: [FIRING:1] High CPU Usage production myhost01.com The issue hash is derived from the group_by labels. This is the desired and logical behavior, since both alerts refer to the same underlying problem. Also note: each Jira receiver is tied to one Jira project and one issue type, which helps maintain consistency across alert routes. But maybe it´s a good idea to enhance the documentation by this points. |
Agree!
This where I am concerned. Alertmanager doesn't work like that and doesn't force that assumption onto users. It doesn't assume that two different alert groups, from two different routes, are the same problem, which is why all Alertmanager integrations respect GroupKey as the logical separator between notifications. I don't think this change can be the default because 1.) now Jira does something different from every other integration and 2.) it becomes inconsistent when used together with another integration in the same receiver. I would much prefer allowing templating of the Jira issue labels so users can opt-in to this behavior if they want it? |
got you. can you give a bit more details how your desired solution would look like? |
|
There is something I didn't understand about the original issue:
Can you help me understand what makes this true? As far as I can see there is no information in this GroupKey that identifies a Jira project, so what makes it unique to the project? |
My point here is when using groupkey for calculate the hash you´ll end up with two different hashes for the same alert in two different jira projects. given an example So in our use case: One main Jira Project with 24/7 issue handling. This is where ALL issues are being created no matter what. Before this PR: in both Jira projects the issue will be created but the hash differs. You can still build our own JQL to filter for identical issues but you dont have the possibility to use the hash to search project independent for identical issues. After this PR: Still two separately issues in both projects will be created but they share the common hash as a Jira tag. In a future PR this could be tweaked even more for configuring which jira projects should be used for deduplication. |
|
Ah OK I think I am following. In this example there are two distinct routes creating distinct issues in two different jira projects, and because there are two distinct routes, any aggregation groups created from these routes have distinct GroupKeys.
So from Alertmanager's PoV, this is very much intentional as these are two completely distinct routes with distinct matchers. This is how Alertmanager is supposed to work as notifications are delivered based on the route and the resulting aggregation group (i.e. It sounds to me like allowing an optional custom template that replaces the |
This comment was marked as spam.
This comment was marked as spam.
Yes, my point is do you really force this logic down to each individual integration? Would this make sense? Because on the dispatch logic how AM sends its individual alert to it´s integration is untouched, see this earlier comment
The hash I changed is only being used within Jira Integration for generating the JQL to identify existing issues Implementing this with a custom template will make things more complicated for end users at the end. I´m not quite sure this is the way too go. Deduplication Jira issues on the their logical alert grouping would make most sense for most user IMHO. |
Yes as a default behavior. |
It still will be the default behavior for most integrations. For those who have good reasons to do so may opt to choose the shared function HashGroupLabels For my POV this gives the integrations more flexibility without leaving standards behind. If it´s not possible I can have a look at the templated solution. |
|
So as I said before, I don't think it's reasonable to have a default behavior where two different aggregation groups from two different matchers re-use the same Jira issue. It's both an unexpected and a breaking change and no other Jira users have demanded it. There is also no way for users to use the old behaviour in this PR either right? For all of those reasons I think it has to be an opt-in behavior. |
61b6e48 to
e3729d8
Compare
reworked it as a opt in feature. |
|
@grobinson-grafana you think this change is beneficial enough for other users too? |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe Jira receiver adds an optional ChangesJira hash identifier
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant Alertmanager
participant JiraNotify
participant JiraAPI
Alertmanager->>JiraNotify: Send alert group
JiraNotify->>JiraNotify: Render HashIdentifier from group labels
JiraNotify->>JiraAPI: Search existing issue using jiraHash
JiraNotify->>JiraAPI: Create issue with jiraHash
Possibly related PRs
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
config/notifiers.go (1)
983-983: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winValidate
hash_identifieras a template at configuration load time.
HashIdentifieris a template string.UnmarshalYAMLvalidatesProject,IssueType, andAPIType, but it does not parseHashIdentifier. An invalid template is then detected only when a notification is sent, and every notification fails. The OpsGenie responder validation in this same file already parses templates at load time.Parse
HashIdentifierhere to fail fast.♻️ Proposed validation for `hash_identifier`
if c.APIType != "auto" && c.APIType != "cloud" && c.APIType != "datacenter" { return errors.New("unknown api_type on jira_config, must be auto, cloud or datacenter") } + if c.HashIdentifier != "" { + if _, err := template.New("").Parse(c.HashIdentifier); err != nil { + return fmt.Errorf("hash_identifier is not a valid template in jira_config: %w", err) + } + } return nilAlso applies to: 988-1007
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@config/notifiers.go` at line 983, Update the notifier configuration’s UnmarshalYAML validation to parse HashIdentifier as a template alongside Project, IssueType, and APIType, using the existing template-validation pattern in this file. Return the parsing error during configuration loading so invalid hash_identifier values fail fast before notifications are sent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@config/notifiers.go`:
- Around line 704-720: Update the responder validation loop around c.Responders
to iterate by index and persist the lowercased Type on the corresponding slice
element. Keep template-valued types unchanged and preserve the existing
validation and error behavior.
- Around line 374-391: Update PagerdutyConfig.Details and its initialization in
UnmarshalYAML to use the same shared map type expected by notify/pagerduty.New,
namely map[string]any. Preserve the existing nil-to-empty-map behavior and YAML
unmarshalling validation while removing the conflicting map[string]string
definition.
- Around line 577-587: Update the credential requirement check in the
incident.io validation method to also reject configurations where HTTPConfig is
nil and both AlertSourceToken and AlertSourceTokenFile are empty. Evaluate the
missing-credential condition independently of HTTPConfig presence, while
preserving the existing authorization and mutual-exclusion checks.
In `@notify/jira/jira_test.go`:
- Around line 494-535: The test fixture’s Jira configuration and expected issue
fields use incompatible types. Update the fixture around the Jira test case to
use the local JiraConfig type, represent Summary and Description with the local
JiraFieldConfig shape, and assign issue.Fields.Summary and Description using the
expected pointer field types while preserving their current values.
---
Nitpick comments:
In `@config/notifiers.go`:
- Line 983: Update the notifier configuration’s UnmarshalYAML validation to
parse HashIdentifier as a template alongside Project, IssueType, and APIType,
using the existing template-validation pattern in this file. Return the parsing
error during configuration loading so invalid hash_identifier values fail fast
before notifications are sent.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: fdc5885b-e9b8-4746-8fef-ee853efb710c
📒 Files selected for processing (4)
config/notifiers.godocs/configuration.mdnotify/jira/jira.gonotify/jira/jira_test.go
| func (c *PagerdutyConfig) UnmarshalYAML(unmarshal func(any) error) error { | ||
| *c = DefaultPagerdutyConfig | ||
| type plain PagerdutyConfig | ||
| if err := unmarshal((*plain)(c)); err != nil { | ||
| return err | ||
| } | ||
| if c.RoutingKey == "" && c.ServiceKey == "" && c.RoutingKeyFile == "" && c.ServiceKeyFile == "" { | ||
| return errors.New("missing service or routing key in PagerDuty config") | ||
| } | ||
| if len(c.RoutingKey) > 0 && len(c.RoutingKeyFile) > 0 { | ||
| return errors.New("at most one of routing_key & routing_key_file must be configured") | ||
| } | ||
| if len(c.ServiceKey) > 0 && len(c.ServiceKeyFile) > 0 { | ||
| return errors.New("at most one of service_key & service_key_file must be configured") | ||
| } | ||
| if c.Details == nil { | ||
| c.Details = make(map[string]string) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Locate all PagerdutyConfig and JiraConfig declarations and their usages.
ast-grep run --pattern 'type PagerdutyConfig struct { $$$ }' --lang go .
ast-grep run --pattern 'type JiraConfig struct { $$$ }' --lang go .
rg -nP --type=go -C2 '\b(pagerduty|jira)\.(Pagerduty|Jira)Config\b'
rg -nP --type=go -C2 '\bconfig\.(Pagerduty|Jira)Config\b'Repository: prometheus/alertmanager
Length of output: 8864
🏁 Script executed:
#!/bin/bash
set -e
echo "config package imports/usages of Pagerduty/Jira types:"
rg -n --type=go -C2 '(config\.)?(Pagerduty|Jira)Config|\bPagerduty|Jira' config/notifiers.go config/config.go notify/config.go notify/pagerduty/config.go notify/jira/config.go 2>/dev/null | sed -n '1,240p'
echo
echo "all PagerdutyConfig usages:"
rg -n --type=go -C2 'PagerdutyConfig' .
echo
echo "all JiraConfig usages:"
rg -n --type=go -C2 'JiraConfig' .
echo
echo "Relevant config/config.go section:"
sed -n '1,260p' config/config.go
echo
echo "Relevant config/notifiers.go Pagerduty/Jira sections:"
sed -n '300,410p' config/notifiers.go
sed -n '940,1025p' config/notifiers.go
echo
echo "Relevant notify config structs:"
sed -n '1,85p' notify/pagerduty/config.go
sed -n '1,85p' notify/jira/config.goRepository: prometheus/alertmanager
Length of output: 50379
Align PagerdutyConfig.Details with the receiver config type.
config/config.go loads pagerduty_configs as []*pagerduty.PagerdutyConfig, and config/receiver/receiver.go passes those configs to notify/pagerduty.New. That config type has Details map[string]any, while this file declares Details map[string]string; keep one shared definition to avoid accepting invalid details or dropping the current unmarshal validation.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@config/notifiers.go` around lines 374 - 391, Update PagerdutyConfig.Details
and its initialization in UnmarshalYAML to use the same shared map type expected
by notify/pagerduty.New, namely map[string]any. Preserve the existing
nil-to-empty-map behavior and YAML unmarshalling validation while removing the
conflicting map[string]string definition.
| if c.AlertSourceToken != "" && c.AlertSourceTokenFile != "" { | ||
| return errors.New("at most one of alert_source_token & alert_source_token_file must be configured") | ||
| } | ||
| if c.HTTPConfig != nil && c.HTTPConfig.Authorization != nil && (c.AlertSourceToken != "" || c.AlertSourceTokenFile != "") { | ||
| return errors.New("cannot specify alert_source_token or alert_source_token_file when using http_config.authorization") | ||
| } | ||
|
|
||
| if c.UpdateMessage && c.APIURL.String() != "https://slack.com/api/chat.postMessage" { | ||
| return errors.New("update_message can only be used with bot tokens. api_url must be set to https://slack.com/api/chat.postMessage") | ||
| if (c.HTTPConfig != nil && c.HTTPConfig.Authorization == nil) && c.AlertSourceToken == "" && c.AlertSourceTokenFile == "" { | ||
| return errors.New("at least one of alert_source_token, alert_source_token_file or http_config.authorization must be configured") | ||
| } | ||
| return nil |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Fix the incident.io authentication check for a nil HTTPConfig.
Line 584 requires c.HTTPConfig != nil before it enforces that a credential exists. If a user omits http_config entirely and also omits alert_source_token and alert_source_token_file, the whole check is skipped. The configuration then loads without any credential, and the notifier fails at delivery time instead of at configuration load time.
Evaluate the credential requirement independently of c.HTTPConfig being set.
🐛 Proposed fix for the credential check
- if (c.HTTPConfig != nil && c.HTTPConfig.Authorization == nil) && c.AlertSourceToken == "" && c.AlertSourceTokenFile == "" {
+ hasAuthorization := c.HTTPConfig != nil && c.HTTPConfig.Authorization != nil
+ if !hasAuthorization && c.AlertSourceToken == "" && c.AlertSourceTokenFile == "" {
return errors.New("at least one of alert_source_token, alert_source_token_file or http_config.authorization must be configured")
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if c.AlertSourceToken != "" && c.AlertSourceTokenFile != "" { | |
| return errors.New("at most one of alert_source_token & alert_source_token_file must be configured") | |
| } | |
| if c.HTTPConfig != nil && c.HTTPConfig.Authorization != nil && (c.AlertSourceToken != "" || c.AlertSourceTokenFile != "") { | |
| return errors.New("cannot specify alert_source_token or alert_source_token_file when using http_config.authorization") | |
| } | |
| if c.UpdateMessage && c.APIURL.String() != "https://slack.com/api/chat.postMessage" { | |
| return errors.New("update_message can only be used with bot tokens. api_url must be set to https://slack.com/api/chat.postMessage") | |
| if (c.HTTPConfig != nil && c.HTTPConfig.Authorization == nil) && c.AlertSourceToken == "" && c.AlertSourceTokenFile == "" { | |
| return errors.New("at least one of alert_source_token, alert_source_token_file or http_config.authorization must be configured") | |
| } | |
| return nil | |
| if c.AlertSourceToken != "" && c.AlertSourceTokenFile != "" { | |
| return errors.New("at most one of alert_source_token & alert_source_token_file must be configured") | |
| } | |
| if c.HTTPConfig != nil && c.HTTPConfig.Authorization != nil && (c.AlertSourceToken != "" || c.AlertSourceTokenFile != "") { | |
| return errors.New("cannot specify alert_source_token or alert_source_token_file when using http_config.authorization") | |
| } | |
| hasAuthorization := c.HTTPConfig != nil && c.HTTPConfig.Authorization != nil | |
| if !hasAuthorization && c.AlertSourceToken == "" && c.AlertSourceTokenFile == "" { | |
| return errors.New("at least one of alert_source_token, alert_source_token_file or http_config.authorization must be configured") | |
| } | |
| return nil |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@config/notifiers.go` around lines 577 - 587, Update the credential
requirement check in the incident.io validation method to also reject
configurations where HTTPConfig is nil and both AlertSourceToken and
AlertSourceTokenFile are empty. Evaluate the missing-credential condition
independently of HTTPConfig presence, while preserving the existing
authorization and mutual-exclusion checks.
| for _, r := range c.Responders { | ||
| if r.ID == "" && r.Username == "" && r.Name == "" { | ||
| return fmt.Errorf("opsGenieConfig responder %v has to have at least one of id, username or name specified", r) | ||
| } | ||
|
|
||
| if strings.Contains(r.Type, "{{") { | ||
| _, err := template.New("").Parse(r.Type) | ||
| if err != nil { | ||
| return fmt.Errorf("opsGenieConfig responder %v type is not a valid template: %w", r, err) | ||
| } | ||
| } else { | ||
| r.Type = strings.ToLower(r.Type) | ||
| if !opsgenieTypeMatcher.MatchString(r.Type) { | ||
| return fmt.Errorf("opsGenieConfig responder %v type does not match valid options %s", r, opsgenieValidTypesRe) | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Persist the lowercased responder type back into c.Responders.
The loop ranges by value, so r is a copy. Line 715 lowercases only the copy. The stored c.Responders[i].Type keeps the original casing. Validation still passes, but the normalization is discarded, so downstream code receives values such as Team instead of team.
Index the slice and write the normalized element back.
🐛 Proposed fix to keep the normalized responder type
- for _, r := range c.Responders {
+ for i, r := range c.Responders {
if r.ID == "" && r.Username == "" && r.Name == "" {
return fmt.Errorf("opsGenieConfig responder %v has to have at least one of id, username or name specified", r)
}
if strings.Contains(r.Type, "{{") {
_, err := template.New("").Parse(r.Type)
if err != nil {
return fmt.Errorf("opsGenieConfig responder %v type is not a valid template: %w", r, err)
}
} else {
r.Type = strings.ToLower(r.Type)
if !opsgenieTypeMatcher.MatchString(r.Type) {
return fmt.Errorf("opsGenieConfig responder %v type does not match valid options %s", r, opsgenieValidTypesRe)
}
}
+ c.Responders[i] = r
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for _, r := range c.Responders { | |
| if r.ID == "" && r.Username == "" && r.Name == "" { | |
| return fmt.Errorf("opsGenieConfig responder %v has to have at least one of id, username or name specified", r) | |
| } | |
| if strings.Contains(r.Type, "{{") { | |
| _, err := template.New("").Parse(r.Type) | |
| if err != nil { | |
| return fmt.Errorf("opsGenieConfig responder %v type is not a valid template: %w", r, err) | |
| } | |
| } else { | |
| r.Type = strings.ToLower(r.Type) | |
| if !opsgenieTypeMatcher.MatchString(r.Type) { | |
| return fmt.Errorf("opsGenieConfig responder %v type does not match valid options %s", r, opsgenieValidTypesRe) | |
| } | |
| } | |
| } | |
| for i, r := range c.Responders { | |
| if r.ID == "" && r.Username == "" && r.Name == "" { | |
| return fmt.Errorf("opsGenieConfig responder %v has to have at least one of id, username or name specified", r) | |
| } | |
| if strings.Contains(r.Type, "{{") { | |
| _, err := template.New("").Parse(r.Type) | |
| if err != nil { | |
| return fmt.Errorf("opsGenieConfig responder %v type is not a valid template: %w", r, err) | |
| } | |
| } else { | |
| r.Type = strings.ToLower(r.Type) | |
| if !opsgenieTypeMatcher.MatchString(r.Type) { | |
| return fmt.Errorf("opsGenieConfig responder %v type does not match valid options %s", r, opsgenieValidTypesRe) | |
| } | |
| } | |
| c.Responders[i] = r | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@config/notifiers.go` around lines 704 - 720, Update the responder validation
loop around c.Responders to iterate by index and persist the lowercased Type on
the corresponding slice element. Keep template-valued types unchanged and
preserve the existing validation and error behavior.
Signed-off-by: Holger Waschke <holger.waschke@dvag.com>
af39460 to
5609dab
Compare
|
Sync against main, ready to be merged. |
Problem
The hash used to identify existing Jira issues is not unique across multiple Jira projects.
Root Cause
Currently, the hash is generated using the ExtractGroupKey function, which relies on both the route matchers and group labels, see here.
Example result:
"{}/{env=\"prod\"}:{alertname=\"HighErrorRate\", cluster=\"bb\", service=\"api\"}"This makes the hash unique only within a single Jira project.
In larger environments, where the same alert may be mirrored or transferred across multiple Jira projects you cant identitify the same issue by its hash.
Change Summary
This update modifies the hash calculation to use only the group labels via the notify.GroupLabels function.
This ensures that the resulting hash uniquely identifies an issue based solely on alert labels, independent of the Jira project.
Impact
Jira issue lookup remains scoped to a single project, as defined by the JQL query:
This change does not cause cross-project updates or searches.
It lays the groundwork for a future enhancement to allow configurable multi-project issue lookups.
Future Considerations
A potential next step could be introducing a parameter that defines which Jira projects should be included in the update/search scope.