#!/usr/pythoncontroller/python

import sys, os, time
import socket
from util import *
#from vdiskcontrol import *

CTRLSOCKET_PATH = "/var/run/vdiskctrl"
SOCKET_CONNECT_RETRIES = 10
SOCKET_CONNECT_INTERVALS = 1

def _ctrl_socket_open(path):
    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    retry = 0
    while retry < SOCKET_CONNECT_RETRIES:
        try:
            s.connect(path)
            break
        except socket.error, e:
            if e.errno == 111:
                # retry after some sleep
                #print "Failed to connect to path %s, retry number %d" % (path, retry)
                time.sleep(SOCKET_CONNECT_INTERVALS)
                retry += 1
    return s

def _ctrl_socket_close(s):
    s.close()

def ctrl_socket_command(path, cmd, acquire=True):
    node = os.path.basename(os.path.dirname(path)) 
    lockfile = "/tmp/ctrl_socket_command_%s_%s.lock" % (node,os.path.basename(path).split('_')[1])
    status = 0
    try:
        if acquire:
            status = getLock(lockfile)
        if not os.path.exists(path):
            return 'result=FAILURE error="ctrl_socket_command - path %s does not exist!"' % path
        s = _ctrl_socket_open(path)
	s.settimeout(45) # set socket timeout to 45 seconds
        s.send("%s\r\n" % cmd)
        data = s.recv(131072)
        _ctrl_socket_close(s)
        return str(data[:-2])
    except socket.timeout:
	return 'result=FAILURE error="failed for path %s with socket timeout"' % path
    except Exception, e:
        return 'result=FAILURE error="ctrl_socket_command - failed for path %s and cmd %s with exception: %s"' % (path, str(cmd), str(e))
    finally:
        if status > 0:
            releaseLock(lockfile)

if len(sys.argv) != 4 and len(sys.argv) != 5:
    print "Usage: %s <vdisk uuid> <node uuid> <cmd to send> [nolock]" % sys.argv[0]
    print "Sends a control socket cmd to a local rspamd server"

else:
    vdiskuuid = sys.argv[1]
    node = sys.argv[2]
    cmd = sys.argv[3]
    lock = True
    if len(sys.argv) > 4:
        if sys.argv[4] == 'nolock':
            lock = False
    #result = 'result=SUCCESS'

    path = CTRLSOCKET_PATH + "/%s/control_%s" % (node,vdiskuuid)
    if os.path.exists(path):
        status = ctrl_socket_command(path,cmd, acquire=lock)
        #sdict = stringToDict(status, pairsplitter='=', separator=' ')
        #result = 'result=FAILURE' if (len(status)>1 and status[0] != "OK") else 'result=SUCCESS'
        #print result, status
        print status
    else:
        print 'result=FAILURE error="vdisk/node control socket not found: invalid uuid or invalid storage node, or rspamd not running"'

sys.exit(0)

