#!/usr/bin/env python

# Copyright (c) 2014 Anchor Systems

# https://github.com/anchor/elasticsearch-scripts

"""
NAME

    es-autoflush-disable - disable automatic transaction log flushing
                           across an ElasticSearch cluster


SYNOPSIS

    es-autoflush-disable [HOST[:PORT]]


DESCRIPTION

    Connect to the ElasticSearch HTTP server at HOST:PORT (defaults to 
    localhost:9200), and submit an API request to disable automatic 
    transaction log flushing.  When this command returns -- with exit 
    status zero -- it is safe to snapshot (or otherwise back up) your 
    ElasticSearch data directory.

    Remember to call es-autoflush-enable afterwards.

    You may supply the HOST:PORT of any one of the servers in your 
    ElasticSearch cluster.  The server that receives our request will 
    forward it on to its peers.


RETURN VALUES

    es-autoflush-disable will return zero on success; non-zero on 
    failure.  Success is defined by the underlying ElasticSearch API.  
    See BACKGROUND INFORMATION.


BACKGROUND INFORMATION

    - http://www.elasticsearch.org/guide/reference/api/admin-indices-update-settings.html
    - http://www.elasticsearch.org/guide/reference/index-modules/translog.html
    - https://github.com/elasticsearch/elasticsearch/issues/906


SEE ALSO

    es-autoflush-enable

"""
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 9200

from esadmin import Connection
import logging
import os
import socket
import sys

logger = logging.getLogger(__name__)

def usage(argv):
    print >>sys.stderr, ("Usage:\n\t%s [HOST[:PORT]]\n" %
                         os.path.basename(argv[0]))

def main(argv=None):
    if argv is None:
        argv = sys.argv

    host = DEFAULT_HOST
    port = DEFAULT_PORT

    try:
        address = sys.argv[1]
    except IndexError:
        pass
    else:
        if address.find(":") == -1:
            host = address
        else:
            host, port = address.split(":")
            try:
                port = int(port)
            except ValueError:
                usage(argv)
                return 2

    logger.info("Disabling automatic transaction log flushes...")

    with Connection(host, port) as conn:
        if len(conn.indices()) == 0:
    	    logger.info("No indices.  Nothing to do.")
    	    return 0

        old_status = conn.flushing_disabled()
        logger.info("Old status: %s" % old_status.upper())

        conn.put('/_settings', '{"index":{"translog.disable_flush":true}}')

        new_status = conn.flushing_disabled()
        logger.info("New status: %s" % new_status.upper())

        assert new_status == "disabled"

    logger.info("Done")
    return 0

if __name__ == '__main__':
    hostname = socket.gethostname()
    fmt = ('[%s] [%%(process)d]: [%%(levelname)s] '
           '%%(message)s' % hostname)
    logging.basicConfig(level=logging.INFO, format=fmt)

    sys.exit(main(sys.argv))
