#!/usr/bin/python3

################################################################################
# Copyright (c) 2022 VMware, Inc.
# All rights reserved. -- VMware Confidential
################################################################################

"""Monitor systemstorage scratch/osdata partitions.

   Warn by raising a vob when they run out of storage.
   The script runs every five minutes as part of a CRON job.
"""

import os
import syslog
from systemStorage import MiB, SCRATCH_LINK, OSDATA_LINK
from systemStorage.esxfs import getFssVolumes
from esx import vob

MAX_PERCENT_USAGE = 95
def getVolume(path):
    realPath = os.path.realpath(path)
    try:
       volumes = getFssVolumes()
    except Exception as e:
       raise OSError("Failed to get the FSS volume details: %s" % e)
    for volume in volumes:
       if realPath.startswith(volume.path):
          return volume
    raise OSError("%s: no such volume", realPath)

def raiseVob(vobuserId, msg, size):
    try:
       vob.DynamicVob(vobuserId, msg, vob.string(size)).send()
    except Exception as e:
       syslog.syslog(syslog.LOG_ERR, "Failed to send vob: {e}")

def osdataMonitor(volume):
    if volume.fsPercentUsed >= MAX_PERCENT_USAGE:
       vobuserId = "vob.user.osdata.partition.full"
       msg = ("OSData is low on available space (%s MiB free)."
              "This may result in system failure."
              "Please refer to KB article: KB 87212")
       sizeInMb = volume.fsFree / MiB
       raiseVob(vobuserId, msg, sizeInMb)

def scratchMonitor(volume):
    if volume.fsPercentUsed >= MAX_PERCENT_USAGE:
       vobuserId = "vob.user.scratch.partition.full"
       msg = ("Scratch is low on available space (%s MiB free)."
              "This may result in system failure."
              "Please refer to KB article: KB 87212")
       sizeInMb = volume.fsFree / MiB
       raiseVob(vobuserId, msg, sizeInMb)



def main():
    scratchVolume = getVolume(SCRATCH_LINK)
    osdataVolume = getVolume(OSDATA_LINK)
    scratchMonitor(scratchVolume)
    osdataMonitor(osdataVolume)

if __name__ == "__main__":
    main()
