#coding:utf-8
import shlex
import sunhpc
import socket
import subprocess
class Command(sunhpc.commands.Command):
    """
    Checks that all Sunhpc required services are up and running, If a
    required services is not running it will reported.
    
    <example cmd='check host services'>
    Check that all required services are up and running.
    </example>
    """
    def checkService(self, cmdname, error_msg):
        """check if the given cmdname returns 0 once executed.
        If cmdname fails it returns  runninvg"""
        devnull = open('/dev/null', 'w')
        process = subprocess.Popen(shlex.split(cmdname), stdout=devnull, stderr=devnull)
        retcode = process.wait()
        devnull.close()
        if retcode != 0:
            self.abort(error_msg)

    def run(self, params, args):

        if len(args) != 0:
            self.msg("check services does not accept any argument", 'a')

        if socket.gethostname().split('.')[0] != self.newdb.getFrontendName():
            self.msg('this command should run only on the frontend', 'a')

        # dhcpd
        cmd = "service dhcpd status"
        error_msg = "dhcpd is not running.\n" + \
            "Restart it with 'systemctl start dhcpd'"
        self.checkService(cmd, error_msg)

        # xinetd
        cmd = "curl 'tftp://localhost/pxelinux.0' -o /dev/null"
        error_msg = "unable to download pxelinux with tftp.\n" + \
            "Verify that xinetd is running with 'systemctl start tftp'"
        self.checkService(cmd, error_msg)

        # httpd wget kickstart
        cmd = "bash -c \"curl -k http://localhost/install/sbin/kickstart.cgi\""
        error_msg = "unable to download kickstart.\n" + \
            "Verify httpd is running with 'systemctl start httpd'"
        self.checkService(cmd, error_msg)
        return True

RollName = "base"
