azure-kusto-data 5.0.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- azure/kusto/__init__.py +4 -0
- azure/kusto/data/__init__.py +15 -0
- azure/kusto/data/_cloud_settings.py +118 -0
- azure/kusto/data/_converters.py +32 -0
- azure/kusto/data/_decorators.py +14 -0
- azure/kusto/data/_models.py +213 -0
- azure/kusto/data/_string_utils.py +3 -0
- azure/kusto/data/_telemetry.py +127 -0
- azure/kusto/data/_token_providers.py +736 -0
- azure/kusto/data/_version.py +3 -0
- azure/kusto/data/aio/__init__.py +1 -0
- azure/kusto/data/aio/_models.py +19 -0
- azure/kusto/data/aio/client.py +228 -0
- azure/kusto/data/aio/response.py +93 -0
- azure/kusto/data/aio/streaming_response.py +234 -0
- azure/kusto/data/client.py +364 -0
- azure/kusto/data/client_base.py +260 -0
- azure/kusto/data/client_details.py +96 -0
- azure/kusto/data/client_request_properties.py +60 -0
- azure/kusto/data/data_format.py +42 -0
- azure/kusto/data/env_utils.py +62 -0
- azure/kusto/data/exceptions.py +216 -0
- azure/kusto/data/helpers.py +155 -0
- azure/kusto/data/kcsb.json +219 -0
- azure/kusto/data/kcsb.py +650 -0
- azure/kusto/data/kusto_trusted_endpoints.py +106 -0
- azure/kusto/data/py.typed +0 -0
- azure/kusto/data/response.py +236 -0
- azure/kusto/data/security.py +128 -0
- azure/kusto/data/streaming_response.py +273 -0
- azure/kusto/data/wellKnownKustoEndpoints.json +109 -0
- azure_kusto_data-5.0.5-py3.8-nspkg.pth +1 -0
- azure_kusto_data-5.0.5.dist-info/METADATA +117 -0
- azure_kusto_data-5.0.5.dist-info/RECORD +37 -0
- azure_kusto_data-5.0.5.dist-info/WHEEL +6 -0
- azure_kusto_data-5.0.5.dist-info/namespace_packages.txt +1 -0
- azure_kusto_data-5.0.5.dist-info/top_level.txt +1 -0
azure/kusto/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Copyright (c) Microsoft Corporation.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
from ._version import VERSION as __version__
|
|
5
|
+
from .client import KustoClient
|
|
6
|
+
from .client_request_properties import ClientRequestProperties
|
|
7
|
+
from .kcsb import KustoConnectionStringBuilder
|
|
8
|
+
from .data_format import DataFormat
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"KustoClient",
|
|
12
|
+
"ClientRequestProperties",
|
|
13
|
+
"KustoConnectionStringBuilder",
|
|
14
|
+
"DataFormat",
|
|
15
|
+
]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import dataclasses
|
|
2
|
+
from threading import Lock
|
|
3
|
+
from typing import Optional, Dict
|
|
4
|
+
from urllib.parse import urlparse
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from azure.core.tracing.decorator import distributed_trace
|
|
9
|
+
from azure.core.tracing import SpanKind
|
|
10
|
+
|
|
11
|
+
from .env_utils import get_env
|
|
12
|
+
from ._telemetry import Span, MonitoredActivity
|
|
13
|
+
from .exceptions import KustoServiceError, KustoNetworkError
|
|
14
|
+
|
|
15
|
+
METADATA_ENDPOINT = "v1/rest/auth/metadata"
|
|
16
|
+
|
|
17
|
+
DEFAULT_AUTH_ENV_VAR_NAME = "AadAuthorityUri"
|
|
18
|
+
DEFAULT_KUSTO_CLIENT_APP_ID = "db662dc1-0cfe-4e1c-a843-19a68e65be58"
|
|
19
|
+
DEFAULT_PUBLIC_LOGIN_URL = "https://login.microsoftonline.com"
|
|
20
|
+
DEFAULT_REDIRECT_URI = "http://localhost"
|
|
21
|
+
DEFAULT_KUSTO_SERVICE_RESOURCE_ID = "https://kusto.kusto.windows.net"
|
|
22
|
+
DEFAULT_DEV_KUSTO_SERVICE_RESOURCE_ID = "https://kusto.dev.kusto.windows.net"
|
|
23
|
+
DEFAULT_FIRST_PARTY_AUTHORITY_URL = "https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclasses.dataclass
|
|
27
|
+
class CloudInfo:
|
|
28
|
+
"""This class holds the data for a specific cloud instance."""
|
|
29
|
+
|
|
30
|
+
login_endpoint: str
|
|
31
|
+
login_mfa_required: bool
|
|
32
|
+
kusto_client_app_id: str
|
|
33
|
+
kusto_client_redirect_uri: str
|
|
34
|
+
kusto_service_resource_id: str
|
|
35
|
+
first_party_authority_url: str
|
|
36
|
+
|
|
37
|
+
def authority_uri(self, authority_id: Optional[str]):
|
|
38
|
+
return self.login_endpoint + "/" + (authority_id or "organizations")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class CloudSettings:
|
|
42
|
+
"""This class holds data for all cloud instances, and returns the specific data instance by parsing the dns suffix from a URL"""
|
|
43
|
+
|
|
44
|
+
_cloud_info = None
|
|
45
|
+
_cloud_cache = {}
|
|
46
|
+
_cloud_cache_lock = Lock()
|
|
47
|
+
|
|
48
|
+
DEFAULT_CLOUD = CloudInfo(
|
|
49
|
+
login_endpoint=get_env(DEFAULT_AUTH_ENV_VAR_NAME, default=DEFAULT_PUBLIC_LOGIN_URL),
|
|
50
|
+
login_mfa_required=False,
|
|
51
|
+
kusto_client_app_id=DEFAULT_KUSTO_CLIENT_APP_ID,
|
|
52
|
+
kusto_client_redirect_uri=DEFAULT_REDIRECT_URI,
|
|
53
|
+
kusto_service_resource_id=DEFAULT_KUSTO_SERVICE_RESOURCE_ID,
|
|
54
|
+
first_party_authority_url=DEFAULT_FIRST_PARTY_AUTHORITY_URL,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
@distributed_trace(name_of_span="CloudSettings.get_cloud_info", kind=SpanKind.CLIENT)
|
|
59
|
+
def get_cloud_info_for_cluster(cls, kusto_uri: str, proxies: Optional[Dict[str, str]] = None, session: requests.Session = None) -> CloudInfo:
|
|
60
|
+
normalized_authority = cls._normalize_uri(kusto_uri)
|
|
61
|
+
|
|
62
|
+
# tracing attributes for cloud info
|
|
63
|
+
Span.set_cloud_info_attributes(kusto_uri)
|
|
64
|
+
|
|
65
|
+
if normalized_authority in cls._cloud_cache: # Double-checked locking to avoid unnecessary lock access
|
|
66
|
+
return cls._cloud_cache[normalized_authority]
|
|
67
|
+
|
|
68
|
+
with cls._cloud_cache_lock:
|
|
69
|
+
if normalized_authority in cls._cloud_cache:
|
|
70
|
+
return cls._cloud_cache[normalized_authority]
|
|
71
|
+
|
|
72
|
+
url_parts = urlparse(kusto_uri)
|
|
73
|
+
url = f"{url_parts.scheme}://{url_parts.netloc}/{METADATA_ENDPOINT}"
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
# trace http get call for result
|
|
77
|
+
result = MonitoredActivity.invoke(
|
|
78
|
+
lambda: (session or requests).get(url, proxies=proxies, allow_redirects=False),
|
|
79
|
+
name_of_span="CloudSettings.http_get",
|
|
80
|
+
tracing_attributes=Span.create_http_attributes(url=url, method="GET"),
|
|
81
|
+
)
|
|
82
|
+
except Exception as e:
|
|
83
|
+
raise KustoNetworkError(url) from e
|
|
84
|
+
|
|
85
|
+
if result.status_code == 200:
|
|
86
|
+
content = result.json()
|
|
87
|
+
if content is None or content == {}:
|
|
88
|
+
raise KustoServiceError("Kusto returned an invalid cloud metadata response", result)
|
|
89
|
+
root = content["AzureAD"]
|
|
90
|
+
if root is not None:
|
|
91
|
+
cls._cloud_cache[normalized_authority] = CloudInfo(
|
|
92
|
+
login_endpoint=root["LoginEndpoint"],
|
|
93
|
+
login_mfa_required=root["LoginMfaRequired"],
|
|
94
|
+
kusto_client_app_id=root["KustoClientAppId"],
|
|
95
|
+
kusto_client_redirect_uri=root["KustoClientRedirectUri"],
|
|
96
|
+
kusto_service_resource_id=root["KustoServiceResourceId"],
|
|
97
|
+
first_party_authority_url=root["FirstPartyAuthorityUrl"],
|
|
98
|
+
)
|
|
99
|
+
else:
|
|
100
|
+
cls._cloud_cache[normalized_authority] = cls.DEFAULT_CLOUD
|
|
101
|
+
elif result.status_code == 404:
|
|
102
|
+
# For now as long not all proxies implement the metadata endpoint, if no endpoint exists return public cloud data
|
|
103
|
+
cls._cloud_cache[normalized_authority] = cls.DEFAULT_CLOUD
|
|
104
|
+
else:
|
|
105
|
+
raise KustoServiceError("Kusto returned an invalid cloud metadata response", result)
|
|
106
|
+
return cls._cloud_cache[normalized_authority]
|
|
107
|
+
|
|
108
|
+
@classmethod
|
|
109
|
+
def add_to_cache(cls, url: str, cloud_info: CloudInfo):
|
|
110
|
+
with cls._cloud_cache_lock:
|
|
111
|
+
cls._cloud_cache[cls._normalize_uri(url)] = cloud_info
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def _normalize_uri(cls, kusto_uri):
|
|
115
|
+
"""Extracts and returns the authority part of the URI (schema, host, port)"""
|
|
116
|
+
url_parts = urlparse(kusto_uri)
|
|
117
|
+
# Return only the scheme and netloc (which contains host and port if present)
|
|
118
|
+
return f"{url_parts.scheme}://{url_parts.netloc}"
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Copyright (c) Microsoft Corporation.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from datetime import timedelta
|
|
6
|
+
|
|
7
|
+
from dateutil import parser
|
|
8
|
+
|
|
9
|
+
# Regex for TimeSpan
|
|
10
|
+
_TIMESPAN_PATTERN = re.compile(r"(-?)((?P<d>[0-9]*).)?(?P<h>[0-9]{2}):(?P<m>[0-9]{2}):(?P<s>[0-9]{2}(\.[0-9]+)?$)")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def to_datetime(value):
|
|
14
|
+
"""Converts a string to a datetime."""
|
|
15
|
+
if isinstance(value, int):
|
|
16
|
+
return parser.parse(value)
|
|
17
|
+
return parser.isoparse(value)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def to_timedelta(value):
|
|
21
|
+
"""Converts a string to a timedelta."""
|
|
22
|
+
if isinstance(value, (int, float)):
|
|
23
|
+
return timedelta(microseconds=(float(value) / 10))
|
|
24
|
+
match = _TIMESPAN_PATTERN.match(value)
|
|
25
|
+
if match:
|
|
26
|
+
if match.group(1) == "-":
|
|
27
|
+
factor = -1
|
|
28
|
+
else:
|
|
29
|
+
factor = 1
|
|
30
|
+
return factor * timedelta(days=int(match.group("d") or 0), hours=int(match.group("h")), minutes=int(match.group("m")), seconds=float(match.group("s")))
|
|
31
|
+
else:
|
|
32
|
+
raise ValueError("Timespan value '{}' cannot be decoded".format(value))
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
def aio_documented_by(original):
|
|
2
|
+
def wrapper(target):
|
|
3
|
+
target.__doc__ = "Aio function: {original_doc}".format(original_doc=original.__doc__)
|
|
4
|
+
return target
|
|
5
|
+
|
|
6
|
+
return wrapper
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def documented_by(original):
|
|
10
|
+
def wrapper(target):
|
|
11
|
+
target.__doc__ = original.__doc__
|
|
12
|
+
return target
|
|
13
|
+
|
|
14
|
+
return wrapper
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# Copyright (c) Microsoft Corporation.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from abc import ABCMeta, abstractmethod
|
|
6
|
+
from decimal import Decimal
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from typing import Iterator, List, Any, Union, Optional, Dict
|
|
9
|
+
|
|
10
|
+
from . import _converters
|
|
11
|
+
from .exceptions import KustoMultiApiError, KustoStreamingQueryError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class WellKnownDataSet(str, Enum):
|
|
15
|
+
"""Categorizes data tables according to the role they play in the data set that a Kusto query returns."""
|
|
16
|
+
|
|
17
|
+
PrimaryResult = "PrimaryResult"
|
|
18
|
+
QueryCompletionInformation = "QueryCompletionInformation"
|
|
19
|
+
TableOfContents = "TableOfContents"
|
|
20
|
+
QueryProperties = "QueryProperties"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class KustoResultRow:
|
|
24
|
+
"""Iterator over a Kusto result row."""
|
|
25
|
+
|
|
26
|
+
conversion_funcs = {"datetime": _converters.to_datetime, "timespan": _converters.to_timedelta, "decimal": Decimal}
|
|
27
|
+
|
|
28
|
+
def __init__(self, columns: "List[KustoResultColumn]", row: list):
|
|
29
|
+
self._value_by_name = {}
|
|
30
|
+
self._value_by_index = []
|
|
31
|
+
|
|
32
|
+
for i, value in enumerate(row):
|
|
33
|
+
column = columns[i]
|
|
34
|
+
try:
|
|
35
|
+
column_type = column.column_type.lower()
|
|
36
|
+
except AttributeError:
|
|
37
|
+
self._value_by_index.append(value)
|
|
38
|
+
self._value_by_name[columns[i]] = value
|
|
39
|
+
continue
|
|
40
|
+
|
|
41
|
+
# If you are here to read this, you probably hit some datetime/timedelta inconsistencies.
|
|
42
|
+
# Azure-Data-Explorer(Kusto) supports 7 decimal digits, while the corresponding python types supports only 6.
|
|
43
|
+
# One example why one might want this precision, is when working with pandas.
|
|
44
|
+
# In that case, use azure.kusto.data.helpers.dataframe_from_result_table which takes into account the original value.
|
|
45
|
+
typed_value = self.get_typed_value(column_type, value)
|
|
46
|
+
|
|
47
|
+
self._value_by_index.append(typed_value)
|
|
48
|
+
self._value_by_name[column.column_name] = typed_value
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def get_typed_value(column_type: str, value: Any) -> Any:
|
|
52
|
+
return KustoResultRow.conversion_funcs[column_type](value) if value is not None and column_type in KustoResultRow.conversion_funcs else value
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def columns_count(self) -> int:
|
|
56
|
+
return len(self._value_by_name)
|
|
57
|
+
|
|
58
|
+
def __iter__(self) -> Iterator[Any]:
|
|
59
|
+
for i in range(self.columns_count):
|
|
60
|
+
yield self[i]
|
|
61
|
+
|
|
62
|
+
def __getitem__(self, key: Union[str, int]) -> Any:
|
|
63
|
+
if isinstance(key, int):
|
|
64
|
+
return self._value_by_index[key]
|
|
65
|
+
return self._value_by_name[key]
|
|
66
|
+
|
|
67
|
+
def __len__(self) -> int:
|
|
68
|
+
return self.columns_count
|
|
69
|
+
|
|
70
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
71
|
+
return self._value_by_name
|
|
72
|
+
|
|
73
|
+
def to_list(self) -> list:
|
|
74
|
+
return self._value_by_index
|
|
75
|
+
|
|
76
|
+
def __str__(self) -> str:
|
|
77
|
+
return "['{}']".format("', '".join([str(val) for val in self._value_by_index]))
|
|
78
|
+
|
|
79
|
+
def __repr__(self) -> str:
|
|
80
|
+
values = [repr(val) for val in self._value_by_name.values()]
|
|
81
|
+
return "KustoResultRow(['{}'], [{}])".format("', '".join(self._value_by_name), ", ".join(values))
|
|
82
|
+
|
|
83
|
+
def __eq__(self, other) -> bool:
|
|
84
|
+
if len(self) != len(other):
|
|
85
|
+
return False
|
|
86
|
+
for value_index, value in enumerate(self):
|
|
87
|
+
if value != other[value_index]:
|
|
88
|
+
return False
|
|
89
|
+
return True
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class KustoResultColumn:
|
|
93
|
+
def __init__(self, json_column: Dict[str, Any], ordinal: int):
|
|
94
|
+
self.column_name = json_column["ColumnName"]
|
|
95
|
+
self.column_type = json_column.get("ColumnType") or json_column["DataType"]
|
|
96
|
+
self.ordinal = ordinal
|
|
97
|
+
|
|
98
|
+
def __repr__(self) -> str:
|
|
99
|
+
return "KustoResultColumn({},{})".format(json.dumps({"ColumnName": self.column_name, "ColumnType": self.column_type}), self.ordinal)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class BaseKustoResultTable(metaclass=ABCMeta):
|
|
103
|
+
def __init__(self, json_table: Dict[str, Any]):
|
|
104
|
+
self.table_name = json_table.get("TableName")
|
|
105
|
+
self.table_id = json_table.get("TableId")
|
|
106
|
+
self.table_kind = WellKnownDataSet[json_table["TableKind"]] if "TableKind" in json_table else None
|
|
107
|
+
self.columns = [KustoResultColumn(column, index) for index, column in enumerate(json_table["Columns"])]
|
|
108
|
+
|
|
109
|
+
self.raw_columns = json_table["Columns"]
|
|
110
|
+
self.raw_rows = json_table["Rows"]
|
|
111
|
+
self.kusto_result_rows = None
|
|
112
|
+
|
|
113
|
+
def __bool__(self) -> bool:
|
|
114
|
+
return any(self.columns)
|
|
115
|
+
|
|
116
|
+
__nonzero__ = __bool__
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def columns_count(self) -> int:
|
|
120
|
+
return len(self.columns)
|
|
121
|
+
|
|
122
|
+
@abstractmethod
|
|
123
|
+
def __len__(self) -> Optional[int]:
|
|
124
|
+
pass
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
@abstractmethod
|
|
128
|
+
def rows_count(self) -> int:
|
|
129
|
+
pass
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class BaseStreamingKustoResultTable(BaseKustoResultTable):
|
|
133
|
+
def __init__(self, json_table: Dict[str, Any]):
|
|
134
|
+
super().__init__(json_table)
|
|
135
|
+
|
|
136
|
+
self.finished = False
|
|
137
|
+
self.row_count = 0
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def rows_count(self) -> int:
|
|
141
|
+
if not self.finished:
|
|
142
|
+
raise KustoStreamingQueryError("Can't retrieve rows count before the iteration is finished")
|
|
143
|
+
return self.row_count
|
|
144
|
+
|
|
145
|
+
def __len__(self) -> Optional[int]:
|
|
146
|
+
if not self.finished:
|
|
147
|
+
return None # We return None here instead of an exception, because otherwise calling list() on the object will throw
|
|
148
|
+
return self.rows_count
|
|
149
|
+
|
|
150
|
+
def iter_rows(self) -> "BaseStreamingKustoResultTable":
|
|
151
|
+
return self
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class KustoResultTable(BaseKustoResultTable):
|
|
155
|
+
"""Iterator over a Kusto result table."""
|
|
156
|
+
|
|
157
|
+
def __init__(self, json_table: Dict[str, Any]):
|
|
158
|
+
super().__init__(json_table)
|
|
159
|
+
errors = [row for row in json_table["Rows"] if isinstance(row, dict)]
|
|
160
|
+
if errors:
|
|
161
|
+
raise KustoMultiApiError(errors)
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def rows(self) -> List[KustoResultRow]:
|
|
165
|
+
if not self.kusto_result_rows:
|
|
166
|
+
self.kusto_result_rows = [KustoResultRow(self.columns, row) for row in self.raw_rows]
|
|
167
|
+
return self.kusto_result_rows
|
|
168
|
+
|
|
169
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
170
|
+
"""Converts the table to a dict."""
|
|
171
|
+
return {"name": self.table_name, "kind": self.table_kind, "data": [r.to_dict() for r in self]}
|
|
172
|
+
|
|
173
|
+
@property
|
|
174
|
+
def rows_count(self) -> int:
|
|
175
|
+
return len(self.raw_rows)
|
|
176
|
+
|
|
177
|
+
def __len__(self) -> int:
|
|
178
|
+
return self.rows_count
|
|
179
|
+
|
|
180
|
+
def __iter__(self) -> Iterator[KustoResultRow]:
|
|
181
|
+
for row_index, row in enumerate(self.raw_rows):
|
|
182
|
+
if self.kusto_result_rows:
|
|
183
|
+
yield self.kusto_result_rows[row_index]
|
|
184
|
+
else:
|
|
185
|
+
yield KustoResultRow(self.columns, row)
|
|
186
|
+
|
|
187
|
+
def __getitem__(self, key: int) -> KustoResultRow:
|
|
188
|
+
return self.rows[key]
|
|
189
|
+
|
|
190
|
+
def __str__(self) -> str:
|
|
191
|
+
d = self.to_dict()
|
|
192
|
+
# enum is not serializable, using value instead
|
|
193
|
+
d["kind"] = d["kind"].value
|
|
194
|
+
return json.dumps(d, default=str)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class KustoStreamingResultTable(BaseStreamingKustoResultTable):
|
|
198
|
+
"""
|
|
199
|
+
Iterator over a Kusto result table in streaming.
|
|
200
|
+
This class can be iterated only once.
|
|
201
|
+
"""
|
|
202
|
+
|
|
203
|
+
def __next__(self) -> KustoResultRow:
|
|
204
|
+
try:
|
|
205
|
+
row = next(self.raw_rows)
|
|
206
|
+
except StopIteration:
|
|
207
|
+
self.finished = True
|
|
208
|
+
raise
|
|
209
|
+
self.row_count += 1
|
|
210
|
+
return KustoResultRow(self.columns, row)
|
|
211
|
+
|
|
212
|
+
def __iter__(self) -> Iterator[KustoResultRow]:
|
|
213
|
+
return self
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
from typing import Callable, Optional, TypeVar
|
|
2
|
+
|
|
3
|
+
from azure.core.settings import settings
|
|
4
|
+
from azure.core.tracing.decorator import distributed_trace
|
|
5
|
+
from azure.core.tracing.decorator_async import distributed_trace_async
|
|
6
|
+
from azure.core.tracing import SpanKind
|
|
7
|
+
|
|
8
|
+
from .client_request_properties import ClientRequestProperties
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Span:
|
|
12
|
+
"""
|
|
13
|
+
Additional ADX attributes for telemetry spans
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
_KUSTO_CLUSTER = "kusto_cluster"
|
|
17
|
+
_DATABASE = "database"
|
|
18
|
+
_TABLE = "table"
|
|
19
|
+
|
|
20
|
+
_AUTH_METHOD = "authentication_method"
|
|
21
|
+
_CLIENT_ACTIVITY_ID = "client_activity_id"
|
|
22
|
+
|
|
23
|
+
_SPAN_COMPONENT = "component"
|
|
24
|
+
_HTTP = "http"
|
|
25
|
+
_HTTP_USER_AGENT = "http.user_agent"
|
|
26
|
+
_HTTP_METHOD = "http.method"
|
|
27
|
+
_HTTP_URL = "http.url"
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def add_attributes(cls, **kwargs) -> None:
|
|
31
|
+
"""
|
|
32
|
+
Add ADX attributes to the current span
|
|
33
|
+
:key dict tracing_attributes: key, val ADX attributes to include in span of trace
|
|
34
|
+
"""
|
|
35
|
+
tracing_attributes: dict = kwargs.pop("tracing_attributes", {})
|
|
36
|
+
span_impl_type = settings.tracing_implementation()
|
|
37
|
+
if span_impl_type is None:
|
|
38
|
+
return
|
|
39
|
+
current_span = span_impl_type.get_current_span()
|
|
40
|
+
span = span_impl_type(span=current_span)
|
|
41
|
+
for key, val in tracing_attributes.items():
|
|
42
|
+
span.add_attribute(key, val)
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def set_query_attributes(cls, cluster: str, database: str, properties: Optional[ClientRequestProperties] = None) -> None:
|
|
46
|
+
query_attributes: dict = cls.create_query_attributes(cluster, database, properties)
|
|
47
|
+
cls.add_attributes(tracing_attributes=query_attributes)
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def set_streaming_ingest_attributes(cls, cluster: str, database: str, table: str, properties: Optional[ClientRequestProperties] = None) -> None:
|
|
51
|
+
ingest_attributes: dict = cls.create_streaming_ingest_attributes(cluster, database, table, properties)
|
|
52
|
+
cls.add_attributes(tracing_attributes=ingest_attributes)
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def set_cloud_info_attributes(cls, url: str) -> None:
|
|
56
|
+
cloud_info_attributes: dict = cls.create_cloud_info_attributes(url)
|
|
57
|
+
cls.add_attributes(tracing_attributes=cloud_info_attributes)
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def create_query_attributes(cls, cluster: str, database: str, properties: Optional[ClientRequestProperties] = None) -> dict:
|
|
61
|
+
query_attributes: dict = {cls._KUSTO_CLUSTER: cluster, cls._DATABASE: database}
|
|
62
|
+
if properties:
|
|
63
|
+
query_attributes.update(properties.get_tracing_attributes())
|
|
64
|
+
|
|
65
|
+
return query_attributes
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def create_streaming_ingest_attributes(cls, cluster: str, database: str, table: str, properties: Optional[ClientRequestProperties] = None) -> dict:
|
|
69
|
+
ingest_attributes: dict = {cls._KUSTO_CLUSTER: cluster, cls._DATABASE: database, cls._TABLE: table}
|
|
70
|
+
if properties:
|
|
71
|
+
ingest_attributes.update(properties.get_tracing_attributes())
|
|
72
|
+
|
|
73
|
+
return ingest_attributes
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def create_http_attributes(cls, method: str, url: str, headers: dict = None) -> dict:
|
|
77
|
+
if headers is None:
|
|
78
|
+
headers = {}
|
|
79
|
+
http_tracing_attributes: dict = {
|
|
80
|
+
cls._SPAN_COMPONENT: cls._HTTP,
|
|
81
|
+
cls._HTTP_METHOD: method,
|
|
82
|
+
cls._HTTP_URL: url,
|
|
83
|
+
}
|
|
84
|
+
user_agent = headers.get("User-Agent")
|
|
85
|
+
if user_agent:
|
|
86
|
+
http_tracing_attributes[cls._HTTP_USER_AGENT] = user_agent
|
|
87
|
+
return http_tracing_attributes
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def create_cloud_info_attributes(cls, url: str) -> dict:
|
|
91
|
+
ingest_attributes: dict = {cls._HTTP_URL: url}
|
|
92
|
+
return ingest_attributes
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def create_cluster_attributes(cls, cluster_uri: str) -> dict:
|
|
96
|
+
cluster_attributes = {cls._KUSTO_CLUSTER: cluster_uri}
|
|
97
|
+
return cluster_attributes
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class MonitoredActivity:
|
|
101
|
+
"""
|
|
102
|
+
Invoker class for telemetry
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
T = TypeVar("T")
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def invoke(invoker: Callable[[], T], name_of_span: str = None, tracing_attributes=None, kind: str = SpanKind.INTERNAL) -> T:
|
|
109
|
+
"""
|
|
110
|
+
Runs the span on given function
|
|
111
|
+
"""
|
|
112
|
+
if tracing_attributes is None:
|
|
113
|
+
tracing_attributes = {}
|
|
114
|
+
span_shell: Callable = distributed_trace(name_of_span=name_of_span, tracing_attributes=tracing_attributes, kind=kind)
|
|
115
|
+
span = span_shell(invoker)
|
|
116
|
+
return span()
|
|
117
|
+
|
|
118
|
+
@staticmethod
|
|
119
|
+
async def invoke_async(invoker: Callable[[], T], name_of_span: str = None, tracing_attributes=None, kind: str = SpanKind.INTERNAL) -> T:
|
|
120
|
+
"""
|
|
121
|
+
Runs a span on given function
|
|
122
|
+
"""
|
|
123
|
+
if tracing_attributes is None:
|
|
124
|
+
tracing_attributes = {}
|
|
125
|
+
span_shell: Callable = distributed_trace_async(name_of_span=name_of_span, tracing_attributes=tracing_attributes, kind=kind)
|
|
126
|
+
span = span_shell(invoker)
|
|
127
|
+
return await span()
|