#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN)
#
# Licensed under the EUPL, Version 1.1 only (the "Licence").
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at:
#
# http://joinup.ec.europa.eu/system/files/EN/EUPL%20v.1.1%20-%20Licence.pdf
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" basis,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
#-------------------------------------------------------------------------------
"""
WNoDeS post-execution script
"""

import socket
import commands
import os
import sys
import time
import pickle

TMPFILE   = "/tmp/my_bait"
#NS_HOST   = "dom0-103-13-26-b.cr.cnaf.infn.it"
NS_HOST   = "wnodes-ns-1.cr.cnaf.infn.it"
NS_PORT   = 8219
BAIT_PORT = 8111

vmParameters = {}
hostname = socket.gethostname().split('.')[0]

def sendRequest(HOST, PORT, msg):
    """
    Send a msg to a WNoDeS TCP socket server.
    Msg format MUST BE a dictionary with one value-pair attribute.
    Key  MUST BE the method name you want to execute on the NameServer.
    Value MUST BE the options method weather they exist.
    If msg is not in this format an error is raised

    It returns a tuple with this format (status, data).
    """

    try:
        if len(msg.keys()) == 1:
            msg = str(pickle.dumps(msg).replace('\n', '1%2'))
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.connect((HOST, int(PORT)))
                sock.sendall(msg + '\n')
                socketfile = sock.makefile('r', 0)
                response = socketfile.readline().strip()
                sock.shutdown(2)
                sock.close()
                try:
                    data = pickle.loads(response.replace('1%2', '\n'))
                    returnstuff = (0, data)
                    return returnstuff
                except pickle.UnpicklingError:
                    print sys.exc_info()[0]
                    returnstuff = (1, None)
                    return returnstuff
                except Exception:
                    print sys.exc_info()[0]
                    returnstuff = (1, None)
                    return returnstuff
            except socket.error:
                print sys.exc_info()[0]
                returnstuff = (1, None)
                return returnstuff
        else:
            returnstuff = (1, None)
            return returnstuff
    except:
        print sys.exc_info()[0]
        returnstuff = (1, '')
        return returnstuff

def whoIs_TheBait():
    try:
        for line in open(TMPFILE):
            if job_id in line:
                my_bait = line.strip().split("%")[2]
                break
        else:
            raise IOError
    except IOError:
        # jump here if file not found or if the job ID cannot be read
        msg = {'whoIs_TheBait' : [hostname]}
        OUTPUT = sendRequest(NS_HOST, NS_PORT, msg)

        if OUTPUT[0] == 0:
            OUTPUT = OUTPUT[1]
            if OUTPUT[0] == 0:
                my_bait = OUTPUT[1]
            else:
                sys.exit('B I cannot retrieve BAIT HOSTNAME %s' % str(OUTPUT))
        else:
            sys.exit('A I cannot retrieve BAIT HOSTNAME %s' % str(OUTPUT))

        flog = open(TMPFILE, 'a')
        flog.write('BAIT%' + job_id + '%' + my_bait + '\n')
        flog.close()
        os.chmod(TMPFILE, 0777)

    return my_bait

job_id = os.environ.get("LSB_JOBID")
BAIT_HOST = whoIs_TheBait()

if 'vwn' in hostname:
   msg = {'reportPostExecutionScript': [job_id]}
   OUTPUT = sendRequest(BAIT_HOST, int(BAIT_PORT), msg)
