#!/bin/env python3.4
# vim: expandtab:tabstop=4:shiftwidth=4

"""
 A small server to check for an existing clamd socket
 and expose that information to prometheus.
"""

from itertools import chain

import os
import stat
import time

# pylint: disable-msg=no-value-for-parameter, import-error
from prometheus_client import start_http_server, Counter

import psutil
import yaml


class ClamLogSrv(object):
    """ Class to receive and report scan results. """


    # pylint: disable=too-many-locals, too-many-statements
    @staticmethod
    def get_controller(config_path):
        """ Get info about the clam-controller that will be used to process positive scan results

            Returns:
                A dictionary with the address and port of the clam-controller.
         """

        config_settings = {}

        if os.path.isfile(config_path):
            with open(config_path, 'r') as log_config:
                yaml_config = yaml.load(log_config)

                try:
                    config_settings['oii_control_host'] = yaml_config['oii_control_host']
                except KeyError:
                    pass

                try:
                    config_settings['oii_contrl_port'] = yaml_config['oii_contrl_port']
                except KeyError:
                    pass

        return config_settings


    @staticmethod
    def check_srv():
        """ Listen on specified port for incoming clam logs. """

        listener_running = Counter('scanlog_listener_not_running', \
                                   'scanlog_listener is not running.')

        orchestrator_running = Counter('orchestrator_not_running', \
                                       'orchestrator is not running.')

        clamd_socket_exists = Counter('clamd_socket_missing', \
                                      'image-inspector cannot access clamd.sock.')

        path = '/host/host/var/run/clamd.scan/clamd.sock'

        while True:
            time.sleep(3600)

            try:
                mode = os.stat(path).st_mode
                is_socket = stat.S_ISSOCK(mode)
                if not is_socket:
                    print('File exists, but is not a socket.')
                    clamd_socket_exists.inc()
            except OSError as os_error:
                print(os_error)
                clamd_socket_exists.inc()

            socket_list = psutil.net_connections(kind='unix')

            if '@ScanlogListener' not in chain.from_iterable(socket_list):
                listener_running.inc()

            if '@Orchestrator' not in chain.from_iterable(socket_list):
                orchestrator_running.inc()


    def main(self):
        """ Main function. """

        start_http_server(8000)
        self.check_srv()


if __name__ == '__main__':
    CLAMLOG = ClamLogSrv()
    CLAMLOG.main()
