import logging
import os
import sys
from subprocess import PIPE
from subprocess import Popen

NOVA_CONF_DIR = '/etc/kolla/nova-compute/'
LOG_PATH = '/var/log/shaman/fence.log'
logging.basicConfig(filename=LOG_PATH,
                    format='%(asctime)s | %(levelname)s | %(message)s',
                    level=logging.INFO)


def execute(cmd):
    logging.info('Execute: "{}"'.format(' '.join(cmd)))
    try:
        p = Popen(cmd, stdout=PIPE, stderr=PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            logging.error('Retcode: {} stderr: {}'.format(p.returncode,
                                                          err.decode('ascii').strip()))
            return 1
    except Exception:
        logging.exception('Execution failed')
        return 1
    logging.info('Execution complete')
    return 0

def main():
    try:
        event_type = os.getenv('EVENT')
        if not os.path.exists(NOVA_CONF_DIR):
            logging.info('Ignore event %s: it is not a compute node', event_type)
            return 0
        if event_type == 'FENCE':
            logging.info('Fence vms')
            # the last argument is the rule, so it must be passed as one parameter
            cmd = ['/usr/bin/ovs-ofctl', 'add-flow', 'br-int', 'table=0,priority=65535,actions=drop']
        elif event_type == 'UNFENCE':
            logging.info('Unfence vms')
            # the last argument is the rule, so it must be passed as one parameter
            cmd = ['/usr/bin/ovs-ofctl', '--strict', 'del-flows', 'br-int', 'table=0,priority=65535']
        else:
            logging.info('Event %s ignored', event_type)
            return 0
        return execute(cmd)
    except Exception:
        logging.exception('Failed to fence/unfence vms')
    return 1

if __name__ == '__main__':
    sys.exit(main())
