Project

General

Profile

Revision b82c4c03

IDb82c4c03d09c8b7e46f2b6aeb716385a14c373ff
Parent 7bde24ad
Child fbbf34f8

Added by Francois POIROTTE over 8 years ago

[#1510] Chargement plus générique de l'application

Rend plus générique le chargement des IHMs :
- Le dossier de surcharge (public/) est pris à partir de l'emplacement
du fichier settings.ini plutôt que hard-codé.
- Idem pour le fichier app_cfg.py.

Ces modifications permettent d'héberger plusieurs instances de VigiMap
conjointement sur la même machine (par exemple, pour PreludeMap).

Change-Id: Iaf43087160023a7eda95c3d366a336ba17e0b93f
Refs: #1510.
Reviewed-on: https://vigilo-dev.si.c-s.fr/review/1926
Tested-by: Build system <>
Reviewed-by: Francois POIROTTE <>

View differences:

MANIFEST.in
13 13
include *.ini
14 14
include jsl.cfg
15 15
include babeljs.py
16
include app_cfg.py
Makefile
49 49
	mkdir -p $(DESTDIR)$(LOCALSTATEDIR)/log/vigilo/$(NAME)
50 50
	[ `id -u` -ne 0 ] || chown $(HTTPD_USER): $(DESTDIR)$(LOCALSTATEDIR)/log/vigilo/$(NAME)
51 51
	install -m 644 -p -D deployment/logrotate.conf $(DESTDIR)/etc/logrotate.d/$(PKGNAME)
52
	# Déplacement du app_cfg.py
53
	mv $(DESTDIR)`grep '$(NAME)/config/app_cfg.py$$' INSTALLED_FILES` $(DESTDIR)$(SYSCONFDIR)/vigilo/$(NAME)/
54
	ln -s $(SYSCONFDIR)/vigilo/$(NAME)/app_cfg.py $(DESTDIR)`grep '$(NAME)/config/app_cfg.py$$' INSTALLED_FILES`
55
	echo $(SYSCONFDIR)/vigilo/$(NAME)/app_cfg.py >> INSTALLED_FILES
52
	# Installation du app_cfg.py
53
	install -m 644 -p app_cfg.py $(DESTDIR)$(SYSCONFDIR)/vigilo/$(NAME)/
56 54
	# Cache
57 55
	mkdir -p $(DESTDIR)$(LOCALSTATEDIR)/cache/vigilo/sessions
58 56
	chmod 750 $(DESTDIR)$(LOCALSTATEDIR)/cache/vigilo/sessions
app_cfg.py
1
# -*- coding: utf-8 -*-
2
# vim: set fileencoding=utf-8 sw=4 ts=4 et :
3
################################################################################
4
#
5
# Copyright (C) 2007-2015 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
Global configuration file for TG2-specific settings in vigiboard.
23

  
24
This file complements development/deployment.ini.
25

  
26
Please note that **all the argument values are strings**. If you want to
27
convert them into boolean, for example, you should use the
28
:func:`paste.deploy.converters.asbool` function, as in::
29

  
30
    from paste.deploy.converters import asbool
31
    setting = asbool(global_conf.get('the_setting'))
32

  
33
"""
34

  
35
from vigilo.turbogears import VigiloAppConfig
36

  
37
import vigiboard
38
from vigiboard.lib import app_globals, helpers # pylint: disable-msg=W0611
39
# W0611: Unused import: imports nécessaires pour le fonctionnement
40

  
41

  
42
import logging
43
LOGGER = logging.getLogger(__name__)
44

  
45
class VigiboardConfig(VigiloAppConfig):
46
    def setup_sqlalchemy(self):
47
        super(VigiboardConfig, self).setup_sqlalchemy()
48

  
49
        # On est obligés d'attendre que la base de données
50
        # soit configurée pour charger les plugins.
51
        from pkg_resources import working_set
52
        from vigiboard.controllers.plugins import VigiboardRequestPlugin
53
        from tg import config
54

  
55
        plugins = []
56
        for plugin_name in config['vigiboard_plugins']:
57
            try:
58
                ep = working_set.iter_entry_points(
59
                        "vigiboard.columns", plugin_name).next()
60
            except StopIteration:
61
                pass
62

  
63
            if ep.name in dict(plugins):
64
                continue
65

  
66
            try:
67
                plugin_class = ep.load(require=True)
68
                if issubclass(plugin_class, VigiboardRequestPlugin):
69
                    plugins.append((unicode(ep.name), plugin_class()))
70
            except Exception: # pylint: disable-msg=W0703
71
                # W0703: Catch "Exception"
72
                LOGGER.exception(u'Unable to import plugin %s', plugin_name)
73

  
74
        config['columns_plugins'] = plugins
75

  
76
base_config = VigiboardConfig('VigiBoard')
77
base_config.package = vigiboard
78
base_config.mimetype_lookup = {
79
    '.csv': 'text/csv',
80
}
81

  
82
##################################
83
# Settings specific to Vigiboard #
84
##################################
85

  
86
# Configuration des liens
87
# Les elements suivants peuvent etre utilises dans la chaine de formatage :
88
# - %(idcorrevent)d : identifiant de l'aggregat (alerte correlee)
89
# - %(host)s : le nom de l'hote concerne par l'alerte
90
# - %(service)s : le nom du service concerne par l'alerte
91
# - %(message) : le message transmis par Nagios dans l'alerte
92
#
93
# Permet de satisfaire l'exigence VIGILO_EXIG_VIGILO_BAC_0130.
94
base_config['vigiboard_links.eventdetails'] = (
95
    {
96
        'label': u'Détail de l\'hôte dans Nagios',
97
        'uri': '/nagios/%(host)s/cgi-bin/status.cgi?host=%(host)s',
98
    },
99
    {
100
        'label': u'Détail de la métrologie',
101
        'uri': 'http://vigilo.example.com/vigilo/vigigraph/rpc/fullHostPage?host=%(host)s',
102
    },
103
    {
104
        'label': u'Détail de la sécurité',
105
        'uri': 'http://security.example.com/?host=%(host)s',
106
    },
107
    {
108
        'label': 'Inventaire',
109
        'uri': 'http://cmdb.example.com/?host=%(host)s',
110
    },
111
    {
112
        'label': 'Documentation',
113
        'uri': 'http://doc.example.com/?q=%(message)s',
114
    },
115
)
116

  
117
# URL des tickets, possibilités:
118
# - %(idcorrevent)d
119
# - %(host)s
120
# - %(service)s
121
# - %(tt)s
122
base_config['vigiboard_links.tt'] = 'http://bugs.example.com/?ticket=%(tt)s'
123

  
124
# Plugins to use
125
base_config['vigiboard_plugins'] = (
126
#    'id',
127
    'details',
128
#    'state',
129
    'groups',
130
    'date',
131
    'priority',
132
    'occurrences',
133
    'hostname',
134
    'servicename',
135
    'output',
136
#    'masked_events',
137
    'hls',
138
    'status',
139
#    'test',
140
    'map',
141
)
142

  
143
base_config['csv_columns'] = (
144
    'id',
145
    'state',
146
    'initial_state',
147
    'peak_state',
148
    'date',
149
    'duration',
150
    'priority',
151
    'occurrences',
152
    'hostname',
153
    'servicename',
154
    'output',
155
    'ack',
156
    'trouble_ticket_id',
157
    'trouble_ticket_link',
158
)
vigiboard/config/app_cfg.py
1
# -*- coding: utf-8 -*-
2
# vim: set fileencoding=utf-8 sw=4 ts=4 et :
3
################################################################################
4
#
5
# Copyright (C) 2007-2015 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
Global configuration file for TG2-specific settings in vigiboard.
23

  
24
This file complements development/deployment.ini.
25

  
26
Please note that **all the argument values are strings**. If you want to
27
convert them into boolean, for example, you should use the
28
:func:`paste.deploy.converters.asbool` function, as in::
29

  
30
    from paste.deploy.converters import asbool
31
    setting = asbool(global_conf.get('the_setting'))
32

  
33
"""
34

  
35
from vigilo.turbogears import VigiloAppConfig
36

  
37
import vigiboard
38
from vigiboard.lib import app_globals, helpers # pylint: disable-msg=W0611
39
# W0611: Unused import: imports nécessaires pour le fonctionnement
40

  
41

  
42
import logging
43
LOGGER = logging.getLogger(__name__)
44

  
45
class VigiboardConfig(VigiloAppConfig):
46
    def setup_sqlalchemy(self):
47
        super(VigiboardConfig, self).setup_sqlalchemy()
48

  
49
        # On est obligés d'attendre que la base de données
50
        # soit configurée pour charger les plugins.
51
        from pkg_resources import working_set
52
        from vigiboard.controllers.plugins import VigiboardRequestPlugin
53
        from tg import config
54

  
55
        plugins = []
56
        for plugin_name in config['vigiboard_plugins']:
57
            try:
58
                ep = working_set.iter_entry_points(
59
                        "vigiboard.columns", plugin_name).next()
60
            except StopIteration:
61
                pass
62

  
63
            if ep.name in dict(plugins):
64
                continue
65

  
66
            try:
67
                plugin_class = ep.load(require=True)
68
                if issubclass(plugin_class, VigiboardRequestPlugin):
69
                    plugins.append((unicode(ep.name), plugin_class()))
70
            except Exception: # pylint: disable-msg=W0703
71
                # W0703: Catch "Exception"
72
                LOGGER.exception(u'Unable to import plugin %s', plugin_name)
73

  
74
        config['columns_plugins'] = plugins
75

  
76
base_config = VigiboardConfig('VigiBoard')
77
base_config.package = vigiboard
78
base_config.mimetype_lookup = {
79
    '.csv': 'text/csv',
80
}
81

  
82
##################################
83
# Settings specific to Vigiboard #
84
##################################
85

  
86
# Configuration des liens
87
# Les elements suivants peuvent etre utilises dans la chaine de formatage :
88
# - %(idcorrevent)d : identifiant de l'aggregat (alerte correlee)
89
# - %(host)s : le nom de l'hote concerne par l'alerte
90
# - %(service)s : le nom du service concerne par l'alerte
91
# - %(message) : le message transmis par Nagios dans l'alerte
92
#
93
# Permet de satisfaire l'exigence VIGILO_EXIG_VIGILO_BAC_0130.
94
base_config['vigiboard_links.eventdetails'] = (
95
    {
96
        'label': u'Détail de l\'hôte dans Nagios',
97
        'uri': '/nagios/%(host)s/cgi-bin/status.cgi?host=%(host)s',
98
    },
99
    {
100
        'label': u'Détail de la métrologie',
101
        'uri': 'http://vigilo.example.com/vigilo/vigigraph/rpc/fullHostPage?host=%(host)s',
102
    },
103
    {
104
        'label': u'Détail de la sécurité',
105
        'uri': 'http://security.example.com/?host=%(host)s',
106
    },
107
    {
108
        'label': 'Inventaire',
109
        'uri': 'http://cmdb.example.com/?host=%(host)s',
110
    },
111
    {
112
        'label': 'Documentation',
113
        'uri': 'http://doc.example.com/?q=%(message)s',
114
    },
115
)
116

  
117
# URL des tickets, possibilités:
118
# - %(idcorrevent)d
119
# - %(host)s
120
# - %(service)s
121
# - %(tt)s
122
base_config['vigiboard_links.tt'] = 'http://bugs.example.com/?ticket=%(tt)s'
123

  
124
# Plugins to use
125
base_config['vigiboard_plugins'] = (
126
#    'id',
127
    'details',
128
#    'state',
129
    'groups',
130
    'date',
131
    'priority',
132
    'occurrences',
133
    'hostname',
134
    'servicename',
135
    'output',
136
#    'masked_events',
137
    'hls',
138
    'status',
139
#    'test',
140
    'map',
141
)
142

  
143
base_config['csv_columns'] = (
144
    'id',
145
    'state',
146
    'initial_state',
147
    'peak_state',
148
    'date',
149
    'duration',
150
    'priority',
151
    'occurrences',
152
    'hostname',
153
    'servicename',
154
    'output',
155
    'ack',
156
    'trouble_ticket_id',
157
    'trouble_ticket_link',
158
)
vigiboard/config/deployment.ini_tmpl
1
#
2
# vigiboard - TurboGears configuration
3
#
4
# The %(here)s variable will be replaced with the parent directory of this file
5
#
6
# Copyright (C) 2006-2011 CS-SI
7
# License: GNU GPL v2 <http://www.gnu.org/licenses/gpl-2.0.html>
8

  
9
[DEFAULT]
10
# WARGING == If debug is not set to false, you'll get the interactive
11
# debugger on production, which is a huge security hole. 
12

  
13
debug = false
14
email_to = you@yourdomain.com
15
smtp_server = localhost
16
error_email_from = paste@localhost
17

  
18
[server:main]
19
use = egg:Paste#http
20
host = 0.0.0.0
21
port = 8080
22

  
23
[app:main]
24
use = egg:vigiboard
25
full_stack = true
26
cache_dir = %(here)s/data
27
beaker.session.key = vigiboard
28
beaker.session.secret = ${app_instance_secret}
29
app_instance_uuid = ${app_instance_uuid}
30

  
31
# If you'd like to fine-tune the individual locations of the cache data dirs
32
# for the Cache data, or the Session saves, un-comment the desired settings
33
# here:
34
#beaker.cache.data_dir = %(here)s/data/cache
35
#beaker.session.data_dir = %(here)s/data/sessions
36
# Specify the database for SQLAlchemy to use via
37
# turbogears.database
38
# %(here) may include a ':' character on Windows environments; this can
39
# invalidate the URI when specifying a SQLite db via path name
40
sqlalchemy.url = sqlite:///%(here)s/somedb.db
41
sqlalchemy.echo = False
42

  
43
# WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT*
44
# Debug mode will enable the interactive debugging tool, allowing ANYONE to
45
# execute malicious code after an exception is raised.
46
#set debug = false
47

  
48
# Logging configuration
49
# Add additional loggers, handlers, formatters here
50
# Uses python's logging config file format
51
# http://docs.python.org/lib/logging-config-fileformat.html
52

  
53
[loggers]
54
keys = root, vigiboard, sqlalchemy, auth
55

  
56
[handlers]
57
keys = console
58

  
59
[formatters]
60
keys = generic
61

  
62
# If you create additional loggers, add them as a key to [loggers]
63
[logger_root]
64
level = INFO
65
handlers = console
66

  
67
[logger_vigiboard]
68
level = INFO
69
handlers =
70
qualname = vigiboard
71

  
72
[logger_sqlalchemy]
73
level = WARN
74
handlers =
75
qualname = sqlalchemy.engine
76
# "level = INFO" logs SQL queries.
77
# "level = DEBUG" logs SQL queries and results.
78
# "level = WARN" logs neither.  (Recommended for production systems.)
79

  
80

  
81
# A logger for authentication, identification and authorization -- this is
82
# repoze.who and repoze.what:
83
[logger_auth]
84
level = WARN
85
handlers = 
86
qualname = auth
87

  
88
# If you create additional handlers, add them as a key to [handlers]
89
[handler_console]
90
class = StreamHandler
91
args = (sys.stderr,)
92
level = NOTSET
93
formatter = generic
94

  
95
# If you create additional formatters, add them as a key to [formatters]
96
[formatter_generic]
97
format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
98
datefmt = %H:%M:%S
vigiboard/config/environment.py
1
# -*- coding: utf-8 -*-
2
################################################################################
3
#
4
# Copyright (C) 2007-2015 CS-SI
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License version 2 as
8
# published by the Free Software Foundation.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
################################################################################
19

  
20
"""WSGI environment setup for vigiboard."""
21
from __future__ import absolute_import
22
from .app_cfg import base_config
23

  
24
__all__ = ['load_environment']
25

  
26
#Use base_config to setup the environment loader function
27
load_environment = base_config.make_load_environment()
vigiboard/config/middleware.py
20 20

  
21 21
"""WSGI middleware initialization for the vigiboard application."""
22 22

  
23
from vigiboard.config.app_cfg import base_config
24
from vigiboard.config.environment import load_environment
25

  
23
import imp
24
import os.path
26 25
from pkg_resources import resource_filename
27 26
from paste.cascade import Cascade
28 27
from paste.urlparser import StaticURLParser
29 28

  
30 29
__all__ = ['make_app']
31 30

  
32
# Use base_config to setup the necessary PasteDeploy application factory.
33
# make_base_app will wrap the TG2 app with all the middleware it needs.
34
make_base_app = base_config.setup_tg_wsgi_app(load_environment)
35

  
36 31

  
37 32
def make_app(global_conf, full_stack=True, **app_conf):
38 33
    """
......
52 47
    @return: The vigiboard application with all the relevant middleware
53 48
        loaded.
54 49
    """
55
    app = make_base_app(global_conf, full_stack=full_stack, **app_conf)
50
    # Charge le fichier "app_cfg.py" se trouvant aux côtés de "settings.ini".
51
    mod_info = imp.find_module('app_cfg', [ global_conf['here'] ])
52
    app_cfg = imp.load_module('vigiboard.config.app_cfg', *mod_info)
53
    base_config = app_cfg.base_config
54

  
55
    # Initialisation de l'application et de son environnement d'exécution.
56
    load_environment = base_config.make_load_environment()
57
    make_base_app = base_config.setup_tg_wsgi_app(load_environment)
58
    app = make_base_app(global_conf, full_stack=True, **app_conf)
56 59

  
57 60
    max_age = app_conf.get("cache_max_age")
58 61
    try:
......
60 63
    except (ValueError, TypeError):
61 64
        max_age = None
62 65

  
63
    # Personalisation des fichiers statiques via /etc/vigilo/vigiboard/public/.
64
    custom_static = StaticURLParser('/etc/vigilo/vigiboard/public/',
66
    # Personalisation des fichiers statiques via un dossier public/
67
    # dans le répertoire contenant le fichier settings.ini chargé.
68
    custom_static = StaticURLParser(os.path.join(global_conf['here'], 'public'),
65 69
                                    cache_max_age=max_age)
66 70

  
67 71
    # On définit 2 middlewares pour fichiers statiques qui cherchent
vigiboard/websetup.py
22 22
# pylint: disable-msg=W0613
23 23
# W0613: Unused arguments: on doit respecter l'API
24 24

  
25
import imp
26

  
25 27
__all__ = ['setup_app', 'populate_db']
26 28

  
27 29
def _(msg):
......
36 38
def setup_app(command, conf, variables):
37 39
    """Place any commands to setup vigiboard here"""
38 40
    from vigilo.turbogears import populate_db as tg_pop_db
39
    from vigiboard.config.environment import load_environment
40 41

  
42
    # Charge le fichier "app_cfg.py" se trouvant aux côtés de "settings.ini".
43
    mod_info = imp.find_module('app_cfg', [ conf.global_conf['here'] ])
44
    app_cfg = imp.load_module('vigiboard.config.app_cfg', *mod_info)
45

  
46
    # Initialisation de l'environnement d'exécution.
47
    load_environment = app_cfg.base_config.make_load_environment()
41 48
    load_environment(conf.global_conf, conf.local_conf)
42 49
    tg_pop_db()
43 50

  

Also available in: Unified diff