view dash.py @ 32:a957a56bb694

release zur abgabe
author sean
date Sun, 23 Aug 2015 21:52:33 +0200
parents 140c9023df7a
children
line wrap: on
line source
"""
    This software is part of "Bottledash"
    author: sean engelhardt > sean.engelhardt@intevation.de
    license: GNU >= V2. See LICENSE for details
"""

from bottle import get, post, request, view, response, route
from bottle import template, run, static_file, error
import os.path, sys, configparser, functools, bottle
import logging

CONFIG_FILE = "dash.conf"
PATH = os.path.abspath(os.path.dirname(sys.argv[0]))
CONFIG_PATH = PATH + "/" + CONFIG_FILE

# Create a new list with absolute paths
MY_TEMPLATE_PATH = [
   os.path.abspath(os.path.join(os.path.dirname(__file__), './views')),
]

# Patch @view() so it uses the customized path list instead of the global one
view = functools.partial(bottle.view, template_lookup=MY_TEMPLATE_PATH)

tiles = []
settings = {}

default_settings = configparser.ConfigParser()
default_settings['settings'] = {'show_top_bar': False, 'rows': 2}

#logging:

logger = logging.getLogger('myapp')
hdlr = logging.FileHandler(PATH + '/bottledash.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)

### debug function: prints the current status of the "tiles" in
### the log-file
def log_tile_status():
    global tiles

    try:
        for tile in tiles:
            logger.info("found tile : " + str(tile))
            for option in tiles[0]:
                logger.info(str(option) + ' : ' + str(tile[option]))
    except KeyError:
        pass

###read the config file. usually "dash.conf"
def read_config():
    global settings
    # print(PATH)

    if os.path.isfile(CONFIG_PATH) == False:
        write_default_config()

    # print("read existing config file...")
    config = configparser.ConfigParser()
    config.read(CONFIG_PATH)

    for section in config.items():
        if "tile" in section[0]:
            tiles.append(section[1])

    ###log read tiles
    logger.info("------- read tiles --------")
    log_tile_status()

    try:
        if config["settings"]:
            settings = config["settings"]
        else:
            settings = default_settings["settings"]
    except KeyError:
        settings = default_settings["settings"]

###write the default condfig file if there is none
def write_default_config():
    logger.info("No config-file found. create new config file")
    file = open(CONFIG_PATH, "w")
    file.write("""
### bottledash default configuration
### created by sean engelhardt >sean.engelhardt@intevation.de
### license: GNU GPL >= v2. See LICENSE for details
###
### Usage:
### define the tiles for the dashboard in sections

# Settings:
# example:
# --------------------
# [settings]
# show_top_bar=False
# rows=3
# --------------------
# options:
#   show_top_bar (True / False) [optional]
#     If True, the dashboard will show the current date and the time on the top
#     if False, the dashboard will not show a top-bar
#   default: False
#   hint: the top-bar has got a height of 5%!
#
#   rows (integer-number) [recommended]
#     the number or rows for the tiles. Not every number makes sence since
#     you usually cannot scroll on the screen. This only works on the default
#     tile template - it is always possivle to write an own template!
#   example:
#     If there are 4 tiles in 2 rows the reult would be the following:
#       ▢▢
#       ▢▢
#
#     if there are 3 tiles in 3 rows the result would be the following
#       ▢
#       ▢
#       ▢
#
#     if there re 12 tiles in 3 rows the reult would be the following
#       ▢▢▢▢
#       ▢▢▢▢
#       ▢▢▢▢
#


[settings]
show_top_bar=False
rows=3

# Tiles:
# example:
# --------------------
# [tile1]
# type=mon
# source=192.168.0.2
# status=up
# --------------------
# options:
#   type (mon / web_view) [required]
#     tells the program what kind of tile you need.
#     a "mon" tile can be used for IT infrastructure monitoring purposes
#     a "web_view" tile can be used to display a chart
#   default: -
#
#   source (<IP> or <FQDN>) [required for mon-types]
#     ONLY FOR MON-Type tiles!
#     tells the tile which resource to watch
#     ONLY FOR DEBUGGING PURPOSE - WILL BE REMOVED LATER
#     simulates up and down events for mon-type-tiles
#
#   div_name: (identifier) [required for d3js-types]
#
#   script: (name of a script without extension) [required for d3js-types0]
#
[tile1]
type=mon
source=red2-Bottle-App
status=wait

[tile2]
type=mon
source=Intevation_Homepage
status=wait

[tile3]
type=mon
source=mpuls-jmd-demo
status=wait

[tile4]
type=mon
source=aise-icn
status=wait

[tile5]
type=mon
source=mpuls-s_bew_prev
status=wait

[tile6]
type=web_view
div_name=techintern
script=display_issues_techintern
""")
    file.close()

##Bottle
@route('/')
@view('bottledash_view')
def call_dashboard():
    return dict(tiles=tiles, settings=settings)

#wait for post-request which shall inform the system about running services
@post('/updown')
def updown():
    global tiles

    service = request.forms.get('service')
    status = request.forms.get('status')
    try:
        for tile in tiles:
            if tile["source"] == str(service):
                tile["status"] = str(status)
    except KeyError:
        logger.info("this tile got no source : " + str(tile))


    logger.info('------- new alert --------')
    logger.info('Service : ' + str(service))
    logger.info('Status : ' + str(status))
    # log_tile_status()

    return ":: " + str(service) + " is " + str(status) + " !"


@post('/ask-systemstate')
def get_systemstate():
    global tiles
    service = request.forms.get('service')

    # print("service: " + service)

    try:
        for tile in tiles:
            if tile["source"] == str(service):
                # return "service : " + str(service) + " is " + str(tile["status"])
                return tile["status"]
    except KeyError:
        return "cannot find the service: " + str(service)

    return "did not found anything in my list for : " + service


@route('/static/<filename>')
def server_static(filename):
    return static_file(filename, root=PATH + '/static/')

@error(404)
def error404(error):
    return 'Nothing here, sorry <br /> 404'

read_config()
# print(tiles)
run(host='localhost', port=8080, debug=False, quiet=True)
This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)