Skip to content
Open
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
10 changes: 5 additions & 5 deletions azure-kusto-ingest/azure/kusto/ingest/_resource_manager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from typing import List, Dict
from urllib.parse import urlparse

Expand Down Expand Up @@ -85,11 +85,11 @@ def __set_throttling_settings(self, num_of_attempts: int = 4, max_seconds_per_re
def _refresh_ingest_client_resources(self):
if (
not self._ingest_client_resources
or (self._ingest_client_resources_last_update + self._refresh_period) <= datetime.utcnow()
or (self._ingest_client_resources_last_update + self._refresh_period) <= datetime.now(tz=timezone.utc)
or not self._ingest_client_resources.is_applicable()
):
self._ingest_client_resources = self._get_ingest_client_resources_from_service()
self._ingest_client_resources_last_update = datetime.utcnow()
self._ingest_client_resources_last_update = datetime.now(tz=timezone.utc)
self._populate_ranked_storage_account_set()

def _get_resource_by_name(self, table: KustoResultTable, resource_name: str):
Expand Down Expand Up @@ -119,10 +119,10 @@ def _refresh_authorization_context(self):
if (
not self._authorization_context
or self._authorization_context.isspace()
or (self._authorization_context_last_update + self._refresh_period) <= datetime.utcnow()
or (self._authorization_context_last_update + self._refresh_period) <= datetime.now(tz=timezone.utc)
):
self._authorization_context = self._get_authorization_context_from_service()
self._authorization_context_last_update = datetime.utcnow()
self._authorization_context_last_update = datetime.now(tz=timezone.utc)

def _get_authorization_context_from_service(self):
# trace all calls to get identity token
Expand Down
5 changes: 3 additions & 2 deletions azure-kusto-ingest/azure/kusto/ingest/ingestion_blob_info.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License
import json
from datetime import datetime
from datetime import datetime, timezone
from typing import TYPE_CHECKING

if TYPE_CHECKING:
Expand All @@ -28,7 +28,8 @@ def __init__(
self.properties["IgnoreSizeLimit"] = False
self.properties["ReportLevel"] = ingestion_properties.report_level.value
self.properties["ReportMethod"] = ingestion_properties.report_method.value
self.properties["SourceMessageCreationTime"] = datetime.utcnow().isoformat()
# Preserve the legacy timezone-less UTC wire format.
self.properties["SourceMessageCreationTime"] = datetime.now(tz=timezone.utc).replace(tzinfo=None).isoformat()
self.properties["Id"] = str(blob_descriptor.source_id)
self.properties["ApplicationForTracing"] = application_for_tracing
self.properties["ClientVersionForTracing"] = client_version_for_tracing
Expand Down
23 changes: 21 additions & 2 deletions azure-kusto-ingest/tests/test_ingestion_blob_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import json
import re
import unittest
from datetime import datetime, timezone
from unittest.mock import patch
from uuid import UUID

from azure.kusto.data.data_format import DataFormat
Expand All @@ -18,7 +20,7 @@
)
from azure.kusto.ingest.ingestion_blob_info import IngestionBlobInfo

TIMESTAMP_REGEX = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{6}"
TIMESTAMP_REGEX = r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{6})?"


class IngestionBlobInfoTest(unittest.TestCase):
Expand Down Expand Up @@ -110,6 +112,22 @@ def test_blob_json_mapping_reference(self):
blob_info = IngestionBlobInfo(blob, properties, auth_context="authorizationContextText")
self._verify_ingestion_blob_info_result(blob_info.to_json())

def test_source_message_creation_time_preserves_legacy_format(self):
properties = IngestionProperties(database="database", table="table", data_format=DataFormat.CSV)
blob = BlobDescriptor("somepath", 10)

for instant, expected in [
(datetime(2025, 1, 1, tzinfo=timezone.utc), "2025-01-01T00:00:00"),
(datetime(2025, 1, 1, 0, 0, 0, 123456, tzinfo=timezone.utc), "2025-01-01T00:00:00.123456"),
]:
with self.subTest(microsecond=instant.microsecond):
with patch("azure.kusto.ingest.ingestion_blob_info.datetime", wraps=datetime) as mock_datetime:
mock_datetime.now.return_value = instant
timestamp = json.loads(IngestionBlobInfo(blob, properties).to_json())["SourceMessageCreationTime"]
mock_datetime.now.assert_called_once_with(tz=timezone.utc)

assert timestamp == expected

def _verify_ingestion_blob_info_result(self, ingestion_blob_info):
result = json.loads(ingestion_blob_info)
assert result is not None
Expand All @@ -124,7 +142,8 @@ def _verify_ingestion_blob_info_result(self, ingestion_blob_info):
assert isinstance(result["ReportMethod"], int)
assert isinstance(result["ReportLevel"], int)
assert isinstance(UUID(result["Id"]), UUID)
assert re.match(TIMESTAMP_REGEX, result["SourceMessageCreationTime"])
assert re.fullmatch(TIMESTAMP_REGEX, result["SourceMessageCreationTime"])
assert datetime.fromisoformat(result["SourceMessageCreationTime"]).tzinfo is None
assert result["AdditionalProperties"]["authorizationContext"] == "authorizationContextText"
assert result["AdditionalProperties"]["ingestIfNotExists"] == '["ingestIfNotExistTags"]'
assert result["AdditionalProperties"]["ValidationPolicy"] in (
Expand Down
66 changes: 65 additions & 1 deletion azure-kusto-ingest/tests/test_kusto_ingest_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
import json
import os
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import patch
from unittest.mock import call, patch

import pytest
import responses
Expand Down Expand Up @@ -568,6 +569,69 @@ def test_containers(self):
assert containers_selected_with_round_robin[1].storage_account_name == containers_selected_with_round_robin[3].storage_account_name
assert containers_selected_with_round_robin[1].storage_account_name != containers_selected_with_round_robin[2].storage_account_name

@pytest.mark.parametrize(
("elapsed", "expected_fetches"),
[
(timedelta(minutes=59, seconds=59), 1),
(timedelta(hours=1), 2),
(timedelta(hours=1, seconds=1), 2),
],
)
def test_ingestion_resources_cache_refresh(self, elapsed: timedelta, expected_fetches: int) -> None:
container = _resource_manager._ResourceUri(TEMP_STORAGE_URL)
queue = _resource_manager._ResourceUri(STORAGE_QUEUE_URL)
resources = _resource_manager._IngestClientResources(
secured_ready_for_aggregation_queues=[queue],
failed_ingestions_queues=[queue],
successful_ingestions_queues=[queue],
containers=[container],
status_tables=[container],
)
start = datetime(2025, 1, 1, tzinfo=timezone.utc)

with _resource_manager.KustoClient("https://ingest-somecluster.kusto.windows.net") as client:
resource_manager = _resource_manager._ResourceManager(client)
with patch.object(resource_manager, "_get_ingest_client_resources_from_service", return_value=resources) as get_resources:
with patch("azure.kusto.ingest._resource_manager.datetime", wraps=datetime) as mock_datetime:
mock_datetime.now.return_value = start
assert resource_manager.get_containers() == [container]

mock_datetime.now.return_value = start + elapsed
assert resource_manager.get_ingestion_queues() == [queue]
assert resource_manager.get_containers() == [container]
assert mock_datetime.now.call_args_list
assert all(now_call == call(tz=timezone.utc) for now_call in mock_datetime.now.call_args_list)

assert get_resources.call_count == expected_fetches

@pytest.mark.parametrize(
("elapsed", "expected_fetches", "expected_context"),
[
(timedelta(minutes=59, seconds=59), 1, "authorization_context"),
(timedelta(hours=1), 2, "refreshed_authorization_context"),
(timedelta(hours=1, seconds=1), 2, "refreshed_authorization_context"),
],
)
def test_authorization_context_cache_refresh(self, elapsed: timedelta, expected_fetches: int, expected_context: str) -> None:
start = datetime(2025, 1, 1, tzinfo=timezone.utc)

with _resource_manager.KustoClient("https://ingest-somecluster.kusto.windows.net") as client:
resource_manager = _resource_manager._ResourceManager(client)
with patch.object(
resource_manager, "_get_authorization_context_from_service", side_effect=["authorization_context", "refreshed_authorization_context"]
) as get_context:
with patch("azure.kusto.ingest._resource_manager.datetime", wraps=datetime) as mock_datetime:
mock_datetime.now.return_value = start
assert resource_manager.get_authorization_context() == "authorization_context"

mock_datetime.now.return_value = start + elapsed
assert resource_manager.get_authorization_context() == expected_context
assert resource_manager.get_authorization_context() == expected_context
assert mock_datetime.now.call_args_list
assert all(now_call == call(tz=timezone.utc) for now_call in mock_datetime.now.call_args_list)

assert get_context.call_count == expected_fetches

@responses.activate
@patch(
"azure.kusto.ingest.managed_streaming_ingest_client.ManagedStreamingIngestClient.MAX_STREAMING_SIZE_IN_BYTES", new=0
Expand Down