Completed
Push — master ( 2b80fa...6ea077 )
by Nicolas
01:22
created

glances/plugins/glances_hddtemp.py (1 issue)

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2017 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
"""HDD temperature plugin."""
21
22
import os
23
import socket
24
25
from glances.compat import nativestr, range
26
from glances.logger import logger
27
from glances.plugins.glances_plugin import GlancesPlugin
28
29
30 View Code Duplication
class Plugin(GlancesPlugin):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
31
32
    """Glances HDD temperature sensors plugin.
33
34
    stats is a list
35
    """
36
37
    def __init__(self, args=None):
38
        """Init the plugin."""
39
        super(Plugin, self).__init__(args=args)
40
41
        # Init the sensor class
42
        self.glancesgrabhddtemp = GlancesGrabHDDTemp(args=args)
43
44
        # We do not want to display the stat in a dedicated area
45
        # The HDD temp is displayed within the sensors plugin
46
        self.display_curse = False
47
48
        # Init stats
49
        self.reset()
50
51
    def reset(self):
52
        """Reset/init the stats."""
53
        self.stats = []
54
55
    @GlancesPlugin._check_decorator
56
    @GlancesPlugin._log_result_decorator
57
    def update(self):
58
        """Update HDD stats using the input method."""
59
        # Reset stats
60
        self.reset()
61
62
        if self.input_method == 'local':
63
            # Update stats using the standard system lib
64
            self.stats = self.glancesgrabhddtemp.get()
65
66
        else:
67
            # Update stats using SNMP
68
            # Not available for the moment
69
            pass
70
71
        return self.stats
72
73
74
class GlancesGrabHDDTemp(object):
75
76
    """Get hddtemp stats using a socket connection."""
77
78
    def __init__(self, host='127.0.0.1', port=7634, args=None):
79
        """Init hddtemp stats."""
80
        self.args = args
81
        self.host = host
82
        self.port = port
83
        self.cache = ""
84
        self.reset()
85
86
    def reset(self):
87
        """Reset/init the stats."""
88
        self.hddtemp_list = []
89
90
    def __update__(self):
91
        """Update the stats."""
92
        # Reset the list
93
        self.reset()
94
95
        # Fetch the data
96
        # data = ("|/dev/sda|WDC WD2500JS-75MHB0|44|C|"
97
        #         "|/dev/sdb|WDC WD2500JS-75MHB0|35|C|"
98
        #         "|/dev/sdc|WDC WD3200AAKS-75B3A0|45|C|"
99
        #         "|/dev/sdd|WDC WD3200AAKS-75B3A0|45|C|"
100
        #         "|/dev/sde|WDC WD3200AAKS-75B3A0|43|C|"
101
        #         "|/dev/sdf|???|ERR|*|"
102
        #         "|/dev/sdg|HGST HTS541010A9E680|SLP|*|"
103
        #         "|/dev/sdh|HGST HTS541010A9E680|UNK|*|")
104
        data = self.fetch()
105
106
        # Exit if no data
107
        if data == "":
108
            return
109
110
        # Safety check to avoid malformed data
111
        # Considering the size of "|/dev/sda||0||" as the minimum
112
        if len(data) < 14:
113
            data = self.cache if len(self.cache) > 0 else self.fetch()
114
        self.cache = data
115
116
        try:
117
            fields = data.split(b'|')
118
        except TypeError:
119
            fields = ""
120
        devices = (len(fields) - 1) // 5
121
        for item in range(devices):
122
            offset = item * 5
123
            hddtemp_current = {}
124
            device = os.path.basename(nativestr(fields[offset + 1]))
125
            temperature = fields[offset + 3]
126
            unit = nativestr(fields[offset + 4])
127
            hddtemp_current['label'] = device
128
            try:
129
                hddtemp_current['value'] = float(temperature)
130
            except ValueError:
131
                # Temperature could be 'ERR', 'SLP' or 'UNK' (see issue #824)
132
                # Improper bytes/unicode in glances_hddtemp.py (see issue #887)
133
                hddtemp_current['value'] = nativestr(temperature)
134
            hddtemp_current['unit'] = unit
135
            self.hddtemp_list.append(hddtemp_current)
136
137
    def fetch(self):
138
        """Fetch the data from hddtemp daemon."""
139
        # Taking care of sudden deaths/stops of hddtemp daemon
140
        try:
141
            sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
142
            sck.connect((self.host, self.port))
143
            data = sck.recv(4096)
144
        except socket.error as e:
145
            logger.debug("Cannot connect to an HDDtemp server ({}:{} => {})".format(self.host, self.port, e))
146
            logger.debug("Disable the HDDtemp module. Use the --disable-hddtemp to hide the previous message.")
147
            if self.args is not None:
148
                self.args.disable_hddtemp = True
149
            data = ""
150
        finally:
151
            sck.close()
152
153
        return data
154
155
    def get(self):
156
        """Get HDDs list."""
157
        self.__update__()
158
        return self.hddtemp_list
159