root/lm-sensors/branches/lm-sensors-3.0.0/prog/sensord/rrd.c @ 4828

Revision 4828, 11.9 KB (checked in by khali, 7 years ago)

Scan chip features only once at initialization time, rather than on
each update. The chip list and chip features do not change until
sensors_cleanup() is called, so there's no point in doing the
same work over and over again.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/*
2 * sensord
3 *
4 * A daemon that periodically logs sensor information to syslog.
5 *
6 * Copyright (c) 1999-2002 Merlin Hughes <merlin@merlin.org>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23/*
24 * RRD is the Round Robin Database
25 *
26 * Get this package from:
27 *   http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/
28 *
29 * For compilation you need the development libraries;
30 * for execution you need the runtime libraries; for
31 * Web-based graph access you need the binary rrdtool.
32 */
33
34#include <errno.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <syslog.h>
39#include <unistd.h>
40#include <sys/stat.h>
41#include <sys/types.h>
42
43#include <getopt.h>
44#include <rrd.h>
45
46#include "sensord.h"
47#include "lib/error.h"
48
49#define DO_READ 0
50#define DO_SCAN 1
51#define DO_SET 2
52#define DO_RRD 3
53
54/* one integer */
55#define STEP_BUFF 64
56/* RRA:AVERAGE:0.5:1:12345 */
57#define RRA_BUFF 256
58/* weak: max sensors for RRD .. TODO: fix */
59#define MAX_RRD_SENSORS 256
60/* weak: max raw label length .. TODO: fix */
61#define RAW_LABEL_LENGTH 32
62/* DS:label:GAUGE:900:U:U | :3000 .. TODO: fix */
63#define RRD_BUFF 64
64
65char rrdBuff[MAX_RRD_SENSORS * RRD_BUFF + 1];
66static char rrdLabels[MAX_RRD_SENSORS][RAW_LABEL_LENGTH + 1];
67
68#define LOADAVG "loadavg"
69#define LOAD_AVERAGE "Load Average"
70
71typedef int (*FeatureFN) (void *data, const char *rawLabel, const char *label, const FeatureDescriptor *feature);
72
73static char
74rrdNextChar
75(char c) {
76  if (c == '9') {
77    return 'A';
78  } else if (c == 'Z') {
79    return 'a';
80  } else if (c == 'z') {
81    return 0;
82  } else {
83    return c + 1;
84  }
85}
86
87static void
88rrdCheckLabel
89(const char *rawLabel, int index0) {
90  char *buffer = rrdLabels[index0];
91  int i, j, okay;
92 
93  i = 0;
94  while ((i < RAW_LABEL_LENGTH) && rawLabel[i]) { /* contrain raw label to [A-Za-z0-9_] */
95    char c = rawLabel[i];
96    if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9')) || (c == '_')) {
97      buffer[i] = c;
98    } else {
99      buffer[i] = '_';
100    }
101    ++ i;
102  }
103  buffer[i] = '\0';
104
105  j = 0;
106  okay = (i > 0);
107  while (okay && (j < index0)) /* locate duplicates */
108    okay = strcmp (rrdLabels[j ++], buffer);
109
110  while (!okay) { /* uniquify duplicate labels with _? or _?? */
111    if (!buffer[i]) {
112      if (i > RAW_LABEL_LENGTH - 3)
113        i = RAW_LABEL_LENGTH - 3;
114      buffer[i] = '_';
115      buffer[i + 1] = '0';
116      buffer[i + 2] = '\0';
117    } else if (!buffer[i + 2]) {
118      if (!(buffer[i + 1] = rrdNextChar (buffer[i + 1]))) {
119        buffer[i + 1] = '0';
120        buffer[i + 2] = '0';
121        buffer[i + 3] = '\0';
122      }
123    } else {
124      if (!(buffer[i + 2] = rrdNextChar (buffer[i + 2]))) {
125        buffer[i + 1] = rrdNextChar (buffer[i + 1]);
126        buffer[i + 2] = '0';
127      }
128    }
129    j = 0;
130    okay = 1;
131    while (okay && (j < index0))
132      okay = strcmp (rrdLabels[j ++], buffer);
133  }
134}
135
136static int
137applyToFeatures
138(FeatureFN fn, void *data) {
139  const sensors_chip_name *chip;
140  int i = 0, j, ret = 0, num = 0;
141
142  for (j = 0; (ret == 0) && (j < numChipNames); ++ j) {
143    while ((ret == 0) && ((chip = sensors_get_detected_chips (&chipNames[j], &i)) != NULL)) {
144      int index0, chipindex = -1;
145      for (index0 = 0; knownChips[index0].features; ++ index0)
146        /* Trick: we compare addresses here. We know it works because both
147           pointers were returned by sensors_get_detected_chips(), so they
148           refer to libsensors internal structures, which do not move. */
149        if (knownChips[index0].name == chip) {
150          chipindex = index0;
151          break;
152        }
153      if (chipindex >= 0) {
154        const ChipDescriptor *descriptor = &knownChips[chipindex];
155        const FeatureDescriptor *features = descriptor->features;
156
157        for (index0 = 0; (ret == 0) && (num < MAX_RRD_SENSORS) && features[index0].format; ++ index0) {
158          const FeatureDescriptor *feature = features + index0;
159          int labelNumber = feature->dataNumbers[0];
160          const char *rawLabel = NULL;
161          char *label = NULL;
162
163          if (getRawLabel (chip, labelNumber, &rawLabel)) {
164            sensorLog (LOG_ERR, "Error getting raw sensor label: %s/#%d", chip->prefix, labelNumber);
165            ret = -1;
166          } else if (!(label = sensors_get_label (chip, labelNumber))) {
167            sensorLog (LOG_ERR, "Error getting sensor label: %s/#%d", chip->prefix, labelNumber);
168            ret = -1;
169          } else  {
170            rrdCheckLabel (rawLabel, num);
171            ret = fn (data, rrdLabels[num], label, feature);
172            ++ num;
173          }
174          if (label)
175            free (label);
176        }
177      }
178    }
179  }
180
181  return ret;
182}
183
184struct ds {
185  int num;
186  const char **argv;
187};
188
189static int
190rrdGetSensors_DS
191(void *_data, const char *rawLabel, const char *label, const FeatureDescriptor *feature) {
192  if (!feature || feature->rrd) {
193    struct ds *data = (struct ds *) _data;
194    char *ptr = rrdBuff + data->num * RRD_BUFF;
195    const char *min, *max;
196    data->argv[data->num ++] = ptr;
197    switch (feature ? feature->type : DataType_other) { /* arbitrary sanity limits */
198      case DataType_voltage:
199        min="-25";
200        max="25";
201        break;
202      case DataType_rpm:
203        min = "0";
204        max = "12000";
205        break;
206      case DataType_temperature:
207        min = "0";
208        max = "250";
209        break;
210      default:
211        min = max = "U";
212        break;
213    }
214    sprintf (ptr, "DS:%s:GAUGE:%d:%s:%s", rawLabel, /* number of seconds downtime during which average be used instead of unknown */ 5 * rrdTime, min, max);
215  }
216  return 0;
217}
218
219static int
220rrdGetSensors
221(const char **argv) {
222  int ret = 0;
223  struct ds data = { 0, argv};
224  ret = applyToFeatures (rrdGetSensors_DS, &data);
225  if (!ret && doLoad)
226    ret = rrdGetSensors_DS (&data, LOADAVG, LOAD_AVERAGE, NULL);
227  return ret ? -1 : data.num;
228}
229
230int
231rrdInit
232(void) {
233  int ret = 0;
234  struct stat tmp;
235 
236  sensorLog (LOG_DEBUG, "sensor RRD init"); 
237  if (stat (rrdFile, &tmp)) {
238    if (errno == ENOENT) {
239      char stepBuff[STEP_BUFF], rraBuff[RRA_BUFF];
240      int argc = 4, num;
241      const char *argv[6 + MAX_RRD_SENSORS] = {
242        "sensord", rrdFile, "-s", stepBuff
243      };
244     
245      sensorLog (LOG_INFO, "creating round robin database");
246      num = rrdGetSensors (argv + argc);
247      if (num == 0) {
248        sensorLog (LOG_ERR, "Error creating RRD: %s: %s", rrdFile, "No sensors detected");
249        ret = 2;
250      } else if (num < 0) {
251        ret = -num;
252      } else {
253        sprintf (stepBuff, "%d", rrdTime);
254        sprintf (rraBuff, "RRA:%s:%f:%d:%d", rrdNoAverage?"LAST":"AVERAGE", 0.5 /* fraction of non-unknown samples needed per entry */, 1 /* samples per entry */, 7 * 24 * 60 * 60 / rrdTime /* 1 week */);
255        argc += num;
256        argv[argc ++] = rraBuff;
257        argv[argc] = NULL;
258        optind = 1;
259        opterr = 0;
260        optopt = '?';
261        optarg = NULL;
262        if ((ret = rrd_create (argc, (char **) /* WEAK */ argv))) {
263          sensorLog (LOG_ERR, "Error creating RRD file: %s: %s", rrdFile, rrd_get_error ());
264        }
265      }
266    } else {
267      sensorLog (LOG_ERR, "Error stat()ing RRD: %s: %s", rrdFile, strerror (errno));
268      ret = 1;
269    }
270  }
271  sensorLog (LOG_DEBUG, "sensor RRD inited"); 
272 
273  return ret;
274}
275
276#define RRDCGI "/usr/bin/rrdcgi"
277#define WWWDIR "/sensord"
278
279struct gr {
280  DataType type;
281  const char *h2;
282  const char *image;
283  const char *title;
284  const char *axisTitle;
285  const char *axisDefn;
286  const char *options;
287  int loadAvg;
288};
289
290static int
291rrdCGI_DEF
292(void *_data, const char *rawLabel, const char *label, const FeatureDescriptor *feature) {
293  struct gr *data = (struct gr *) _data;
294  if (!feature || (feature->rrd && (feature->type == data->type)))
295    printf ("\n\tDEF:%s=%s:%s:AVERAGE", rawLabel, rrdFile, rawLabel);
296  return 0;
297}
298
299static int
300rrdCGI_LINE
301(void *_data, const char *rawLabel, const char *label, const FeatureDescriptor *feature) {
302  struct gr *data = (struct gr *) _data;
303  if (!feature || (feature->rrd && (feature->type == data->type)))
304    printf ("\n\tLINE2:%s#%.6x:\"%s\"", rawLabel, (int) random () & 0xffffff, label);
305  return 0;
306}
307
308static struct gr graphs[] = {
309  {
310    DataType_temperature,
311    "Daily Temperature Summary",
312    "daily-temperature",
313    "Temperature",
314    "Temperature (C)",
315    "HOUR:1:HOUR:3:HOUR:3:0:%b %d %H:00",
316    "-s -1d -l 0",
317    1
318  }, {
319    DataType_rpm,
320    "Daily Fan Speed Summary",
321    "daily-rpm",
322    "Fan Speed",
323    "Speed (RPM)",
324    "HOUR:1:HOUR:3:HOUR:3:0:%b %d %H:00",
325    "-s -1d -l 0",
326    0
327  }, {
328    DataType_voltage,
329    "Daily Voltage Summary",
330    "daily-voltage",
331    "Power Supply",
332    "Voltage (V)",
333    "HOUR:1:HOUR:3:HOUR:3:0:%b %d %H:00",
334    "-s -1d --alt-autoscale",
335    0
336  }, {
337    DataType_temperature,
338    "Weekly Temperature Summary",
339    "weekly-temperature",
340    "Temperature",
341    "Temperature (C)",
342    "HOUR:6:DAY:1:DAY:1:86400:%a %b %d",
343    "-s -1w -l 0",
344    1
345  }, {
346    DataType_rpm,
347    "Weekly Fan Speed Summary",
348    "weekly-rpm",
349    "Fan Speed",
350    "Speed (RPM)",
351    "HOUR:6:DAY:1:DAY:1:86400:%a %b %d",
352    "-s -1w -l 0",
353    0
354  }, {
355    DataType_voltage,
356    "Weekly Voltage Summary",
357    "weekly-voltage",
358    "Power Supply",
359    "Voltage (V)",
360    "HOUR:6:DAY:1:DAY:1:86400:%a %b %d",
361    "-s -1w --alt-autoscale",
362    0
363  }, {
364    DataType_other,
365    NULL,
366    NULL,
367    NULL,
368    NULL,
369    NULL,
370    NULL,
371    0
372  } 
373};
374
375int
376rrdUpdate
377(void) {
378  int ret = rrdChips ();
379  if (!ret && doLoad) {
380    FILE *loadavg;
381    if (!(loadavg = fopen ("/proc/loadavg", "r"))) {
382      sensorLog (LOG_ERR, "Error opening `/proc/loadavg': %s", strerror (errno));
383      ret = 1;
384    } else {
385      float value;
386      if (fscanf (loadavg, "%f", &value) != 1) {
387        sensorLog (LOG_ERR, "Error reading load average");
388        ret = 2;
389      } else {
390        sprintf (rrdBuff + strlen (rrdBuff), ":%f", value);
391      }
392      fclose (loadavg);
393    }
394  }
395  if (!ret) {
396    const char *argv[] = {
397      "sensord", rrdFile, rrdBuff, NULL
398    };
399    optind = 1;
400    opterr = 0;
401    optopt = '?';
402    optarg = NULL;
403    if ((ret = rrd_update (3, (char **) /* WEAK */ argv))) {
404      sensorLog (LOG_ERR, "Error updating RRD file: %s: %s", rrdFile, rrd_get_error ());
405    }
406  }
407  sensorLog (LOG_DEBUG, "sensor rrd updated"); 
408 
409  return ret;
410}
411
412int
413rrdCGI
414(void) {
415  int ret = 0;
416  struct gr *graph = graphs;
417
418  printf ("#!" RRDCGI "\n\n<HTML>\n<HEAD>\n<TITLE>sensord</TITLE>\n</HEAD>\n<BODY>\n<H1>sensord</H1>\n");
419  while (graph->type != DataType_other) {
420    printf ("<H2>%s</H2>\n", graph->h2);
421    printf ("<P>\n<RRD::GRAPH %s/%s.png\n\t--imginfo '<IMG SRC=" WWWDIR "/%%s WIDTH=%%lu HEIGHT=%%lu>'\n\t-a PNG\n\t-h 200 -w 800\n", cgiDir, graph->image);
422    printf ("\t--lazy\n\t-v '%s'\n\t-t '%s'\n\t-x '%s'\n\t%s", graph->axisTitle, graph->title, graph->axisDefn, graph->options);
423    if (!ret)
424      ret = applyToFeatures (rrdCGI_DEF, graph);
425    if (!ret && doLoad && graph->loadAvg)
426      ret = rrdCGI_DEF (graph, LOADAVG, LOAD_AVERAGE, NULL);
427    if (!ret)
428      ret = applyToFeatures (rrdCGI_LINE, graph);
429    if (!ret && doLoad && graph->loadAvg)
430      ret = rrdCGI_LINE (graph, LOADAVG, LOAD_AVERAGE, NULL);
431    printf (">\n</P>\n");
432    ++ graph;
433  }
434  printf ("<p>\n<small><b>sensord</b> by <a href=\"mailto:merlin@merlin.org\">Merlin Hughes</a>, all credit to the <a href=\"http://www.lm-sensors.org/\">lm_sensors</a> crew.</small>\n</p>\n");
435  printf ("</BODY>\n</HTML>\n");
436 
437  return ret;
438}
Note: See TracBrowser for help on using the browser.