Skip to content

Commit

Permalink
Implement the new monitor-events CLI for Py35+ users (#236)
Browse files Browse the repository at this point in the history
  • Loading branch information
jongio committed Aug 7, 2018
1 parent b5af592 commit 875bf1c
Show file tree
Hide file tree
Showing 14 changed files with 1,764 additions and 35 deletions.
2 changes: 1 addition & 1 deletion docker/linux/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ RUN AZ_REPO=$(lsb_release -cs) && \
apt-key adv --keyserver packages.microsoft.com --recv-keys 52E16F86FEE04B979B07E28DB02C46DF417A0893 && \
apt-get update && apt-get install azure-cli
RUN az extension add --name azure-cli-iot-ext && \
npm i -g iothub-explorer && npm i -g tree-kill && \
npm i -g iothub-explorer && \
apt-get update && \
apt-get install -y --no-install-recommends python-dev build-essential libssl-dev libffi-dev libxml2-dev libxslt1-dev zlib1g-dev && \
rm -rf /var/lib/apt/lists/*
Expand Down
9 changes: 6 additions & 3 deletions iotedgedev/azurecli.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@ def prepare_az_cli_args(self, args, suppress_output=False):

def invoke_az_cli_outproc(self, args, error_message=None, stdout_io=None, stderr_io=None, suppress_output=False):
try:

if stdout_io or stderr_io:
process = subprocess.Popen(self.prepare_az_cli_args(args, suppress_output), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=not self.envvars.is_posix())
else:
process = subprocess.Popen(self.prepare_az_cli_args(args, suppress_output), shell=not self.envvars.is_posix())

stdout_data, stderr_data = process.communicate()

if stderr_data and b"invalid_grant" in stderr_data:
Expand Down Expand Up @@ -245,11 +246,13 @@ def set_modules(self, device_id, connection_string, hub_name, config):

return self.invoke_az_cli_outproc(["iot", "edge", "set-modules", "-d", device_id, "-n", hub_name, "-k", config, "-l", connection_string], error_message=f("Failed to deploy '{config}' to '{device_id}'..."), suppress_output=True)

def monitor_events(self, device_id, connection_string, hub_name, timeout=300):
return self.invoke_az_cli_outproc(["iot", "hub", "monitor-events", "-d", device_id, "-n", hub_name, "-l", connection_string, '-t', str(timeout)], error_message=f("Failed to start monitoring events."), suppress_output=False)

def get_free_iothub(self):
with output_io_cls() as io:

result = self.invoke_az_cli_outproc(["iot", "hub", "list"],
f("Could not list IoT Hubs in subscription."), stdout_io=io)
result = self.invoke_az_cli_outproc(["iot", "hub", "list"], f("Could not list IoT Hubs in subscription."), stdout_io=io)
if result:
out_string = io.getvalue()
data = json.loads(out_string)
Expand Down
2 changes: 1 addition & 1 deletion iotedgedev/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def stop_simulator():
help="Specify number of milliseconds to monitor for messages")
def monitor(timeout):
utility = Utility(envvars, output)
ih = IoTHub(envvars, utility, output)
ih = IoTHub(envvars, utility, output, azure_cli)
ih.monitor_events(timeout)


Expand Down
5 changes: 5 additions & 0 deletions iotedgedev/compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import sys

PY35 = sys.version_info >= (3, 5)
PY3 = sys.version_info >= (3, 0)
PY2 = sys.version_info < (3, 0)
3 changes: 2 additions & 1 deletion iotedgedev/envvars.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import socket
import sys
from shutil import copyfile
from .compat import PY2

from dotenv import load_dotenv, set_key
from fstrings import f
Expand All @@ -28,7 +29,7 @@ def __init__(self, output):
def clean(self):
"""docker-py had py2 issues with shelling out to docker api if unicode characters are in any environment variable. This will convert to utf-8 if py2."""

if not (sys.version_info > (3, 0)):
if PY2:
environment = os.environ.copy()

clean_enviro = {}
Expand Down
26 changes: 20 additions & 6 deletions iotedgedev/iothub.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
import os

import sys
from .compat import PY35

class IoTHub:
def __init__(self, envvars, utility, output):
def __init__(self, envvars, utility, output, azure_cli):
self.envvars = envvars
self.output = output
self.utility = utility
self.azure_cli = azure_cli


def monitor_events(self, timeout=0):

self.envvars.verify_envvar_has_val("IOTHUB_CONNECTION_STRING", self.envvars.IOTHUB_CONNECTION_STRING)
self.envvars.verify_envvar_has_val("DEVICE_CONNECTION_STRING", self.envvars.DEVICE_CONNECTION_STRING)

if timeout == None:
timeout = 0

try:
self.output.status("It may take 1-2 minutes before you start to see messages below.")
self.output.header("MONITOR EVENTS")
self.output.status("It may take 1-2 minutes before you start to see messages below.")

if PY35:
self.monitor_events_cli(timeout)
else:
self.monitor_events_node(timeout)

def monitor_events_node(self, timeout=0):
try:

if timeout == 0:
self.utility.call_proc(['iothub-explorer', '--login', self.envvars.IOTHUB_CONNECTION_STRING,
'monitor-events', self.envvars.DEVICE_CONNECTION_INFO.DeviceId], shell=not self.envvars.is_posix())
Expand All @@ -26,6 +38,8 @@ def monitor_events(self, timeout=0):
self.utility.call_proc(['node', monitor_js, self.envvars.IOTHUB_CONNECTION_STRING,
self.envvars.DEVICE_CONNECTION_INFO.DeviceId, timeout], shell=not self.envvars.is_posix())
except Exception as ex:
self.output.error(
"Problem while trying to call iothub-explorer. Please ensure that you have installed the iothub-explorer npm package with: npm i -g iothub-explorer.")
self.output.error("Problem while trying to call iothub-explorer. Please ensure that you have installed the iothub-explorer npm package with: npm i -g iothub-explorer.")
self.output.error(str(ex))

def monitor_events_cli(self, timeout=0):
self.azure_cli.monitor_events(self.envvars.DEVICE_CONNECTION_INFO.DeviceId, self.envvars.IOTHUB_CONNECTION_INFO.ConnectionString, self.envvars.IOTHUB_CONNECTION_INFO.HubName, timeout)
5 changes: 1 addition & 4 deletions iotedgedev/monitor.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
const { spawn } = require('child_process');
var kill = require('tree-kill');

var ls = spawn('iothub-explorer', ['monitor-events', '--login', process.argv[2], process.argv[3]], { shell: true }).on('error', function (err) { console.log(err); throw err });

setTimeout(function () { kill(ls.pid) }, process.argv[4])
var ls = spawn('iothub-explorer', ['monitor-events', '--login', process.argv[2], process.argv[3], '--duration', process.argv[4]], { shell: true }).on('error', function (err) { console.log(err); throw err });

ls.stdout.on('data', (data) => {
console.log(`${data}`);
Expand Down
3 changes: 2 additions & 1 deletion iotedgedev/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
from hashlib import sha256
from hmac import HMAC
from time import time
from .compat import PY3

from .deploymentmanifest import DeploymentManifest
from .moduletype import ModuleType

if sys.version_info.major >= 3:
if PY3:
from urllib.parse import quote, urlencode
else:
from urllib import quote, urlencode
Expand Down
Loading

0 comments on commit 875bf1c

Please sign in to comment.