Skip to content

Commit

Permalink
Issue 641 (#715)
Browse files Browse the repository at this point in the history
* add environment test to catch config issues

* flake8

* catch host resolution issue
  • Loading branch information
maaikelimper authored Jul 29, 2024
1 parent 87e6fe6 commit 31d174c
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 1 deletion.
3 changes: 3 additions & 0 deletions wis2box-management/docker/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ wis2box environment create
wis2box environment show
wis2box api setup

# test the wis2box is not misconfigured
wis2box environment test

# ensure cron is running
service cron start
service cron status
Expand Down
33 changes: 33 additions & 0 deletions wis2box-management/wis2box/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,38 @@ def environment():
pass


@click.command()
@click.pass_context
@cli_helpers.OPTION_VERBOSITY
def test(ctx, verbosity):
"""Tests the environment is set up correctly"""

click.echo(f'Setting up logging (loglevel={LOGLEVEL}, logfile={LOGFILE})')
setup_logger(LOGLEVEL, LOGFILE)

click.echo('Testing BROKER_PUBLIC')
# load plugin for plugin-broker
defs = {
'codepath': PLUGINS['pubsub']['mqtt']['plugin'],
'url': BROKER_PUBLIC,
'client_type': 'publisher'
}
broker = load_plugin('pubsub', defs)

try:
result = broker.test(topic='origin/a/wis2/test', message='wis2box pub test') # noqa
except Exception as err:
LOGGER.error(err)
raise EnvironmentError(err)

if result:
click.echo('Broker test successful')
else:
LOGGER.error('Could not connect to broker defined by WI2BOX_BROKER_PUBLIC') # noqa
click.echo('Broker test failed')
exit(1)


@click.command()
@click.pass_context
@cli_helpers.OPTION_VERBOSITY
Expand Down Expand Up @@ -163,3 +195,4 @@ def show(ctx, verbosity):

environment.add_command(create)
environment.add_command(show)
environment.add_command(test)
12 changes: 12 additions & 0 deletions wis2box-management/wis2box/pubsub/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@ def sub(self, topic: str) -> None:

raise NotImplementedError()

def test(self, topic='wis2box/test', message='test') -> bool:
"""
Test the connection to the broker
:param topic: `str` of topic
:param message: `str` of message
:returns: `bool` of test result
"""

raise NotImplementedError()

def bind(self, event: str, function: Callable[..., Any]) -> None:
"""
Binds an event to a function
Expand Down
44 changes: 43 additions & 1 deletion wis2box-management/wis2box/pubsub/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import logging
import random

from time import sleep
from typing import Any, Callable

from paho.mqtt import client as mqtt_client
Expand All @@ -43,6 +44,7 @@ def __init__(self, broker: str) -> None:
"""

super().__init__(broker)
self.test_status = 'unknown'
self.type = 'mqtt'
self._port = self.broker_url.port
self.client_id = f"wis2box-mqtt-{self.broker['client_type']}-{random.randint(0, 1000)}" # noqa
Expand All @@ -66,7 +68,11 @@ def __init__(self, broker: str) -> None:
if self.broker_url.scheme == 'mqtts':
self.conn.tls_set(tls_version=2)

self.conn.connect(self.broker_url.hostname, self._port)
try:
self.conn.connect(self.broker_url.hostname, self._port)
except Exception as e:
LOGGER.error(f'MQTT Broker connect error: {e}')
self.test_status = e
LOGGER.debug('Connection initiated')

def pub(self, topic: str, message: str, qos: int = 1) -> bool:
Expand Down Expand Up @@ -136,5 +142,41 @@ def bind(self, event: str, function: Callable[..., Any]) -> None:

setattr(self.conn, event, function)

def test(self, topic='wis2box/test', message='test') -> bool:
"""
Test the connection to the broker
:returns: `bool` of test result
"""

def on_connect(client, userdata, flags, rc):
if rc == 0:
LOGGER.debug(f'Test: Connected to broker {self.broker}')
client.subscribe(topic, qos=1)
LOGGER.debug(f'Test: Subscribed to topic {topic}')
else:
msg = f'Test: Failed to connect to MQTT-broker: {mqtt_client.connack_string(rc)}' # noqa
LOGGER.error(msg)

def on_message(client, userdata, message):
LOGGER.debug(f'Test: Received message {message.payload.decode()}')
self.test_status = 'success'

if self.test_status != 'unknown':
msg = f'Test: failed to connect to MQTT-broker: {self.test_status}' # noqa
LOGGER.error(msg)
return self.test_status == 'success'

self.conn.on_connect = on_connect
self.conn.on_message = on_message

self.conn.loop_start()
sleep(0.1)
self.conn.publish(topic, message, qos=1)
sleep(0.1)
self.conn.loop_stop()

return self.test_status == 'success'

def __repr__(self):
return '<MQTTPubSubClient>'

0 comments on commit 31d174c

Please sign in to comment.