-
Notifications
You must be signed in to change notification settings - Fork 1.3k
feat: add SNMP provider for network device monitoring #6232
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
Open
Ojas2095
wants to merge
2
commits into
keephq:main
Choose a base branch
from
Ojas2095:snmp-provider-implementation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+190
−0
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| """ | ||
| SNMP Provider is a class that allows to ingest/digest data from SNMP devices. | ||
| """ | ||
|
|
||
| import dataclasses | ||
| import logging | ||
|
|
||
| import pydantic | ||
| from pysnmp.hlapi import * | ||
|
|
||
| from keep.api.models.alert import AlertDto, AlertSeverity, AlertStatus | ||
| from keep.contextmanager.contextmanager import ContextManager | ||
| from keep.providers.base.base_provider import BaseProvider | ||
| from keep.providers.models.provider_config import ProviderConfig, ProviderScope | ||
| from keep.providers.models.provider_method import ProviderMethod | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| @pydantic.dataclasses.dataclass | ||
| class SnmpProviderAuthConfig: | ||
| """ | ||
| SNMP authentication configuration. | ||
| """ | ||
|
|
||
| host: str = dataclasses.field( | ||
| metadata={ | ||
| "required": True, | ||
| "description": "SNMP Device Host", | ||
| "hint": "192.168.1.1", | ||
| "sensitive": False, | ||
| } | ||
| ) | ||
| port: int = dataclasses.field( | ||
| metadata={ | ||
| "required": False, | ||
| "description": "SNMP Device Port", | ||
| "hint": "161", | ||
| "sensitive": False, | ||
| }, | ||
| default=161, | ||
| ) | ||
| community: str = dataclasses.field( | ||
| metadata={ | ||
| "required": True, | ||
| "description": "SNMP Community String", | ||
| "hint": "public", | ||
| "sensitive": True, | ||
| }, | ||
| default="public", | ||
| ) | ||
| version: str = dataclasses.field( | ||
| metadata={ | ||
| "required": False, | ||
| "description": "SNMP Version (1, 2c, 3 - v3 not yet supported)", | ||
| "hint": "2c", | ||
| "sensitive": False, | ||
| }, | ||
| default="2c", | ||
| ) | ||
|
|
||
|
|
||
| class SnmpProvider(BaseProvider): | ||
| """ | ||
| Query SNMP devices from Keep. | ||
| """ | ||
|
|
||
| PROVIDER_CATEGORY = ["Monitoring"] | ||
| PROVIDER_DISPLAY_NAME = "SNMP" | ||
| PROVIDER_TAGS = ["networking", "monitoring"] | ||
|
|
||
| def __init__( | ||
| self, context_manager: ContextManager, provider_id: str, config: ProviderConfig | ||
| ): | ||
| super().__init__(context_manager, provider_id, config) | ||
|
|
||
| def validate_config(self): | ||
| """ | ||
| Validates required configuration for SNMP provider. | ||
| """ | ||
| self.authentication_config = SnmpProviderAuthConfig( | ||
| **self.config.authentication | ||
| ) | ||
|
|
||
| def dispose(self): | ||
| """ | ||
| Dispose the provider. | ||
| """ | ||
| pass | ||
|
|
||
| def _query(self, oid: str, method: str = "get", **kwargs) -> dict: | ||
| """ | ||
| Query an SNMP device. | ||
|
|
||
| Args: | ||
| oid (str): The OID to query. | ||
| method (str): The method to use (get, walk). | ||
|
|
||
| Returns: | ||
| dict: The result of the query. | ||
| """ | ||
| self.logger.info( | ||
| "Querying SNMP device %s for OID %s using %s", | ||
| self.authentication_config.host, oid, method, | ||
| ) | ||
|
|
||
| version = self.authentication_config.version | ||
| if version == "2c": | ||
| mp_model = 1 | ||
| elif version == "1": | ||
| mp_model = 0 | ||
| else: | ||
| raise ValueError( | ||
| f"Unsupported SNMP version: '{version}'. Supported versions: '1', '2c'" | ||
| ) | ||
|
|
||
| community_data = CommunityData( | ||
| self.authentication_config.community, mpModel=mp_model | ||
| ) | ||
| transport_target = UdpTransportTarget( | ||
| (self.authentication_config.host, self.authentication_config.port) | ||
| ) | ||
|
|
||
| results = {} | ||
| if method.lower() == "get": | ||
| error_indication, error_status, error_index, var_binds = next( | ||
| getCmd(SnmpEngine(), community_data, transport_target, ContextData(), ObjectType(ObjectIdentity(oid))) | ||
| ) | ||
| if error_indication: | ||
| raise Exception(f"SNMP Error: {error_indication}") | ||
| elif error_status: | ||
| raise Exception(f"SNMP Status Error: {error_status.prettyPrint()} at {error_index and var_binds[int(error_index) - 1][0] or '?'}") | ||
| else: | ||
| for var_bind in var_binds: | ||
| results[str(var_bind[0])] = str(var_bind[1]) | ||
|
|
||
| elif method.lower() == "walk": | ||
| for (error_indication, error_status, error_index, var_binds) in nextCmd( | ||
| SnmpEngine(), community_data, transport_target, ContextData(), ObjectType(ObjectIdentity(oid)), lexicographicMode=False | ||
| ): | ||
| if error_indication: | ||
| raise Exception(f"SNMP Error: {error_indication}") | ||
| elif error_status: | ||
| raise Exception(f"SNMP Status Error: {error_status.prettyPrint()} at {error_index and var_binds[int(error_index) - 1][0] or '?'}") | ||
| else: | ||
| for var_bind in var_binds: | ||
| results[str(var_bind[0])] = str(var_bind[1]) | ||
|
|
||
| return results | ||
|
|
||
| def _get_alerts(self) -> list[AlertDto]: | ||
| # SNMP provider doesn't pull alerts by default, it's used for querying or receiving traps | ||
| return [] | ||
|
|
||
| @staticmethod | ||
| def _format_alert(event: dict, provider_instance: "BaseProvider" = None) -> AlertDto: | ||
| # Format incoming SNMP trap data into an AlertDto | ||
| # Extract known fields and pass remaining as extra kwargs | ||
| known_keys = {"id", "name", "status", "severity", "source"} | ||
| extra_kwargs = {k: v for k, v in event.items() if k not in known_keys} | ||
|
|
||
| return AlertDto( | ||
| id=event.get("id", "snmp-trap"), | ||
| name=event.get("name", "SNMP Trap"), | ||
| status=AlertStatus.FIRING, | ||
| severity=AlertSeverity.INFO, | ||
| source=["snmp"], | ||
| **extra_kwargs | ||
| ) | ||
|
|
||
| if __name__ == "__main__": | ||
| # Output debug messages | ||
| import logging | ||
|
|
||
| logging.basicConfig(level=logging.DEBUG, handlers=[logging.StreamHandler()]) | ||
| context_manager = ContextManager( | ||
| tenant_id="singletenant", | ||
| workflow_id="test", | ||
| ) | ||
| # Mock config | ||
| config = ProviderConfig( | ||
| description="SNMP Provider", | ||
| authentication={ | ||
| "host": "localhost", | ||
| "community": "public", | ||
| }, | ||
| ) | ||
| provider = SnmpProvider(context_manager, "snmp", config) | ||
| print("SNMP Provider Initialized") | ||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_format_alertcrashes from duplicate keyword argumentsHigh Severity
_format_alertpasses explicit keyword arguments likeid,name,status,severity, andsourcealongside**event. Wheneventcontains any of those same keys — which is the anticipated case given theevent.get("id", ...)pattern — Python raises aTypeErrorfor duplicate keyword arguments beforeAlertDtoever processes them. Other providers (e.g., Kibana) avoid this by usingevent.pop()to remove keys from the dict before**eventunpacking.Reviewed by Cursor Bugbot for commit 7ec59da. Configure here.