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

Revision 4804, 11.6 KB (checked in by khali, 7 years ago)

Drop DataType?_mhz, libsensors doesn't support this kind of feature.

  • 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 index) {
90  char *buffer = rrdLabels[index];
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 < index)) /* 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 < index))
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, subindex, chipindex = -1;
145      for (index0 = 0; knownChips[index0]; ++ index0)
146        for (subindex = 0; knownChips[index0]->names[subindex]; ++ subindex)
147          if (!strcmp (chip->prefix, knownChips[index0]->names[subindex]))
148            chipindex = index0;
149      if (chipindex >= 0) {
150        const ChipDescriptor *descriptor = knownChips[chipindex];
151        const FeatureDescriptor *features = descriptor->features;
152
153        for (index0 = 0; (ret == 0) && (num < MAX_RRD_SENSORS) && features[index0].format; ++ index0) {
154          const FeatureDescriptor *feature = features + index0;
155          int labelNumber = feature->dataNumbers[0];
156          const char *rawLabel = NULL;
157          char *label = NULL;
158
159          if (getRawLabel (chip, labelNumber, &rawLabel)) {
160            sensorLog (LOG_ERR, "Error getting raw sensor label: %s/#%d", chip->prefix, labelNumber);
161            ret = -1;
162          } else if (!(label = sensors_get_label (chip, labelNumber))) {
163            sensorLog (LOG_ERR, "Error getting sensor label: %s/#%d", chip->prefix, labelNumber);
164            ret = -1;
165          } else  {
166            rrdCheckLabel (rawLabel, num);
167            ret = fn (data, rrdLabels[num], label, feature);
168            ++ num;
169          }
170          if (label)
171            free (label);
172        }
173      }
174    }
175  }
176
177  return ret;
178}
179
180struct ds {
181  int num;
182  const char **argv;
183};
184
185static int
186rrdGetSensors_DS
187(void *_data, const char *rawLabel, const char *label, const FeatureDescriptor *feature) {
188  if (!feature || feature->rrd) {
189    struct ds *data = (struct ds *) _data;
190    char *ptr = rrdBuff + data->num * RRD_BUFF;
191    const char *min, *max;
192    data->argv[data->num ++] = ptr;
193    switch (feature ? feature->type : DataType_other) { /* arbitrary sanity limits */
194      case DataType_voltage:
195        min="-25";
196        max="25";
197        break;
198      case DataType_rpm:
199        min = "0";
200        max = "12000";
201        break;
202      case DataType_temperature:
203        min = "0";
204        max = "250";
205        break;
206      default:
207        min = max = "U";
208        break;
209    }
210    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);
211  }
212  return 0;
213}
214
215static int
216rrdGetSensors
217(const char **argv) {
218  int ret = 0;
219  struct ds data = { 0, argv};
220  ret = applyToFeatures (rrdGetSensors_DS, &data);
221  if (!ret && doLoad)
222    ret = rrdGetSensors_DS (&data, LOADAVG, LOAD_AVERAGE, NULL);
223  return ret ? -1 : data.num;
224}
225
226int
227rrdInit
228(void) {
229  int ret = 0;
230  struct stat tmp;
231 
232  sensorLog (LOG_DEBUG, "sensor RRD init"); 
233  if (stat (rrdFile, &tmp)) {
234    if (errno == ENOENT) {
235      char stepBuff[STEP_BUFF], rraBuff[RRA_BUFF];
236      int argc = 4, num;
237      const char *argv[6 + MAX_RRD_SENSORS] = {
238        "sensord", rrdFile, "-s", stepBuff
239      };
240     
241      sensorLog (LOG_INFO, "creating round robin database");
242      num = rrdGetSensors (argv + argc);
243      if (num == 0) {
244        sensorLog (LOG_ERR, "Error creating RRD: %s: %s", rrdFile, "No sensors detected");
245        ret = 2;
246      } else if (num < 0) {
247        ret = -num;
248      } else {
249        sprintf (stepBuff, "%d", rrdTime);
250        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 */);
251        argc += num;
252        argv[argc ++] = rraBuff;
253        argv[argc] = NULL;
254        optind = 1;
255        opterr = 0;
256        optopt = '?';
257        optarg = NULL;
258        if ((ret = rrd_create (argc, (char **) /* WEAK */ argv))) {
259          sensorLog (LOG_ERR, "Error creating RRD file: %s: %s", rrdFile, rrd_get_error ());
260        }
261      }
262    } else {
263      sensorLog (LOG_ERR, "Error stat()ing RRD: %s: %s", rrdFile, strerror (errno));
264      ret = 1;
265    }
266  }
267  sensorLog (LOG_DEBUG, "sensor RRD inited"); 
268 
269  return ret;
270}
271
272#define RRDCGI "/usr/bin/rrdcgi"
273#define WWWDIR "/sensord"
274
275struct gr {
276  DataType type;
277  char *h2;
278  char *image;
279  char *title;
280  char *axisTitle;
281  char *axisDefn;
282  char *options;
283  int loadAvg;
284};
285
286static int
287rrdCGI_DEF
288(void *_data, const char *rawLabel, const char *label, const FeatureDescriptor *feature) {
289  struct gr *data = (struct gr *) _data;
290  if (!feature || (feature->rrd && (feature->type == data->type)))
291    printf ("\n\tDEF:%s=%s:%s:AVERAGE", rawLabel, rrdFile, rawLabel);
292  return 0;
293}
294
295static int
296rrdCGI_LINE
297(void *_data, const char *rawLabel, const char *label, const FeatureDescriptor *feature) {
298  struct gr *data = (struct gr *) _data;
299  if (!feature || (feature->rrd && (feature->type == data->type)))
300    printf ("\n\tLINE2:%s#%.6x:\"%s\"", rawLabel, (int) random () & 0xffffff, label);
301  return 0;
302}
303
304static struct gr graphs[] = {
305  {
306    DataType_temperature,
307    "Daily Temperature Summary",
308    "daily-temperature",
309    "Temperature",
310    "Temperature (C)",
311    "HOUR:1:HOUR:3:HOUR:3:0:%b %d %H:00",
312    "-s -1d -l 0",
313    1
314  }, {
315    DataType_rpm,
316    "Daily Fan Speed Summary",
317    "daily-rpm",
318    "Fan Speed",
319    "Speed (RPM)",
320    "HOUR:1:HOUR:3:HOUR:3:0:%b %d %H:00",
321    "-s -1d -l 0",
322    0
323  }, {
324    DataType_voltage,
325    "Daily Voltage Summary",
326    "daily-voltage",
327    "Power Supply",
328    "Voltage (V)",
329    "HOUR:1:HOUR:3:HOUR:3:0:%b %d %H:00",
330    "-s -1d --alt-autoscale",
331    0
332  }, {
333    DataType_temperature,
334    "Weekly Temperature Summary",
335    "weekly-temperature",
336    "Temperature",
337    "Temperature (C)",
338    "HOUR:6:DAY:1:DAY:1:86400:%a %b %d",
339    "-s -1w -l 0",
340    1
341  }, {
342    DataType_rpm,
343    "Weekly Fan Speed Summary",
344    "weekly-rpm",
345    "Fan Speed",
346    "Speed (RPM)",
347    "HOUR:6:DAY:1:DAY:1:86400:%a %b %d",
348    "-s -1w -l 0",
349    0
350  }, {
351    DataType_voltage,
352    "Weekly Voltage Summary",
353    "weekly-voltage",
354    "Power Supply",
355    "Voltage (V)",
356    "HOUR:6:DAY:1:DAY:1:86400:%a %b %d",
357    "-s -1w --alt-autoscale",
358    0
359  }, {
360    DataType_other
361  } 
362};
363
364int
365rrdUpdate
366(void) {
367  int ret = rrdChips ();
368  if (!ret && doLoad) {
369    FILE *loadavg;
370    if (!(loadavg = fopen ("/proc/loadavg", "r"))) {
371      sensorLog (LOG_ERR, "Error opening `/proc/loadavg': %s", strerror (errno));
372      ret = 1;
373    } else {
374      float value;
375      if (fscanf (loadavg, "%f", &value) != 1) {
376        sensorLog (LOG_ERR, "Error reading load average");
377        ret = 2;
378      } else {
379        sprintf (rrdBuff + strlen (rrdBuff), ":%f", value);
380      }
381      fclose (loadavg);
382    }
383  }
384  if (!ret) {
385    const char *argv[] = {
386      "sensord", rrdFile, rrdBuff, NULL
387    };
388    optind = 1;
389    opterr = 0;
390    optopt = '?';
391    optarg = NULL;
392    if ((ret = rrd_update (3, (char **) /* WEAK */ argv))) {
393      sensorLog (LOG_ERR, "Error updating RRD file: %s: %s", rrdFile, rrd_get_error ());
394    }
395  }
396  sensorLog (LOG_DEBUG, "sensor rrd updated"); 
397 
398  return ret;
399}
400
401int
402rrdCGI
403(void) {
404  int ret = 0;
405  struct gr *graph = graphs;
406
407  printf ("#!" RRDCGI "\n\n<HTML>\n<HEAD>\n<TITLE>sensord</TITLE>\n</HEAD>\n<BODY>\n<H1>sensord</H1>\n");
408  while (graph->type != DataType_other) {
409    printf ("<H2>%s</H2>\n", graph->h2);
410    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);
411    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);
412    if (!ret)
413      ret = applyToFeatures (rrdCGI_DEF, graph);
414    if (!ret && doLoad && graph->loadAvg)
415      ret = rrdCGI_DEF (graph, LOADAVG, LOAD_AVERAGE, NULL);
416    if (!ret)
417      ret = applyToFeatures (rrdCGI_LINE, graph);
418    if (!ret && doLoad && graph->loadAvg)
419      ret = rrdCGI_LINE (graph, LOADAVG, LOAD_AVERAGE, NULL);
420    printf (">\n</P>\n");
421    ++ graph;
422  }
423  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");
424  printf ("</BODY>\n</HTML>\n");
425 
426  return ret;
427}
Note: See TracBrowser for help on using the browser.