#!/usr/bin/env python
import os
import csha
import signal

csha.log.debug('HA ha_stop_daemon')

nodeid = csha.get_current_host_node_id()
my_host_uuid = csha.util.get_current_host_uuid()

# Leave the lockspace indicating xapi's liveness on this host, to ensure there
# are no active lockspaces at shutdown. If there are any active lockspaces, dlm
# cannot exit cleanly on shutdown.
# We do nothing if we aren't in the lockspace, to avoid failing and make this
# script idempotent.
if nodeid in csha.get_xapi_ha_lockspace_members():
    csha.leave_xapi_ha_lockspace()
csha.log.debug('Members of xapi-ha-lockspace: {}'.format(
    csha.get_xapi_ha_lockspace_members()))

csha.remove_signal_file()

sf = csha.Statefile()

master = sf.get_master()
if master.uuid == my_host_uuid:
    try:
        os.kill(master.pid, signal.SIGTERM)
    except:
        csha.log.debug('HA ha_stop_daemon failed to kill master lock process')
    sf.set_master(csha.Master(None, None))
