#!/usr/bin/python -B

# Copyright 2019 VMware, Inc.
# All rights reserved. -- VMware Confidential

"""ESX System Storage Audit

Internal-only utility to collect debugging information about the ESX System
Storage subsytem, and POST the JSON-formated report to the testesx.eng REST
service.

The script is designed to fail gracefully upon errors, and to exit in a timely
manner if testesx.eng is unreachable or becomes unresponsive.
"""
from http import HTTPStatus
import json
import sys
from traceback import format_exc

from borautils.rest import RestClient
from esxutils import getBuildNum
from systemStorage import IS_SYSTEM_STORAGE_NEXT_ENABLED
from systemStorage.systemStorageDebug import SystemStorageInfo

ESXDB_URI = "http://testesx.eng.vmware.com"
ESXDB_PORT = 8021
ESXDB_TIMEOUT = 5


def uploadSystemStorageReport():
   """Post a System Storage JSON report to testesx.eng.
   """
   try:
      debug = SystemStorageInfo()
      jsonData = debug.toJson()
   except Exception:
      jsonData = json.dumps({'error': format_exc()})

   with RestClient(ESXDB_URI, port=ESXDB_PORT, timeout=ESXDB_TIMEOUT) as esxdb:
      resp = esxdb.post('esx/systemStorage', jsonData)

      # Make sure to consume the whole HTTP response, not just the header.
      esxdb.readBody(resp)

   return 0 if resp.status == HTTPStatus.OK else 1


if __name__ == "__main__":
   DEV_BUILD_NUM = "00000"

   if not IS_SYSTEM_STORAGE_NEXT_ENABLED or getBuildNum() == DEV_BUILD_NUM:
      # Don't report System Storage debug info if the SystemStorageNext FSS is
      # disabled, and for developer builds.
      sys.exit(0)

   status = uploadSystemStorageReport()
   sys.exit(status)
