Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement the logicmonitor import source (#112226)

Tom Owers9970192716fe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index e9b168f87eac..b50cb2a7b3bf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -482,6 +482,7 @@ the row lists both.
| llama_cloud | HTTP | requests | ✅ |
| lob | HTTP | requests | ✅ |
| lodgify | HTTP | requests | ✅ |
+| logicmonitor | HTTP | requests | ✅ |
| logz_io | HTTP | requests | ✅ |
| loop_returns | HTTP | requests + `rest_source.RESTClient` | ✅ |
| loops | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -1224,7 +1225,6 @@ doesn't conflict with concurrent PRs.
- linnworks
- liveblocks
- llama_cloud
-- logicmonitor
- logrocket
- lokalise
- looker
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/logicmonitor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/logicmonitor.py
index 042bad044451..e877cae142fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/logicmonitor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/logicmonitor.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class LogicmonitorSourceConfig(config.Config):
- pass
+ portal_url: str
+ bearer_token: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/canonical_descriptions.py
new file mode 100644
index 000000000000..21d09c71ca7d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/canonical_descriptions.py
@@ -0,0 +1,82 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.settings import API_DOCS_URL
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "alerts": {
+ "description": "Alerts for monitored resources, including active and cleared alerts within the account's retention period.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Unique alert identifier.",
+ "startEpoch": "Time when the alert started, in Unix seconds.",
+ "endEpoch": "Time when the alert ended, in Unix seconds.",
+ "severity": "Severity: 2 means warning, 3 means error, and 4 means critical.",
+ "acked": "Whether a user acknowledged the alert.",
+ "cleared": "Whether the alert cleared.",
+ "monitorObjectId": "Identifier of the monitored object.",
+ "monitorObjectName": "Name of the monitored object.",
+ "resourceTemplateName": "Name of the DataSource in alert.",
+ "instanceName": "Name of the instance in alert.",
+ "dataPointName": "Name of the datapoint in alert.",
+ },
+ },
+ "devices": {
+ "description": "Monitored device inventory and collector assignments.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Unique device identifier.",
+ "name": "Hostname or IP address of the device.",
+ "displayName": "Device name shown in LogicMonitor.",
+ "createdOn": "Time when the device was added, in Unix seconds.",
+ "updatedOn": "Time when the device last changed, in Unix seconds.",
+ "preferredCollectorId": "Identifier of the preferred collector for this device.",
+ "hostGroupIds": "Comma-separated identifiers of groups that contain this device.",
+ },
+ },
+ "device_groups": {
+ "description": "Groups that organize monitored devices.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Unique device group identifier.",
+ "name": "Device group name.",
+ "fullPath": "Group path, including parent groups.",
+ "parentId": "Identifier of the parent group.",
+ "createdOn": "Time when the group was created, in Unix seconds.",
+ },
+ },
+ "collectors": {
+ "description": "Collectors, their availability, and the number of devices they monitor.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Unique collector identifier.",
+ "hostname": "Hostname of the device that runs the collector.",
+ "collectorGroupId": "Identifier of the collector's group.",
+ "numberOfHosts": "Number of devices monitored by the collector.",
+ "isDown": "Whether the collector is currently down.",
+ "build": "Collector version.",
+ },
+ },
+ "sdts": {
+ "description": "Scheduled downtime for resources and monitoring components.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Scheduled downtime identifier, including its resource type prefix.",
+ "type": "Type of resource covered by this scheduled downtime.",
+ "sdtType": "Schedule type, such as one-time, daily, weekly, or monthly.",
+ "startDateTime": "Start of the scheduled downtime, in Unix milliseconds.",
+ "endDateTime": "End of the scheduled downtime, in Unix milliseconds.",
+ },
+ },
+ "websites": {
+ "description": "Website monitors and their alert settings.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Unique website monitor identifier.",
+ "name": "Website monitor name.",
+ "type": "Check type: pingcheck or webcheck.",
+ "overallAlertLevel": "Alert severity when the website fails its configured checks.",
+ "disableAlerting": "Whether alerting is disabled for this website.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/logicmonitor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/logicmonitor.py
new file mode 100644
index 000000000000..3caa89cd2535
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/logicmonitor.py
@@ -0,0 +1,222 @@
+import re
+import time
+from collections.abc import Iterator
+from dataclasses import replace
+from typing import Any
+from urllib.parse import urlsplit
+
+from requests import Response
+from requests.exceptions import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.logicmonitor import (
+ LogicmonitorSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.settings import (
+ API_VERSION,
+ ENDPOINTS,
+ FIELDS,
+ MAX_ALERTS_PER_WINDOW,
+ PAGE_SIZE,
+ PRIMARY_KEYS,
+)
+
+AUTH_ERROR = "LogicMonitor rejected the bearer token. Check the token and its expiration date."
+PERMISSION_ERROR = "LogicMonitor denied access. Give the token's user view permission for the selected resource."
+DENSE_WINDOW_ERROR = (
+ "LogicMonitor returned too many alerts in one second. Contact support to export this alert history."
+)
+
+
+@frozen
+class LogicMonitorResumeConfig:
+ offset: int = 0
+ window_start: int = 0
+ window_end: int = 0
+ sync_end: int = 0
+ complete: bool = False
+
+
+def portal_url(value: str) -> str:
+ message = "Enter an HTTPS LogicMonitor portal URL, such as https://example.logicmonitor.com, without a path."
+ try:
+ parsed = urlsplit(value.strip())
+ if (
+ parsed.scheme != "https"
+ or not re.fullmatch(
+ r"[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.logicmonitor\.com", parsed.hostname or ""
+ )
+ or parsed.username is not None
+ or parsed.password is not None
+ or parsed.port not in (None, 443)
+ or parsed.path not in ("", "/")
+ or parsed.query
+ or parsed.fragment
+ ):
+ raise ValueError(message)
+ except ValueError:
+ raise ValueError(message) from None
+ return f"https://{parsed.hostname}"
+
+
+def validate_portal_host(value: str, team_id: int) -> tuple[bool, str | None]:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ( # noqa: PLC0415 -- keeps Django models off the source registration path
+ ValidateDatabaseHostMixin,
+ )
+
+ try:
+ url = portal_url(value)
+ except ValueError as error:
+ return False, str(error)
+ return ValidateDatabaseHostMixin().is_database_host_valid(urlsplit(url).hostname or "", team_id)
+
+
+class AlertWindowTooLarge(Exception):
+ pass
+
+
+class AlertPaginator(OffsetPaginator):
+ def update_state(self, response: Response, data: list[Any] | None = None) -> None:
+ total = response.json().get("total")
+ if not isinstance(total, int) or total < 0:
+ raise ValueError("LogicMonitor did not return a valid alert count.")
+ if total > MAX_ALERTS_PER_WINDOW:
+ if self.offset:
+ raise ValueError("LogicMonitor alert counts changed during pagination. Restart the full refresh.")
+ raise AlertWindowTooLarge
+ super().update_state(response, data)
+
+
+class LogicMonitorClient:
+ def __init__(self, config: LogicmonitorSourceConfig) -> None:
+ self.base_url = f"{portal_url(config.portal_url)}/santaba/rest/"
+ self.token = config.bearer_token
+
+ def validate_credentials(self) -> tuple[bool, str | None]:
+ client = RESTClient(
+ base_url=self.base_url,
+ auth=BearerTokenAuth(token=self.token),
+ headers={"X-Version": API_VERSION},
+ allowed_hosts=[],
+ allow_redirects=False,
+ request_timeout=60,
+ )
+ try:
+ next(
+ client.paginate(
+ path=ENDPOINTS["devices"],
+ params={"size": 1, "fields": "id"},
+ paginator=SinglePagePaginator(),
+ data_selector="items",
+ data_selector_required=True,
+ )
+ )
+ except HTTPError as error:
+ if error.response is not None and error.response.status_code in (401, 403):
+ return False, AUTH_ERROR if error.response.status_code == 401 else PERMISSION_ERROR
+ raise
+ return True, None
+
+ def source_response(
+ self, inputs: SourceInputs, manager: ResumableSourceManager[LogicMonitorResumeConfig]
+ ) -> SourceResponse:
+ if inputs.schema_name not in ENDPOINTS:
+ raise ValueError(f"Unknown LogicMonitor table: {inputs.schema_name}")
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=lambda: self.iter_rows(inputs, manager),
+ primary_keys=PRIMARY_KEYS,
+ sort_mode=None,
+ on_complete=manager.clear_state,
+ )
+
+ def iter_rows(
+ self, inputs: SourceInputs, manager: ResumableSourceManager[LogicMonitorResumeConfig]
+ ) -> Iterator[list[dict[str, Any]]]:
+ saved = manager.load_state() if manager.can_resume() else None
+ sync_end = int(time.time()) + 1
+ state = saved or LogicMonitorResumeConfig(window_end=sync_end, sync_end=sync_end)
+ is_alerts = inputs.schema_name == "alerts"
+ while not state.complete:
+ params: dict[str, Any] = {}
+ if inputs.schema_name in FIELDS:
+ params["fields"] = FIELDS[inputs.schema_name]
+ if is_alerts:
+ params["filter"] = f'cleared:"*",startEpoch>:{state.window_start},startEpoch<{state.window_end}'
+ params["sort"] = "startEpoch"
+ paginator_class = AlertPaginator if is_alerts else OffsetPaginator
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": self.base_url,
+ "auth": {"type": "bearer", "token": self.token},
+ "headers": {"X-Version": API_VERSION},
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": 60,
+ "paginator": paginator_class(limit=PAGE_SIZE, limit_param="size", total_path="total"),
+ },
+ "resources": [
+ {
+ "name": inputs.schema_name,
+ "table_format": "delta",
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": ENDPOINTS[inputs.schema_name],
+ "params": params,
+ "data_selector": "items",
+ "data_selector_required": True,
+ },
+ }
+ ],
+ }
+
+ def save_checkpoint(
+ paginator_state: dict[str, Any] | None, state: LogicMonitorResumeConfig = state
+ ) -> None:
+ if paginator_state is not None:
+ manager.save_state(replace(state, offset=int(paginator_state["offset"])))
+ else:
+ manager.save_state(
+ replace(
+ state,
+ offset=0,
+ window_start=state.window_end,
+ window_end=state.sync_end,
+ complete=not is_alerts or state.window_end >= state.sync_end,
+ )
+ )
+
+ resource = rest_api_resource(
+ config,
+ inputs.team_id,
+ inputs.job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state={"offset": state.offset},
+ )
+ try:
+ yield from resource
+ except AlertWindowTooLarge:
+ if state.window_end - state.window_start <= 1:
+ raise ValueError(DENSE_WINDOW_ERROR) from None
+ # Split before yielding this window so a retry cannot duplicate its rows.
+ state = replace(state, window_end=(state.window_start + state.window_end) // 2, offset=0)
+ manager.save_state(state)
+ manager.safe_point()
+ continue
+ if not is_alerts or state.window_end >= state.sync_end:
+ break
+ state = replace(state, window_start=state.window_end, window_end=state.sync_end, offset=0)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/settings.py
new file mode 100644
index 000000000000..b83a34cad16e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/settings.py
@@ -0,0 +1,22 @@
+API_VERSION = "3"
+API_DOCS_URL = "https://www.logicmonitor.com/support/rest-api-v3-swagger-documentation"
+PAGE_SIZE = 1000
+MAX_ALERTS_PER_WINDOW = 10000
+
+ENDPOINTS: dict[str, str] = {
+ "alerts": "alert/alerts",
+ "devices": "device/devices",
+ "device_groups": "device/groups",
+ "collectors": "setting/collector/collectors",
+ "sdts": "sdt/sdts",
+ "websites": "website/websites",
+}
+
+# Select inventory fields because device properties and collector configuration can contain credentials.
+FIELDS: dict[str, str] = {
+ "devices": "id,name,displayName,description,createdOn,updatedOn,preferredCollectorId,hostGroupIds,disableAlerting",
+ "device_groups": "id,name,description,fullPath,parentId,createdOn,disableAlerting",
+ "collectors": "id,hostname,description,createdOn,updatedOn,collectorGroupId,numberOfHosts,isDown,build",
+ "websites": "id,name,description,type,overallAlertLevel,disableAlerting",
+}
+PRIMARY_KEYS = ["id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/source.py
index d101b349b872..4f50f18a28df 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/source.py
@@ -1,27 +1,140 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.logicmonitor import (
LogicmonitorSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.logicmonitor import (
+ AUTH_ERROR,
+ DENSE_WINDOW_ERROR,
+ PERMISSION_ERROR,
+ LogicMonitorClient,
+ LogicMonitorResumeConfig,
+ validate_portal_host,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.settings import (
+ API_DOCS_URL,
+ API_VERSION,
+ ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class LogicmonitorSource(SimpleSource[LogicmonitorSourceConfig]):
+class LogicmonitorSource(ResumableSource[LogicmonitorSourceConfig, LogicMonitorResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = API_DOCS_URL
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LOGICMONITOR
+ @property
+ def connection_host_fields(self) -> list[str]:
+ return ["portal_url"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": PERMISSION_ERROR,
+ DENSE_WINDOW_ERROR: DENSE_WINDOW_ERROR,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: LogicmonitorSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ # A start-time watermark misses later acknowledgments and clear events for older alerts.
+ return build_endpoint_schemas(ENDPOINTS, {}, names)
+
+ def validate_credentials(
+ self,
+ config: LogicmonitorSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ valid, error = validate_portal_host(config.portal_url, team_id)
+ if not valid:
+ return False, error
+ return LogicMonitorClient(config).validate_credentials()
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LogicMonitorResumeConfig]:
+ return ResumableSourceManager(inputs, LogicMonitorResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: LogicmonitorSourceConfig,
+ resumable_source_manager: ResumableSourceManager[LogicMonitorResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ valid, error = validate_portal_host(config.portal_url, inputs.team_id)
+ if not valid:
+ raise ValueError(error)
+ return LogicMonitorClient(config).source_response(inputs, resumable_source_manager)
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.LOGICMONITOR,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="LogicMonitor",
+ caption=(
+ "Create a bearer token in Settings > Users & Roles > API Tokens > Bearer. "
+ "Give its user view access to Resources, Dashboards, Collectors, and Websites for the tables you select. "
+ "Alerts use full refresh to capture acknowledgments and cleared status."
+ ),
iconPath="/static/services/logicmonitor.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="portal_url",
+ label="Portal URL",
+ type=SourceFieldInputConfigType.TEXT,
+ placeholder="https://example.logicmonitor.com",
+ required=True,
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="bearer_token",
+ label="Bearer token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ placeholder="",
+ required=True,
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/tests/test_logicmonitor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/tests/test_logicmonitor.py
new file mode 100644
index 000000000000..b910a7a0b677
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/tests/test_logicmonitor.py
@@ -0,0 +1,264 @@
+from collections.abc import Iterable
+from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests_mock
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.logicmonitor import (
+ LogicmonitorSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.logicmonitor import (
+ AUTH_ERROR,
+ PERMISSION_ERROR,
+ LogicMonitorClient,
+ LogicMonitorResumeConfig,
+ portal_url,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.source import LogicmonitorSource
+
+BASE = "https://example.logicmonitor.com/santaba/rest/"
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.logicmonitor"
+
+
+def config() -> LogicmonitorSourceConfig:
+ return LogicmonitorSourceConfig(portal_url="https://example.logicmonitor.com", bearer_token="fake-bearer-token")
+
+
+def inputs(table: str) -> SourceInputs:
+ return SourceInputs(
+ schema_name=table,
+ schema_id="test-schema",
+ source_id="test-source",
+ team_id=1,
+ job_id="test-job",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=999,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+def manager() -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ return manager
+
+
+def rows(client: LogicMonitorClient, table: str, manager: MagicMock) -> list[dict[str, Any]]:
+ response = client.source_response(inputs(table), manager)
+ return [row for page in cast(Iterable[list[dict[str, Any]]], response.items()) for row in page]
+
+
+ ("table", "path"),
+ [
+ ("devices", "device/devices"),
+ ("device_groups", "device/groups"),
+ ("collectors", "setting/collector/collectors"),
+ ("sdts", "sdt/sdts"),
+ ("websites", "website/websites"),
+ ],
+)
[email protected]("resume_offset", [0, 1000])
+def test_pagination_auth_and_resume(manager: MagicMock, table: str, path: str, resume_offset: int) -> None:
+ if resume_offset:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = LogicMonitorResumeConfig(offset=resume_offset)
+ first = [{"id": i} for i in range(resume_offset, resume_offset + 1000)]
+ last = {"id": resume_offset + 1000}
+ total = resume_offset + 1001
+ with requests_mock.Mocker() as http:
+ http.get(BASE + path, [{"json": {"items": first, "total": total}}, {"json": {"items": [last], "total": total}}])
+ assert rows(LogicMonitorClient(config()), table, manager) == [*first, last]
+ assert [request.qs["offset"] for request in http.request_history] == [
+ [str(resume_offset)],
+ [str(resume_offset + 1000)],
+ ]
+ for request in http.request_history:
+ assert request.headers["Authorization"] == "Bearer fake-bearer-token"
+ assert request.headers["X-Version"] == "3"
+ assert request.qs["size"] == ["1000"]
+ assert "filter" not in request.qs
+ assert request.timeout == 60
+ if table == "collectors":
+ assert "bearertoken" not in http.request_history[0].qs["fields"][0]
+ assert "config" not in http.request_history[0].qs["fields"][0]
+ assert manager.save_state.call_args_list[0].args[0].offset == resume_offset + 1000
+ assert manager.save_state.call_args.args[0].complete
+ manager.clear_state.assert_not_called()
+ response = LogicMonitorClient(config()).source_response(inputs(table), manager)
+ assert response.on_complete is not None
+ response.on_complete()
+ manager.clear_state.assert_called_once()
+
+
[email protected]("count", [0, 1, 1000])
+def test_terminal_page(manager: MagicMock, count: int) -> None:
+ data = [{"id": i} for i in range(count)]
+ with requests_mock.Mocker() as http:
+ http.get(BASE + "device/devices", json={"items": data, "total": count})
+ assert rows(LogicMonitorClient(config()), "devices", manager) == data
+ assert http.call_count == 1
+
+
+def test_alert_windows_split_and_keep_both_statuses(manager: MagicMock) -> None:
+ with requests_mock.Mocker() as http, patch(f"{MODULE}.time.time", return_value=7):
+ http.get(
+ BASE + "alert/alerts",
+ [
+ {"json": {"items": [{"id": "must-not-yield"}], "total": 10001}},
+ {"json": {"items": [{"id": "early", "startEpoch": 3, "cleared": False}], "total": 1}},
+ {"json": {"items": [{"id": "later", "startEpoch": 4, "cleared": True}], "total": 1}},
+ ],
+ )
+ assert [row["id"] for row in rows(LogicMonitorClient(config()), "alerts", manager)] == ["early", "later"]
+ params = [parse_qs(urlsplit(request.url).query) for request in http.request_history]
+ assert [p["filter"] for p in params] == [
+ ['cleared:"*",startEpoch>:0,startEpoch<8'],
+ ['cleared:"*",startEpoch>:0,startEpoch<4'],
+ ['cleared:"*",startEpoch>:4,startEpoch<8'],
+ ]
+ assert all(p["sort"] == ["startEpoch"] and p["offset"] == ["0"] for p in params)
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved[0] == LogicMonitorResumeConfig(window_start=0, window_end=4, sync_end=8)
+ assert saved[1] == LogicMonitorResumeConfig(window_start=4, window_end=8, sync_end=8)
+ assert saved[2].complete
+ manager.safe_point.assert_called_once()
+
+
[email protected]("complete", [False, True])
+def test_alert_resume_preserves_window_and_offset(manager: MagicMock, complete: bool) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = LogicMonitorResumeConfig(
+ window_start=4, window_end=8, sync_end=8, offset=1000, complete=complete
+ )
+ with requests_mock.Mocker() as http:
+ http.get(BASE + "alert/alerts", json={"items": [{"id": "remaining"}], "total": 1001})
+ result = rows(LogicMonitorClient(config()), "alerts", manager)
+ assert result == ([] if complete else [{"id": "remaining"}])
+ assert http.call_count == (0 if complete else 1)
+ if not complete:
+ params = parse_qs(urlsplit(http.last_request.url).query)
+ assert params["offset"] == ["1000"]
+ assert params["filter"] == ['cleared:"*",startEpoch>:4,startEpoch<8']
+
+
[email protected]("total", [10000, 10001, None, -1])
+def test_alert_single_second_limit(manager: MagicMock, total: int | None) -> None:
+ with requests_mock.Mocker() as http, patch(f"{MODULE}.time.time", return_value=0):
+ if total == 10000:
+ http.get(
+ BASE + "alert/alerts",
+ [
+ {"json": {"items": [{"id": i} for i in range(offset, offset + 1000)], "total": total}}
+ for offset in range(0, total, 1000)
+ ],
+ )
+ result = rows(LogicMonitorClient(config()), "alerts", manager)
+ assert [row["id"] for row in result] == list(range(total))
+ assert http.call_count == 10
+ assert http.last_request.qs["offset"] == ["9000"]
+ else:
+ http.get(BASE + "alert/alerts", json={"items": [], "total": total})
+ with pytest.raises(ValueError, match="too many alerts" if total == 10001 else "valid alert count"):
+ rows(LogicMonitorClient(config()), "alerts", manager)
+ assert http.call_count == 1
+
+
+def test_alert_growth_after_a_page_fails_without_replaying(manager: MagicMock) -> None:
+ with requests_mock.Mocker() as http, patch(f"{MODULE}.time.time", return_value=100):
+ http.get(
+ BASE + "alert/alerts",
+ [
+ {"json": {"items": [{"id": i} for i in range(1000)], "total": 10000}},
+ {"json": {"items": [{"id": "extra"}], "total": 10001}},
+ ],
+ )
+ with pytest.raises(ValueError, match="counts changed"):
+ rows(LogicMonitorClient(config()), "alerts", manager)
+ assert http.call_count == 2
+
+
[email protected]("status", [401, 403, 404])
+def test_error_mapping(manager: MagicMock, status: int) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(BASE + "device/devices", status_code=status, json={"errorCode": status, "errorMessage": "fake error"})
+ client = LogicMonitorClient(config())
+ if status in (401, 403):
+ assert client.validate_credentials() == (False, AUTH_ERROR if status == 401 else PERMISSION_ERROR)
+ else:
+ with pytest.raises(HTTPError):
+ client.validate_credentials()
+ with pytest.raises(HTTPError) as error:
+ rows(client, "devices", manager)
+ if status in (401, 403):
+ assert any(pattern in str(error.value) for pattern in LogicmonitorSource().get_non_retryable_errors())
+ assert http.call_count == 2
+
+
+def test_credential_probe_uses_one_small_request() -> None:
+ with requests_mock.Mocker() as http:
+ http.get(BASE + "device/devices", json={"items": [], "total": 0})
+ assert LogicMonitorClient(config()).validate_credentials() == (True, None)
+ assert http.call_count == 1
+ assert http.last_request.qs == {"size": ["1"], "fields": ["id"]}
+ assert http.last_request.headers["Authorization"] == "Bearer fake-bearer-token"
+ assert http.last_request.headers["X-Version"] == "3"
+
+
[email protected]("body", [{}, {"errorCode": 1000}, {"data": {"items": []}}])
+def test_malformed_success_fails(manager: MagicMock, body: dict[str, Any]) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(BASE + "device/devices", json=body)
+ with pytest.raises(ValueError, match="data_selector"):
+ rows(LogicMonitorClient(config()), "devices", manager)
+
+
+def test_redirect_does_not_receive_token(manager: MagicMock) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(BASE + "device/devices", status_code=302, headers={"Location": "https://example.com/"})
+ with pytest.raises(ValueError, match="redirect"):
+ rows(LogicMonitorClient(config()), "devices", manager)
+ assert http.call_count == 1
+
+
+ "value",
+ [
+ "http://example.logicmonitor.com",
+ "https://localhost",
+ "https://127.0.0.1",
+ "https://example.logicmonitor.com.example.com",
+ "https://example.com",
+ "https://[email protected]",
+ "https://example.logicmonitor.com:444",
+ "https://example.logicmonitor.com/path",
+ "https://example.logicmonitor.com?a=1",
+ "https://example.logicmonitor.com#fragment",
+ "https://example.logicmonitor.com:invalid",
+ "https://-example.logicmonitor.com",
+ "https://example-.logicmonitor.com",
+ ],
+)
+def test_reject_invalid_portal(value: str) -> None:
+ with pytest.raises(ValueError, match="HTTPS LogicMonitor"):
+ portal_url(value)
+
+
+def test_normalize_portal() -> None:
+ assert portal_url(" https://EXAMPLE.logicmonitor.com:443/ ") == "https://example.logicmonitor.com"
+
+
+def test_unknown_table(manager: MagicMock) -> None:
+ with pytest.raises(ValueError, match="Unknown LogicMonitor table"):
+ LogicMonitorClient(config()).source_response(inputs("unknown"), manager)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/tests/test_logicmonitor_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/tests/test_logicmonitor_source.py
new file mode 100644
index 000000000000..41b32eda7980
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/logicmonitor/tests/test_logicmonitor_source.py
@@ -0,0 +1,46 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.logicmonitor import (
+ LogicmonitorSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.logicmonitor import (
+ validate_portal_host,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.source import LogicmonitorSource
+
+HOST_CHECK = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.ValidateDatabaseHostMixin.is_database_host_valid"
+CLIENT = "products.warehouse_sources.backend.temporal.data_imports.sources.logicmonitor.source.LogicMonitorClient"
+
+
[email protected]("valid", [True, False])
+def test_host_check_controls_credential_probe(valid: bool) -> None:
+ config = LogicmonitorSourceConfig(portal_url="https://example.logicmonitor.com", bearer_token="fake-token")
+ with (
+ patch(HOST_CHECK, return_value=(valid, None if valid else "Host is private")) as check,
+ patch(CLIENT) as client,
+ ):
+ client.return_value.validate_credentials.return_value = (True, None)
+ assert LogicmonitorSource().validate_credentials(config, 42) == (
+ (True, None) if valid else (False, "Host is private")
+ )
+ check.assert_called_once_with("example.logicmonitor.com", 42)
+ assert client.call_count == int(valid)
+
+
+def test_invalid_portal_fails_before_dns() -> None:
+ with patch(HOST_CHECK) as check:
+ valid, error = validate_portal_host("http://localhost", 42)
+ assert not valid
+ assert error and "HTTPS LogicMonitor" in error
+ check.assert_not_called()
+
+
+def test_pipeline_rechecks_host() -> None:
+ config = LogicmonitorSourceConfig(portal_url="https://example.logicmonitor.com", bearer_token="fake-token")
+ inputs = MagicMock(team_id=42)
+ with patch(HOST_CHECK, return_value=(False, "Host is private")) as check, patch(CLIENT) as client:
+ with pytest.raises(ValueError, match="Host is private"):
+ LogicmonitorSource().source_for_pipeline(config, MagicMock(), inputs)
+ check.assert_called_once_with("example.logicmonitor.com", 42)
+ client.assert_not_called()