Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 131 additions & 1 deletion linode_api4/groups/monitor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Optional, Union
from typing import Any, Dict, Optional, Union

from linode_api4 import PaginatedList
from linode_api4.errors import UnexpectedResponseError
Expand All @@ -18,10 +18,13 @@
MonitorService,
MonitorServiceToken,
)
from linode_api4.objects.filtering import and_
from linode_api4.objects.monitor import (
AkamaiObjectStorageLogsDestinationDetails,
ChannelDetails,
CustomHTTPSLogsDestinationDetails,
LogsStreamDetails,
WebhookDetails,
)

__all__ = [
Expand Down Expand Up @@ -423,6 +426,133 @@ def alert_definition_entities(
endpoint=endpoint,
)

def channel_create(
self,
label: str,
channel_type: str,
details: ChannelDetails,
) -> AlertChannel:
"""
Creates a new alert channel for the authenticated account.

An alert channel defines a notification destination (for example: an
email list) that can be associated with one or more alert definitions.
The supported ``channel_type`` values are ``email`` and ``webhook``.

API Documentation: https://techdocs.akamai.com/linode-api/reference/post-notification-channel

:param label: Human-readable name for the new alert channel.
:type label: str
:param channel_type: The notification channel type (``"email"`` or ``"webhook"``).
:type channel_type: str
:param details: Notification-type-specific configuration.
:type details: ChannelDetails

:returns: The newly created :class:`AlertChannel`.
:rtype: AlertChannel

.. note::
If you need to obtain a single :class:`AlertChannel`, use :meth:`LinodeClient.load`.
Example: ``client.load(AlertChannel, channel_id)``.
For updating an alert channel, use the ``save()`` method on the :class:`AlertChannel` object.
For deleting an alert channel, use the ``delete()`` method directly on the :class:`AlertChannel` object.
"""
params = {
"label": label,
"channel_type": channel_type,
"details": details.dict,
}

result = self.client.post("/monitor/alert-channels", data=params)

if "id" not in result:
raise UnexpectedResponseError(
"Unexpected response when creating alert channel!",
json=result,
)

return AlertChannel(self.client, result["id"], result)

def verify_webhook(
self, webhook: Union[WebhookDetails, Dict[str, Any]]
) -> Dict[str, Any]:
"""
Verify that a webhook configuration can receive alert notifications.

API Documentation: https://techdocs.akamai.com/linode-api/reference/verify-notification-channel

:param webhook: The webhook configuration to verify.
:type webhook: WebhookDetails or dict

:returns: The API response containing the verification result.
:rtype: dict
"""
params = {
"webhook": (
webhook.dict if isinstance(webhook, WebhookDetails) else webhook
)
}

return self.client.post(
"/monitor/alert-channels/verify",
data=params,
)

def alert_channel_alerts(self, channel_id: int, *filters) -> PaginatedList:
"""
Retrieve all alerts associated with a specific alert channel.

Returns a paginated collection of alert definitions associated with the
specified alert channel. This allows you to see which alert definitions
are configured to notify this specific channel.

API Documentation: https://techdocs.akamai.com/linode-api/reference/get-notification-channel-alerts

:param channel_id: The ID of the alert channel to retrieve alerts for.
:type channel_id: int
:param filters: Optional filter expressions to apply to the collection.
See :doc:`Filtering Collections</linode_api4/objects/filtering>` for details.

:returns: A paginated list of alert definitions associated with this channel.
:rtype: PaginatedList[AlertDefinition]
"""
endpoint = f"/monitor/alert-channels/{channel_id}/alerts"

parsed_filters = None
if filters:
parsed_filters = (
and_(*filters).dct if len(filters) > 1 else filters[0].dct
)

response_json = self.client.get(endpoint, filters=parsed_filters)

if "data" not in response_json:
raise UnexpectedResponseError(
"Unexpected response when retrieving alert channel alerts!",
json=response_json,
)

result = [
AlertDefinition.make_instance(
obj["id"],
self.client,
parent_id=obj.get("service_type"),
json=obj,
)
for obj in response_json.get("data", [])
if "id" in obj
]

return PaginatedList(
self.client,
endpoint[1:],
page=result,
max_pages=response_json.get("pages", 1),
total_items=response_json.get("results", len(result)),
parent_id=None,
filters=parsed_filters,
)

def destinations(self, *filters) -> PaginatedList:
"""
List available logs destinations.
Expand Down
142 changes: 87 additions & 55 deletions linode_api4/objects/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,22 @@
__all__ = [
"AggregateFunction",
"AlertChannel",
"AlertChannelType",
"AlertDefinition",
"AlertDefinitionChannel",
"AlertDefinitionEntity",
"AlertEntities",
"AlertScope",
"AlertType",
"ChannelDetails",
"EmailDetails",
"MonitorDashboard",
"MonitorMetricsDefinition",
"MonitorService",
"MonitorServiceToken",
"RuleCriteria",
"TriggerConditions",
"WebhookDetails",
"AkamaiObjectStorageLogsDestinationDetails",
"AuthenticationType",
"BasicAuthenticationDetails",
Expand Down Expand Up @@ -276,8 +280,8 @@ class MonitorDashboard(Base):
"id": Property(identifier=True),
"created": Property(is_datetime=True),
"label": Property(),
"service_type": Property(ServiceType),
"type": Property(DashboardType),
"service_type": Property(),
"type": Property(),
"group_by": Property(),
"widgets": Property(json_object=DashboardWidget),
"updated": Property(is_datetime=True),
Expand All @@ -294,7 +298,7 @@ class MonitorService(Base):
api_endpoint = "/monitor/services/{service_type}"
id_attribute = "service_type"
properties = {
"service_type": Property(ServiceType),
"service_type": Property(),
"label": Property(),
"alert": Property(json_object=ServiceAlert),
}
Expand Down Expand Up @@ -437,6 +441,13 @@ class AlertScope(StrEnum):
account = "account"


class AlertChannelType(StrEnum):
"""Type values for alert channels."""

system = "system"
user = "user"


@dataclass
class AlertEntities(JSONObject):
"""
Expand Down Expand Up @@ -495,14 +506,56 @@ class AlertDefinition(DerivedBase):
"entity_ids": Property(mutable=True),
"description": Property(mutable=True),
"service_class": Property(alias_of="class"),
"scope": Property(AlertScope),
"scope": Property(),
"regions": Property(mutable=True),
"entities": Property(json_object=AlertEntities),
"channel_ids": Property(mutable=True),
"group_by": Property(mutable=True),
}


@dataclass
class BasicAuthenticationDetails(JSONObject):
"""
Includes additional parameters necessary to define basic authentication.
"""

basic_authentication_user: Optional[str] = None
basic_authentication_password: Optional[str] = None


@dataclass
class DestinationAuthentication(JSONObject):
"""
Authentication details required to access the endpoint_url.
"""

type: Optional[AuthenticationType] = None
details: Optional[BasicAuthenticationDetails] = None


@dataclass
class CustomHeader(JSONObject):
"""
Pairs of parameters used to optionally include custom headers in the request.
"""

name: str = ""
value: str = ""


@dataclass
class ClientCertificateDetails(JSONObject):
"""
Contains TLS client certificate information to additionally secure the connection.
"""

client_ca_certificate: Optional[str] = None
client_certificate: Optional[str] = None
client_private_key: Optional[str] = None
tls_hostname: Optional[str] = None


@dataclass
class EmailDetails(JSONObject):
"""
Expand All @@ -513,13 +566,35 @@ class EmailDetails(JSONObject):
recipient_type: Optional[str] = None


@dataclass
class WebhookDetails(JSONObject):
"""
Represents webhook-specific details for an alert channel.

Fields:
- endpoint_url: The URL where webhook events are sent.
- authentication: Authentication configuration for the webhook endpoint.
- data_compression: Compression method for webhook payloads ("gzip" or "none").
- client_certificate_details: TLS client certificate configuration.
- custom_headers: List of custom HTTP headers to include in webhook requests.
"""

endpoint_url: Optional[str] = None
authentication: Optional[DestinationAuthentication] = None
data_compression: Optional[str] = None
client_certificate_details: Optional[ClientCertificateDetails] = None
custom_headers: Optional[List[CustomHeader]] = None


@dataclass
class ChannelDetails(JSONObject):
"""
Represents the details block for an AlertChannel, which varies by channel type.
Supports email and webhook channel details.
"""

email: Optional[EmailDetails] = None
webhook: Optional[WebhookDetails] = None


@dataclass
Expand All @@ -541,25 +616,24 @@ class AlertChannel(Base):
"""
Represents an alert channel used to deliver notifications when alerts
fire. Alert channels define a destination and configuration for
notifications (for example: email lists, webhooks, PagerDuty, Slack, etc.).
notifications (for example: email lists, webhooks, Slack, etc.).

API Documentation: https://techdocs.akamai.com/linode-api/reference/get-notification-channels
API Documentation:
List/Get: https://techdocs.akamai.com/linode-api/reference/get-notification-channel
Create: https://techdocs.akamai.com/linode-api/reference/post-notification-channel

This class maps to the Monitor API's `/monitor/alert-channels` resource
and is used by the SDK to list, load, and inspect channels.

NOTE: Only read operations are supported for AlertChannel at this time.
Create, update, and delete (CRUD) operations are not allowed.
This class maps to the Monitor API's ``/monitor/alert-channels`` resource
and is used by the SDK to list, load, create, and inspect channels.
"""

api_endpoint = "/monitor/alert-channels/{id}"

properties = {
"id": Property(identifier=True),
"label": Property(),
"label": Property(mutable=True),
"type": Property(),
"channel_type": Property(),
"details": Property(mutable=False, json_object=ChannelDetails),
"details": Property(mutable=True, json_object=ChannelDetails),
"alerts": Property(mutable=False, json_object=AlertInfo),
"created": Property(is_datetime=True),
"updated": Property(is_datetime=True),
Expand All @@ -568,48 +642,6 @@ class AlertChannel(Base):
}


@dataclass
class BasicAuthenticationDetails(JSONObject):
"""
Includes additional parameters necessary to define basic authentication.
"""

basic_authentication_user: Optional[str] = None
basic_authentication_password: Optional[str] = None


@dataclass
class DestinationAuthentication(JSONObject):
"""
Authentication details required to access the endpoint_url.
"""

type: Optional[AuthenticationType] = None
details: Optional[BasicAuthenticationDetails] = None


@dataclass
class CustomHeader(JSONObject):
"""
Pairs of parameters used to optionally include custom headers in the request.
"""

name: str = ""
value: str = ""


@dataclass
class ClientCertificateDetails(JSONObject):
"""
Contains TLS client certificate information to additionally secure the connection.
"""

client_ca_certificate: Optional[str] = None
client_certificate: Optional[str] = None
client_private_key: Optional[str] = None
tls_hostname: Optional[str] = None


@dataclass
class LogsDestinationDetailsBase(JSONObject):
"""
Expand Down
Loading