#!/usr/bin/python -W ignore
import sys
import os
import socket
import ConfigParser
import urllib3
import time
import signal

# this is a hack to get the hpe driver module
# and it's utils module on the search path.
cmd_folder = os.path.realpath(os.path.abspath("..") )
if cmd_folder not in sys.path:
     sys.path.insert(0, cmd_folder)

from hpe3parclient import client, exceptions
import common

sys.path.append("/usr/share/ganeti/default")
from ganeti import utils

class TimeoutError(Exception):
    pass

def _sig_alarm(sig, tb):
    raise TimeoutError("timeout")


def main():
  sys.stderr.write('Attach started...\n')

  (host,login,password,default_cpg,snap_cpg) = common.getConfig()
  (vol_name,vol_cname,vol_size,vol_new_size,vol_uuid,vol_metadata,vol_snapshot_name,vol_snapshot_size,vol_open_exclusive,cpg) = common.readEnv()

  sys.stderr.write('name: %s, cname: %s\n' % (vol_name,vol_cname))

  cl = client.HPE3ParClient(host, False, False, None, True)

  try: 
    cl.login(login,password)
  except exceptions.HTTPUnauthorized as ex:
       pprint.pprint("Login Failed")
  
  try:
    export_host = socket.gethostname()
    vluns = cl.getVLUNs()
    found = False

    if vluns:
      for vlun in vluns['members']:
        if (vlun['volumeName'] == vol_cname and vlun['hostname'] == export_host) :
	   found = True
	
    if (found == True) :
        sys.stderr.write('Volume already exported : %s\n' % vol_cname )
    else :  
        loc = cl.createVLUN(vol_cname,None,export_host,None,None,None,True)

    vlun = cl.getVLUN(vol_cname)
    uuid = vlun['volumeWWN']


    #Get multipath device
    result = utils.RunCmd('ls -d /sys/class/fc_host/host*/issue_lip | xargs -i echo "echo 1 > {}" | sh')
    result = utils.RunCmd('multipath')

    signal.signal(signal.SIGALRM, _sig_alarm)
    try:
        signal.alarm(30)
        cmd = "multipath -ll 3%s | head -1 | awk '{print $1}'" % uuid.lower().strip()
        device = utils.RunCmd(cmd)

        while device.output.strip() == "":
           cmd = "multipath -ll 3%s | head -1 | awk '{print $1}'" % uuid.lower().strip()
           device = utils.RunCmd(cmd)
           sys.stdout.write('multipath -> %s\n' % device.output.strip())
           time.sleep(1)

        sys.stdout.write("/dev/mapper/%s" % device.output.strip())
    except TimeoutError:
        pass

  except exceptions.HTTPUnauthorized as ex:
       pprint.pprint("You must login first")
  except Exception as ex:
       print(ex)

  cl.logout()

if __name__ == "__main__":
  sys.exit(main())

