# HG changeset patch
# User Andrey Skvortsov <andrej.skvortzov@gmail.com>
# Date 1552476444 -10800
# Node ID a3ec35ee94e72f8e4fa8c9707eaf7df901a4bc76
# Parent  92f0980888e8fa772702ee0b4d13e18d3835a4a8
Fix crash in runtime if PSK secret is missing

 ./Beremiz_service.py -s $PWD/psk2.txt -n beremiz /tmp/beremiz
Beremiz_service:  1.2-1378c18402c3+

Traceback (most recent call last):
  File "./Beremiz_service.py", line 511, in <module>
    ensurePSK(servicename, PSKpath)
  File "/home/developer/WorkData/PLC/beremiz/beremiz/runtime/Stunnel.py", line 32, in ensurePSK
    PSKgen(ID, PSKpath)
  File "/home/developer/WorkData/PLC/beremiz/beremiz/runtime/Stunnel.py", line 23, in PSKgen
    call(restart_stunnel_cmdline)
  File "/home/developer/WorkData/PLC/beremiz/beremiz/runtime/spawn_subprocess.py", line 116, in call
    pid = posix_spawn.posix_spawnp(cmd[0], cmd)
  File "/home/developer/.local/lib/python2.7/site-packages/posix_spawn/_impl.py", line 120, in posix_spawnp
    return _posix_spawn(lib.posix_spawnp, *args, **kwargs)
  File "/home/developer/.local/lib/python2.7/site-packages/posix_spawn/_impl.py", line 111, in _posix_spawn
    _check_error(res, path)
  File "/home/developer/.local/lib/python2.7/site-packages/posix_spawn/_impl.py", line 10, in _check_error
    raise OSError(errno, os.strerror(errno), path)
OSError: [Errno 2] No such file or directory: '/etc/init.d/S50stunnel'

diff -r 92f0980888e8 -r a3ec35ee94e7 connectors/ConnectorBase.py
--- a/connectors/ConnectorBase.py	Wed Mar 13 14:14:31 2019 +0300
+++ b/connectors/ConnectorBase.py	Wed Mar 13 14:27:24 2019 +0300
@@ -22,4 +22,3 @@
                     return blobID
                 blobID = self.AppendChunkToBlob(chunk, blobID)
                 s.update(chunk)
-
diff -r 92f0980888e8 -r a3ec35ee94e7 runtime/Stunnel.py
--- a/runtime/Stunnel.py	Wed Mar 13 14:14:31 2019 +0300
+++ b/runtime/Stunnel.py	Wed Mar 13 14:27:24 2019 +0300
@@ -1,4 +1,5 @@
 from __future__ import absolute_import
+from __future__ import print_function
 import os
 from binascii import b2a_hqx
 try:
@@ -11,6 +12,17 @@
 _PSKpath = None
 
 
+def restartStunnel():
+    """
+    Restart stunnel service using SysV init stript
+    to apply new generated credentials
+    """
+    try:
+        call(restart_stunnel_cmdline)
+    except OSError:
+        print(_("Couldn't restart stunnel service"))
+
+
 def PSKgen(ID, PSKpath):
 
     # b2a_hqx output len is 4/3 input len
@@ -20,7 +32,7 @@
     PSKstring = ID+":"+secretstring
     with open(PSKpath, 'w') as f:
         f.write(PSKstring)
-    call(restart_stunnel_cmdline)
+    restartStunnel()
 
 
 def ensurePSK(ID, PSKpath):