Skip to content
This repository was archived by the owner on Jan 12, 2024. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
69 commits
Select commit Hold shift + click to select a range
89282df
Updates to IQ# syntax highlighting
rmshaffer May 28, 2020
f53eb9c
Validate targets and load provider packages
rmshaffer May 28, 2020
75a8e35
Update Python interface for Azure commands
rmshaffer May 29, 2020
1787ea4
Merge branch 'feature/azure-client' into rmshaffer/azure-targets
rmshaffer Jun 1, 2020
52098e6
Simplify AzureExecutionTarget class
rmshaffer Jun 1, 2020
53fd8e9
Generate EntryPoint and compile into new assembly
rmshaffer Jun 1, 2020
a33a2c9
Changes for JobNotCompleted case
rmshaffer Jun 2, 2020
e47c9df
Merge branch 'rmshaffer/azure-targets' into rmshaffer/azure-entrypoint
rmshaffer Jun 2, 2020
4449040
Refactor entry point code into new classes
rmshaffer Jun 2, 2020
6f3a6fe
Use correct input and output types
rmshaffer Jun 2, 2020
d47fddd
Simplify property syntax
Jun 2, 2020
5215155
Add simple tests for AzureExecutionTarget class
rmshaffer Jun 2, 2020
eeb4b11
Merge branch 'rmshaffer/azure-targets' into rmshaffer/azure-entrypoint
rmshaffer Jun 2, 2020
5e62413
Recompile everything for specified execution target
rmshaffer Jun 3, 2020
26a79ea
Add tests and error handling
rmshaffer Jun 3, 2020
69a4fe6
Improve variable names
rmshaffer Jun 3, 2020
c63a006
Add status message while loading provider package
rmshaffer Jun 3, 2020
1c7d83f
Merge branch 'feature/azure-client' into rmshaffer/azure-targets
rmshaffer Jun 3, 2020
cbdd00e
Merge branch 'rmshaffer/azure-targets' into rmshaffer/azure-entrypoint
rmshaffer Jun 3, 2020
944cec0
Merge branch 'feature/azure-client' into rmshaffer/azure-targets
rmshaffer Jun 3, 2020
12c7e12
Merge branch 'rmshaffer/azure-targets' into rmshaffer/azure-entrypoint
rmshaffer Jun 3, 2020
b8e680b
Merge branch 'feature/azure-client' into rmshaffer/azure-targets
rmshaffer Jun 3, 2020
126f43b
Merge branch 'rmshaffer/azure-targets' into rmshaffer/azure-entrypoint
rmshaffer Jun 3, 2020
43c07ae
Add documentation to AzureExecutionTarget.GetProvider
rmshaffer Jun 5, 2020
2552632
Merge branch 'feature/azure-client' into rmshaffer/azure-targets
rmshaffer Jun 5, 2020
4bf71db
Merge branch 'rmshaffer/azure-targets' into rmshaffer/azure-entrypoint
rmshaffer Jun 5, 2020
52c481d
Extend tests to call EntryPoint.SubmitAsync
rmshaffer Jun 5, 2020
a470662
Wait for job completion on %azure.execute
rmshaffer Jun 5, 2020
354d826
Update comment
rmshaffer Jun 5, 2020
9041701
Add timeout for %azure.execute
rmshaffer Jun 5, 2020
0300ecd
Minor fixes in AzureClient
rmshaffer Jun 5, 2020
8ce9c63
Minor formatting and comment tweaks
rmshaffer Jun 5, 2020
e3e7bcc
Style improvements in test code
rmshaffer Jun 5, 2020
f807723
More consistent handling of job objects
rmshaffer Jun 5, 2020
1409213
Consistent error handling for IWorkspace calls
rmshaffer Jun 5, 2020
78196ff
Update to latest QDK released version
rmshaffer Jun 5, 2020
fce176e
Merge branch 'feature/azure-client' into rmshaffer/azure-entrypoint
rmshaffer Jun 8, 2020
0164134
Merge branch 'feature/azure-client' into rmshaffer/azure-entrypoint
rmshaffer Jun 8, 2020
edbe96e
Add encoders for CloudJob and TargetStatus
rmshaffer Jun 8, 2020
1b27c4b
Move extension methods into encoder files
rmshaffer Jun 8, 2020
3dabab4
Change signature of CloudJob.ToDictionary
rmshaffer Jun 8, 2020
7c69473
Update histogram deserialization and add encoders
rmshaffer Jun 8, 2020
a9bc3d3
Use JsonConverter classes directly
rmshaffer Jun 8, 2020
c9dec08
Small cleanup
rmshaffer Jun 8, 2020
b92db91
Register single JsonEncoder
rmshaffer Jun 8, 2020
bb82ac4
Add a simple HTML histogram display based on StateVectorToHtmlResultE…
rmshaffer Jun 9, 2020
78886f7
Various improvements from PR suggestions
rmshaffer Jun 9, 2020
274ebde
Use UTC for dates returned to Python
rmshaffer Jun 9, 2020
62a358e
Support jobName and shots parameters
rmshaffer Jun 9, 2020
204ed5a
Unify submission and execution code
rmshaffer Jun 9, 2020
7450585
Add some documentation to AzureSubmissionContext
rmshaffer Jun 9, 2020
bc90371
Documentation fix
rmshaffer Jun 9, 2020
f30a387
Add timeout and pollingInterval parameters
rmshaffer Jun 9, 2020
ce542ca
Refactor authentication and service calls
rmshaffer Jun 10, 2020
cb9a7df
Add mock AzureEnvironment and integration tests
rmshaffer Jun 10, 2020
9b3b74b
Use switch syntax for entryPointInput
Jun 10, 2020
eb8de48
Remove 'All rights reserved.'
Jun 10, 2020
0429635
Addressing PR feedback and compiler warnings
rmshaffer Jun 11, 2020
5213b99
Use LINQ for decodedParameters
rmshaffer Jun 11, 2020
7e1146e
Merge branch 'rmshaffer/azure-entrypoint' into rmshaffer/azure-encoders
rmshaffer Jun 11, 2020
c0a7ce0
Merge branch 'rmshaffer/azure-encoders' into rmshaffer/azure-jobsettings
rmshaffer Jun 11, 2020
eb76029
Merge branch 'rmshaffer/azure-jobsettings' into rmshaffer/azure-clien…
rmshaffer Jun 11, 2020
a9a8adb
Merge branch 'rmshaffer/azure-client-refactoring' into rmshaffer/azur…
rmshaffer Jun 11, 2020
5323e1c
Move AzureClientError and update copyright strings
rmshaffer Jun 11, 2020
f778023
Test for specific AzureClientError results
rmshaffer Jun 11, 2020
cf771df
Add Python tests and consolidate return types
rmshaffer Jun 11, 2020
8f33c12
Use setup_module instead of checking for pytest
rmshaffer Jun 11, 2020
60170ca
Use pytest fixture for initialization
rmshaffer Jun 11, 2020
286dc87
Merge branch 'feature/azure-client' into rmshaffer/azure-mock
rmshaffer Jun 12, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build/test.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ function Test-Python {
Write-Host "##[info]Testing Python inside $testFolder"
Push-Location (Join-Path $PSScriptRoot $testFolder)
python --version
pytest --log-level=DEBUG
pytest -v --log-level=DEBUG
Pop-Location

if ($LastExitCode -ne 0) {
Expand Down
333 changes: 154 additions & 179 deletions src/AzureClient/AzureClient.cs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/AzureClient/AzureClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Azure.Quantum.Client" Version="0.11.2006.207" />
<PackageReference Include="Microsoft.Azure.Quantum.Client" Version="0.11.2006.403" />
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.21" />
<PackageReference Include="Microsoft.Rest.ClientRuntime.Azure" Version="3.3.19" />
<PackageReference Include="System.Reactive" Version="4.3.2" />
Expand Down
93 changes: 93 additions & 0 deletions src/AzureClient/AzureClientError.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#nullable enable

using System.ComponentModel;

namespace Microsoft.Quantum.IQSharp.AzureClient
{
/// <summary>
/// Describes possible error results from <see cref="IAzureClient"/> methods.
/// </summary>
public enum AzureClientError
{
/// <summary>
/// Method completed with an unknown error.
/// </summary>
[Description(Resources.AzureClientErrorUnknownError)]
UnknownError = 1000,

/// <summary>
/// No connection has been made to any Azure Quantum workspace.
/// </summary>
[Description(Resources.AzureClientErrorNotConnected)]
NotConnected,

/// <summary>
/// A target has not yet been configured for job submission.
/// </summary>
[Description(Resources.AzureClientErrorNoTarget)]
NoTarget,

/// <summary>
/// The specified target is not valid for job submission.
/// </summary>
[Description(Resources.AzureClientErrorInvalidTarget)]
InvalidTarget,

/// <summary>
/// A job meeting the specified criteria was not found.
/// </summary>
[Description(Resources.AzureClientErrorJobNotFound)]
JobNotFound,

/// <summary>
/// The result of a job was requested, but the job has not yet completed.
/// </summary>
[Description(Resources.AzureClientErrorJobNotCompleted)]
JobNotCompleted,

/// <summary>
/// The job output failed to be downloaded from the Azure storage location.
/// </summary>
[Description(Resources.AzureClientErrorJobOutputDownloadFailed)]
JobOutputDownloadFailed,

/// <summary>
/// No Q# operation name was provided where one was required.
/// </summary>
[Description(Resources.AzureClientErrorNoOperationName)]
NoOperationName,

/// <summary>
/// The specified Q# operation name is not recognized.
/// </summary>
[Description(Resources.AzureClientErrorUnrecognizedOperationName)]
UnrecognizedOperationName,

/// <summary>
/// The specified Q# operation cannot be used as an entry point.
/// </summary>
[Description(Resources.AzureClientErrorInvalidEntryPoint)]
InvalidEntryPoint,

/// <summary>
/// The Azure Quantum job submission failed.
/// </summary>
[Description(Resources.AzureClientErrorJobSubmissionFailed)]
JobSubmissionFailed,

/// <summary>
/// Authentication with the Azure service failed.
/// </summary>
[Description(Resources.AzureClientErrorAuthenticationFailed)]
AuthenticationFailed,

/// <summary>
/// A workspace meeting the specified criteria was not found.
/// </summary>
[Description(Resources.AzureClientErrorWorkspaceNotFound)]
WorkspaceNotFound,
}
}
126 changes: 111 additions & 15 deletions src/AzureClient/AzureEnvironment.cs
Original file line number Diff line number Diff line change
@@ -1,74 +1,170 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#nullable enable

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Quantum.Client;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;
using Microsoft.Jupyter.Core;

namespace Microsoft.Quantum.IQSharp.AzureClient
{
internal enum AzureEnvironmentType { Production, Canary, Dogfood };
internal enum AzureEnvironmentType { Production, Canary, Dogfood, Mock };

internal class AzureEnvironment
{
public string ClientId { get; private set; } = string.Empty;
public string Authority { get; private set; } = string.Empty;
public List<string> Scopes { get; private set; } = new List<string>();
public Uri? BaseUri { get; private set; }
public static string EnvironmentVariableName => "AZURE_QUANTUM_ENV";
public AzureEnvironmentType Type { get; private set; }

private string SubscriptionId { get; set; } = string.Empty;
private string ClientId { get; set; } = string.Empty;
private string Authority { get; set; } = string.Empty;
private List<string> Scopes { get; set; } = new List<string>();
private Uri? BaseUri { get; set; }

private AzureEnvironment()
{
}

public static AzureEnvironment Create(string environment, string subscriptionId)
public static AzureEnvironment Create(string subscriptionId)
{
if (Enum.TryParse(environment, true, out AzureEnvironmentType environmentType))
var azureEnvironmentName = System.Environment.GetEnvironmentVariable(EnvironmentVariableName);

if (Enum.TryParse(azureEnvironmentName, true, out AzureEnvironmentType environmentType))
{
switch (environmentType)
{
case AzureEnvironmentType.Production:
return Production();
return Production(subscriptionId);
case AzureEnvironmentType.Canary:
return Canary();
return Canary(subscriptionId);
case AzureEnvironmentType.Dogfood:
return Dogfood(subscriptionId);
case AzureEnvironmentType.Mock:
return Mock();
default:
throw new InvalidOperationException("Unexpected EnvironmentType value.");
}
}

return Production();
return Production(subscriptionId);
}

private static AzureEnvironment Production() =>
public async Task<IAzureWorkspace?> GetAuthenticatedWorkspaceAsync(IChannel channel, string resourceGroupName, string workspaceName, bool refreshCredentials)
{
if (Type == AzureEnvironmentType.Mock)
{
channel.Stdout("AZURE_QUANTUM_ENV set to Mock. Using mock Azure workspace rather than connecting to the real service.");
return new MockAzureWorkspace(workspaceName);
}

// Find the token cache folder
var cacheDirectoryEnvVarName = "AZURE_QUANTUM_TOKEN_CACHE";
var cacheDirectory = System.Environment.GetEnvironmentVariable(cacheDirectoryEnvVarName);
if (string.IsNullOrEmpty(cacheDirectory))
{
cacheDirectory = Path.Join(System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile), ".azure-quantum");
}

// Register the token cache for serialization
var cacheFileName = "aad.bin";
var storageCreationProperties = new StorageCreationPropertiesBuilder(cacheFileName, cacheDirectory, ClientId).Build();
var cacheHelper = await MsalCacheHelper.CreateAsync(storageCreationProperties);
var msalApp = PublicClientApplicationBuilder.Create(ClientId).WithAuthority(Authority).Build();
cacheHelper.RegisterCache(msalApp.UserTokenCache);

// Perform the authentication
bool shouldShowLoginPrompt = refreshCredentials;
AuthenticationResult? authenticationResult = null;
if (!shouldShowLoginPrompt)
{
try
{
var accounts = await msalApp.GetAccountsAsync();
authenticationResult = await msalApp.AcquireTokenSilent(
Scopes, accounts.FirstOrDefault()).WithAuthority(msalApp.Authority).ExecuteAsync();
}
catch (MsalUiRequiredException)
{
shouldShowLoginPrompt = true;
}
}

if (shouldShowLoginPrompt)
{
authenticationResult = await msalApp.AcquireTokenWithDeviceCode(
Scopes,
deviceCodeResult =>
{
channel.Stdout(deviceCodeResult.Message);
return Task.FromResult(0);
}).WithAuthority(msalApp.Authority).ExecuteAsync();
}

if (authenticationResult == null)
{
return null;
}

// Construct and return the AzureWorkspace object
var credentials = new Rest.TokenCredentials(authenticationResult.AccessToken);
var azureQuantumClient = new QuantumClient(credentials)
{
SubscriptionId = SubscriptionId,
ResourceGroupName = resourceGroupName,
WorkspaceName = workspaceName,
BaseUri = BaseUri,
};
var azureQuantumWorkspace = new Azure.Quantum.Workspace(
azureQuantumClient.SubscriptionId,
azureQuantumClient.ResourceGroupName,
azureQuantumClient.WorkspaceName,
authenticationResult?.AccessToken,
BaseUri);

return new AzureWorkspace(azureQuantumClient, azureQuantumWorkspace);
}

private static AzureEnvironment Production(string subscriptionId) =>
new AzureEnvironment()
{
Type = AzureEnvironmentType.Production,
ClientId = "84ba0947-6c53-4dd2-9ca9-b3694761521b", // QDK client ID
Authority = "https://login.microsoftonline.com/common",
Scopes = new List<string>() { "https://quantum.microsoft.com/Jobs.ReadWrite" },
BaseUri = new Uri("https://app-jobscheduler-prod.azurewebsites.net/"),
SubscriptionId = subscriptionId,
};

private static AzureEnvironment Dogfood(string subscriptionId) =>
new AzureEnvironment()
{
Type = AzureEnvironmentType.Dogfood,
ClientId = "46a998aa-43d0-4281-9cbb-5709a507ac36", // QDK dogfood client ID
Authority = GetDogfoodAuthority(subscriptionId),
Scopes = new List<string>() { "api://dogfood.azure-quantum/Jobs.ReadWrite" },
BaseUri = new Uri("https://app-jobscheduler-test.azurewebsites.net/"),
SubscriptionId = subscriptionId,
};

private static AzureEnvironment Canary()
private static AzureEnvironment Canary(string subscriptionId)
{
var canary = Production();
var canary = Production(subscriptionId);
canary.Type = AzureEnvironmentType.Canary;
canary.BaseUri = new Uri("https://app-jobs-canarysouthcentralus.azurewebsites.net/");
return canary;
}

private static AzureEnvironment Mock() =>
new AzureEnvironment() { Type = AzureEnvironmentType.Mock };

private static string GetDogfoodAuthority(string subscriptionId)
{
try
Expand Down
22 changes: 11 additions & 11 deletions src/AzureClient/AzureExecutionTarget.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#nullable enable
Expand All @@ -11,28 +11,28 @@ internal enum AzureProvider { IonQ, Honeywell, QCI }

internal class AzureExecutionTarget
{
public string TargetName { get; private set; }
public string PackageName => $"Microsoft.Quantum.Providers.{GetProvider(TargetName)}";
public string TargetId { get; private set; } = string.Empty;
public string PackageName => $"Microsoft.Quantum.Providers.{GetProvider(TargetId)}";

public static bool IsValid(string targetName) => GetProvider(targetName) != null;
public static bool IsValid(string targetId) => GetProvider(targetId) != null;

public static AzureExecutionTarget? Create(string targetName) =>
IsValid(targetName)
? new AzureExecutionTarget() { TargetName = targetName }
public static AzureExecutionTarget? Create(string targetId) =>
IsValid(targetId)
? new AzureExecutionTarget() { TargetId = targetId }
: null;

/// <summary>
/// Gets the Azure Quantum provider corresponding to the given execution target.
/// </summary>
/// <param name="targetName">The Azure Quantum execution target name.</param>
/// <param name="targetId">The Azure Quantum execution target ID.</param>
/// <returns>The <see cref="AzureProvider"/> enum value representing the provider.</returns>
/// <remarks>
/// Valid target names are structured as "provider.target".
/// Valid target IDs are structured as "provider.target".
/// For example, "ionq.simulator" or "honeywell.qpu".
/// </remarks>
private static AzureProvider? GetProvider(string targetName)
private static AzureProvider? GetProvider(string targetId)
{
var parts = targetName.Split('.', 2);
var parts = targetId.Split('.', 2);
if (Enum.TryParse(parts[0], true, out AzureProvider provider))
{
return provider;
Expand Down
Loading