-
Notifications
You must be signed in to change notification settings - Fork 11
feat: alerts REST client #416
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 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ae5cecb
BREAKING CHANGE: removed requests from solnlib dependencies
sgoral-splunk ecbb499
BREAKING CHANGE: removed urllib3 from solnlib dependencies
sgoral-splunk 641e7ab
docs: refactor of a documentation
sgoral-splunk 1016f87
BREAKING CHANGE: removed requests from solnlib's dependencies (#412)
sgoral-splunk 53613e6
Alerts REST client
kkedziak-splunk 294ca3f
Merge branch 'develop' into feat/alerts_client
kkedziak-splunk 3519ff7
Update docstring
kkedziak-splunk 408bc18
Change the default permission
kkedziak-splunk 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,16 @@ | ||
| # Removed requests and urllib3 from solnlib | ||
| The `requests` and `urllib3` libraries has been removed from solnlib, so solnlib now depends on the `requests` and `urllib3` libraries from the running environment. | ||
| By default, Splunk delivers the above libraries and their version depends on the Splunk version. More information [here](https://docs.splunk.com/Documentation/Splunk/9.2.3/ReleaseNotes/Credits). | ||
|
|
||
| **IMPORTANT**: `urllib3` is available in Splunk `v8.1.0` and later | ||
|
|
||
| Please note that if `requests` or `urllib3` are installed in `<Add-on>/lib` e.g. as a dependency of another library, that version will be taken first. | ||
| If `requests` or `urllib3` is missing in the add-on's `lib` directory, the version provided by Splunk will be used. | ||
|
|
||
| ## Custom Version of requests and urllib3 | ||
| In case the Splunk's `requests` or `urllib3` version is not sufficient for you, | ||
| you can deliver version you need by simply adding it to the `requirements.txt` or `pyproject.toml` file in your add-on. | ||
|
|
||
| ## Use solnlib outside the Splunk | ||
| **Solnlib** no longer provides `requests` and `urllib3` so if you want to use **solnlib** outside the Splunk, please note that you will need to | ||
| provide these libraries yourself in the environment where **solnlib** is used. |
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,252 @@ | ||
| # | ||
| # Copyright 2024 Splunk Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| import json | ||
| from enum import Enum | ||
| from typing import Tuple, Union, Optional | ||
|
|
||
| from solnlib import splunk_rest_client as rest_client | ||
|
|
||
|
|
||
| class AlertType(Enum): | ||
| CUSTOM = "custom" | ||
| NUMBER_OF_EVENTS = "number of events" | ||
| NUMBER_OF_HOSTS = "number of hosts" | ||
| NUMBER_OF_SOURCES = "number of sources" | ||
|
|
||
|
|
||
| class AlertSeverity(Enum): | ||
| DEBUG = 1 | ||
| INFO = 2 | ||
| WARN = 3 | ||
| ERROR = 4 | ||
| SEVERE = 5 | ||
| FATAL = 6 | ||
|
|
||
|
|
||
| class AlertComparator(Enum): | ||
| GREATER_THAN = "greater than" | ||
| LESS_THAN = "less than" | ||
| EQUAL_TO = "equal to" | ||
| RISES_BY = "rises by" | ||
| DROPS_BY = "drops by" | ||
| RISES_BY_PERC = "rises by perc" | ||
| DROPS_BY_PERC = "drops by perc" | ||
|
|
||
|
|
||
| class AlertsRestClient: | ||
| """REST client for handling alerts.""" | ||
|
|
||
| ENDPOINT = "/services/saved/searches" | ||
| headers = [("Content-Type", "application/json")] | ||
|
|
||
| def __init__( | ||
| self, | ||
| session_key: str, | ||
| app: str, | ||
| **context: dict, | ||
| ): | ||
| """Initializes AlertsRestClient. | ||
|
|
||
| Arguments: | ||
| session_key: Splunk access token. | ||
| app: App name of namespace. | ||
| context: Other configurations for Splunk rest client. | ||
| """ | ||
| self.session_key = session_key | ||
| self.app = app | ||
|
|
||
| self._rest_client = rest_client.SplunkRestClient( | ||
| self.session_key, app=self.app, **context | ||
| ) | ||
|
|
||
| def create_search_alert( | ||
| self, | ||
| name: str, | ||
| search: str, | ||
| *, | ||
| disabled: bool = True, | ||
| description: str = "", | ||
| alert_type: AlertType = AlertType.NUMBER_OF_EVENTS, | ||
| alert_condition: str = "", | ||
| alert_comparator: AlertComparator = AlertComparator.GREATER_THAN, | ||
| alert_threshold: Union[int, float, str] = 0, | ||
| time_window: Tuple[str, str] = ("-15m", "now"), | ||
| alert_severity: AlertSeverity = AlertSeverity.WARN, | ||
| cron_schedule: str = "* * * * *", | ||
| expires: Union[int, str] = "24h", | ||
| **kwargs, | ||
| ): | ||
| """Creates a search alert in Splunk. | ||
|
|
||
| Arguments: | ||
| name: Name of the alert. | ||
| search: Search query for the alert. | ||
| disabled: Whether the alert is disabled. Default is True. | ||
| description: Description of the alert. | ||
| alert_type: Type of the alert (see AlertType). If it equals to CUSTOM, Splunk executes a check in | ||
| alert_condition. Otherwise, alert_comparator and alert_threshold are used. | ||
| alert_condition: Condition for the alert. | ||
| alert_comparator: Comparator for the alert. Default is GREATER_THAN. | ||
| alert_threshold: Threshold for the alert. Default is 0. | ||
| time_window: Time window for the alert. Tuple of earliest and latest time. Default is ("-1h", "now"). | ||
kkedziak-splunk marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| alert_severity: Severity level of the alert. Default is WARN. | ||
| cron_schedule: Cron schedule for the alert. Default is "* * * * *". | ||
| expires: Expiration time for the alert (i.e. how long you can access the result of triggered alert). | ||
| Default is "24h". | ||
| kwargs: Additional parameters for the alert. See Splunk documentation for more details. | ||
| """ | ||
| params = { | ||
| "output_mode": "json", | ||
| "name": name, | ||
| "search": search, | ||
| "description": description, | ||
| "alert_type": alert_type.value, | ||
| "alert_condition": alert_condition, | ||
| "alert_comparator": alert_comparator.value, | ||
| "alert_threshold": alert_threshold, | ||
| "alert.severity": str(alert_severity.value), | ||
| "is_scheduled": "1", | ||
| "cron_schedule": cron_schedule, | ||
| "dispatch.earliest_time": time_window[0], | ||
| "dispatch.latest_time": time_window[1], | ||
| "alert.digest_mode": "1", | ||
| "alert.expires": str(expires), | ||
| "disabled": "1" if disabled else "0", | ||
| "realtime_schedule": "1", | ||
| } | ||
|
|
||
| params.update(kwargs) | ||
|
|
||
| self._rest_client.post(self.ENDPOINT, body=params, headers=self.headers) | ||
|
|
||
| def delete_search_alert(self, name: str): | ||
| """Deletes a search alert in Splunk. | ||
|
|
||
| Arguments: | ||
| name: Name of the alert to delete. | ||
| """ | ||
| self._rest_client.delete(f"{self.ENDPOINT}/{name}") | ||
|
|
||
| def get_search_alert(self, name: str): | ||
| """Retrieves a specific search alert from Splunk. | ||
|
|
||
| Arguments: | ||
| name: Name of the alert to retrieve. | ||
|
|
||
| Returns: | ||
| A dictionary containing the alert details. | ||
| """ | ||
| response = ( | ||
| self._rest_client.get(f"{self.ENDPOINT}/{name}", output_mode="json") | ||
| .body.read() | ||
| .decode("utf-8") | ||
| ) | ||
|
|
||
| return json.loads(response) | ||
|
|
||
| def get_all_search_alerts(self): | ||
| """Retrieves all search alerts from Splunk. | ||
|
|
||
| Returns: | ||
| A dictionary containing all search alerts. | ||
| """ | ||
| response = ( | ||
| self._rest_client.get(self.ENDPOINT, output_mode="json") | ||
| .body.read() | ||
| .decode("utf-8") | ||
| ) | ||
|
|
||
| return json.loads(response) | ||
|
|
||
| def update_search_alert( | ||
| self, | ||
| name: str, | ||
| *, | ||
| search: Optional[str] = None, | ||
| disabled: Optional[bool] = None, | ||
| description: Optional[str] = None, | ||
| alert_type: Optional[AlertType] = None, | ||
| alert_condition: Optional[str] = None, | ||
| alert_comparator: Optional[AlertComparator] = None, | ||
| alert_threshold: Optional[Union[int, float, str]] = None, | ||
| time_window: Optional[Tuple[str, str]] = None, | ||
| alert_severity: Optional[AlertSeverity] = None, | ||
| cron_schedule: Optional[str] = None, | ||
| expires: Optional[Union[int, str]] = None, | ||
| **kwargs, | ||
| ): | ||
| """Updates a search alert in Splunk. | ||
|
|
||
| Arguments: | ||
| name: Name of the alert to update. | ||
| search: Search query for the alert. | ||
| disabled: Whether the alert is disabled. | ||
| description: Description of the alert. | ||
| alert_type: Type of the alert (see AlertType). If it equals to CUSTOM, Splunk executes a check in | ||
| alert_condition. Otherwise, alert_comparator and alert_threshold are used. | ||
| alert_condition: Condition for the alert. | ||
| alert_comparator: Comparator for the alert. | ||
| alert_threshold: Threshold for the alert. | ||
| time_window: Time window for the alert. Tuple of earliest and latest time. | ||
| alert_severity: Severity level of the alert. | ||
| cron_schedule: Cron schedule for the alert. | ||
| expires: Expiration time for the alert. | ||
| kwargs: Additional parameters for the alert. See Splunk documentation for more details. | ||
| """ | ||
| params = { | ||
| "output_mode": "json", | ||
| } | ||
|
|
||
| if search: | ||
| params["search"] = search | ||
|
|
||
| if disabled is not None: | ||
| params["disabled"] = "1" if disabled else "0" | ||
|
|
||
| if description: | ||
| params["description"] = description | ||
|
|
||
| if alert_type: | ||
| params["alert_type"] = alert_type.value | ||
|
|
||
| if alert_condition: | ||
| params["alert_condition"] = alert_condition | ||
|
|
||
| if alert_comparator: | ||
| params["alert_comparator"] = alert_comparator.value | ||
|
|
||
| if alert_threshold: | ||
| params["alert_threshold"] = str(alert_threshold) | ||
|
|
||
| if time_window: | ||
| params["dispatch.earliest_time"] = time_window[0] | ||
| params["dispatch.latest_time"] = time_window[1] | ||
|
|
||
| if alert_severity: | ||
| params["alert.severity"] = str(alert_severity.value) | ||
|
|
||
| if cron_schedule: | ||
| params["is_scheduled"] = "1" | ||
| params["cron_schedule"] = cron_schedule | ||
|
|
||
| if expires: | ||
| params["alert.expires"] = str(expires) | ||
|
|
||
| params.update(kwargs) | ||
|
|
||
| self._rest_client.post( | ||
| f"{self.ENDPOINT}/{name}", body=params, headers=self.headers | ||
| ) | ||
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,8 +1,23 @@ | ||
| import os | ||
| import sys | ||
|
|
||
| # path manipulation get the 'splunk' library for the imports while running on GH Actions | ||
| sys.path.append( | ||
| os.path.sep.join([os.environ["SPLUNK_HOME"], "lib", "python3.7", "site-packages"]) | ||
| ) | ||
| # TODO: 'python3.7' needs to be updated as and when Splunk has new folder for Python. | ||
| import pytest | ||
|
|
||
| import context | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True, scope="session") | ||
| def setup_env(): | ||
| # path manipulation get the 'splunk' library for the imports while running on GH Actions | ||
| if "SPLUNK_HOME" in os.environ: | ||
| sys.path.append( | ||
| os.path.sep.join( | ||
| [os.environ["SPLUNK_HOME"], "lib", "python3.7", "site-packages"] | ||
| ) | ||
| ) | ||
| # TODO: 'python3.7' needs to be updated as and when Splunk has new folder for Python. | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session") | ||
| def session_key(): | ||
| return context.get_session_key() |
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.