Skip to content

Commit

Permalink
Merge branch 'main' into feature/mgmt-track2-network
Browse files Browse the repository at this point in the history
  • Loading branch information
archerzz committed Jul 30, 2021
2 parents 1197797 + 562d181 commit c75731d
Show file tree
Hide file tree
Showing 555 changed files with 356,577 additions and 114,361 deletions.
6 changes: 5 additions & 1 deletion .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@
/sdk/cognitiveservices/Vision.ComputerVision/ @ryogok @TFR258 @tburns10 @areddish @toothache

# ServiceLabel: %Cognitive - Face %Service Attention
/sdk/cognitiveservices/Vision.Face/ @JinyuID @dipidoo @SteveMSFT @TFR258
/sdk/cognitiveservices/Vision.Face/ @JinyuID @dipidoo @SteveMSFT @msyache @longli0 @ShaoAnLin @lulululululu

# PRLabel: %Cognitive - Form Recognizer
/sdk/formrecognizer/ @annelo-msft @kinelski @maririos
Expand Down Expand Up @@ -639,6 +639,10 @@ sdk/trafficmanager/Microsoft.Azure.Management.TrafficManager/ @tmsupp
# ServiceLabel: %WebPubSub %Service Attention
/sdk/webpubsub/ @vicancy @JialinXin

# ServiceLabel: %Personalizer %Service Attention
# PRLabel: %Personalizer
/sdk/personalizer/ @orenmichaely @tyclintw @Mohit-Chakraborty

# ######## Management Plane ########

/**/*Management*/ @m-nash @fengzhou-msft @archerzz @ArcturusZhang @yungezz
Expand Down
2 changes: 2 additions & 0 deletions common/ManagementCoreShared/ClientContext.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable enable

using System;
using Azure.Core;
using Azure.Core.Pipeline;
Expand Down
72 changes: 72 additions & 0 deletions common/ManagementCoreShared/SharedExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable enable

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Azure.ResourceManager.Core
{
/// <summary>
/// helper class
/// </summary>
internal static class SharedExtensions
{
/// <summary>
/// An extension method for supporting replacing one dictionary content with another one.
/// This is used to support resource tags.
/// </summary>
/// <param name="dest"> The destination dictionary in which the content will be replaced. </param>
/// <param name="src"> The source dictionary from which the content is copied from. </param>
/// <returns> The destination dictionary that has been altered. </returns>
public static IDictionary<string, string> ReplaceWith(this IDictionary<string, string> dest, IDictionary<string, string> src)
{
dest.Clear();
foreach (var kv in src)
{
dest.Add(kv);
}

return dest;
}

public static List<T> Trim<T>(this List<T> list, int numberToTrim)
{
if (list is null)
throw new ArgumentNullException(nameof(list));
if (numberToTrim < 0 || numberToTrim > list.Count)
throw new ArgumentOutOfRangeException(nameof(numberToTrim));
list.RemoveRange(0, numberToTrim);
return list;
}

public static async Task<TSource?> FirstOrDefaultAsync<TSource>(
this AsyncPageable<TSource> source,
Func<TSource, bool> predicate,
CancellationToken token = default)
where TSource : notnull
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));

token.ThrowIfCancellationRequested();

await foreach (var item in source.ConfigureAwait(false))
{
token.ThrowIfCancellationRequested();

if (predicate(item))
{
return item;
}
}

return default;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ protected void CleanupResourceGroups()
{
try
{
var sub = _cleanupClient.GetSubscriptions().TryGet(TestEnvironment.SubscriptionId);
sub?.GetResourceGroups().Get(resourceGroup).Value.StartDelete();
var sub = _cleanupClient.GetSubscriptions().GetIfExists(TestEnvironment.SubscriptionId);
sub.Value?.GetResourceGroups().Get(resourceGroup).Value.StartDelete();
}
catch (RequestFailedException e) when (e.Status == 404)
{
Expand Down Expand Up @@ -201,8 +201,8 @@ public void OneTimeCleanupResourceGroups()
{
Parallel.ForEach(OneTimeResourceGroupCleanupPolicy.ResourceGroupsCreated, resourceGroup =>
{
var sub = _cleanupClient.GetSubscriptions().TryGet(SessionEnvironment.SubscriptionId);
sub?.GetResourceGroups().Get(resourceGroup).Value.StartDelete();
var sub = _cleanupClient.GetSubscriptions().GetIfExists(SessionEnvironment.SubscriptionId);
sub.Value?.GetResourceGroups().Get(resourceGroup).Value.StartDelete();
});
Parallel.ForEach(OneTimeManagementGroupCleanupPolicy.ManagementGroupsCreated, mgmtGroupId =>
{
Expand Down
9 changes: 9 additions & 0 deletions doc/ApiDocGeneration/Generate-Api-Docs.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ $DocOutHtmlDir = "${DocOutDir}/_site"
$MDocTool = "${BinDirectory}/mdoc/mdoc.exe"
$DocFxTool = "${BinDirectory}/docfx/docfx.exe"
$DocCommonGenDir = "${RepoRoot}/eng/common/docgeneration"
$GACampaignId = "UA-62780441-41"

if ($LibType -eq 'management') {
$ArtifactName = $ArtifactName.Substring($ArtifactName.LastIndexOf('.Management') + 1)
Expand Down Expand Up @@ -146,6 +147,14 @@ New-Item -Path "${DocOutDir}" -Name templates -ItemType directory
Copy-Item "${DocCommonGenDir}/templates/**" -Destination "${DocOutDir}/templates" -Recurse -Force
Copy-Item "${DocCommonGenDir}/docfx.json" -Destination "${DocOutDir}" -Force

$headerTemplateLocation = "${DocOutDir}/templates/matthews/partials/head.tmpl.partial"

if (Test-Path $headerTemplateLocation){
$headerTemplateContent = Get-Content -Path $headerTemplateLocation -Raw
$headerTemplateContent = $headerTemplateContent -replace "GA_CAMPAIGN_ID", $GACampaignId
Set-Content -Path $headerTemplateLocation -Value $headerTemplateContent -NoNewline
}

Write-Verbose "Create Toc for Site Navigation"
New-Item "${DocOutDir}/toc.yml" -Force
Add-Content -Path "${DocOutDir}/toc.yml" -Value "- name: ${ArtifactName}`r`n href: index.md"
Expand Down
1 change: 1 addition & 0 deletions eng/.docsettings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ known_content_issues:
- ['sdk/core/Microsoft.Azure.Core.Spatial/README.md', '#15423']
- ['sdk/core/Microsoft.Azure.Core.Spatial.NewtonsoftJson/README.md', '#15423']
- ['sdk/servicebus/Microsoft.Azure.WebJobs.Extensions.ServiceBus/README.md', '#15423']
- ['sdk/personalizer/README.md','azure-sdk-tools/issues/42']

# .net climbs upwards. placing these to prevent assigning readmes to the wrong project
package_indexing_exclusion_list:
Expand Down
2 changes: 1 addition & 1 deletion eng/Packages.Data.props
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@
All should have PrivateAssets="All" set so they don't become pacakge dependencies
-->
<ItemGroup>
<PackageReference Update="Microsoft.Azure.AutoRest.CSharp" Version="3.0.0-beta.20210722.1" PrivateAssets="All" />
<PackageReference Update="Microsoft.Azure.AutoRest.CSharp" Version="3.0.0-beta.20210729.3" PrivateAssets="All" />
<PackageReference Update="Azure.ClientSdk.Analyzers" Version="0.1.1-dev.20210601.1" PrivateAssets="All" />
<PackageReference Update="coverlet.collector" Version="1.3.0" PrivateAssets="All" />
<PackageReference Update="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.1" PrivateAssets="All" />
Expand Down
16 changes: 14 additions & 2 deletions eng/common/scripts/Create-APIReview.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Param (
)

# Submit API review request and return status whether current revision is approved or pending or failed to create review
function Submit-APIReview($packagename, $filePath, $uri, $apiKey, $apiLabel)
function Submit-APIReview($packagename, $filePath, $uri, $apiKey, $apiLabel, $releaseStatus)
{
$multipartContent = [System.Net.Http.MultipartFormDataContent]::new()
$FileStream = [System.IO.FileStream]::new($filePath, [System.IO.FileMode]::Open)
Expand All @@ -33,6 +33,17 @@ function Submit-APIReview($packagename, $filePath, $uri, $apiKey, $apiLabel)
$StringContent = [System.Net.Http.StringContent]::new($apiLabel)
$StringContent.Headers.ContentDisposition = $stringHeader
$multipartContent.Add($stringContent)
Write-Host "Request param, label: $apiLabel"

if ($releaseStatus -and ($releaseStatus -ne "Unreleased"))
{
$compareAllParam = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")
$compareAllParam.Name = "compareAllRevisions"
$compareAllParamContent = [System.Net.Http.StringContent]::new($true)
$compareAllParamContent.Headers.ContentDisposition = $compareAllParam
$multipartContent.Add($compareAllParamContent)
Write-Host "Request param, compareAllRevisions: true"
}

$headers = @{
"ApiKey" = $apiKey;
Expand Down Expand Up @@ -103,13 +114,14 @@ if ($packages)

Write-Host "Version: $($version)"
Write-Host "SDK Type: $($pkgInfo.SdkType)"
Write-Host "Release Status: $($pkgInfo.ReleaseStatus)"

# Run create review step only if build is triggered from main branch or if version is GA.
# This is to avoid invalidating review status by a build triggered from feature branch
if ( ($SourceBranch -eq $DefaultBranch) -or (-not $version.IsPrerelease))
{
Write-Host "Submitting API Review for package $($pkg)"
$respCode = Submit-APIReview -packagename $pkg -filePath $pkgPath -uri $APIViewUri -apiKey $APIKey -apiLabel $APILabel
$respCode = Submit-APIReview -packagename $pkg -filePath $pkgPath -uri $APIViewUri -apiKey $APIKey -apiLabel $APILabel -releaseStatus $pkgInfo.ReleaseStatus
Write-Host "HTTP Response code: $($respCode)"
# HTTP status 200 means API is in approved status
if ($respCode -eq '200')
Expand Down
174 changes: 174 additions & 0 deletions eng/common/scripts/stress-testing/deploy-stress-tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
[CmdletBinding(DefaultParameterSetName = 'Default')]
param(
[string]$SearchDirectory,
[hashtable]$Filters,
[string]$Environment,
[string]$Repository,
[switch]$PushImages,
[string]$ClusterGroup,
[string]$DeployId,

[Parameter(ParameterSetName = 'DoLogin', Mandatory = $true)]
[switch]$Login,

[Parameter(ParameterSetName = 'DoLogin')]
[string]$Subscription
)

$ErrorActionPreference = 'Stop'

. $PSScriptRoot/find-all-stress-packages.ps1
$FailedCommands = New-Object Collections.Generic.List[hashtable]

if (!(Get-Module powershell-yaml)) {
Install-Module -Name powershell-yaml -RequiredVersion 0.4.1 -Force -Scope CurrentUser
}

# Powershell does not (at time of writing) treat exit codes from external binaries
# as cause for stopping execution, so do this via a wrapper function.
# See https://github.com/PowerShell/PowerShell-RFC/pull/277
function Run() {
Write-Host "`n==> $args`n" -ForegroundColor Green
$command, $arguments = $args
& $command $arguments
if ($LASTEXITCODE) {
Write-Error "Command '$args' failed with code: $LASTEXITCODE" -ErrorAction 'Continue'
$FailedCommands.Add(@{ command = "$args"; code = $LASTEXITCODE })
}
}

function RunOrExitOnFailure() {
run @args
if ($LASTEXITCODE) {
exit $LASTEXITCODE
}
}

function Login([string]$subscription, [string]$clusterGroup, [boolean]$pushImages) {
Write-Host "Logging in to subscription, cluster and container registry"
az account show *> $null
if ($LASTEXITCODE) {
RunOrExitOnFailure az login --allow-no-subscriptions
}

$clusterName = (az aks list -g $clusterGroup -o json| ConvertFrom-Json).name

RunOrExitOnFailure az aks get-credentials `
-n "$clusterName" `
-g "$clusterGroup" `
--subscription "$subscription" `
--overwrite-existing

if ($pushImages) {
$registry = (az acr list -g $clusterGroup -o json | ConvertFrom-Json).name
RunOrExitOnFailure az acr login -n $registry
}
}

function DeployStressTests(
[string]$searchDirectory = '.',
[hashtable]$filters = @{},
[string]$environment = 'test',
[string]$repository = 'images',
[boolean]$pushImages = $false,
[string]$clusterGroup = 'rg-stress-test-cluster-',
[string]$deployId = 'local',
[string]$subscription = 'Azure SDK Test Resources'
) {
if ($PSCmdlet.ParameterSetName -eq 'DoLogin') {
Login $subscription $clusterGroup $pushImages
}

RunOrExitOnFailure helm repo add stress-test-charts https://stresstestcharts.blob.core.windows.net/helm/
Run helm repo update
if ($LASTEXITCODE) { return $LASTEXITCODE }

$pkgs = FindStressPackages $searchDirectory $filters
Write-Host "" "Found $($pkgs.Length) stress test packages:"
Write-Host $pkgs.Directory ""
foreach ($pkg in $pkgs) {
Write-Host "Deploying stress test at '$($pkg.Directory)'"
DeployStressPackage $pkg $deployId $environment $repository $pushImages
}

Write-Host "Releases deployed by $deployId"
Run helm list --all-namespaces -l deployId=$deployId

if ($FailedCommands) {
Write-Warning "The following commands failed:"
foreach ($cmd in $FailedCommands) {
Write-Error "'$($cmd.command)' failed with code $($cmd.code)" -ErrorAction 'Continue'
}
exit 1
}
}

function DeployStressPackage(
[object]$pkg,
[string]$deployId,
[string]$environment,
[string]$repository,
[boolean]$pushImages
) {
$registry = (az acr list -g $clusterGroup -o json | ConvertFrom-Json).name
if (!$registry) {
Write-Host "Could not find container registry in resource group $clusterGroup"
exit 1
}

if ($pushImages) {
Run helm dependency update $pkg.Directory
if ($LASTEXITCODE) { return $LASTEXITCODE }

$dockerFiles = Get-ChildItem "$($pkg.Directory)/Dockerfile*"
foreach ($dockerFile in $dockerFiles) {
# Infer docker image name from parent directory name, if file is named `Dockerfile`
# or from suffix, is file is named like `Dockerfile.myimage` (for multiple dockerfiles).
$prefix, $imageName = $dockerFile.Name.Split(".")
if (!$imageName) {
$imageName = $dockerFile.Directory.Name
}
$imageTag = "${registry}.azurecr.io/$($repository.ToLower())/$($imageName):$deployId"
Write-Host "Building and pushing stress test docker image '$imageTag'"
Run docker build -t $imageTag -f $dockerFile.FullName $dockerFile.DirectoryName
if ($LASTEXITCODE) { return $LASTEXITCODE }
Run docker push $imageTag
if ($LASTEXITCODE) {
if ($PSCmdlet.ParameterSetName -ne 'DoLogin') {
Write-Warning "If docker push is failing due to authentication issues, try calling this script with '-Login'"
}
return $LASTEXITCODE
}
}
}

Write-Host "Creating namespace $($pkg.Namespace) if it does not exist..."
kubectl create namespace $pkg.Namespace --dry-run=client -o yaml | kubectl apply -f -

Write-Host "Installing or upgrading stress test $($pkg.ReleaseName) from $($pkg.Directory)"
Run helm upgrade $pkg.ReleaseName $pkg.Directory `
-n $pkg.Namespace `
--install `
--set repository=$registry.azurecr.io/$repository `
--set tag=$deployId `
--set stress-test-addons.env=$environment
if ($LASTEXITCODE) {
# Issues like 'UPGRADE FAILED: another operation (install/upgrade/rollback) is in progress'
# can be the result of cancelled `upgrade` operations (e.g. ctrl-c).
# See https://github.com/helm/helm/issues/4558
Write-Warning "The issue may be fixable by first running 'helm rollback -n $($pkg.Namespace) $($pkg.ReleaseName)'"
return $LASTEXITCODE
}

# Helm 3 stores release information in kubernetes secrets. The only way to add extra labels around
# specific releases (thereby enabling filtering on `helm list`) is to label the underlying secret resources.
# There is not currently support for setting these labels via the helm cli.
$helmReleaseConfig = kubectl get secrets `
-n $pkg.Namespace `
-l status=deployed,name=$($pkg.ReleaseName) `
-o jsonpath='{.items[0].metadata.name}'

Run kubectl label secret -n $pkg.Namespace --overwrite $helmReleaseConfig deployId=$deployId
}

DeployStressTests @PSBoundParameters
Loading

0 comments on commit c75731d

Please sign in to comment.