#! /opt/vertica/oss/python/bin/python

#Copyright (c) 2006 - 2014, Hewlett-Packard Development Co., L.P. 
# 
# Description: admin tools: allow user to choose and run admin tools
#
# Original Author: Nga Tran
# Create Date: July 19, 2006

import os
import pwd
import sys
import string
import signal
import traceback
import time
from vertica.utils import dialog
import socket
import commands
import logging
import hashlib
import copy
import threading
from optparse import OptionParser

from vertica.tools import DBfunctions
from vertica.config import DBinclude
from vertica.config import FileLocker
from vertica.ui import adminCtrl
from vertica.engine import adminExec
from vertica.network import SSH
from vertica.ui import commandLineCtrl
from vertica.network import adapterpool


sys.path.append("/opt/vertica/bin")


l = logging.getLogger("vertica.default")
l.setLevel(logging.INFO)



def DisableKeyboardInterrupt():
    # ignore the keyboard interrupte signal. 
    if threading.current_thread().name != 'MainThread':
        return

    return signal.signal(signal.SIGINT,signal.SIG_IGN)

def EnableKeyboardInterrupt( handler=signal.default_int_handler):
    # enable the keyboard interrupt with, potentially,  a custom
    # signal handler
    if threading.current_thread().name != 'MainThread':
        return

    return signal.signal(signal.SIGINT, handler)


def general_help(parser):
    clc = commandLineCtrl.commandLineCtrl(False,False)
    tools = clc.getCommandLineTools()

    parser.print_help()
    print "\nAvailable tools:"
    sorted_list = tools.keys()
    sorted_list.sort()

    for tool in sorted_list:
        func = tools[tool]
        if not hasattr(func, '_hidden'):
            print "\t%s" % tool

    print ""

def admintools_help(option, opt, value, parser):
    if '-t' in sys.argv:
        try:
            tool = sys.argv[ sys.argv.index( '-t' ) + 1 ]
            clc   = commandLineCtrl.commandLineCtrl(False,False)
            tools = clc.getCommandLineTools()

            for subcommand in tools.keys():
                if subcommand == tool:
                    toolFunc = tools[ subcommand ]
                    toolFunc( "--help" )
            sys.exit(0)
        except:
            # fall back to general help
            pass

    general_help( parser )
    sys.exit(0)


def license_check():
    lcheck=os.system(DBinclude.LCHK_DIR+"/lchk.sh "+DBinclude.CONFIG_DIR+" "+DBinclude.LCHK_DIR+" "+DBinclude.libDir)
    lcheck = os.WEXITSTATUS( lcheck )
    if lcheck == 1:
        sys.exit(1)
    elif lcheck == 2:
        # newly accepted license.
        # please distribute across the 'known' cluster?
        # we'll have to do this again when we run 'add-a-node'
        lexecutor = adminExec.adminExec( False, False )
        lnodes = lexecutor.getNodeInfo()
        lhosts = []
        for node in lnodes.values():
            lhosts.append( node[1] )

        if len(lhosts) == 0:
            print "\nThere are no hosts defined in the cluster."
            print "Make sure you have run install_vertica before "
            print "running adminTools for the first time."
            sys.exit(1)

        from vertica.network.adapterpool import AdapterConnectionPool_3
        pool = AdapterConnectionPool_3.Instance()
        pool.connect2(lhosts, userName, None)
        SSH.scpToPool( pool, DBinclude.CONFIG_DIR + "/d5415f948449e9d4c421b568f2411140.dat")

def eula_acceptance_exists_and_eula_is_unchanged():
    if os.path.exists(DBinclude.CONFIG_DIR+"/d5415f948449e9d4c421b568f2411140.dat"):
        # acceptance exists. make sure the hash exists and matches the current eula. if not, require it to be re-accepted.
        eula_acceptance_file = open(DBinclude.CONFIG_DIR+"/d5415f948449e9d4c421b568f2411140.dat","r")
        stored_hash = ""
        for line in eula_acceptance_file.readlines():
            if "EULA Hash:" in line:
                # grab the hash, ignore trailing \n
                stored_hash = line[len("EULA Hash:"):-1] 

        if stored_hash == "":
            # there is no hash recorded. The EULA policy has changed.
            return False

        # compute the hash of the EULA file
        eula_file = open( DBinclude.binDir+"/d237f83d0a61c3594829a574c63530b.dat")
        md5hash = hashlib.md5()
        for line in eula_file.readlines():
            md5hash.update(line)

        if stored_hash != md5hash.hexdigest():
            # hash has changed.
            return False
        else:
            return True
    else:
        return False

def remove_eula_acceptance_if_exists():
    if os.path.exists(DBinclude.CONFIG_DIR+"/d5415f948449e9d4c421b568f2411140.dat"):
        os.remove(DBinclude.CONFIG_DIR+"/d5415f948449e9d4c421b568f2411140.dat")

##
## Begin monolithic main routine.
##

# Globals
exit_code = 0
toolName = None
toolArgs = []
options = None
makeUniquePorts = False
showNodes = False
nonInteractive = False
userName = pwd.getpwuid(os.getuid())[0]

if userName == "root":
    print "\nRoot user is not allowed to use this tool."
    print "Try again as the DB administrative user."
    sys.exit(1)

#
# confirm the installer has been run
#
if not os.path.exists(DBinclude.ADMINTOOLS_CONF):
    print """
ERROR: %s does not exist.
This file is created by the installer upon successful completion.
You must successfully run %s/install_vertica before running admintools.
""" % (DBinclude.ADMINTOOLS_CONF,DBinclude.sbinDir)
    sys.exit(1)

#
# Super secret arguments (not in -h, not documented, and unknown users.)  Also
# known as instant technical debt.  Notice also that they need to be specified
# in order.
#
# Almost all of them are for internal testing.  If you are a customer reading
# this, please do not use these options.  We promise to break your work in the
# future.
#

# -u unique ports for database creation. Causes newly created databases to get
# the next available port range
args_to_parse = sys.argv[1:]
if (len(args_to_parse) > 0 and args_to_parse[0] == "-u"):
    args_to_parse = args_to_parse[1:]
    makeUniquePorts = True

# -n for showing node names rather than host names on some dialogs.  This value
# travels around, but is only used within adminCtrl.
#
# Removed in Dragline 7.1 as entirely vestigal and an obstacle for IPv6 support.
if (len(args_to_parse) > 0 and args_to_parse[0] == "-n"):
    disable_dashn = True # change to False to re-enable -n
    if disable_dashn:
        msg = """
Error: The secret -n option to adminTools has been removed.
    Perhaps you meant to place -n <nodename> after -t <command> ?

    Vertica Internal: You can reinstate -n behavior by editing adminTools.
    Change line 206 to read disable_dashn = False rather than True.
    Please contact drice."""
        print >> sys.stderr, msg
        print msg
        sys.exit(1)
    else:
        args_to_parse = args_to_parse[1:]
        showNodes = True

# -i marks the process as non-interactive, which prevents certain prompts, I
# assume.  XXX: This is used by vnetperf to suppress the eula acceptance output
# when using -t list_host to get the list of hosts in the cluster.
if (len(args_to_parse) > 0 and args_to_parse[0] == "-i"):
    args_to_parse = args_to_parse[1:]
    nonInteractive = True

# This is a ridiculous option.
if (len(args_to_parse) > 0 and args_to_parse[0] == "--no-log"):
    args_to_parse = args_to_parse[1:]
    DBfunctions.setNoLogging(True)

# Scripting mode: take adminCtrl / uiMgr (aka the dialog based GUI)
# commands from a file rather than stdin
if (len(args_to_parse) > 1 and args_to_parse[0] == "--ui-input"):
    DBinclude.uiMgrInput = args_to_parse[1]
    args_to_parse = args_to_parse[2:]
    nonInteractive = True
    DBfunctions.record( "[adminTools] Reading input from %s" % DBinclude.uiMgrInput)

if (len(args_to_parse) > 1 and args_to_parse[0] == "--ui-output"):
    DBinclude.uiMgrLog = args_to_parse[1]
    args_to_parse = args_to_parse[2:]
    nonInteractive = True
    DBfunctions.record( "[adminTools] writing ui output to %s" % DBinclude.uiMgrLog)


#
# Time for some real argument parsing, now. Sorta.
#
if len(args_to_parse) > 0:
    # if the first arg is -t/--tool take the next arg as toolname and
    # join the rest of the options as an arg string to pass to the tool
    if args_to_parse[0] == "-t" or args_to_parse[0] == "--tool":
        if (len(args_to_parse) > 1):
            toolName = args_to_parse[1]
        if (len(args_to_parse) > 2):
            toolArgs = args_to_parse[2:]
    else:
        parser = OptionParser()
        parser.add_option( "-a","--help_all",action="store_true",dest="help_all",help="List all command line sub-commands and switches")

        # change help option behavior
        help_option = parser.get_option("-h")
        help_option.action="callback"
        help_option.callback=admintools_help
        help_option.help = "Display this help. \nCan be combined with -t <tool> for help on a specific tool"

        (options, args) = parser.parse_args(args_to_parse)

# Specially check for --unique-ports in argv so that we can set up the
# command line controls appropriate
cmdController = ""
try:
    cmdController = commandLineCtrl.commandLineCtrl(makeUniquePorts, showNodes)
except FileLocker.FileLockException, e:
    print """\
admintools was unable read %s
due to a conflict with another process that was writing to this
file.  Please retry or if necessary remove the .lock file
in the config directory""" % DBinclude.ADMINTOOLS_CONF
    sys.exit(1)

commandLineTools = cmdController.getCommandLineTools()
if not cmdController.isOkToRun():
    print "User %s is not allowed to run adminTools. To enable access run install_vertica" % userName
    sys.exit(1)

# admin log in /tmp. Not sure if these should be merged or separate
# wipe the log at startup

myargs = copy.copy(sys.argv)
for i in range(0,len(myargs)):
    try:
        # password 'protection'
        if myargs[i] == "-p":
            myargs[i+1] = "********"
    except:
        pass

DBfunctions.record( "[adminTools] Starting admin tools (%s)..." % myargs)
DBfunctions.record( "[adminTools] Use unique ports = %s" % makeUniquePorts)
DBfunctions.record( "[adminTools] Configuration=\n%s" % DBinclude.getStringRep())

CONFIG_INFO_DIR = DBinclude.CONFIG_INFO_DIR
dbDesignerConfig = DBinclude.dbDesignerConfig

NO_FILE = "No such file or directory"


if options is not None and options.help_all:
    print "Usage:"
    print "       adminTools [-t | --tool] toolName [options]"
    print "Valid tools are: "

    sorted_cmds = sorted(commandLineTools.keys())

    for subcommand in sorted_cmds:
        func = commandLineTools[subcommand]
        if not hasattr(func, '_hidden'):
            print "\t\t%s" % subcommand

    for subcommand in sorted_cmds:
        func = commandLineTools[subcommand]
        if not hasattr(func, '_hidden'):
            print "-"*73
            func(["--help"])

    sys.exit(0)

#
# check shell.  Why does it matter what the login shell is? What's the CURRENT
# shell?
#
loginShell = pwd.getpwuid(os.getuid())[6]
if loginShell != "/bin/bash":
    print """
WARNING:  The admin tools depend on your login shell being /bin/bash.
Your login shell is currently set to %s.  If you continue to run the admin tools
with this default shell you may experience technical difficulties
""" % loginShell
    if not DBfunctions.yesno("Do you wish to continue? "):
        sys.exit()

for neededPath in [ DBinclude.CONFIG_SHARE_DIR, DBinclude.CONFIG_USER_DIR ]:
   if not (os.path.exists(neededPath)):
      cmd = "mkdir -p " + neededPath
      os.system(cmd)
      cmd = "chmod 777 "+ neededPath
      os.system(cmd)

userPath = DBinclude.CONFIG_USER_DIR + "/" + userName
if not (os.path.exists(userPath)):   
   cmd = "mkdir -p " + userPath
   os.system(cmd)
   cmd = "chmod go-w "+ userPath
   os.system(cmd)
   if os.path.exists( CONFIG_INFO_DIR ):
      #
      # if the old configInfo directory exists, and the files there are owned
      # by this user, then move them to the right locations.
      #
      if os.path.exists(CONFIG_INFO_DIR):
         for fName in ["/siteinfo.dat","/dbinfo.dat"]:
            if os.path.exists(CONFIG_INFO_DIR+fName):
               stblock = os.stat(CONFIG_INFO_DIR+fName)
               myUID = os.getuid()
               if myUID == stblock.st_uid:
                  os.rename( CONFIG_INFO_DIR+fName, userPath+fName)

try:
  try: # again
   if toolName == None:
     lastChanceFileName = DBinclude.adminToolErrorLog
     lastChanceFile = None
     ac = adminCtrl.adminController(makeUniquePorts, showNodes)
     if not ac.isOkToRun():
        print "User %s is not allowed to run adminTools. To enable access run install_vertica" % userName
        sys.exit(1)

     lastChanceFile = open( lastChanceFileName, "a")
     ac.licenseInstall()

     # make sure the EULA is accepted
     if not nonInteractive and not eula_acceptance_exists_and_eula_is_unchanged():
        remove_eula_acceptance_if_exists()
        if not ac.handleEULADisplayAndAcceptance():
            sys.exit(1)

     ac.runApp()

     lastChanceFile.flush()
     lastChanceFile.close()

   else: # user specified a command line tool so run that
     lastChanceFileName = DBinclude.adminToolErrorLog
     lastChanceFile = None
     if not cmdController.isOkToRun():
        print "User %s is not allowed to run adminTools. To enable access run install_vertica" % userName
        sys.exit(1)

     if toolName not in commandLineTools:
         print "Unknown tool %s" % toolName
         sys.exit(1)

     if not nonInteractive:
         # clear out the acceptance file if it's not longer valid
         if not eula_acceptance_exists_and_eula_is_unchanged():
             remove_eula_acceptance_if_exists()
         license_check()

     lastChanceFile = open( lastChanceFileName, "a")
     toolFunc = commandLineTools[toolName]
     exit_code = toolFunc(toolArgs)

  except KeyboardInterrupt:
     os.system("reset")
     print "adminTools exited on ctrl-c or other user interrupt"
  except SystemExit:
     #
     # raised by sys.exit() so we let it go for now
     #
     pass
  except dialog.DialogError:
     print "adminTools failed to create an interface object." 
     print "Please resize your window to a larger width and height"
     exit_code = 1
  except FileLocker.FileLockException:
      print "admintools was unable read %s/config/admintools.conf" % DBinclude.DB_DIR
      print "due to a conflict with another process that was writing to this"
      print "file.  Please retry or if necessary remove the .lock file"
      print "in the config directory"
  except OSError, e:
      print "A system-related error has occurred.  For more information"
      print "see the error number returned below. Exiting."
      print "%s" % e 
  except socket.gaierror, gai:
      print "An error in the python socket library occurred.  This is"
      print "probably due to a network lookup error with one of the hosts"
      print "in your cluster."
      print "%s" % gai
  except:
     #
     # last chance handler - we land here for any unhandled exceptions
     # raised in the system.  We log the traceback to a file in /tmp
     # (or stdout if we couldn't write to /tmp), print some useful erro
     # text, and exit.
     #
     errmsg = sys.exc_info()[1]
     raisedError = sys.exc_info()[0]
     if lastChanceFile == None:
       lastChanceFile = sys.stdout
     lastChanceFile.write( "-" * 32 )
     lastChanceFile.write("\n")
     htime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())         
     lastChanceFile.write("handler invoked: %s\n" % htime )
     rerr = str(raisedError)
     lastChanceFile.write("raised error: %s\n" % rerr )
     traceback.print_exc( file=lastChanceFile )

     print "\n\n\nadminTools Last Chance Error Handler running..."
     print "raised error: ",raisedError
     print "error message: %s" % errmsg
     print "trace file: ",lastChanceFileName
     print "REPORT THIS INFORMATION TO TECHNICAL SUPPORT"
     print "AND INCLUDE CONTENTS OF THE TRACE FILE IN YOUR REPORT"
     exit_code = 1

finally:
   # close ssh connections pool
   # disable ^C during this time as we want to clean up all our connections
   DisableKeyboardInterrupt()
   pool = adapterpool.AdapterConnectionPool_3.Instance()
   pool.close()
   EnableKeyboardInterrupt()


   sys.exit(exit_code)
