Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

vigiboard / vigiboard / controllers / plugins / details.py @ dc005588

History | View | Annotate | Download (6.35 KB)

1
# -*- coding: utf-8 -*-
2
# vim:set expandtab tabstop=4 shiftwidth=4:
3
################################################################################
4
#
5
# Copyright (C) 2007-2011 CS-SI
6
#
7
# This program is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU General Public License version 2 as
9
# published by the Free Software Foundation.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
################################################################################
20

    
21
"""
22
Un plugin pour VigiBoard qui ajoute une colonne avec les liens vers les
23
entrées d'historiques liées à l'événement, ainsi que les liens vers les
24
applications externes.
25
"""
26

    
27
import urllib
28
from tg import config, url, request
29
from sqlalchemy.sql.expression import null as expr_null, union_all
30

    
31
from repoze.what.predicates import has_permission, in_group
32
from vigilo.turbogears.helpers import get_current_user
33

    
34
from vigilo.models.session import DBSession
35
from vigilo.models.tables import Event, CorrEvent, Host, LowLevelService, \
36
    StateName, Map, MapNode, MapNodeHost, MapGroup
37
from vigilo.models.tables.secondary_tables import MAP_GROUP_TABLE
38

    
39
from vigiboard.controllers.plugins import VigiboardRequestPlugin
40

    
41
class PluginDetails(VigiboardRequestPlugin):
42
    """
43
    Plugin qui ajoute des liens vers les historiques et les applications
44
    externes.
45
    """
46

    
47
    def get_json_data(self, idcorrevent, *args, **kwargs):
48
        """
49
        Renvoie les éléments pour l'affichage de la fenêtre de dialogue
50
        contenant des détails sur un événement corrélé.
51

52
        @param idcorrevent: identifiant de l'événement corrélé.
53
        @type idcorrevent: C{int}
54
        """
55

    
56
        # Obtention de données sur l'événement et sur son historique
57
        host_query = DBSession.query(
58
            Host.idhost.label("idsupitem"),
59
            Host.idhost.label("idhost"),
60
            Host.name.label("host"),
61
            expr_null().label("service"),
62
        )
63
        lls_query = DBSession.query(
64
            LowLevelService.idservice.label("idsupitem"),
65
            Host.idhost.label("idhost"),
66
            Host.name.label("host"),
67
            LowLevelService.servicename.label("service"),
68
        ).join(
69
            (Host, Host.idhost == LowLevelService.idhost),
70
        )
71
        supitems = union_all(lls_query, host_query, correlate=False).alias()
72
        event = DBSession.query(
73
            CorrEvent.idcorrevent,
74
            CorrEvent.idcause,
75
            supitems.c.idhost,
76
            supitems.c.host,
77
            supitems.c.service,
78
            Event.message,
79
            Event.initial_state,
80
            Event.current_state,
81
            Event.peak_state
82
        ).join(
83
            (Event, Event.idevent == CorrEvent.idcause),
84
            (supitems, supitems.c.idsupitem == Event.idsupitem),
85
        ).filter(CorrEvent.idcorrevent == idcorrevent
86
        ).first()
87

    
88
        # On détermine les cartes auxquelles cet utilisateur a accès.
89
        user_maps = {}
90
        max_maps = int(config['max_maps'])
91
        is_manager = in_group('managers').is_met(request.environ)
92
        if max_maps != 0 and (is_manager or
93
            has_permission('vigimap-access').is_met(request.environ)):
94
            items = DBSession.query(
95
                    Map.idmap,
96
                    Map.title,
97
                ).distinct(
98
                ).join(
99
                    (MAP_GROUP_TABLE, MAP_GROUP_TABLE.c.idmap == Map.idmap),
100
                    (MapGroup, MapGroup.idgroup == MAP_GROUP_TABLE.c.idgroup),
101
                    (MapNodeHost, MapNodeHost.idmap == Map.idmap),
102
                ).order_by(Map.title.asc()
103
                ).filter(MapNodeHost.idhost == event.idhost)
104

    
105
            if not is_manager:
106
                mapgroups = get_current_user().mapgroups(only_direct=True)
107
                # pylint: disable-msg=E1103
108
                items = items.filter(MapGroup.idgroup.in_(mapgroups))
109

    
110
            # La valeur -1 supprime la limite.
111
            if max_maps > 0:
112
                # On limite au nombre maximum de cartes demandés + 1.
113
                # Un message sera affiché s'il y a effectivement plus
114
                # de cartes que la limite configurée.
115
                items = items.limit(max_maps + 1)
116

    
117
            user_maps = dict([(m.idmap, m.title) for m in items.all()])
118

    
119
        context = {
120
            'idcorrevent': idcorrevent,
121
            'host': event.host,
122
            'service': event.service,
123
            'message': event.message,
124
            'maps': user_maps,
125
        }
126

    
127
        eventdetails = {}
128
        for edname, edlink in enumerate(config['vigiboard_links.eventdetails']):
129
            # Évite que les gardes ne se polluent entre elles.
130
            local_ctx = context.copy()
131

    
132
            # Les liens peuvent être conditionnés à l'aide
133
            # d'une expression ou d'un callable qui agira
134
            # comme un prédicat de test.
135
            if 'only_if' in edlink:
136
                if callable(edlink['only_if']):
137
                    display_link = edlink['only_if'](local_ctx)
138
                else:
139
                    display_link = edlink['only_if']
140
                if not display_link:
141
                    continue
142

    
143
            if callable(edlink['uri']):
144
                uri = edlink['uri'](local_ctx)
145
            else:
146
                uri = edlink['uri'] % local_ctx
147

    
148
            eventdetails[unicode(edname)] = {
149
                'url': url(uri),
150
                'target': edlink.get('target', '_blank')
151
            }
152

    
153
        return dict(
154
                current_state = StateName.value_to_statename(
155
                                    event.current_state),
156
                initial_state = StateName.value_to_statename(
157
                                    event.initial_state),
158
                peak_state = StateName.value_to_statename(
159
                                    event.peak_state),
160
                idcorrevent = idcorrevent,
161
                host = event.host,
162
                service = event.service,
163
                eventdetails = eventdetails,
164
                maps = user_maps,
165
                idcause = event.idcause,
166
            )