Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 6 additions & 8 deletions azure-quantum/azure/quantum/_authentication/_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@

if TYPE_CHECKING:
# pylint:disable=unused-import,ungrouped-imports
from typing import Any, Optional
from azure.core.credentials import AccessToken
from typing import Any

_LOGGER = logging.getLogger(__name__)

_TOKEN_FILE_ENV_VARIABLE="AZURE_QUANTUM_TOKEN_FILE"
_TOKEN_FILE_ENV_VARIABLE = "AZURE_QUANTUM_TOKEN_FILE"


class _TokenFileCredential(object):
"""
Expand Down Expand Up @@ -70,13 +70,11 @@ def get_token(self, *scopes, **kwargs): # pylint:disable=unused-argument
raise CredentialUnavailableError(message="Token already expired at {}".format(time.asctime(time.gmtime(token.expires_on))))

return token

def _parse_token_file(self, path):
# type: (*str) -> AccessToken

with open(path, "r") as file:
data = json.load(file)
expires_on = int(data["expires_on"]) / 1000 # Convert ms to seconds, since python time.time only handles epoch time in seconds
expires_on = int(data["expires_on"]) / 1000 # Convert ms to seconds, since python time.time only handles epoch time in seconds
token = AccessToken(data["access_token"], expires_on)

return token
return token
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@

from ._chained import *
from ._default import _DefaultAzureCredential
from ._token import _TokenFileCredential
4 changes: 4 additions & 0 deletions azure-quantum/azure/quantum/aio/_authentication/_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
VisualStudioCodeCredential,
)
from ._chained import _ChainedTokenCredential
from ._token import _TokenFileCredential

try:
from typing import TYPE_CHECKING
Expand Down Expand Up @@ -81,6 +82,7 @@ def __init__(self, **kwargs):
"visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)
)

self.exclude_token_file_credential = kwargs.pop("exclude_token_file_credential", False)
self.exclude_environment_credential = kwargs.pop("exclude_environment_credential", False)
self.exclude_managed_identity_credential = kwargs.pop("exclude_managed_identity_credential", False)
self.exclude_shared_token_cache_credential = kwargs.pop("exclude_shared_token_cache_credential", False)
Expand All @@ -104,6 +106,8 @@ def _initialize_credentials(self):
self.interactive_browser_tenant_id = self._get_tenant_id(arm_base_url=self.arm_base_url, subscription_id=self.subscription_id)

credentials = [] # type: List[AsyncTokenCredential]
if not self.exclude_token_file_credential:
credentials.append(_TokenFileCredential())
if not self.exclude_environment_credential:
credentials.append(EnvironmentCredential(authority=self.authority))
if not self.exclude_managed_identity_credential:
Expand Down
81 changes: 81 additions & 0 deletions azure-quantum/azure/quantum/aio/_authentication/_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
import json
from json.decoder import JSONDecodeError
import logging
import os
import time
from aiofile import async_open

from azure.identity import CredentialUnavailableError
from azure.core.credentials import AccessToken

try:
from typing import TYPE_CHECKING
except ImportError:
TYPE_CHECKING = False

if TYPE_CHECKING:
# pylint:disable=unused-import,ungrouped-imports
from typing import Any

_LOGGER = logging.getLogger(__name__)

_TOKEN_FILE_ENV_VARIABLE = "AZURE_QUANTUM_TOKEN_FILE"


class _TokenFileCredential(object):
"""
Implements a custom TokenCredential to use a local file as the source for an AzureQuantum token.

It will only use the local file if the AZURE_QUANTUM_TOKEN_FILE environment variable is set, and references
an existing json file that contains the access_token and expires_on timestamp in milliseconds.

If the environment variable is not set, the file does not exist, or the token is invalid in any way (expired, for example),
then the credential will throw CredentialUnavailableError, so that _ChainedTokenCredential can fallback to other methods.
"""
def __init__(self, **kwargs):
# type: (**Any) -> None
self.token_file = os.environ.get(_TOKEN_FILE_ENV_VARIABLE)
if self.token_file:
_LOGGER.debug("Using provided token file location: {}".format(self.token_file))
else:
_LOGGER.debug("No token file location provided for {} environment variable.".format(_TOKEN_FILE_ENV_VARIABLE))

async def get_token(self, *scopes, **kwargs): # pylint:disable=unused-argument
# type: (*str, **Any) -> AccessToken
"""Request an access token for `scopes`.
This method is called automatically by Azure SDK clients.
:param str scopes: desired scopes for the access token. This method only returns tokens for the https://quantum.microsoft.com/.default scope.
:raises ~azure.identity.CredentialUnavailableError: when failing to get token. The exception has a
`message` attribute with the error message.
"""
if not self.token_file:
raise CredentialUnavailableError(message="Token file location not set.")

if not os.path.isfile(self.token_file):
raise CredentialUnavailableError(message="Token file at {} does not exist.".format(self.token_file))

try:
token = await self._parse_token_file(self.token_file)
except JSONDecodeError:
raise CredentialUnavailableError(message="Failed to parse token file: Invalid JSON.")
except KeyError as e:
raise CredentialUnavailableError(message="Failed to parse token file: Missing expected value: " + str(e))
except Exception as e:
raise CredentialUnavailableError(message="Failed to parse token file: " + str(e))

if token.expires_on <= time.time():
raise CredentialUnavailableError(message="Token already expired at {}".format(time.asctime(time.gmtime(token.expires_on))))

return token

async def _parse_token_file(self, path):
# type: (*str) -> AccessToken
async with async_open(path, "r") as file:
data = json.load(file)
expires_on = int(data["expires_on"]) / 1000 # Convert ms to seconds, since python time.time only handles epoch time in seconds
token = AccessToken(data["access_token"], expires_on)
return token
4 changes: 2 additions & 2 deletions azure-quantum/azure/quantum/aio/job/base_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

logger = logging.getLogger(__name__)

DEFAULT_TIMEOUT = 300 # Default timeout for waiting for job to complete
DEFAULT_TIMEOUT = 300 # Default timeout for waiting for job to complete


class BaseJob(SyncBaseJob):
Expand Down Expand Up @@ -203,7 +203,7 @@ async def upload_input_data(
input_data: bytes,
content_type: str,
blob_name: str = "inputData",
encoding = "",
encoding: str = "",
return_sas_token: bool = False
) -> str:
"""Upload input data file
Expand Down
13 changes: 4 additions & 9 deletions azure-quantum/azure/quantum/aio/job/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,18 @@
import logging
import json

from typing import TYPE_CHECKING

from azure.quantum._client.models import JobDetails
from azure.quantum.aio.job.base_job import BaseJob, DEFAULT_TIMEOUT
from azure.quantum.job.job import Job as SyncJob
from azure.quantum.job.filtered_job import FilteredJob

__all__ = ["Job"]

logger = logging.getLogger(__name__)

if TYPE_CHECKING:
from azure.quantum.aio.workspace import Workspace


_log = logging.getLogger(__name__)

class Job(BaseJob, SyncJob):

class Job(BaseJob, SyncJob, FilteredJob):
"""Azure Quantum Job that is submitted to a given Workspace.

:param workspace: Workspace instance to submit job to
Expand Down Expand Up @@ -80,7 +75,7 @@ async def wait_until_completed(
else poll_wait * 1.5
)

async def get_results(self, timeout_secs: float=DEFAULT_TIMEOUT) -> dict:
async def get_results(self, timeout_secs: float = DEFAULT_TIMEOUT) -> dict:
"""Get job results by downloading the results blob from the
storage container linked via the workspace.

Expand Down
10 changes: 10 additions & 0 deletions azure-quantum/azure/quantum/aio/optimization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,13 @@
from .problem import *
from .online_problem import *
from .streaming_problem import *
from .online_problem import *
from azure.quantum.aio.target import Solver
from azure.quantum.aio.target.microsoft.qio import (
ParallelTempering,
PopulationAnnealing,
QuantumMonteCarlo,
SimulatedAnnealing,
SubstochasticMonteCarlo,
Tabu,
)
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@


class OnlineProblem(SyncOnlineProblem):
async def download(self, workspace:"Workspace") -> Problem:
async def download(self, workspace: "Workspace") -> Problem:
logger.warning("The problem will be downloaded to the client")
return await Problem.download(self, workspace)
2 changes: 1 addition & 1 deletion azure-quantum/azure/quantum/aio/optimization/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ async def upload(
self.uploaded_blob_uri = input_data_uri
return input_data_uri

async def download(self, workspace:"Workspace"):
async def download(self, workspace: "Workspace"):
"""Downloads the uploaded problem as an instance of `Problem`"""
if not self.uploaded_blob_uri:
raise Exception(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ async def add_terms(self, terms: List[Term]):
self.terms_queue.put_nowait(terms)
await uploader_task


async def download(self):
"""Downloads the uploaded problem as an instance of `Problem`"""
if not self.uploaded_uri:
Expand Down
7 changes: 2 additions & 5 deletions azure-quantum/azure/quantum/aio/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ async def create_container_using_client(container_client: ContainerClient):
"""
Creates and initializes a container.
"""
try:
await container_client.get_container_properties()
logger.debug(f'{" - uploading to existing container"}')
except Exception:
if not await container_client.exists():
logger.debug(
f'{" - uploading to **new** container:"}'
f"{container_client.container_name}"
Expand Down Expand Up @@ -156,7 +153,7 @@ async def append_blob(
content_settings=content_settings, metadata=metadata
)

blob.append_block(data, len(data))
await blob.append_block(data, len(data))
logger.debug(f" - blob '{blob_name}' appended. generating sas token.")

if return_sas_token:
Expand Down
4 changes: 4 additions & 0 deletions azure-quantum/azure/quantum/aio/target/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
from azure.quantum.aio.target.ionq import IonQ
from azure.quantum.aio.target.honeywell import Honeywell
from azure.quantum.aio.target.target import Target
Expand Down
3 changes: 0 additions & 3 deletions azure-quantum/azure/quantum/aio/target/ionq.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
import io
import json
from typing import Any, Dict

from azure.quantum.aio.target.target import Target
from azure.quantum.aio.job.job import Job
from azure.quantum.aio.workspace import Workspace
from azure.quantum.target import IonQ as SyncIonQ


Expand Down
2 changes: 2 additions & 0 deletions azure-quantum/azure/quantum/aio/target/solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
logger = logging.getLogger(__name__)

__all__ = [
"HardwarePlatform",
"RangeSchedule",
"Solver",
]

Expand Down
17 changes: 13 additions & 4 deletions azure-quantum/azure/quantum/aio/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ class Workspace:

Defaults to \"DefaultAzureCredential\", which will attempt multiple
forms of authentication.

:param user_agent:
Add the specified value as a prefix to the HTTP User-Agent header when communicating to the Azure Quantum service.
"""

credentials = None
Expand Down Expand Up @@ -117,6 +120,7 @@ def __init__(
# See _DefaultAzureCredential documentation for more info.
if credential is None:
credential = _DefaultAzureCredential(exclude_interactive_browser_credential=False,
exclude_shared_token_cache_credential=True,
subscription_id=subscription_id,
arm_base_url=ARM_BASE_URL)

Expand All @@ -127,7 +131,7 @@ def __init__(
self.storage = storage
self.user_agent = user_agent

if self.user_agent == None:
if self.user_agent is None:
self.user_agent = os.environ.get("AZURE_QUANTUM_PYTHON_APPID", "azure-quantum-async")

# Convert user-provided location into names
Expand All @@ -136,20 +140,25 @@ def __init__(
# "West US" should be converted to "westus".
self.location = "".join(location.split()).lower()

# Create QuantumClient
self._client = self._create_client()

def _create_client(self) -> QuantumClient:
base_url = BASE_URL(self.location)
logger.debug(
f"Creating client for: subs:{self.subscription_id},"
+ f"rg={self.resource_group}, ws={self.name}, frontdoor={base_url}"
)

self._client = QuantumClient(
client = QuantumClient(
credential=self.credentials,
subscription_id=self.subscription_id,
resource_group_name=self.resource_group,
workspace_name=self.name,
base_url=base_url,
user_agent=self.user_agent
)
return client

async def _get_linked_storage_sas_uri(
self, container_name: str, blob_name: str = None
Expand Down Expand Up @@ -181,8 +190,8 @@ async def get_job(self, job_id: str) -> Job:
return Job(self, details)

async def list_jobs(
self,
name_match: str = None,
self,
name_match: str = None,
status: Optional[JobStatus] = None,
created_after: Optional[datetime] = None
) -> List[Job]:
Expand Down
5 changes: 2 additions & 3 deletions azure-quantum/azure/quantum/job/base_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

from urllib.parse import urlparse
from typing import Any, Dict, TYPE_CHECKING
from urllib.parse import urlparse
from azure.storage.blob import BlobClient

from azure.quantum.storage import upload_blob, download_blob, ContainerClient
Expand All @@ -21,7 +20,7 @@

logger = logging.getLogger(__name__)

DEFAULT_TIMEOUT = 300 # Default timeout for waiting for job to complete
DEFAULT_TIMEOUT = 300 # Default timeout for waiting for job to complete


class BaseJob(abc.ABC):
Expand Down Expand Up @@ -211,7 +210,7 @@ def upload_input_data(
input_data: bytes,
content_type: str,
blob_name: str = "inputData",
encoding = "",
encoding: str = "",
return_sas_token: bool = False
) -> str:
"""Upload input data file
Expand Down
3 changes: 2 additions & 1 deletion azure-quantum/azure/quantum/job/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

_log = logging.getLogger(__name__)


class Job(BaseJob, FilteredJob):
"""Azure Quantum Job that is submitted to a given Workspace.

Expand Down Expand Up @@ -95,7 +96,7 @@ def wait_until_completed(
else poll_wait * 1.5
)

def get_results(self, timeout_secs: float=DEFAULT_TIMEOUT) -> dict:
def get_results(self, timeout_secs: float = DEFAULT_TIMEOUT) -> dict:
"""Get job results by downloading the results blob from the
storage container linked via the workspace.

Expand Down
Loading