Skip to content

Commit

Permalink
Staging point. (#202)
Browse files Browse the repository at this point in the history
  • Loading branch information
digimaun authored Jun 18, 2020
1 parent c07dd41 commit 962f26f
Show file tree
Hide file tree
Showing 15 changed files with 473 additions and 557 deletions.
127 changes: 0 additions & 127 deletions azext_iot/common/_azure.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@

from knack.util import CLIError
from azext_iot.common.utility import validate_key_value_pairs
from azext_iot.common.utility import trim_from_start
from azext_iot._factory import iot_hub_service_factory
from azext_iot.common.auth import get_aad_token


Expand Down Expand Up @@ -48,131 +46,6 @@ def parse_iot_device_module_connection_string(cs):
CONN_STR_TEMPLATE = "HostName={};SharedAccessKeyName={};SharedAccessKey={}"


def get_iot_hub_connection_string(
cmd,
hub_name,
resource_group_name,
policy_name="iothubowner",
key_type="primary",
include_events=False,
login=None,
):
"""
Function used to build up dictionary of IoT Hub connection string parts
Args:
cmd (object): Knack cmd
hub_name (str): IoT Hub name
resource_group_name (str): name of Resource Group contianing IoT Hub
policy_name (str): Security policy name for shared key; e.g. 'iothubowner'(default)
key_type (str): Shared key; either 'primary'(default) or 'secondary'
include_events (bool): Include key event hub properties
Returns:
(dict): of connection string elements.
Raises:
CLIError: on input validation failure.
"""

result = {}
target_hub = None
policy = None

if login:
try:
decomposed = parse_iot_hub_connection_string(login)
decomposed_lower = dict((k.lower(), v) for k, v in decomposed.items())
except ValueError as e:
raise CLIError(e)

result = {}
result["cs"] = login
result["policy"] = decomposed_lower["sharedaccesskeyname"]
result["primarykey"] = decomposed_lower["sharedaccesskey"]
result["entity"] = decomposed_lower["hostname"]
return result

client = None
if getattr(cmd, "cli_ctx", None):
client = iot_hub_service_factory(cmd.cli_ctx)
else:
client = cmd

def _find_iot_hub_from_list(hubs, hub_name):
if hubs:
return next(
(hub for hub in hubs if hub_name.lower() == hub.name.lower()), None
)
return None

if resource_group_name is None:
hubs = client.list_by_subscription()
if not hubs:
raise CLIError("No IoT Hub found in current subscription.")
target_hub = _find_iot_hub_from_list(hubs, hub_name)
else:
try:
target_hub = client.get(resource_group_name, hub_name)
except Exception:
pass

if target_hub is None:
raise CLIError(
"No IoT Hub found with name {} in current subscription.".format(hub_name)
)

try:
addprops = getattr(target_hub, "additional_properties", None)
resource_group_name = (
addprops.get("resourcegroup")
if addprops
else getattr(target_hub, "resourcegroup", None)
)

policy = client.get_keys_for_key_name(
resource_group_name, target_hub.name, policy_name
)
except Exception:
pass

if policy is None:
raise CLIError(
"No keys found for policy {} of IoT Hub {}.".format(policy_name, hub_name)
)

result["cs"] = CONN_STR_TEMPLATE.format(
target_hub.properties.host_name,
policy.key_name,
policy.primary_key if key_type == "primary" else policy.secondary_key,
)
result["entity"] = target_hub.properties.host_name
result["policy"] = policy_name
result["primarykey"] = policy.primary_key
result["secondarykey"] = policy.secondary_key
result["subscription"] = client.config.subscription_id
result["resourcegroup"] = resource_group_name
result["location"] = target_hub.location
result["sku_tier"] = target_hub.sku.tier.value

if include_events:
events = {}
events["endpoint"] = trim_from_start(
target_hub.properties.event_hub_endpoints["events"].endpoint, "sb://"
).strip("/")
events["partition_count"] = target_hub.properties.event_hub_endpoints[
"events"
].partition_count
events["path"] = target_hub.properties.event_hub_endpoints["events"].path
events["partition_ids"] = target_hub.properties.event_hub_endpoints[
"events"
].partition_ids
result["events"] = events

return result


def get_iot_dps_connection_string(
client,
dps_name,
Expand Down
2 changes: 1 addition & 1 deletion azext_iot/digitaltwins/_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def load_digitaltwins_help():

helps["dt"] = """
type: group
short-summary: Manage Azure Digital Twins (ADT) solutions & infrastructure.
short-summary: Manage Azure Digital Twins solutions & infrastructure.
"""

helps["dt create"] = """
Expand Down
28 changes: 0 additions & 28 deletions azext_iot/iothub/mgmt_helpers.py

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,3 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

import pytest
from azext_iot.digitaltwins.providers.resource import ResourceProvider


@pytest.fixture
def dt_rp(fixture_cmd2):
rp = ResourceProvider(fixture_cmd2)
yield rp
33 changes: 33 additions & 0 deletions azext_iot/iothub/models/iothub_target.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# 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.
# --------------------------------------------------------------------------------------------

from azext_iot.common._azure import parse_iot_hub_connection_string


# TODO: Align with vNext for IoT Hub
class IotHubTarget:
def __init__(self, decomposed: dict):
# Revisit
decomposed_lower = dict((k.lower(), v) for k, v in decomposed.items())

self.cs = decomposed_lower.get("cs")
self.policy = decomposed_lower.get("sharedaccesskeyname")
self.shared_access_key = decomposed_lower.get("sharedaccesskey")
self.entity = decomposed_lower.get("hostname")

@classmethod
def from_connection_string(cls, cstring):
decomposed = parse_iot_hub_connection_string(cs=cstring)
decomposed["cs"] = cstring
return cls(decomposed)

def as_dict(self):
return {
"cs": self.cs,
"policy": self.policy,
"primarykey": self.shared_access_key,
"entity": self.entity,
}
8 changes: 4 additions & 4 deletions azext_iot/iothub/providers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

from azext_iot.common._azure import get_iot_hub_connection_string
from azext_iot.iothub.providers.discovery import IotHubDiscovery
from azext_iot._factory import SdkResolver
from msrest.exceptions import SerializationError
from msrestazure.azure_exceptions import CloudError
Expand All @@ -18,10 +18,10 @@ def __init__(self, cmd, hub_name, rg, login=None):
self.cmd = cmd
self.hub_name = hub_name
self.rg = rg
self.target = get_iot_hub_connection_string(
cmd=self.cmd,
self.discovery = IotHubDiscovery(cmd)
self.target = self.discovery.get_target(
hub_name=self.hub_name,
resource_group_name=self.rg,
rg=self.rg,
login=login,
)
self.resolver = SdkResolver(self.target)
Expand Down
Loading

0 comments on commit 962f26f

Please sign in to comment.