summaryrefslogtreecommitdiffstats
path: root/events/src/utils.py
blob: 772221a1e2549b8bd3ee6fac3d49528aed866732 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# -*- coding: utf-8 -*-
#
#  Copyright (c) 2016 Red Hat, Inc. <http://www.redhat.com>
#  This file is part of GlusterFS.
#
#  This file is licensed to you under your choice of the GNU Lesser
#  General Public License, version 3 or any later version (LGPLv3 or
#  later), or the GNU General Public License, version 2 (GPLv2), in all
#  cases as published by the Free Software Foundation.
#

import json
import os
import logging

import requests
from eventsapiconf import (LOG_FILE,
                           WEBHOOKS_FILE,
                           DEFAULT_CONFIG_FILE,
                           CUSTOM_CONFIG_FILE)
import eventtypes

from gluster.cliutils import get_node_uuid


# Webhooks list
_webhooks = {}
# Default Log Level
_log_level = "INFO"
# Config Object
_config = {}

# Init Logger instance
logger = logging.getLogger(__name__)


def get_event_type_name(idx):
    """
    Returns Event Type text from the index. For example, VOLUME_CREATE
    """
    return eventtypes.all_events[idx].replace("EVENT_", "")


def setup_logger():
    """
    Logging initialization, Log level by default will be INFO, once config
    file is read, respective log_level will be set.
    """
    global logger
    logger.setLevel(logging.INFO)

    # create the logging file handler
    fh = logging.FileHandler(LOG_FILE)

    formatter = logging.Formatter("[%(asctime)s] %(levelname)s "
                                  "[%(module)s - %(lineno)s:%(funcName)s] "
                                  "- %(message)s")

    fh.setFormatter(formatter)

    # add handler to logger object
    logger.addHandler(fh)


def load_config():
    """
    Load/Reload the config from REST Config files. This function will
    be triggered during init and when SIGUSR2.
    """
    global _config
    _config = {}
    if os.path.exists(DEFAULT_CONFIG_FILE):
        _config = json.load(open(DEFAULT_CONFIG_FILE))
    if os.path.exists(CUSTOM_CONFIG_FILE):
        _config.update(json.load(open(CUSTOM_CONFIG_FILE)))


def load_log_level():
    """
    Reads log_level from Config file and sets accordingly. This function will
    be triggered during init and when SIGUSR2.
    """
    global logger, _log_level
    new_log_level = _config.get("log_level", "INFO")
    if _log_level != new_log_level:
        logger.setLevel(getattr(logging, new_log_level.upper()))
        _log_level = new_log_level.upper()


def load_webhooks():
    """
    Load/Reload the webhooks list. This function will
    be triggered during init and when SIGUSR2.
    """
    global _webhooks
    _webhooks = {}
    if os.path.exists(WEBHOOKS_FILE):
        _webhooks = json.load(open(WEBHOOKS_FILE))


def load_all():
    """
    Wrapper function to call all load/reload functions. This function will
    be triggered during init and when SIGUSR2.
    """
    load_config()
    load_webhooks()
    load_log_level()


def publish(ts, event_key, data):
    message = {
        "nodeid": get_node_uuid(),
        "ts": int(ts),
        "event": get_event_type_name(event_key),
        "message": data
    }
    if _webhooks:
        plugin_webhook(message)
    else:
        # TODO: Default action?
        pass


def plugin_webhook(message):
    message_json = json.dumps(message, sort_keys=True)
    logger.debug("EVENT: {0}".format(message_json))
    for url, token in _webhooks.items():
        http_headers = {"Content-Type": "application/json"}
        if token != "" and token is not None:
            http_headers["Authorization"] = "Bearer " + token

        try:
            resp = requests.post(url, headers=http_headers, data=message_json)
        except requests.ConnectionError as e:
            logger.warn("Event push failed to URL: {url}, "
                        "Event: {event}, "
                        "Status: {error}".format(
                            url=url,
                            event=message_json,
                            error=e))
            continue

        if resp.status_code != 200:
            logger.warn("Event push failed to URL: {url}, "
                        "Event: {event}, "
                        "Status Code: {status_code}".format(
                            url=url,
                            event=message_json,
                            status_code=resp.status_code))