-
Notifications
You must be signed in to change notification settings - Fork 305
New custom slack sink, slack_sink_preview #1789
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
47 commits
Select commit
Hold shift + click to select a range
ce49b90
WIP
aantn 96a69e2
Update sender.py
aantn 0f3710f
Update sender.py
aantn cdec3f7
Update sender.py
aantn 7ff23d6
Update sender.py
aantn 26ed319
Update sender.py
aantn ef3214d
Update sender.py
aantn d79a00d
Update sender.py
aantn 64bafc5
Update sender.py
aantn 787846a
incorporate feedback from igor
aantn c693938
Merge branch 'master' into claude-slack
aantn d72e001
add templating
aantn c4866c3
remove unused code
aantn 092f0c8
add logs
aantn 8c1a9a8
simplify code - always use jinja
aantn 9b15ca1
add legacy option
aantn 6bafca4
Merge branch 'master' into claude-slack
Avi-Robusta 9281648
bugfix sending to slack
Avi-Robusta 92c1b76
fixing template
Avi-Robusta 4e6b055
refactoring code
Avi-Robusta abe1c74
saving progress
Avi-Robusta cca0d57
added tests
Avi-Robusta ea81979
refactoring changes
Avi-Robusta 5df775d
misc changes
Avi-Robusta ed0178c
changess
Avi-Robusta 567372c
working version
Avi-Robusta 317fbf4
refactor send finding to slack
Avi-Robusta bb5d1c2
added space
Avi-Robusta 181adc1
removing unneeded code atm
Avi-Robusta d4a85a1
refactor
Avi-Robusta edd0cbd
fixing
Avi-Robusta 4650e18
docs update
Avi-Robusta ba20164
updated tests
Avi-Robusta c468f5a
bugfixes and header support
Avi-Robusta fa8a68e
fixed mentions
Avi-Robusta fcad848
added channel override test
Avi-Robusta b1dda3b
refactoring, removing useless changes
Avi-Robusta a73bf41
Merge branch 'master' into claude-slack
Avi-Robusta 3c1f709
refactoring sender
Avi-Robusta 57f094c
remove unneeded code
Avi-Robusta 7b9daf2
added additional features
Avi-Robusta 6546ba5
changed manual tests
Avi-Robusta 640ae37
add aggregation key
Avi-Robusta 1a7ee23
pr changes
Avi-Robusta e5094c4
added fingerprint to template
Avi-Robusta 24d32c7
Merge branch 'master' into claude-slack
arikalon1 052d6f4
Merge branch 'master' into claude-slack
Avi-Robusta File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,5 @@ | ||
| from robusta.core.sinks.slack.slack_sink_params import SlackSinkParams, SlackSinkConfigWrapper | ||
| from robusta.core.sinks.slack.slack_sink import SlackSink | ||
| from robusta.core.sinks.slack.slack_sink_params import SlackSinkConfigWrapper, SlackSinkParams | ||
|
|
||
| # to prevent circular imports in SlackSender, SlackSinkParams and SlackSinkPreviewParams | ||
| __all__ = ["SlackSink", "SlackSinkParams", "SlackSinkConfigWrapper"] |
10 changes: 10 additions & 0 deletions
10
src/robusta/core/sinks/slack/preview/slack_sink_preview.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| from robusta.core.sinks.slack.preview.slack_sink_preview_params import SlackSinkPreviewConfigWrapper, SlackSinkPreviewParams | ||
| from robusta.core.sinks.slack.slack_sink import SlackSink | ||
|
|
||
|
|
||
| class SlackSinkPreview(SlackSink): | ||
| params: SlackSinkPreviewParams | ||
|
|
||
| def __init__(self, sink_config: SlackSinkPreviewConfigWrapper, registry): | ||
| super().__init__(sink_config, registry, is_preview=True) | ||
|
|
34 changes: 34 additions & 0 deletions
34
src/robusta/core/sinks/slack/preview/slack_sink_preview_params.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| from robusta.core.sinks.sink_base_params import SinkBaseParams | ||
| from robusta.core.sinks.sink_config import SinkConfigBase | ||
| from robusta.core.sinks.slack.slack_sink_params import SlackSinkParams | ||
| from typing import Optional, Dict | ||
| from pydantic import validator | ||
|
|
||
|
|
||
| class SlackSinkPreviewParams(SlackSinkParams): | ||
| #TODO: improve the SlackSinkPreviewParams so the slack_custom_templates can be defined once globally and | ||
| # only a template name needs to be passed to each channel in the config | ||
| slack_custom_templates: Optional[Dict[str, str]] = None # Template name -> custom template content | ||
| hide_buttons: bool = False | ||
| hide_enrichments: bool = False | ||
|
|
||
|
|
||
| @validator('slack_custom_templates') | ||
| def check_one_item(cls, v): | ||
| if v is not None and len(v) != 1: | ||
| raise ValueError("slack_custom_templates must contain exactly one key-value pair") | ||
| return v | ||
|
|
||
| def get_custom_template(self) -> Optional[str]: | ||
| """Get the custom template if defined""" | ||
| if not self.slack_custom_templates: | ||
| return None | ||
|
|
||
| return next(iter(self.slack_custom_templates.values())) | ||
|
|
||
|
|
||
| class SlackSinkPreviewConfigWrapper(SinkConfigBase): | ||
| slack_sink_preview: SlackSinkPreviewParams | ||
|
|
||
| def get_params(self) -> SinkBaseParams: | ||
| return self.slack_sink_preview |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| {# Default template for Slack message headers #} | ||
| {# This creates a JIRA-style header with title and context blocks #} | ||
|
|
||
| {# First create the title block with status #} | ||
| { | ||
| "type": "section", | ||
| "text": { | ||
| "type": "mrkdwn", | ||
| "text": "{{ status_emoji }} *[{{ status_text }}] {% if platform_enabled and include_investigate_link %}<{{ investigate_uri }}|{{ title }}>{% else %}{{ title }}{% endif %}*{% if mention %} {{ mention }}{% endif %}" | ||
| } | ||
| } | ||
|
|
||
| {# Then create the context block with metadata #} | ||
| { | ||
| "type": "context", | ||
| "elements": [ | ||
| { | ||
| "type": "mrkdwn", | ||
| "text": ":bell: Type: {{ alert_type }}" | ||
| }, | ||
| { | ||
| "type": "mrkdwn", | ||
| "text": "{{ severity_emoji }} Severity: {{ severity }}" | ||
| }, | ||
| { | ||
| "type": "mrkdwn", | ||
| "text": ":globe_with_meridians: Cluster: {{ cluster_name }}" | ||
| } | ||
| {% if resource_text %} | ||
| ,{ | ||
| "type": "mrkdwn", | ||
| "text": "{{ resource_emoji }} Resource: {{ resource_text }}" | ||
| } | ||
| {% endif %} | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import json | ||
| import logging | ||
| import os | ||
| from typing import Any, Dict, List | ||
|
|
||
| from jinja2 import Environment, FileSystemLoader, Template, select_autoescape | ||
|
|
||
| # Get the directory where our templates are stored | ||
| TEMPLATE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__))) | ||
|
|
||
|
|
||
| class SlackTemplateLoader: | ||
| """ | ||
| Loads and renders Jinja2 templates for Slack messages. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| """Initialize the template environment.""" | ||
| self.env = Environment( | ||
| loader=FileSystemLoader(TEMPLATE_DIR), | ||
| autoescape=select_autoescape(["html", "xml"]), | ||
| trim_blocks=True, | ||
| lstrip_blocks=True, | ||
| ) | ||
| # Cache for templates | ||
| self._templates: Dict[str, Template] = {} | ||
|
|
||
| def get_template(self, template_name: str) -> Template: | ||
| """ | ||
| Get a template by name, loading from file if not already cached. | ||
|
|
||
| Args: | ||
| template_name: The name of the template file (e.g., "header.j2") | ||
|
|
||
| Returns: | ||
| A Jinja2 Template object | ||
| """ | ||
| if template_name not in self._templates: | ||
| try: | ||
| self._templates[template_name] = self.env.get_template(template_name) | ||
| except Exception as e: | ||
| logging.error(f"Error loading template {template_name}: {e}") | ||
| # Return a simple default template as fallback | ||
| return Template("Template loading error") | ||
|
|
||
| return self._templates[template_name] | ||
|
|
||
| def render_to_blocks(self, template: Template, context: Dict[str, Any]) -> List[Dict[str, Any]]: | ||
| """ | ||
| Render a Jinja2 Template object using the provided context and parse the result as JSON to get Slack blocks. | ||
| Args: | ||
| template: A Jinja2 Template object | ||
| context: Dictionary of variables to pass to the template | ||
| Returns: | ||
| List of Slack block objects (dictionaries) | ||
| """ | ||
| try: | ||
| rendered = template.render(**context) | ||
| blocks = [] | ||
| for block_str in rendered.strip().split("\n\n"): | ||
| if not block_str.strip(): | ||
| continue | ||
| try: | ||
| # Try to parse as JSON, but if it fails, log and skip | ||
| block = json.loads(block_str) | ||
| blocks.append(block) | ||
| except json.JSONDecodeError as e: | ||
| logging.exception(f"Error parsing JSON from template output: {e}") | ||
| logging.warning(f"Problematic JSON (repr): {repr(block_str)}") | ||
| continue # Skip this block and continue | ||
| except Exception as e: | ||
| logging.error(f"Unexpected error parsing block: {e}") | ||
| logging.warning(f"Problematic JSON (repr): {repr(block_str)}") | ||
| continue | ||
| return blocks | ||
| except Exception as e: | ||
| logging.error(f"Error rendering template: {e}") | ||
| return [] | ||
|
|
||
| def render_custom_template_to_blocks(self, custom_template: str, context: Dict[str, Any]) -> List[Dict[str, Any]]: | ||
| try: | ||
| template = Template(custom_template) | ||
| return self.render_to_blocks(template, context) | ||
| except Exception as e: | ||
| logging.error(f"Error rendering custom template: {e}") | ||
| return self.render_default_template_to_blocks(context) | ||
|
|
||
| def render_default_template_to_blocks(self, context: Dict[str, Any]) -> List[Dict[str, Any]]: | ||
| DEFAULT_TEMPLATE_NAME="header.j2" | ||
| template = self.get_template(DEFAULT_TEMPLATE_NAME) | ||
| return self.render_to_blocks(template, context) | ||
|
|
||
|
|
||
| # Singleton instance | ||
| template_loader = SlackTemplateLoader() | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.