Skip to content

Commit

Permalink
Generated batch clients
Browse files Browse the repository at this point in the history
  • Loading branch information
annatisch committed Mar 31, 2016
1 parent 01874b0 commit afe71c4
Show file tree
Hide file tree
Showing 233 changed files with 22,499 additions and 0 deletions.
2 changes: 2 additions & 0 deletions azure-batch/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include *.rst
exclude azure/__init__.py
41 changes: 41 additions & 0 deletions azure-batch/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
Microsoft Azure SDK for Python
==============================

This is the Microsoft Azure Batch Client Library.

This package has been tested with Python 2.7, 3.3, 3.4 and 3.5.


Compatibility
=============

**IMPORTANT**: If you have an earlier version of the azure package
(version < 1.0), you should uninstall it before installing this package.

You can check the version using pip:

.. code:: shell
pip freeze
If you see azure==0.11.0 (or any version below 1.0), uninstall it first:

.. code:: shell
pip uninstall azure
Usage
=====

For code examples, see `the Batch samples repo
<https://github.com/Azure/azure-batch-samples/tree/master/Python>`__
on GitHub.


Provide Feedback
================

If you encounter any bugs or have suggestions, please file an issue in the
`Issues <https://github.com/Azure/azure-sdk-for-python/issues>`__
section of the project.
1 change: 1 addition & 0 deletions azure-batch/azure/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__import__('pkg_resources').declare_namespace(__name__)
31 changes: 31 additions & 0 deletions azure-batch/azure/batch/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft and contributors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------

from .batch_service_client import BatchServiceClient, BatchServiceClientConfiguration
from .version import VERSION

__all__ = [
'BatchServiceClient',
'BatchServiceClientConfiguration'
]

__version__ = VERSION

136 changes: 136 additions & 0 deletions azure-batch/azure/batch/batch_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft and contributors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
# --------------------------------------------------------------------------

import time
import keyring
import ast
import base64
import hmac
import hashlib
import datetime

import requests
from requests.auth import AuthBase
from msrest.authentication import Authentication
from msrest import Serializer

try:
from urlparse import urlparse, parse_qs

except ImportError:
from urllib.parse import urlparse, parse_qs

class SharedKeyAuth(AuthBase):

headers_to_sign = [
'content-encoding',
'content-language',
'content-length',
'content-md5',
'content-type',
'date',
'if-modified-since',
'if-match',
'if-none-match',
'if-unmodified-since',
'range']

def __init__(self, header, account_name, key):
self._header = header
self._account_name = account_name
self._key = key

def __call__(self, request):

if not request.headers.get('ocp-date'):
request.headers['ocp-date'] = Serializer.serialize_rfc(
datetime.datetime.utcnow())

url = urlparse(request.url)
uri_path = url.path
uri_path = uri_path.replace('%5C', '/')
uri_path = uri_path.replace('%2F', '/')

# method to sign
string_to_sign = request.method + '\n'

# get headers to sign
request_header_dict = {
key.lower(): val for key, val in request.headers.items() if val}

request_headers = [
str(request_header_dict.get(x, '')) for x in self.headers_to_sign]

string_to_sign += '\n'.join(request_headers) + '\n'

# get ocp- header to sign
ocp_headers = []
for name, value in request.headers.items():
if 'ocp-' in name and value:
ocp_headers.append((name.lower(), value))

for name, value in sorted(ocp_headers):
string_to_sign += "{}:{}\n".format(name, value)

# get account_name and uri path to sign
string_to_sign += "/{}{}".format(self._account_name, uri_path)

# get query string to sign if it is not table service
query_to_sign = parse_qs(url.query)

for name in sorted(query_to_sign.keys()):
value = query_to_sign[name][0]
if value:
string_to_sign += "\n{}:{}".format(name, value)

# sign the request
auth_string = "SharedKey {}:{}".format(
self._account_name, self._sign_string(string_to_sign))

request.headers[self._header] = auth_string

return request

def _sign_string(self, string_to_sign):

_key = self._key.encode('utf-8')
string_to_sign = string_to_sign.encode('utf-8')

try:
key = base64.b64decode(_key)
except TypeError:
raise ValueError("Invalid key value: {}".format(self._key))

signed_hmac_sha256 = hmac.HMAC(key, string_to_sign, hashlib.sha256)
digest = signed_hmac_sha256.digest()

return base64.b64encode(digest).decode('utf-8')


class SharedKeyCredentials(Authentication):

def __init__(self, account_name, key):
super(SharedKeyCredentials, self).__init__()
self.auth = SharedKeyAuth(self.header, account_name, key)

def signed_session(self):

session = super(SharedKeyCredentials, self).signed_session()
session.auth = self.auth

return session

134 changes: 134 additions & 0 deletions azure-batch/azure/batch/batch_service_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft and contributors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------

from msrest.service_client import ServiceClient
from msrest import Serializer, Deserializer
from msrestazure import AzureConfiguration
from .version import VERSION
from .operations.application_operations import ApplicationOperations
from .operations.pool_operations import PoolOperations
from .operations.account_operations import AccountOperations
from .operations.job_operations import JobOperations
from .operations.certificate_operations import CertificateOperations
from .operations.file_operations import FileOperations
from .operations.job_schedule_operations import JobScheduleOperations
from .operations.task_operations import TaskOperations
from .operations.compute_node_operations import ComputeNodeOperations
from . import models


class BatchServiceClientConfiguration(AzureConfiguration):
"""Configuration for BatchServiceClient
Note that all parameters used to create this instance are saved as instance
attributes.
:param credentials: Gets Azure subscription credentials.
:type credentials: :mod:`A msrestazure Credentials
object<msrestazure.azure_active_directory>`
:param api_version: Client API Version.
:type api_version: str
:param accept_language: Gets or sets the preferred language for the
response.
:type accept_language: str
:param long_running_operation_retry_timeout: Gets or sets the retry
timeout in seconds for Long Running Operations. Default value is 30.
:type long_running_operation_retry_timeout: int
:param generate_client_request_id: When set to true a unique
x-ms-client-request-id value is generated and included in each request.
Default is true.
:type generate_client_request_id: bool
:param str base_url: Service URL
:param str filepath: Existing config
"""

def __init__(
self, credentials, api_version='2016-02-01.3.0', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None):

if credentials is None:
raise ValueError('credentials must not be None.')
if not base_url:
base_url = 'https://batch.core.windows.net'

super(BatchServiceClientConfiguration, self).__init__(base_url, filepath)

self.add_user_agent('batchserviceclient/{}'.format(VERSION))
self.add_user_agent('Azure-SDK-For-Python')

self.credentials = credentials
self.api_version = api_version
self.accept_language = accept_language
self.long_running_operation_retry_timeout = long_running_operation_retry_timeout
self.generate_client_request_id = generate_client_request_id


class BatchServiceClient(object):
"""A client for issuing REST requests to the Azure Batch service.
:param config: Configuration for client.
:type config: BatchServiceClientConfiguration
:ivar application: Application operations
:vartype application: .operations.ApplicationOperations
:ivar pool: Pool operations
:vartype pool: .operations.PoolOperations
:ivar account: Account operations
:vartype account: .operations.AccountOperations
:ivar job: Job operations
:vartype job: .operations.JobOperations
:ivar certificate: Certificate operations
:vartype certificate: .operations.CertificateOperations
:ivar file: File operations
:vartype file: .operations.FileOperations
:ivar job_schedule: JobSchedule operations
:vartype job_schedule: .operations.JobScheduleOperations
:ivar task: Task operations
:vartype task: .operations.TaskOperations
:ivar compute_node: ComputeNode operations
:vartype compute_node: .operations.ComputeNodeOperations
"""

def __init__(self, config):

self._client = ServiceClient(config.credentials, config)

client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer()
self._deserialize = Deserializer(client_models)

self.config = config
self.application = ApplicationOperations(
self._client, self.config, self._serialize, self._deserialize)
self.pool = PoolOperations(
self._client, self.config, self._serialize, self._deserialize)
self.account = AccountOperations(
self._client, self.config, self._serialize, self._deserialize)
self.job = JobOperations(
self._client, self.config, self._serialize, self._deserialize)
self.certificate = CertificateOperations(
self._client, self.config, self._serialize, self._deserialize)
self.file = FileOperations(
self._client, self.config, self._serialize, self._deserialize)
self.job_schedule = JobScheduleOperations(
self._client, self.config, self._serialize, self._deserialize)
self.task = TaskOperations(
self._client, self.config, self._serialize, self._deserialize)
self.compute_node = ComputeNodeOperations(
self._client, self.config, self._serialize, self._deserialize)
Loading

0 comments on commit afe71c4

Please sign in to comment.