- Add Dockerfile

- Add Config in backend using env vars
- Clean up mock actor
This commit is contained in:
Dorian Zedler 2021-08-19 11:27:39 +02:00
parent cbffbc92a6
commit b6f8b54bc2
Signed by: dozedler
GPG key ID: 989DE36109AFA354
9 changed files with 121 additions and 36 deletions

1
backend/.dockerignore Normal file
View file

@ -0,0 +1 @@
__pycache__

8
backend/Dockerfile Normal file
View file

@ -0,0 +1,8 @@
FROM python:3-alpine
RUN apk --no-cache add build-base openldap-dev python2-dev python3-dev
RUN pip3 install python-ldap requests coloredlogs
COPY ./* ./
ENTRYPOINT [ "python3", "mlmAccess.py" ]

6
backend/actor.py Normal file
View file

@ -0,0 +1,6 @@
class MaActor:
def __init__(self, id):
self._id = id
def _mqttOnConnect(self, client, userdata, flags, rc):
client.subscribe("mlmAccess/pair/request/actor")

View file

@ -2,22 +2,23 @@ import pymysql
import json
class MaDbHelper:
def __init__(self):
self.mysqlConn = pymysql.connect(host='localhost',
user='root',
passwd='MlmAccess',
db='MlmAccess',
port=4306)
def __init__(self, config):
self.mysqlConn = pymysql.connect(host=config["MYSQL_HOST"],
user=config["MYSQL_USER"],
passwd=config["MYSQL_PASSWORD"],
db=config["MYSQL_DATABASE"],
port=config["MYSQL_PORT"])
self.mysqlCur = self.mysqlConn.cursor()
self._initDb()
def _initDb(self):
"""
Generates required tables and users
Generates required tables
"""
"""
CREATE TABLE vmq_auth_acl
query = """
CREATE TABLE IF NOT EXISTS vmq_auth_acl
(
mountpoint VARCHAR(10) NOT NULL,
client_id VARCHAR(128) NOT NULL,
@ -29,6 +30,12 @@ class MaDbHelper:
)
"""
self.mysqlCur.execute(
query
)
self.mysqlConn.commit()
def addUser(self, username, password, publishAclPatterns, subscribeAclPatterns):
if self.userExists(username):

View file

@ -1,7 +1,7 @@
import paho.mqtt.client as mqtt
from dbHelper import MaDbHelper
from pairingHandler import MaPairingHandler
import logging, coloredlogs
import logging, coloredlogs, os, sys, random, string
coloredlogs.install(level='INFO', fmt='%(asctime)s - [%(levelname)s] %(message)s')
@ -9,6 +9,8 @@ class MlmAccess:
def __init__(self):
logging.info("=== MlmAccess ===")
self._config = self._readConfig()
self._initDb()
self._initMqtt()
@ -18,10 +20,10 @@ class MlmAccess:
def _initDb(self):
logging.info("Initializing Database")
self._db = MaDbHelper()
self._db = MaDbHelper(self._config)
initUsers = [
("backend", "backend", ["mlmAccess/#"], ["mlmAccess/#"]),
("pair-actor", "pair-actor", ["mlmAccess/pair/request/actor"], ["mlmAccess/pair/response/actor"])
("backend", self._config["MQTT_BACKEND_PASSWORD"], ["mlmAccess/#"], ["mlmAccess/#"]),
("pair-actor", self._config["PAIR_SECRET"], ["mlmAccess/pair/request/actor"], ["mlmAccess/pair/response/actor"])
]
for username, password, publishAclPatterns, subscribeAclPatterns in initUsers:
@ -31,12 +33,12 @@ class MlmAccess:
def _initMqtt(self):
logging.info("Initializing MQTT")
self._mqtt = client = mqtt.Client(client_id="backend")
self._mqtt.username_pw_set("backend", "backend")
self._mqtt.username_pw_set("backend", self._config["MQTT_BACKEND_PASSWORD"])
self._mqtt.on_connect = self._mqttOnConnect
self._mqtt.on_message = self._mqttOnMessage
self._mqtt.connect("localhost", 1883, 60)
self._mqtt.connect(self._config["MQTT_HOST"], self._config["MQTT_PORT"], 60)
def _mqttOnConnect(self, client, userdata, flags, rc):
if rc != 0:
@ -65,5 +67,48 @@ class MlmAccess:
if topic.startswith("pair"):
self._pairingHanlder.handlePairingRequest(topic, messageContent)
def _readConfig(self):
configKeyPrefix = "MLMACCESS_"
requiredConfigKeys = [
'MYSQL_USER',
'MYSQL_PASSWORD',
'MYSQL_DATABASE',
'PAIR_SECRET'
]
allowedConfigKeys = [
'MYSQL_HOST',
'MYSQL_PORT',
'MQTT_HOST',
'MQTT_PORT',
]
backendPassword = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=20))
config = {
"MYSQL_HOST": "mysql",
"MYSQL_PORT": 4306,
"MQTT_HOST": "mqtt",
"MQTT_PORT": 1883,
"MQTT_BACKEND_PASSWORD": backendPassword
}
for configKey in requiredConfigKeys:
if configKeyPrefix + configKey not in os.environ:
logging.error(f"Required environment value {configKeyPrefix + configKey} is not set")
sys.exit(1)
config[configKey] = os.environ[configKeyPrefix + configKey]
for configKey in allowedConfigKeys:
if configKeyPrefix + configKey in os.environ:
config[configKey] = os.environ[configKeyPrefix + configKey]
logging.info("CONFIG:")
for key, value in config.items():
logging.info(" * {:25}: {}".format(key, value))
return config
if __name__ == "__main__":
MlmAccess()