-
Notifications
You must be signed in to change notification settings - Fork 479
Expand file tree
/
Copy pathAzdAppLogRetriever.cs
More file actions
235 lines (196 loc) · 9.47 KB
/
AzdAppLogRetriever.cs
File metadata and controls
235 lines (196 loc) · 9.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
using Azure.Monitor.Query.Logs;
using Azure.Monitor.Query.Logs.Models;
using Azure.ResourceManager;
using Azure.ResourceManager.AppContainers;
using Azure.ResourceManager.AppService;
using Azure.ResourceManager.Resources;
namespace Azure.Mcp.Tools.Deploy.Services.Util;
public class AzdAppLogRetriever(ArmClient armClient, LogsQueryClient logsQueryClient, string subscriptionId, string azdEnvName)
{
private readonly string _subscriptionId = subscriptionId;
private readonly string _azdEnvName = azdEnvName;
private readonly Dictionary<string, string> _apps = new();
private readonly Dictionary<string, string> _logs = new();
private readonly List<string> _logAnalyticsWorkspaceIds = new();
private string _resourceGroupName = string.Empty;
private readonly ArmClient _armClient = armClient ?? throw new ArgumentNullException(nameof(armClient));
private readonly LogsQueryClient _queryClient = logsQueryClient ?? throw new ArgumentNullException(nameof(logsQueryClient));
public async Task InitializeAsync()
{
_resourceGroupName = await GetResourceGroupNameAsync();
if (string.IsNullOrEmpty(_resourceGroupName))
{
throw new InvalidOperationException($"No resource group with tag {{\"azd-env-name\": {_azdEnvName}}} found.");
}
}
public async Task GetLogAnalyticsWorkspacesInfoAsync()
{
var subscription = _armClient.GetSubscriptionResource(new($"/subscriptions/{_subscriptionId}"));
var resourceGroup = await subscription.GetResourceGroupAsync(_resourceGroupName);
var filter = "resourceType eq 'Microsoft.OperationalInsights/workspaces'";
await foreach (var resource in resourceGroup.Value.GetGenericResourcesAsync(filter: filter))
{
_logAnalyticsWorkspaceIds.Add(resource.Id.ToString());
}
if (_logAnalyticsWorkspaceIds.Count == 0)
{
throw new InvalidOperationException($"No log analytics workspaces found for resource group {_resourceGroupName}. Logs cannot be retrieved using this tool.");
}
}
public async Task<GenericResource> RegisterAppAsync(ResourceType resourceType, string serviceName)
{
var subscription = _armClient.GetSubscriptionResource(new($"/subscriptions/{_subscriptionId}"));
var resourceGroup = await subscription.GetResourceGroupAsync(_resourceGroupName);
var filter = $"tagName eq 'azd-service-name' and tagValue eq '{serviceName}'";
var apps = new List<GenericResource>();
await foreach (var resource in resourceGroup.Value.GetGenericResourcesAsync(filter: filter))
{
var resourceTypeString = resourceType.GetResourceTypeString();
var parts = resourceTypeString.Split('|');
var type = parts[0];
var kind = parts.Length > 1 ? parts[1] : null;
if (resource.Data.ResourceType.ToString() == type &&
(kind == null || resource.Data.Kind?.StartsWith(kind) == true))
{
_logs[resource.Id.ToString()] = string.Empty;
apps.Add(resource);
}
}
return apps.Count switch
{
0 => throw new InvalidOperationException($"No resources found for resource type {resourceType} with tag azd-service-name={serviceName}"),
> 1 => throw new InvalidOperationException($"Multiple resources found for resource type {resourceType} with tag azd-service-name={serviceName}"),
_ => apps[0]
};
}
private static string GetContainerAppLogsQuery(string containerAppName, int limit) =>
$"ContainerAppConsoleLogs_CL | where ContainerAppName_s == '{containerAppName}' | order by _timestamp_d desc | project TimeGenerated, Log_s | take {limit}";
private static string GetAppServiceLogsQuery(string appServiceResourceId, int limit) =>
$"AppServiceConsoleLogs | where _ResourceId == '{appServiceResourceId.ToLowerInvariant()}' | order by TimeGenerated desc | project TimeGenerated, ResultDescription | take {limit}";
private static string GetFunctionAppLogsQuery(string functionAppName, int limit) =>
$"AppTraces | where AppRoleName == '{functionAppName}' | order by TimeGenerated desc | project TimeGenerated, Message | take {limit}";
public async Task<string> QueryAppLogsAsync(ResourceType resourceType, string serviceName, int? limit = null)
{
var app = await RegisterAppAsync(resourceType, serviceName);
var getLogErrors = new List<string>();
var getLogSuccess = false;
var logSearchQuery = string.Empty;
DateTimeOffset? lastDeploymentTime = null;
var actualLimit = limit ?? 200;
DateTimeOffset endTime = DateTime.UtcNow;
DateTimeOffset startTime = endTime.AddHours(-4);
switch (resourceType)
{
case ResourceType.ContainerApps:
logSearchQuery = GetContainerAppLogsQuery(app.Data.Name, actualLimit);
// Get last deployment time for container apps
var containerAppResource = _armClient.GetContainerAppResource(app.Id);
var containerApp = await containerAppResource.GetAsync();
await foreach (var revision in containerApp.Value.GetContainerAppRevisions())
{
var revisionData = await revision.GetAsync();
if (revisionData.Value.Data.IsActive == true)
{
lastDeploymentTime = revisionData.Value.Data.CreatedOn;
break;
}
}
break;
case ResourceType.AppService:
case ResourceType.FunctionApp:
var webSiteResource = _armClient.GetWebSiteResource(app.Id);
await foreach (var deployment in webSiteResource.GetSiteDeployments())
{
var deploymentData = await deployment.GetAsync();
if (deploymentData.Value.Data.IsActive == true)
{
lastDeploymentTime = deploymentData.Value.Data.StartOn;
break;
}
}
logSearchQuery = resourceType == ResourceType.AppService
? GetAppServiceLogsQuery(app.Id.ToString(), actualLimit)
: GetFunctionAppLogsQuery(app.Data.Name, actualLimit);
break;
default:
throw new ArgumentException($"Unsupported resource type: {resourceType}");
}
// startTime is now, endTime is 1 hour ago
if (lastDeploymentTime.HasValue && lastDeploymentTime > startTime)
{
startTime = lastDeploymentTime ?? startTime;
}
foreach (var logAnalyticsId in _logAnalyticsWorkspaceIds)
{
try
{
var timeRange = new LogsQueryTimeRange(startTime, endTime);
var response = await _queryClient.QueryResourceAsync(new(logAnalyticsId), logSearchQuery, timeRange);
if (response.Value.Status == LogsQueryResultStatus.Success)
{
foreach (var table in response.Value.AllTables)
{
foreach (var row in table.Rows)
{
_logs[app.Id.ToString()] += $"[{row[0]}] {row[1]}\n";
}
}
getLogSuccess = true;
break;
}
}
catch (Exception ex)
{
getLogErrors.Add($"Error retrieving logs for {app.Data.Name} from {logAnalyticsId}: {ex.Message}");
}
}
if (!getLogSuccess)
{
throw new InvalidOperationException($"Errors: {string.Join(", ", getLogErrors)}");
}
return $"Console Logs for {serviceName} with resource ID {app.Id} between {startTime} and {endTime}:\n{_logs[app.Id.ToString()]}";
}
private async Task<string> GetResourceGroupNameAsync()
{
var subscription = _armClient.GetSubscriptionResource(new($"/subscriptions/{_subscriptionId}"));
await foreach (var resourceGroup in subscription.GetResourceGroups())
{
if (resourceGroup.Data.Tags.TryGetValue("azd-env-name", out var envName) && envName == _azdEnvName)
{
return resourceGroup.Data.Name;
}
}
return string.Empty;
}
}
public enum ResourceType
{
AppService,
ContainerApps,
FunctionApp
}
public static class ResourceTypeExtensions
{
private static readonly Dictionary<string, ResourceType> HostToResourceType = new()
{
{ "containerapp", ResourceType.ContainerApps },
{ "appservice", ResourceType.AppService },
{ "function", ResourceType.FunctionApp }
};
private static readonly Dictionary<ResourceType, string> ResourceTypeToString = new()
{
{ ResourceType.AppService, "Microsoft.Web/sites|app" },
{ ResourceType.ContainerApps, "Microsoft.App/containerApps" },
{ ResourceType.FunctionApp, "Microsoft.Web/sites|functionapp" }
};
public static ResourceType GetResourceTypeFromHost(string host)
{
return HostToResourceType.TryGetValue(host, out var resourceType)
? resourceType
: throw new ArgumentException($"Unknown host type: {host}");
}
public static string GetResourceTypeString(this ResourceType resourceType)
{
return ResourceTypeToString[resourceType];
}
}