#!/usr/bin/env python
##############################################################################
# Copyright (c) Members of the EGEE Collaboration. 2011.
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.
#
# Licensed 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.
##############################################################################
#
# NAME :        check_space_token
#
# DESCRIPTION : Checks the available space per space token
#
# AUTHORS :     Alexandre.Beche@cern.ch
#
##############################################################################

import commands
import datetime
import dpm
import os
import time
from lcgdmcommon import *

class check_space_token:
  """Checks the available space per space token"""
  __version__     = "0.0.1"
  __nagios_id__   = "DM-SPACE-TOKEN"

  DEFAULT_WARNING = 30
  DEFAULT_CRITICAL = 10

  # Specific parameters, where key = short, value = long (i.e. {"h":"help", "C:":"command="})
  # getopt format. The long version will be the one passed even when the short is specified
  __additional_opts__ = {"w:": "warning=",
                         "c:": "critical="}

  # Specific usage information
  __usage__ = """
\t-w, --warning\tDefault warning threshold in percent of unused space in a space token. (Default: %d ).
\t-c, --critical\tDefault warning threshold in percent of unused space in a space token. (Default: %d ).

Description of work executed by the probe:

\t3. Retreive for each monitored space token
\t\tThe free space
\t\tThe used space
\t4. Return values to nagios
\t\tWarning alert is trgiggered if free space is under 30 percent of the total space
\t\tCritical alert is trgiggered if free space is under 10 percent of the total space
""" % (DEFAULT_WARNING, DEFAULT_CRITICAL)

  # Methods
  def __init__(self, opt = {}, args = []):
    """
    Constructor

    @param opt  Contains a dictionary with the long option name as the key, and the argument as value
    @param args Contains the arguments not associated with any option
    """

    opt_warning = self.DEFAULT_WARNING
    opt_critical = self.DEFAULT_CRITICAL

    if "warning" in opt:
      opt_warning = opt["warning"]
    if "critical" in opt:
      opt_critical = opt["critical"]

    self.warning = int(opt_warning)
    self.critical = int(opt_critical)


  def main(self):
    """
    Test code itself. May raise exceptions.

    @return A tuple (exit code, message, performance)
    """

    return_code = EX_OK
    return_detail = ""
    warning, critical = 0,0

    space_token_summary = {}

    (replies, space_tokens) = dpm.dpm_getspacetoken(None)

    for space_token in space_tokens:
      (replies, token) = dpm.dpm_getspacemd([space_token])

      u_token, total_space, available_space = token[0].u_token, token[0].t_space, token[0].u_space
      warning_threshold, critical_threshold = float(self.warning * total_space / 100), float(self.critical * total_space / 100)

      space_token_summary[u_token] = [available_space, warning_threshold, critical_threshold, total_space]
    
      if available_space < critical_threshold:
        if return_code < EX_CRITICAL:
          return_code = EX_CRITICAL
        critical += 1
        continue

      if available_space < warning_threshold:
        if return_code < EX_WARNING:
          return_code = EX_WARNING
        warning +=1
        continue 

    performance_data = ""
    for key, value in space_token_summary.iteritems():
      performance_data += key
      performance_data += "="
      performance_data += str(value[0])
      performance_data += "B;"
      performance_data += str(value[1]) + ";" + str(value[2]) + ";0;" + str(value[3]) + " "

    return_data = str(critical) + " critical(s) and " + str(warning) + " warning(s) found"
    return_data += return_detail
    

    return (return_code, return_data, performance_data)


# When called directly
if __name__ == "__main__":
  run(check_space_token)

