#!/usr/bin/env python

'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

import uuid
import datetime
import time
import json
import logging
import optparse
import shutil
import sys
import subprocess
import os.path
import socket

logger = logging.getLogger('Precheck')
has_warnings=False
has_errors=False

#request types
HTTP_REQUEST_GET='GET'
HTTP_REQUEST_POST='POST'
HTTP_REQUEST_DELETE='DELETE'

#HTTP CODE
HTTP_OK=200
HTTP_CREATED=201
HTTP_BAD_REQUEST=400
HTTP_FORBIDDEN=403
HTTP_CONFLICT=409

#defaults
EXIT_MESSAGE = "Make sure to provide correct cluster information including port, admin user name and password. Default values will be used if you omit the command parameters.";
DEFAULT_HTTP_PORT=8080
DEFAULT_ADMIN_USER='admin'
DEFAULT_LOG_DIR='/tmp/preinstall_checks'
DEFAULT_LOG_FILE='preinstall_checks.log'
DEFAULT_HTTP_REQUEST_TYPE=HTTP_REQUEST_GET
DEFAULT_AMBARI_SERVER_PROPERTIES='/etc/ambari-server/conf/ambari.properties'
DEFAULT_MAX_COUNTER=4
DEFAULT_TIMER_LONG=5
DEFAULT_POLLING_TIMER_REQUEST=10
DEFAULT_MINDISKSPACE=2.0 #in GB
DEFAULT_MINDISKSPACEUSRLIB=1.0 #in GB

#ops
OPERATION_HOST_CHECK='host_check'
OPERATION_VALIDATE_BLUEPRINT='validate_blueprint'
OPERATIONS=[OPERATION_HOST_CHECK, OPERATION_VALIDATE_BLUEPRINT]

#codes
CODE_SUCCESS=0
CODE_ERROR=1
CODE_WARNING=2
CODE_CONNECTION_REFUSED=7

#labels
LABEL_OK='[   OK  ]'
LABEL_WARNING='[WARNING]'
LABEL_ERROR='[ ERROR ]'

#status
STATUS_ACCEPTED='Accepted'
STATUS_COMPLETED='COMPLETED'
STATUS_PASSED='PASSED'
STATUS_WARNING='FAILED'
STATUS_FAILED='WARNING'
STATUS_ABORTED='ABORTED'
STATUS_IN_PROGRESS='IN_PROGRESS'
STATUS_PENDING='PENDING'
#list of status indicating the operation has yet to finish
LIST_FINISHED_REQUEST_STATUS=[STATUS_FAILED, STATUS_COMPLETED, STATUS_ABORTED]

def init_parser_options(parser):
  parser.add_option('-p', '--port',
                    dest="port", default=DEFAULT_HTTP_PORT,
                    help="Ambari Server port corrsponding to the network protocol. Default port is {0} for an HTTP connection".format(DEFAULT_HTTP_PORT))
  parser.add_option('-u', '--user',
                    dest="user", default=DEFAULT_ADMIN_USER,
                    help="Ambari admin user. Default user name is {0}".format(DEFAULT_ADMIN_USER))
  parser.add_option('-a', '--password',
                    dest="password",
                    help="Ambari admin user password.")
  parser.add_option('-l', '--log',
                    dest="log",
                    default=DEFAULT_LOG_DIR,
                    help="The log file home location. Default log file home is {0}.".format(DEFAULT_LOG_DIR),
                    metavar="DIR")
  parser.add_option('--blueprint',
                    dest="blueprint",
                    default=None,
                    help="Blueprint to validate",
                    metavar="FILE")
  parser.add_option('--operation',
                    dest='operation', default=OPERATION_HOST_CHECK,
                    help='Operation can one of the following {0}'.format(', '.join(OPERATIONS)))
  parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Output verbosity.")

"""
Validate parameters passed in from the command line.
Exit if there are validation errors.
"""
def validate_options(options):
  errors = []

  """General parameters that must be passed in via command line or set with a default value"""
  if not options.port:
    errors.append("No Ambari server port provided.")
  if not options.user:
      errors.append("No Ambari admin user name provided.")
  if not options.password:
    errors.append("No Ambari admin user passsword provided.")
  if not options.log:
      errors.append("No log home path provided.")

  """General check for operations"""
  if not options.operation:
    errors.append('No operation provided')
  elif not options.operation in OPERATIONS:
    errors.append('Unknow operation {0}. Specify one of the following operations: {1}'.format(options.operation, ', '.join(OPERATIONS)))
  elif options.operation == OPERATION_VALIDATE_BLUEPRINT:
    if not options.blueprint:
      errors.append('No blueprint file provided')

  if not errors:
    return 'Parameters validation finished successfully', CODE_SUCCESS
  else:
    return 'Parameters validation finished with error(s). {0}'.format('. '.join(errors)), CODE_ERROR

def get_log_file(log_home):
  return '{0}/{1}'.format(log_home, DEFAULT_LOG_FILE)

def init_logger(options):
  log_dir = options.log
  if not os.path.exists(log_dir):
    os.makedirs(log_dir)

  logging_level = logging.DEBUG if options.verbose else logging.INFO
  logger.setLevel(logging_level)
  logger.handlers = []

  formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
  file_handler = logging.FileHandler(get_log_file(log_dir), mode='w')
  file_handler.setFormatter(formatter)
  logger.addHandler(file_handler)

  stdout_handler = logging.StreamHandler(sys.stdout)
  stdout_handler.setFormatter(formatter)
  logger.addHandler(stdout_handler)

"""
Back up log directory if it already exists.
"""
def backup_log(filePath):
  if filePath is not None and os.path.exists(filePath):
    timestamp = datetime.datetime.now()
    simpleformat = '%Y%m%d%H%M%S'
    backup_file = filePath + "." + timestamp.strftime(simpleformat)
    try:
      shutil.move(filePath, backup_file)
    except Exception, err:
      print('Failed to backup "{0}": {1}'.format(str(filePath), str(err)))
      return '', CODE_WARNING
    return backup_file, CODE_SUCCESS
  else:
    return '', CODE_SUCCESS

def get_current_time():
  total_seconds = time.time()
  current_time = datetime.datetime.fromtimestamp(total_seconds).strftime('%Y-%m-%d %H:%M:%S')
  return current_time

def step(msg):
  logger.info('')
  if len(msg) >= 43:
    logger.info('********   Check: {0}   ********'.format(msg))
  else:
    spaces = ' '.ljust((50 - len(msg))/2)
    logger.info('{0}{2}Check: {1}{2}{0}'.format('********',msg,spaces))

def print_check_result(check, msgs, code):
  if len(check)>=43:
    spaces = ' '.ljust(20)
  else:
    spaces = ' '.ljust(63 - len(check))
  if code == CODE_SUCCESS:
    logger.info('{0}{1}{2}'.format(check, spaces, LABEL_OK))
  elif code == CODE_WARNING:
    logger.info('{0}{1}{2}'.format(check, spaces, LABEL_WARNING))
    if msgs:
      for msg in msgs:
        if msg.strip():
          logger.warning('\t{0}'.format(msg.strip()))