#!/opt/vertica/oss/python/bin/python
from vertica.config import DBinclude

# override the default admintools log and
# create a special diagnostics log of our own!
DBinclude.adminToolLog = DBinclude.LOG_DIR + "/diagnostics-" + DBinclude.adminToolLogUser + ".log";

import pwd,  os, sys
from vertica.tools import Diagnostics
from vertica.tools import DBfunctions
from vertica.network import SSH
from vertica.network import adapterpool
from optparse import OptionParser


def cleanup():
    pool = adapterpool.AdapterConnectionPool_3.Instance()
    pool.close()
   
# set up command line arguments
parser = OptionParser()
parser.add_option("-l", "--listdbs",     action="store_true", dest="listdbs", help="lists running databases")
parser.add_option("-s", "--local_diags", action="store_true", dest="local_diags", help="gather diagnostics for local machine only")
parser.add_option("-d", "--database",                         dest="db",      help="only report on database <db>")
parser.add_option("-n", "--hosts",                            dest="host_list",      help="gather diagnostics for these hosts only")
parser.add_option("-o", "--output_dir",                       dest="output_dir", help="redirect output to somewhere other than /opt/vertica/log")
parser.add_option("-z", "--include_gzlogs",   default="1",    dest="gzlogs", help="include a number of gzipped vertica.log logs. defaults to 1. for all gz logs, use 'all'  ")
(options, args) = parser.parse_args(sys.argv)

# if we get here, make a Diagnostics object and call the method that
# corresponds to the user's request.
if not options.output_dir == None:
    options.output_dir = os.path.abspath(os.path.expanduser(options.output_dir))

vsql     = '%s/vsql' % DBinclude.binDir
diags = None
try:
    diags = Diagnostics.Diagnostics( options.output_dir )
except Exception, e:
    print "Failed to initialize diagnostics"
    print e
    sys.exit(1)

# this tool can be run by anyone, but without a valid
# /opt/vertica/config/users/<username> directory, there will be limited
# information about the installation.

username = pwd.getpwuid(os.getuid())[0]
userdir  = DBinclude.CONFIG_USER_DIR + "/" + username
if not os.path.exists( userdir ):
     diags.output("Unable to find %s. Limited information will be available." % userdir )
     if  options.host_list == None :
     	options.local_diags = "yes"


diags.output("Running Diagnostics as user: %s"  % username )
diags.output("")


diags.output("Vertica Diagnostics Report")
diags.output("-----------------------------")
diags.output("Using VSQL:              %s"     % vsql)
diags.output("Result Dir:              %s"     % diags.outputDir)
diags.output("")

try:
    # if they want a db list, run that command and exit
    if (options.listdbs != None):
        diags.ListDBs()
        sys.exit(0)

    if (options.local_diags != None):
        diags.GatherLocalNodeInformation()
        sys.exit(0)
	
    if ( options.gzlogs == "all" ):
	options.gzlogs = None
    else:	
        options.gzlogs = int(options.gzlogs)

# if they want to do node information without a corresponding
# adminTools node def, do that now.
    if (options.db != None):
        hostarray = []
        if options.host_list != None:
            hostarray = options.host_list.split(",")
            DBfunctions.translate_to_internal( hostarray )

        diags.GatherSingleDatabaseInformation(options.db, hostarray, options.gzlogs)
        sys.exit(0)

    if ( options.host_list != None ):
        arr = options.host_list.split(",")
        DBfunctions.translate_to_internal( arr )
        for host in arr:
	    diags.GatherNodeInformation( host )
        sys.exit(0)


# otherwise, we want to do a full diagnostics dump
    diags.ListNodes()                    # info about what nodes are defined
    diags.GatherAllNodeInformation()     # various and sundry info about each node
    diags.GatherAllDatabaseInformation( options.gzlogs ) # various and sundry info about each database

finally:
    cleanup()

