Commit 738918f4 authored by Anael Beutot's avatar Anael Beutot
Browse files

Added helper functions for logging fatal error in ForkedJob

parent b4d3d8a9
Loading
Loading
Loading
Loading
+43 −0
Original line number Diff line number Diff line
@@ -5,7 +5,9 @@ import resource
import signal
import subprocess
import sys
import traceback
from threading import Thread, Event
from StringIO import StringIO

from cloudcontrol.node.exc import JobError
from cloudcontrol.node.utils import num_to_sig
@@ -181,6 +183,47 @@ class ForkedJob(object):
        # overide in sub class
        pass

    def fatal(self, fmt, *args, **kwargs):
        """Write error message in stderr and exit.

        :param str fmt: format string
        :param \*args: arguments for format string
        :param \*\*kwargs: can contain ('status', :int:) -> exit status of process
        """
        try:
            status = int(kwargs.get('status', 1))
        except (ValueError, TypeError):
            sys.stderr.write('Bad status argument %s' % status)
            os._exit(42)

        try:
            fmt = fmt % args
        except (ValueError, TypeError):
            sys.stderr.write('Bad formatting for string: %s' % fmt)
            os._exit(42)

        try:
            sys.stderr.write(fmt)
        except IOError:
            os._exit(42)

        os._exit(status)

    def fatal_exc(self, fmt, *args, **kwargs):
        """Write error message and traceback and exit.

        :param str fmt: format string
        :param \*args: arguments for format string
        :param \*\*kwargs: can contain ('status', :int:) -> exit status of process
        """
        tb = StringIO()
        tb.write('\n')
        traceback.print_exc(file=tb)
        tb.write('\n')
        fmt += '%s'
        args = args + (tb.getvalue(),)
        self.fatal(fmt, *args, status=kwargs.get('status', 1))

    def close_fds(self):
        """Close all fds uneeded fds in children."""
        # get max fd