Plugin for pushing configuration.
authorBenjamin Braatz <bb@bbraatz.eu>
Mon, 26 Jul 2021 15:36:28 +0000 (17:36 +0200)
committerBenjamin Braatz <bb@bbraatz.eu>
Mon, 26 Jul 2021 15:36:28 +0000 (17:36 +0200)
conf-conf.json [new file with mode: 0644]
controlpi_plugins/conf.py [new file with mode: 0644]

diff --git a/conf-conf.json b/conf-conf.json
new file mode 100644 (file)
index 0000000..a856a70
--- /dev/null
@@ -0,0 +1,19 @@
+{
+    "Conf": {
+        "plugin": "Conf"
+    },
+    "Test Procedure": {
+        "plugin": "Init",
+        "messages": [
+            { "target": "Conf", "command": "push",
+              "conf": {
+                  "Conf": { "plugin": "Conf" },
+                  "Example State": { "plugin": "State" },
+                  "Debug Logger": { "plugin": "Log", "filter": [{}] }
+              } }
+        ]
+    },
+    "Debug Logger": {
+        "plugin": "Log", "filter": [{}]
+    }
+}
diff --git a/controlpi_plugins/conf.py b/controlpi_plugins/conf.py
new file mode 100644 (file)
index 0000000..8590a45
--- /dev/null
@@ -0,0 +1,43 @@
+"""Provide plugin to push new configuration on system.
+
+"""
+import asyncio
+import json
+import sys
+
+from controlpi import BasePlugin, Message, MessageTemplate
+
+
+class Conf(BasePlugin):
+    """Replace configuration by command."""
+
+    CONF_SCHEMA = {'properties': {}}
+    """Empty configuration schema."""
+
+    async def _push(self, message: Message) -> None:
+        """Update configuration if changed."""
+        conf = {}
+        try:
+            with open(sys.argv[1]) as conf_file:
+                conf = json.load(conf_file)
+        except (IndexError, FileNotFoundError, json.decoder.JSONDecodeError):
+            pass
+        if conf == message['conf']:
+            await self.bus.send(Message(self.name, {'event': 'unchanged'}))
+        else:
+            with open(sys.argv[1], 'w') as conf_file:
+                json.dump(message['conf'], conf_file)
+            await self.bus.send(Message(self.name, {'event': 'changed'}))
+
+    def process_conf(self) -> None:
+        """Register plugin as bus client."""
+        receives = [MessageTemplate({'target': {'const': self.name},
+                                     'command': {'const': 'push'},
+                                     'conf': {'type': 'object'}})]
+        sends = [MessageTemplate({'event': {'const': 'changed'}}),
+                 MessageTemplate({'event': {'const': 'unchanged'}})]
+        self.bus.register(self.name, 'Wait', sends, receives, self._push)
+
+    async def run(self) -> None:
+        """Run no code proactively."""
+        pass