Completed
Push — master ( bcff18...adb900 )
by Nicolas
01:15
created

glances.GlancesActions.set()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 3
rs 10
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2015 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
"""Manage on alert actions."""
21
22
from subprocess import Popen
23
24
from glances.logger import logger
25
from glances.timer import Timer
26
27
try:
28
    import pystache
29
except ImportError:
30
    logger.warning("PyStache lib not installed (action script with mustache will not work)")
31
    pystache_tag = False
32
else:
33
    pystache_tag = True
34
35
36
class GlancesActions(object):
37
38
    """This class manage action if an alert is reached."""
39
40
    def __init__(self, args=None):
41
        """Init GlancesActions class."""
42
        # Dict with the criticity status
43
        # - key: stat_name
44
        # - value: criticity
45
        # Goal: avoid to execute the same command twice
46
        self.status = {}
47
48
        # Add a timer to avoid any trigger when Glances is started (issue#732)
49
        # Action can be triggered after refresh * 2 seconds
50
        if hasattr(args, 'time'):
51
            self.start_timer = Timer(args.time * 2)
52
        else:
53
            self.start_timer = Timer(3)
54
55
    def get(self, stat_name):
56
        """Get the stat_name criticity."""
57
        try:
58
            return self.status[stat_name]
59
        except KeyError:
60
            return None
61
62
    def set(self, stat_name, criticity):
63
        """Set the stat_name to criticity."""
64
        self.status[stat_name] = criticity
65
66
    def run(self, stat_name, criticity, commands, mustache_dict=None):
67
        """Run the commands (in background).
68
69
        - stats_name: plugin_name (+ header)
70
        - criticity: criticity of the trigger
71
        - commands: a list of command line with optional {{mustache}}
72
        - mustache_dict: Plugin stats (can be use within {{mustache}})
73
74
        Return True if the commands have been ran.
75
        """
76
        if self.get(stat_name) == criticity or not self.start_timer.finished():
77
            # Action already executed => Exit
78
            return False
79
80
        logger.debug("Run action {0} for {1} ({2}) with stats {3}".format(commands,
81
                                                                          stat_name,
82
                                                                          criticity,
83
                                                                          mustache_dict))
84
85
        # Run all actions in background
86
        for cmd in commands:
87
            # Replace {{arg}} by the dict one (Thk to {Mustache})
88
            if pystache_tag:
89
                cmd_full = pystache.render(cmd, mustache_dict)
90
            else:
91
                cmd_full = cmd
92
            # Execute the action
93
            logger.info("Action triggered for {0} ({1}): {2}".format(stat_name, criticity, cmd_full))
94
            logger.debug("Stats value for the trigger: {0}".format(mustache_dict))
95
            try:
96
                Popen(cmd_full, shell=True)
97
            except OSError as e:
98
                logger.error("Can't execute the action ({0})".format(e))
99
100
        self.set(stat_name, criticity)
101
102
        return True
103