Skip to content

Commit 58f8dc6

Browse files
authored
{Application-insights} Migrate az monitor app-insights data-plane using codegen tool (#8641)
* migrate app-insights data-plane * remove data plane sdk
1 parent 7003ac7 commit 58f8dc6

File tree

130 files changed

+3802
-6122
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

130 files changed

+3802
-6122
lines changed

src/application-insights/HISTORY.rst

+5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
33
Release History
44
===============
5+
2.0.0b1
6+
++++++++++++++++++
7+
* `az monitor app-insights events/metrics/query`: Migrate data-plane using codegen tool
8+
* [Breaking Change] `az monitor app-insights events show`: Response schema key `aimessages` and `odatacontext` changed to `@ai.messages` and `@odata.context` to be consistent with swagger api
9+
510
1.2.3
611
++++++++++++++++++
712
* `az monitor app-insights events/metrics/query`: Fix error: Profile.get_login_credentials() got an unexpected keyword argument 'resource'

src/application-insights/azext_applicationinsights/__init__.py

-2
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,8 @@ class ApplicationInsightsCommandsLoader(AzCommandsLoader):
1212

1313
def __init__(self, cli_ctx=None):
1414
from azure.cli.core.commands import CliCommandType
15-
from azext_applicationinsights._client_factory import applicationinsights_data_plane_client
1615
applicationinsights_custom = CliCommandType(
1716
operations_tmpl='azext_applicationinsights.custom#{}',
18-
client_factory=applicationinsights_data_plane_client
1917
)
2018

2119
super().__init__(

src/application-insights/azext_applicationinsights/_client_factory.py

-47
Original file line numberDiff line numberDiff line change
@@ -3,60 +3,13 @@
33
# Licensed under the MIT License. See License.txt in the project root for license information.
44
# --------------------------------------------------------------------------------------------
55

6-
class _Track1Credential: # pylint: disable=too-few-public-methods
7-
8-
def __init__(self, credential, resource):
9-
"""Track 1 credential that can be fed into Track 1 SDK clients. Exposes signed_session protocol.
10-
:param credential: Track 2 credential that exposes get_token protocol
11-
:param resource: AAD resource
12-
"""
13-
self._credential = credential
14-
self._resource = resource
15-
16-
def signed_session(self, session=None):
17-
import requests
18-
from azure.cli.core.auth.util import resource_to_scopes
19-
session = session or requests.Session()
20-
token = self._credential.get_token(*resource_to_scopes(self._resource))
21-
header = "{} {}".format('Bearer', token.token)
22-
session.headers['Authorization'] = header
23-
return session
24-
25-
26-
def applicationinsights_data_plane_client(cli_ctx, _, subscription=None):
27-
"""Initialize Log Analytics data client for use with CLI."""
28-
from .vendored_sdks.applicationinsights import ApplicationInsightsDataClient
29-
from azure.cli.core._profile import Profile
30-
profile = Profile(cli_ctx=cli_ctx)
31-
# Note: temporarily adapt track2 auth to track1 by the guidance:
32-
# https://github.com/Azure/azure-cli/pull/29631#issuecomment-2716799520
33-
# need to be removed after migrated by codegen
34-
cred, _, _ = profile.get_login_credentials(subscription_id=subscription)
35-
return ApplicationInsightsDataClient(
36-
_Track1Credential(cred, cli_ctx.cloud.endpoints.app_insights_resource_id),
37-
base_url=f'{cli_ctx.cloud.endpoints.app_insights_resource_id}/v1'
38-
)
39-
40-
416
def applicationinsights_mgmt_plane_client(cli_ctx, **kwargs):
427
"""Initialize Log Analytics mgmt client for use with CLI."""
438
from .vendored_sdks.mgmt_applicationinsights import ApplicationInsightsManagementClient
449
from azure.cli.core.commands.client_factory import get_mgmt_service_client
4510
return get_mgmt_service_client(cli_ctx, ApplicationInsightsManagementClient, **kwargs)
4611

4712

48-
def cf_query(cli_ctx, _):
49-
return applicationinsights_data_plane_client(cli_ctx, _).query
50-
51-
52-
def cf_metrics(cli_ctx, _):
53-
return applicationinsights_data_plane_client(cli_ctx, _).metrics
54-
55-
56-
def cf_events(cli_ctx, _):
57-
return applicationinsights_data_plane_client(cli_ctx, _).events
58-
59-
6013
def cf_components(cli_ctx, _):
6114
return applicationinsights_mgmt_plane_client(cli_ctx, api_version='2018-05-01-preview').components
6215

src/application-insights/azext_applicationinsights/_params.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def load_arguments(self, _):
7777
c.argument('offset', help='Filter results based on UTC hour offset.', type=get_period_type(as_timedelta=True))
7878

7979
with self.argument_context('monitor app-insights events show') as c:
80-
from .vendored_sdks.applicationinsights.models import EventType
80+
from .util import EventType
8181
c.argument('event_type', options_list=['--type'], arg_type=get_enum_type(EventType), help='The type of events to retrieve.')
8282
c.argument('event', options_list=['--event'], help='GUID of the event to retrieve. This could be obtained by first listing and filtering events, then selecting an event of interest.')
8383
c.argument('start_time', arg_type=get_datetime_type(help='Start-time of time range for which to retrieve data.'))

src/application-insights/azext_applicationinsights/aaz/latest/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@
88
# pylint: skip-file
99
# flake8: noqa
1010

11+
from ._clients import *
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# --------------------------------------------------------------------------------------------
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License. See License.txt in the project root for license information.
4+
#
5+
# Code generated by aaz-dev-tools
6+
# --------------------------------------------------------------------------------------------
7+
8+
# pylint: skip-file
9+
# flake8: noqa
10+
11+
from azure.cli.core.aaz import *
12+
13+
14+
@register_client("AAZMicrosoftInsightsDataPlaneClient_application_insights")
15+
class AAZMicrosoftInsightsDataPlaneClient(AAZBaseClient):
16+
_CLOUD_HOST_TEMPLATES = {
17+
CloudNameEnum.AzureChinaCloud: "https://api.applicationinsights.azure.cn",
18+
CloudNameEnum.AzureCloud: "https://api.applicationinsights.io",
19+
CloudNameEnum.AzureUSGovernment: "https://api.applicationinsights.us",
20+
}
21+
_CLOUD_HOST_METADATA_INDEX = "appInsightsResourceId"
22+
23+
_AAD_CREDENTIAL_SCOPES = [
24+
"https://api.applicationinsights.io/.default",
25+
]
26+
27+
@classmethod
28+
def _build_base_url(cls, ctx, **kwargs):
29+
endpoint = cls.get_cloud_endpoint(ctx, cls._CLOUD_HOST_METADATA_INDEX)
30+
if not endpoint:
31+
endpoint = cls._CLOUD_HOST_TEMPLATES.get(ctx.cli_ctx.cloud.name, None)
32+
return endpoint
33+
34+
@classmethod
35+
def _build_configuration(cls, ctx, credential, **kwargs):
36+
return AAZClientConfiguration(
37+
credential=credential,
38+
credential_scopes=cls._AAD_CREDENTIAL_SCOPES,
39+
**kwargs
40+
)
41+
42+
43+
class _AAZMicrosoftInsightsDataPlaneClientHelper:
44+
"""Helper class for AAZMicrosoftInsightsDataPlaneClient"""
45+
46+
47+
__all__ = [
48+
"AAZMicrosoftInsightsDataPlaneClient",
49+
]

src/application-insights/azext_applicationinsights/aaz/latest/monitor/app_insights/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,5 @@
1010

1111
from .__cmd_group import *
1212
from ._migrate_to_new_pricing_model import *
13+
from ._query_execute import *
14+
from ._query_show import *
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
# --------------------------------------------------------------------------------------------
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License. See License.txt in the project root for license information.
4+
#
5+
# Code generated by aaz-dev-tools
6+
# --------------------------------------------------------------------------------------------
7+
8+
# pylint: skip-file
9+
# flake8: noqa
10+
11+
from azure.cli.core.aaz import *
12+
13+
14+
class QueryExecute(AAZCommand):
15+
"""Executes an Analytics query for data. Doc https://dev.applicationinsights.io/documentation/Using-the-API/Query is an example for using POST with an Analytics query.
16+
"""
17+
18+
_aaz_info = {
19+
"version": "v1",
20+
"resources": [
21+
["data-plane:microsoft.insights", "/apps/{}/query", "v1"],
22+
]
23+
}
24+
25+
def _handler(self, command_args):
26+
super()._handler(command_args)
27+
self._execute_operations()
28+
return self._output()
29+
30+
_args_schema = None
31+
32+
@classmethod
33+
def _build_arguments_schema(cls, *args, **kwargs):
34+
if cls._args_schema is not None:
35+
return cls._args_schema
36+
cls._args_schema = super()._build_arguments_schema(*args, **kwargs)
37+
38+
# define Arg Group ""
39+
40+
_args_schema = cls._args_schema
41+
_args_schema.app_id = AAZStrArg(
42+
options=["--app-id"],
43+
help="ID of the application. This is Application ID from the API Access settings blade in the Azure portal.",
44+
required=True,
45+
)
46+
47+
# define Arg Group "Body"
48+
49+
_args_schema = cls._args_schema
50+
_args_schema.applications = AAZListArg(
51+
options=["--applications"],
52+
arg_group="Body",
53+
help="A list of Application IDs for cross-application queries.",
54+
)
55+
_args_schema.query = AAZStrArg(
56+
options=["--query"],
57+
arg_group="Body",
58+
help="The query to execute.",
59+
required=True,
60+
)
61+
_args_schema.timespan = AAZStrArg(
62+
options=["--timespan"],
63+
arg_group="Body",
64+
help="Optional. The timespan over which to query data. This is an ISO8601 time period value. This timespan is applied in addition to any that are specified in the query expression.",
65+
)
66+
67+
applications = cls._args_schema.applications
68+
applications.Element = AAZStrArg()
69+
return cls._args_schema
70+
71+
def _execute_operations(self):
72+
self.pre_operations()
73+
self.QueryExecute(ctx=self.ctx)()
74+
self.post_operations()
75+
76+
@register_callback
77+
def pre_operations(self):
78+
pass
79+
80+
@register_callback
81+
def post_operations(self):
82+
pass
83+
84+
def _output(self, *args, **kwargs):
85+
result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True)
86+
return result
87+
88+
class QueryExecute(AAZHttpOperation):
89+
CLIENT_TYPE = "AAZMicrosoftInsightsDataPlaneClient_application_insights"
90+
91+
def __call__(self, *args, **kwargs):
92+
request = self.make_request()
93+
session = self.client.send_request(request=request, stream=False, **kwargs)
94+
if session.http_response.status_code in [200]:
95+
return self.on_200(session)
96+
97+
return self.on_error(session.http_response)
98+
99+
@property
100+
def url(self):
101+
return self.client.format_url(
102+
"/v1/apps/{appId}/query",
103+
**self.url_parameters
104+
)
105+
106+
@property
107+
def method(self):
108+
return "POST"
109+
110+
@property
111+
def error_format(self):
112+
return "ODataV4Format"
113+
114+
@property
115+
def url_parameters(self):
116+
parameters = {
117+
**self.serialize_url_param(
118+
"appId", self.ctx.args.app_id,
119+
required=True,
120+
),
121+
}
122+
return parameters
123+
124+
@property
125+
def header_parameters(self):
126+
parameters = {
127+
**self.serialize_header_param(
128+
"Content-Type", "application/json",
129+
),
130+
**self.serialize_header_param(
131+
"Accept", "application/json",
132+
),
133+
}
134+
return parameters
135+
136+
@property
137+
def content(self):
138+
_content_value, _builder = self.new_content_builder(
139+
self.ctx.args,
140+
typ=AAZObjectType,
141+
typ_kwargs={"flags": {"required": True, "client_flatten": True}}
142+
)
143+
_builder.set_prop("applications", AAZListType, ".applications")
144+
_builder.set_prop("query", AAZStrType, ".query", typ_kwargs={"flags": {"required": True}})
145+
_builder.set_prop("timespan", AAZStrType, ".timespan")
146+
147+
applications = _builder.get(".applications")
148+
if applications is not None:
149+
applications.set_elements(AAZStrType, ".")
150+
151+
return self.serialize_content(_content_value)
152+
153+
def on_200(self, session):
154+
data = self.deserialize_http_content(session)
155+
self.ctx.set_var(
156+
"instance",
157+
data,
158+
schema_builder=self._build_schema_on_200
159+
)
160+
161+
_schema_on_200 = None
162+
163+
@classmethod
164+
def _build_schema_on_200(cls):
165+
if cls._schema_on_200 is not None:
166+
return cls._schema_on_200
167+
168+
cls._schema_on_200 = AAZObjectType()
169+
170+
_schema_on_200 = cls._schema_on_200
171+
_schema_on_200.tables = AAZListType(
172+
flags={"required": True},
173+
)
174+
175+
tables = cls._schema_on_200.tables
176+
tables.Element = AAZObjectType()
177+
178+
_element = cls._schema_on_200.tables.Element
179+
_element.columns = AAZListType(
180+
flags={"required": True},
181+
)
182+
_element.name = AAZStrType(
183+
flags={"required": True},
184+
)
185+
_element.rows = AAZListType(
186+
flags={"required": True},
187+
)
188+
189+
columns = cls._schema_on_200.tables.Element.columns
190+
columns.Element = AAZObjectType()
191+
192+
_element = cls._schema_on_200.tables.Element.columns.Element
193+
_element.name = AAZStrType()
194+
_element.type = AAZStrType()
195+
196+
rows = cls._schema_on_200.tables.Element.rows
197+
rows.Element = AAZListType()
198+
199+
_element = cls._schema_on_200.tables.Element.rows.Element
200+
_element.Element = AAZAnyType()
201+
202+
return cls._schema_on_200
203+
204+
205+
class _QueryExecuteHelper:
206+
"""Helper class for QueryExecute"""
207+
208+
209+
__all__ = ["QueryExecute"]

0 commit comments

Comments
 (0)