/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * dmex * */ namespace CustomBuildTool { /// /// Provides methods for interacting with Azure DevOps build information using environment variables and HTTP requests. /// public static partial class BuildDevOps { [GeneratedRegex(@"https://download\.microsoft\.com/download/[^\']+\.json", RegexOptions.IgnoreCase)] private static partial Regex AzureServiceTagsRegex(); /// /// Provides a shared HTTP client instance for communicating with DevOps services. /// /// This static instance is intended for reuse across multiple requests to optimize /// connection management and resource usage. Avoid disposing of this client directly; dispose of it only when the /// application is shutting down. private static readonly HttpClient DevOpsHttpClient; /// /// The build ID from the environment variable BUILD_BUILDID. /// private static readonly string BaseBuild; /// /// The system access token from the environment variable SYSTEM_ACCESSTOKEN. /// private static readonly string BaseToken; /// /// The team project name from the environment variable SYSTEM_TEAMPROJECT. /// private static readonly string BaseName; /// /// The collection URI from the environment variable SYSTEM_COLLECTIONURI. /// private static readonly string BaseUrl; /// /// Initializes static members of the class by reading required environment variables. /// static BuildDevOps() { DevOpsHttpClient = BuildHttpClient.CreateHttpClient(); BaseBuild = Win32.GetEnvironmentVariable("BUILD_BUILDID"); BaseToken = Win32.GetEnvironmentVariable("SYSTEM_ACCESSTOKEN"); BaseName = Win32.GetEnvironmentVariable("SYSTEM_TEAMPROJECT"); BaseUrl = Win32.GetEnvironmentVariable("SYSTEM_COLLECTIONURI"); } /// /// Queries the Azure DevOps build API for the current build's queue time. /// /// /// A tuple containing a boolean indicating success or failure, and the representing the queue time of the build, or if an error occurs. /// public static async Task<(bool Success, DateTime QueueTime)> BuildQueryQueueTime() { DateTime queueTime; if (string.IsNullOrWhiteSpace(BaseBuild) || string.IsNullOrWhiteSpace(BaseToken) || string.IsNullOrWhiteSpace(BaseName) || string.IsNullOrWhiteSpace(BaseUrl)) { queueTime = DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(Environment.TickCount64)); Console.WriteLine($"Build StartTime: {VT.YELLOW}{queueTime}{VT.RESET} (TickCount)"); Console.WriteLine($"Build Elapsed: {VT.YELLOW}{(DateTimeOffset.UtcNow - queueTime)}{VT.RESET} (TickCount)"); return (true, queueTime); } try { using HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/{BaseName}/_apis/build/builds/{BaseBuild}?api-version=7.1"); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", BaseToken); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var content = await BuildHttpClient.SendMessage(DevOpsHttpClient, requestMessage, BuildInfoResponseContext.Default.BuildInfo); if (content == null) { Console.WriteLine($"{VT.RED}[ERROR] Failed to deserialize the response.{VT.RESET}"); ArgumentNullException.ThrowIfNull((BuildInfo)null); } var offset = new DateTimeOffset(DateTime.SpecifyKind(content.QueueTime, DateTimeKind.Utc)); Console.WriteLine($"Build QueueTime: {VT.GREEN}{content.QueueTime}{VT.RESET}"); Console.WriteLine($"Build StartTime: {VT.GREEN}{content.StartTime}{VT.RESET}"); Console.WriteLine($"Build Elapsed: {VT.GREEN}{(DateTimeOffset.UtcNow - offset)}{VT.RESET}"); queueTime = offset.DateTime; return (true, queueTime); } catch (Exception ex) { Console.WriteLine($"{VT.RED}[ERROR] {ex}{VT.RESET} (TickCount)"); queueTime = DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(Environment.TickCount64)); return (false, queueTime); } } /// /// Downloads the Azure service tags JSON and returns all address prefixes. /// /// A list of address prefixes from the weekly service tags JSON file, or null on error. public static async IAsyncEnumerable DownloadAzureServiceTags([EnumeratorCancellation] CancellationToken CancellationToken = default) { const string downloadPageUrl = "https://www.microsoft.com/download/details.aspx?id=56519"; using var requestMessage = new HttpRequestMessage(HttpMethod.Get, downloadPageUrl); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html")); using var response = await BuildHttpClient.SendMessageResponse(DevOpsHttpClient, requestMessage, CancellationToken); if (response == null || !response.IsSuccessStatusCode) { Program.PrintColorMessage("[DownloadAzureServiceTags] download page failed", ConsoleColor.Red); yield break; } var pageContent = await response.Content.ReadAsStringAsync(CancellationToken); var match = AzureServiceTagsRegex().Match(pageContent); if (!match.Success) { Program.PrintColorMessage("[DownloadAzureServiceTags] download url not found", ConsoleColor.Red); yield break; } using var jsonRequest = new HttpRequestMessage(HttpMethod.Get, match.Value); jsonRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); using var jsonResponse = await BuildHttpClient.SendMessageResponse(DevOpsHttpClient, jsonRequest, CancellationToken); if (jsonResponse == null || !jsonResponse.IsSuccessStatusCode) { Program.PrintColorMessage("[DownloadAzureServiceTags] json download failed", ConsoleColor.Red); yield break; } await using var stream = await jsonResponse.Content.ReadAsStreamAsync(CancellationToken); var tags = await JsonSerializer.DeserializeAsync(stream, BuildInfoResponseContext.Default.AzureServiceTagsResponse, CancellationToken); if (tags?.Values == null) { Program.PrintColorMessage("[DownloadAzureServiceTags] invalid json", ConsoleColor.Red); yield break; } var results = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var value in tags.Values) { if (value?.Properties?.AddressPrefixes == null) continue; foreach (var prefix in value.Properties.AddressPrefixes) { if (!string.IsNullOrWhiteSpace(prefix) && results.Add(prefix)) { yield return prefix; } } } } } /// /// Provides a context for source generation of JSON serialization for . /// [JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, GenerationMode = JsonSourceGenerationMode.Default)] [JsonSerializable(typeof(BuildInfo))] [JsonSerializable(typeof(AzureServiceTagsResponse))] public partial class BuildInfoResponseContext : JsonSerializerContext; public class AzureServiceTagsResponse { [JsonPropertyName("values")] public List Values { get; set; } } public class AzureServiceTag { [JsonPropertyName("properties")] public AzureServiceTagProperties Properties { get; set; } } public class AzureServiceTagProperties { [JsonPropertyName("addressPrefixes")] public List AddressPrefixes { get; set; } } /// /// Represents the response from the Azure DevOps build API. /// public class BuildInfo { /// /// Gets or sets the repository links. /// [JsonPropertyName("_links")] public RepoLinks Links { get; set; } /// /// Gets or sets the build ID. /// [JsonPropertyName("id")] public int Id { get; set; } /// /// Gets or sets the build number. /// [JsonPropertyName("buildNumber")] public string BuildNumber { get; set; } /// /// Gets or sets the build status. /// [JsonPropertyName("status")] public string Status { get; set; } /// /// Gets or sets the time the build was queued. /// [JsonPropertyName("queueTime")] public DateTime QueueTime { get; set; } /// /// Gets or sets the time the build started. /// [JsonPropertyName("startTime")] public DateTime StartTime { get; set; } /// /// Gets or sets the build URL. /// [JsonPropertyName("url")] public string Url { get; set; } /// /// Gets or sets the build definition. /// [JsonPropertyName("definition")] public Definition Definition { get; set; } /// /// Gets or sets the project information. /// [JsonPropertyName("project")] public Project Project { get; set; } /// /// Gets or sets the build URI. /// [JsonPropertyName("uri")] public string Uri { get; set; } /// /// Gets or sets the source branch. /// [JsonPropertyName("sourceBranch")] public string SourceBranch { get; set; } /// /// Gets or sets the source version. /// [JsonPropertyName("sourceVersion")] public string SourceVersion { get; set; } /// /// Gets or sets the build priority. /// [JsonPropertyName("priority")] public string Priority { get; set; } /// /// Gets or sets the reason for the build. /// [JsonPropertyName("reason")] public string Reason { get; set; } /// /// Gets or sets the identity of the user the build was requested for. /// [JsonPropertyName("requestedFor")] public Identity RequestedFor { get; set; } /// /// Gets or sets the identity of the user who requested the build. /// [JsonPropertyName("requestedBy")] public Identity RequestedBy { get; set; } /// /// Gets or sets the date the build was last changed. /// [JsonPropertyName("lastChangedDate")] public DateTime LastChangedDate { get; set; } /// /// Gets or sets the identity of the user who last changed the build. /// [JsonPropertyName("lastChangedBy")] public Identity LastChangedBy { get; set; } /// /// Gets or sets the build parameters. /// [JsonPropertyName("parameters")] public string Parameters { get; set; } /// /// Gets or sets the build logs. /// [JsonPropertyName("logs")] public Logs Logs { get; set; } /// /// Gets or sets the repository information. /// [JsonPropertyName("repository")] public Repository Repository { get; set; } /// /// Gets or sets a value indicating whether the build is retained by a release. /// [JsonPropertyName("retainedByRelease")] public bool RetainedByRelease { get; set; } /// /// Gets or sets a value indicating whether the commit message is appended to the run name. /// [JsonPropertyName("appendCommitMessageToRunName")] public bool AppendCommitMessageToRunName { get; set; } // [JsonPropertyName("orchestrationPlan")] // public OrchestrationPlan OrchestrationPlan { get; set; } // [JsonPropertyName("plans")] // public List Plans { get; set; } } /// /// Represents repository-related links in the build information. /// public class RepoLinks { /// /// Gets or sets the self-link. /// [JsonPropertyName("self")] public Link Self { get; set; } /// /// Gets or sets the web link. /// [JsonPropertyName("web")] public Link Web { get; set; } /// /// Gets or sets the source version display URI link. /// [JsonPropertyName("sourceVersionDisplayUri")] public Link SourceVersionDisplayUri { get; set; } /// /// Gets or sets the timeline link. /// [JsonPropertyName("timeline")] public Link Timeline { get; set; } /// /// Gets or sets the badge link. /// [JsonPropertyName("badge")] public Link Badge { get; set; } } /// /// Represents a hyperlink in the build information. /// public class Link { /// /// Gets or sets the hyperlink reference. /// [JsonPropertyName("href")] public string Href { get; set; } } /// /// Represents the build definition details. /// public class Definition { /// /// Gets or sets the definition ID. /// [JsonPropertyName("id")] public int Id { get; set; } /// /// Gets or sets the definition name. /// [JsonPropertyName("name")] public string Name { get; set; } /// /// Gets or sets the definition URL. /// [JsonPropertyName("url")] public string Url { get; set; } /// /// Gets or sets the definition URI. /// [JsonPropertyName("uri")] public string Uri { get; set; } /// /// Gets or sets the definition path. /// [JsonPropertyName("path")] public string Path { get; set; } /// /// Gets or sets the definition type. /// [JsonPropertyName("type")] public string Type { get; set; } /// /// Gets or sets the queue status. /// [JsonPropertyName("queueStatus")] public string QueueStatus { get; set; } /// /// Gets or sets the revision number. /// [JsonPropertyName("revision")] public int Revision { get; set; } /// /// Gets or sets the project associated with the definition. /// [JsonPropertyName("project")] public Project Project { get; set; } /// public override string ToString() { return $"{this.Id} - {this.Name}"; } } /// /// Represents a project in Azure DevOps. /// public class Project { /// /// Gets or sets the project ID. /// [JsonPropertyName("id")] public string Id { get; set; } /// /// Gets or sets the project name. /// [JsonPropertyName("name")] public string Name { get; set; } /// /// Gets or sets the project URL. /// [JsonPropertyName("url")] public string Url { get; set; } /// /// Gets or sets the project state. /// [JsonPropertyName("state")] public string State { get; set; } /// /// Gets or sets the project revision number. /// [JsonPropertyName("revision")] public int Revision { get; set; } /// /// Gets or sets the project visibility. /// [JsonPropertyName("visibility")] public string Visibility { get; set; } /// /// Gets or sets the last update time of the project. /// [JsonPropertyName("lastUpdateTime")] public DateTime LastUpdateTime { get; set; } /// public override string ToString() { return $"{this.Id} - {this.Name}"; } } /// /// Represents an identity (user or service) in Azure DevOps. /// public class Identity { /// /// Gets or sets the display name. /// [JsonPropertyName("displayName")] public string Name { get; set; } /// /// Gets or sets the URL of the identity. /// [JsonPropertyName("url")] public string Url { get; set; } /// /// Gets or sets the identity ID. /// [JsonPropertyName("id")] public string Id { get; set; } /// /// Gets or sets the unique name. /// [JsonPropertyName("uniqueName")] public string UniqueName { get; set; } /// /// Gets or sets the image URL. /// [JsonPropertyName("imageUrl")] public string ImageUrl { get; set; } /// /// Gets or sets the descriptor. /// [JsonPropertyName("descriptor")] public string Descriptor { get; set; } /// public override string ToString() { return $"{this.Id} - {this.Name}"; } } /// /// Represents build logs information. /// public class Logs { /// /// Gets or sets the log ID. /// [JsonPropertyName("id")] public int Id { get; set; } /// /// Gets or sets the log type. /// [JsonPropertyName("type")] public string Type { get; set; } /// /// Gets or sets the log URL. /// [JsonPropertyName("url")] public string Url { get; set; } /// public override string ToString() { return this.Id.ToString(); } } /// /// Represents repository information for a build. /// public class Repository { /// /// Gets or sets the repository ID. /// [JsonPropertyName("id")] public string Id { get; set; } /// /// Gets or sets the repository type. /// [JsonPropertyName("type")] public string Type { get; set; } /// /// Gets or sets the repository name. /// [JsonPropertyName("name")] public string Name { get; set; } /// /// Gets or sets the repository URL. /// [JsonPropertyName("url")] public string Url { get; set; } /// /// Gets or sets a value indicating whether the repository is cleaned before build. /// [JsonPropertyName("clean")] public bool? Clean { get; set; } /// /// Gets or sets a value indicating whether submodules are checked out. /// [JsonPropertyName("checkoutSubmodules")] public bool CheckoutSubmodules { get; set; } /// public override string ToString() { return $"{this.Id} - {this.Name}"; } } }