#!/usr/bin/env python2

import argparse
import zookeeper
from socket import getfqdn
from time import time


def main():
    parser = argparse.ArgumentParser(description='Check zookeeper instance by creating and deleting test node')
    parser.add_argument('--server', dest='server', type=str, default='127.0.0.1:2181', action='store', help='server:port to connect')
    args=parser.parse_args()
    
    hostname = getfqdn().replace('.', '_')
    epoch = str(int(time()))
    node_path = '/zk_check_%s' % hostname

    zookeeper.set_debug_level(zookeeper.LOG_LEVEL_ERROR)
    
    zk = zookeeper.init(args.server)
    try:
        if not zookeeper.exists(zk, node_path) is not None:
            acl_all=[{'scheme': 'world', 'perms': 31, 'id': 'anyone'}]
            zookeeper.create(zk, node_path, epoch, acl_all)
        value, _ = zookeeper.get(zk, node_path)
        if value != epoch:
            raise Exception('Value saved to node does not coincide value read from node')
        zookeeper.delete(zk, node_path)
    except Exception, e:
        print '2; Failed to create and delete zookeeper node: %s' % str(e)
    else:
        zookeeper.close(zk)
        print '0; OK'


if __name__ == '__main__':
   main()


