[PATCH v2] tbot_contrib/utils.py: collect some usefull linux utils

Heiko Schocher hs at denx.de
Wed Apr 22 06:34:11 CEST 2020

collect usefull linux utils functions. Start with

check_systemd_services_running(lnx: linux.LinuxShell, services: list)

check if all systemd services in list services run on linux
machine lnx. If not, try to start them.

Signed-off-by: Heiko Schocher <hs at denx.de>

Changes in v2:
- added comments from Harald
  - rename check_systemd_services_running() to ensure_sd_unit()
  - fix Copyright
  - correct type-annotation for services
  - use lnx.test()
  - use "is-active" instead "status" for getting state of service
- added a services cache, so we only check once per linux
  machine, if systemd services run.

 tbot_contrib/utils.py | 42 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)
 create mode 100644 tbot_contrib/utils.py

diff --git a/tbot_contrib/utils.py b/tbot_contrib/utils.py
new file mode 100644
index 0000000..ee91d00
--- /dev/null
+++ b/tbot_contrib/utils.py
@@ -0,0 +1,42 @@
+# tbot, Embedded Automation Tool
+# Copyright (C) 2020  Heiko Schocher
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# GNU General Public License for more details.
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <https://www.gnu.org/licenses/>.
+from tbot.machine import linux
+import typing
+_SERVICES_CACHE: typing.Dict[str, typing.Dict[str, bool]] = {}
+def ensure_sd_unit(lnx: linux.LinuxShell, services: typing.List[str]) -> None:
+    """
+    check if all systemd services in list services run on linux machine lnx.
+    If not, try to start them.
+    :param lnx: linux shell
+    :param services: list of systemd services
+    """
+    if lnx.name not in _SERVICES_CACHE:
+        _SERVICES_CACHE[lnx.name] = {}
+    for s in services:
+        if s in _SERVICES_CACHE[lnx.name]:
+            continue
+        if not lnx.test("systemctl", "is-active", s, "--no-pager"):
+            lnx.exec0("sudo", "systemctl", "start", s)
+        _SERVICES_CACHE[lnx.name][s] = True

More information about the tbot mailing list