]> git.datanom.net - check_http.git/blobdiff - check_http.py
Finish
[check_http.git] / check_http.py
index ba8a4db54cfa0818d5004202fd623ec4dfed9687..3201dafd10ee5ca7f77661d81b95ad8b5288e7ed 100644 (file)
 #
 ###############################################################################
 
-__author__ = 'Your Name Here'
+__author__ = 'mr.it@cbs.dk - Michael Rasmussen'
 __version__= 0.1
 
-from optparse import OptionParser, OptionGroup
-import logging as log
+try:                                                 #   RHEL8                                         RHEL9
+    from optparse import OptionParser, OptionGroup   #                         
+    import logging as log
+    import sys
+    import urllib3 as urllib                         #   python3-urllib3-1.24.2-5.el8.noarch.rpm       python3-urllib3-1.26.5-3.el9.noarch.rpm
+    import json
+except:
+    sys.exit(2)
 
 ## These will override any args passed to the script normally. Comment out after testing.
 #testargs = '--help'
 #testargs = '--version'
 #testargs = '-vvv'
-
+testing = True
+
+OK_RESPONSE = """
+{
+  "status": "UP",
+  "components": {
+    "db": {
+      "status": "UP",
+      "details": {
+        "database": "PostgreSQL",
+        "validationQuery": "isValid()"
+      }
+    },
+    "diskSpace": {
+      "status": "UP",
+      "details": {
+        "total": 2013582688256,
+        "free": 1635574571008,
+        "threshold": 10485760,
+        "path": "/home/mir/git/soasi-course-catalog-course-target-adapter/.",
+        "exists": true
+      }
+    },
+    "ping": {
+      "status": "UP"
+    }
+  }
+}"""
+DOWN_RESPONSE = """
+{
+  "status": "DOWN",
+  "components": {
+    "db": {
+      "status": "DOWN",
+      "components": {
+        "adapterDataSource": {
+          "status": "DOWN",
+          "details": {
+            "error": "org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection"
+          }
+        },
+        "es3DataSource": {
+          "status": "UP",
+          "details": {
+            "database": "Microsoft SQL Server",
+            "validationQuery": "isValid()"
+          }
+        },
+        "providersDataSource": {
+          "status": "DOWN",
+          "details": {
+            "error": "org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection"
+          }
+        }
+      }
+    },
+    "diskSpace": {
+      "status": "UP",
+      "details": {
+        "total": 1013309239296,
+        "free": 882010726400,
+        "threshold": 10485760,
+        "path": "C:\\Users\\hf.it\\Projects\\smart-integrations\\adapters\\target\\soasi-invigilation-report-target-adapter",
+        "exists": true
+      }
+    },
+    "ping": {
+      "status": "UP"
+    }
+  }
+}
+"""
 def main():
     """ Main plugin logic goes here """
 
@@ -36,9 +113,73 @@ def main():
     # log.error('error message')
     # log.critical('critical message')
     # log.fatal('fatal message')
-
-    gtfo(0)
-
+    options = vars(args)
+    keyword = options['keyword']
+    url = options['url']
+    agent = options['agent']
+    if keyword is None or url is None:
+        message = "Keywork: {0} url: {1}".format(keyword, url)
+        status = 3
+        log.fatal(message)
+    else:
+        try:
+            if not testing:
+                req_headers = {
+                        'User-Agent':  agent
+                }
+                http = urllib.PoolManager()
+                response = http.request(
+                    'GET', url, headers = req_headers
+                    )
+                data = response.data.decode('utf-8').replace("\\"," ")
+            else:
+                data = DOWN_RESPONSE.replace("\\"," ")
+                data = json.loads(data)
+            if 'status' in data and data['status'] == keyword:
+                message = "UP"
+                status = 2
+            else:
+                message = gather_message(data)
+                status = 0
+        except Exception as e:
+            print(e)
+            message = "DOWN"
+            status = 2
+            
+    gtfo(status, message)
+
+def gather_message(json_data):
+    """ Assemble error messages """
+    msg = None
+    try:
+        if 'components' in json_data:
+            components = json_data['components']
+            for component in components:
+                items = components[component]
+                if 'components' in items:
+                    for item in items['components']:
+                        if 'status' in items['components'][item] and items['components'][item]['status'].upper() == 'DOWN':
+                            if msg is not None:
+                                msg += "\n{0}: {1}".format(item, items['components'][item]['details']['error'])
+                            else:
+                                msg = "{0}: {1}".format(item, items['components'][item]['details']['error'])
+                else:
+                    if 'status' in items and items['status'].upper() == 'DOWN':
+                        if msg is not None:
+                            if 'details' in items and 'error' in items['details']:
+                                error = items['details']['error']
+                            else:
+                                error = "No error message"
+                            if msg is not None:
+                                msg += "\n{0}: {1}".format(component, error)
+                            else:
+                                msg = "{0}: {1}".format(component, error)
+        else:
+            sys.exit(3)
+    except:
+        sys.exit(3)
+    return msg
+    
 
 def parse_args():
     """ Parse command-line arguments """
@@ -52,8 +193,11 @@ def parse_args():
 
     ## CLI arguments specific to this script
     group = OptionGroup(parser,'Plugin Options')
-    group.add_option('-x', '--extra', help='Your option here',
-                     default=None)
+    group.add_option('-a', '--agent', help="User agent for request. Default: Python-nagios",
+        default="Python-nagios",  type='string')
+    group.add_option('-k', '--keyword', help="Keyword to search for in response", default=None)
+    group.add_option('-t', '--testing', help="Run in testing mode", default=False, action='store_true')
+    group.add_option('-u', '--url', help="URL to requested resource", default=None)
     
     ## Common CLI arguments
     #parser.add_option('-c', '--critical', help='Set the critical threshold. Default: %(default)s',
This page took 0.043629 seconds and 5 git commands to generate.