Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Azure DevCenter Package #26696

Merged
merged 20 commits into from
Oct 20, 2022
Merged
Show file tree
Hide file tree
Changes from 10 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
10 changes: 10 additions & 0 deletions .vscode/cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -1098,6 +1098,16 @@
"mrenclave",
"infile"
]
},
{
"filename": "sdk/devcenter/azure-developer-devcenter/azure/developer/devcenter/*.py",
"words": [
"Nify",
"ctxt",
"unflattened",
"deseralize",
"wday"
]
}
],
"allowCompoundWords": true
Expand Down
5 changes: 5 additions & 0 deletions sdk/devcenter/azure-developer-devcenter/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Release History

## 1.0.0b1 (2022-11-01)

- Initial version for the DevCenter service
21 changes: 21 additions & 0 deletions sdk/devcenter/azure-developer-devcenter/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
7 changes: 7 additions & 0 deletions sdk/devcenter/azure-developer-devcenter/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
include *.md
include LICENSE
include azure/developer/devcenter/py.typed
recursive-include tests *.py
recursive-include samples *.py *.md
include azure/__init__.py
include azure/developer/__init__.py
156 changes: 156 additions & 0 deletions sdk/devcenter/azure-developer-devcenter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@

# Azure DevCenter Service client library for Python
The Azure DevCenter package provides access to manage resources for Microsoft Dev Box and Azure Deployment Environments. This SDK enables managing developer machines and environments in Azure.

Use the package for Azure DevCenter to:
> Create, access, manage, and delete Dev Box resources
> Create, deploy, manage, and delete Environment resources

## Getting started

### Installating the package

```bash
python -m pip install azure-devcenter
chrissmiller marked this conversation as resolved.
Show resolved Hide resolved
```

#### Prequisites

- Python 3.7 or later is required to use this package.
- You need an [Azure subscription][azure_sub] to use this package.
- You must have [configured](https://learn.microsoft.com/azure/dev-box/quickstart-configure-dev-box-service) a DevCenter, Project, Network Connection, Dev Box Definition, and Pool before you can create Dev Boxes
- You must have [configured](https://learn.microsoft.com/azure/deployment-environments/) a DevCenter, Project, Catalog, and Environment Type before you can create Environments

#### Create with an Azure Active Directory Credential
To use an [Azure Active Directory (AAD) token credential][authenticate_with_token],
provide an instance of the desired credential type obtained from the
[azure-identity][azure_identity_credentials] library.

To authenticate with AAD, you must first [pip][pip] install [`azure-identity`][azure_identity_pip]

After setup, you can choose which type of [credential][azure_identity_credentials] from azure.identity to use.
As an example, [DefaultAzureCredential][default_azure_credential] can be used to authenticate the client:

Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:
`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`

Use the returned token credential to authenticate the client:

```python
>>> import os
>>> from azure.developer.devcenter import DevCenterClient
>>> from azure.identity import DefaultAzureCredential
>>> tenant_id = os.environ['AZURE_TENANT_ID']
>>> client = DevCenterClient(tenant_id: tenant_id, dev_center: "my_dev_center", credential=DefaultAzureCredential())
chrissmiller marked this conversation as resolved.
Show resolved Hide resolved
```

## Examples

### Dev Box Management
```python
>>> import os
>>> from azure.developer.devcenter import DevCenterClient
>>> from azure.identity import DefaultAzureCredential
>>> from azure.core.exceptions import HttpResponseError
>>> tenant_id = os.environ['AZURE_TENANT_ID']
>>> client = DevCenterClient(tenant_id: tenant_id, dev_center: "my_dev_center", credential=DefaultAzureCredential())
chrissmiller marked this conversation as resolved.
Show resolved Hide resolved
>>> try:
# Fetch control plane resource dependencies
projects = list(client.dev_center.list_projects(top=1))
target_project_name = projects[0]['name']

pools = list(client.dev_boxes.list_pools(target_project_name, top=1))
target_pool_name = pools[0]['name']

# Stand up a new dev box
create_response = client.dev_boxes.begin_create_dev_box(target_project_name, "Test_DevBox", {"poolName": target_pool_name})
devbox_result = create_response.result()

LOG.info(f"Provisioned dev box with status {devbox_result['provisioningState']}.")

# Connect to the provisioned dev box
remote_connection_response = client.dev_boxes.get_remote_connection(target_project_name, "Test_DevBox")
LOG.info(f"Connect to the dev box using web URL {remote_connection_response['webUrl']}")

# Tear down the dev box when finished
delete_response = client.dev_boxes.begin_delete_dev_box(target_project_name, "Test_DevBox")
delete_response.wait()
LOG.info("Deleted dev box successfully.")
except HttpResponseError as e:
print('service responds error: {}'.format(e.response.json()))

```

### Environment Management
```python
>>> import os
>>> from azure.developer.devcenter import DevCenterClient
>>> from azure.identity import DefaultAzureCredential
>>> from azure.core.exceptions import HttpResponseError
>>> tenant_id = os.environ['AZURE_TENANT_ID']
>>> client = DevCenterClient(tenant_id: tenant_id, dev_center: "my_dev_center", credential=DefaultAzureCredential())
chrissmiller marked this conversation as resolved.
Show resolved Hide resolved
>>> try:
# Fetch control plane resource dependencies
target_project_name = list(client.dev_center.list_projects(top=1))[0]['name']
target_catalog_item_name = list(client.environments.list_catalog_items(target_project_name, top=1))[0]['name']
target_environment_type_name = list(client.environments.list_environment_types(target_project_name, top=1))[0]['name']

# Stand up a new environment
create_response = client.environments.begin_create_environment(target_project_name,
"Dev_Environment",
{"catalogItemName": target_catalog_item_name, "environmentType": target_environment_type_name})
environment_result = create_response.result()

LOG.info(f"Provisioned environment with status {environment_result['provisioningState']}.")

# Fetch deployment artifacts
artifact_response = client.environments.list_artifacts_by_environment(target_project_name, "Dev_Environment")

for artifact in artifact_response:
LOG.info(artifact)

# Tear down the environment when finished
delete_response = client.environments.begin_delete_environment(target_project_name, "Dev_Environment")
delete_response.wait()
LOG.info("Completed deletion for the environment.")
except HttpResponseError as e:
print('service responds error: {}'.format(e.response.json()))

```
## Key Concepts
Dev Boxes refer to managed developer machines running in Azure. Dev Boxes are provisioned in Pools, which define the network and image used for a Dev Box.

Environments refer to templated developer environments, which combine a template (Catalog Item) and parameters.

## Troubleshooting
Errors can occur during initial requests and long-running operations, and will provide information about how to resolve the error.
Be sure to confirm that dependent resources, such as pools and catalogs, are set up properly and are in a healthy state. You will not be able to create resources with the package when your dependent resources are in a failed state.

## Next Steps
Get started by exploring our samples and starting to use the package!

## Contributing

This project welcomes contributions and suggestions. Most contributions require
you to agree to a Contributor License Agreement (CLA) declaring that you have
the right to, and actually do, grant us the rights to use your contribution.
For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether
you need to provide a CLA and decorate the PR appropriately (e.g., label,
comment). Simply follow the instructions provided by the bot. You will only
need to do this once across all repos using our CLA.

This project has adopted the
[Microsoft Open Source Code of Conduct][code_of_conduct]. For more information,
see the Code of Conduct FAQ or contact opencode@microsoft.com with any
additional questions or comments.

<!-- LINKS -->
[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/
[authenticate_with_token]: https://docs.microsoft.com/azure/cognitive-services/authentication?tabs=powershell#authenticate-with-an-authentication-token
[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#credentials
[azure_identity_pip]: https://pypi.org/project/azure-identity/
[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential
[pip]: https://pypi.org/project/pip/
[azure_sub]: https://azure.microsoft.com/free/
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from ._client import DevCenterClient
from ._version import VERSION

__version__ = VERSION

try:
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
except ImportError:
_patch_all = []
from ._patch import patch_sdk as _patch_sdk

__all__ = ["DevCenterClient"]
__all__.extend([p for p in _patch_all if p not in __all__])

_patch_sdk()
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from copy import deepcopy
from typing import Any, TYPE_CHECKING

from azure.core import PipelineClient
from azure.core.rest import HttpRequest, HttpResponse

from ._configuration import DevCenterClientConfiguration
from ._serialization import Deserializer, Serializer
from .operations import DevBoxesOperations, DevCenterOperations, EnvironmentsOperations

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

from azure.core.credentials import TokenCredential


class DevCenterClient: # pylint: disable=client-accepts-api-version-keyword
"""DevBox API.

:ivar dev_center: DevCenterOperations operations
:vartype dev_center: azure.developer.devcenter.operations.DevCenterOperations
:ivar dev_boxes: DevBoxesOperations operations
:vartype dev_boxes: azure.developer.devcenter.operations.DevBoxesOperations
:ivar environments: EnvironmentsOperations operations
:vartype environments: azure.developer.devcenter.operations.EnvironmentsOperations
:param tenant_id: The tenant to operate on. Required.
:type tenant_id: str
:param dev_center: The DevCenter to operate on. Required.
:type dev_center: str
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param dev_center_dns_suffix: The DNS suffix used as the base for all devcenter requests.
Default value is "devcenter.azure.com".
:type dev_center_dns_suffix: str
:keyword api_version: Api Version. Default value is "2022-03-01-preview". Note that overriding
this default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""

def __init__(
self,
tenant_id: str,
dev_center: str,
credential: "TokenCredential",
dev_center_dns_suffix: str = "devcenter.azure.com",
**kwargs: Any
) -> None:
_endpoint = "https://{tenantId}-{devCenter}.{devCenterDnsSuffix}"
self._config = DevCenterClientConfiguration(
tenant_id=tenant_id,
dev_center=dev_center,
credential=credential,
dev_center_dns_suffix=dev_center_dns_suffix,
**kwargs
)
self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs)

self._serialize = Serializer()
self._deserialize = Deserializer()
self._serialize.client_side_validation = False
self.dev_center = DevCenterOperations(self._client, self._config, self._serialize, self._deserialize)
self.dev_boxes = DevBoxesOperations(self._client, self._config, self._serialize, self._deserialize)
self.environments = EnvironmentsOperations(self._client, self._config, self._serialize, self._deserialize)

def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.

>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>

For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request

:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""

request_copy = deepcopy(request)
path_format_arguments = {
"tenantId": self._serialize.url("self._config.tenant_id", self._config.tenant_id, "str", skip_quote=True),
"devCenter": self._serialize.url(
"self._config.dev_center", self._config.dev_center, "str", skip_quote=True
),
"devCenterDnsSuffix": self._serialize.url(
"self._config.dev_center_dns_suffix", self._config.dev_center_dns_suffix, "str", skip_quote=True
),
}

request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments)
return self._client.send_request(request_copy, **kwargs)

def close(self):
# type: () -> None
self._client.close()

def __enter__(self):
# type: () -> DevCenterClient
self._client.__enter__()
return self

def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
Loading