added --sensor-log-interval option
[psensor.git] / src / server / server.c
1 /*
2  * Copyright (C) 2010-2012 jeanfi@gmail.com
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301 USA
18  */
19 #include <locale.h>
20 #include <libintl.h>
21 #define _(str) gettext(str)
22
23 #include "config.h"
24
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sys/select.h>
32 #include <sys/socket.h>
33 #include <getopt.h>
34 #include <stdint.h>
35 #include <pthread.h>
36 #include <unistd.h>
37 #include <microhttpd.h>
38
39 #ifdef HAVE_GTOP
40 #include "sysinfo.h"
41 #include "cpu.h"
42 #endif
43
44 #include "log.h"
45 #include "psensor_json.h"
46 #include "url.h"
47 #include "server.h"
48 #include "slog.h"
49
50 static const char *DEFAULT_LOG_FILE = "/var/log/psensor-server.log";
51
52 #define HTML_STOP_REQUESTED \
53 (_("<html><body><p>Server stop requested</p></body></html>"))
54
55 static const char *program_name;
56
57 static const int DEFAULT_PORT = 3131;
58
59 #define PAGE_NOT_FOUND (_("<html><body><p>"\
60 "Page not found - Go to <a href='/'>Main page</a></p></body>"))
61
62 static struct option long_options[] = {
63         {"version", no_argument, 0, 'v'},
64         {"help", no_argument, 0, 'h'},
65         {"port", required_argument, 0, 'p'},
66         {"wdir", required_argument, 0, 'w'},
67         {"debug", required_argument, 0, 'd'},
68         {"log-file", required_argument, 0, 'l'},
69         {"sensor-log-file", required_argument, 0, 0},
70         {"sensor-log-interval", required_argument, 0, 0},
71         {0, 0, 0, 0}
72 };
73
74 static struct server_data server_data;
75
76 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
77
78 static int server_stop_requested;
79
80 static void print_version()
81 {
82         printf("psensor-server %s\n", VERSION);
83         printf(_("Copyright (C) %s jeanfi@gmail.com\n"
84                  "License GPLv2: GNU GPL version 2 or later "
85                  "<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n"
86                  "This is free software: you are free to change and redistribute it.\n"
87                  "There is NO WARRANTY, to the extent permitted by law.\n"),
88                "2010-2012");
89 }
90
91 static void print_help()
92 {
93         printf(_("Usage: %s [OPTION]...\n"), program_name);
94
95         puts(_("psensor-server is an HTTP server for monitoring hardware "
96                "sensors remotely."));
97
98         puts("");
99         puts("Options:");
100         puts(_("  -h, --help            display this help and exit\n"
101                "  -v, --version         display version information and exit"));
102
103         puts("");
104         puts(_("  -p,--port=PORT        webserver port\n"
105                "  -w,--wdir=DIR         directory containing webserver pages"));
106
107         puts("");
108         puts(_("  -d, --debug=LEVEL     "
109                "set the debug level, integer between 0 and 3"));
110         puts(_("  -l, --log-file=PATH   set the log file to PATH"));
111         puts(_("  --sensor-log-file=PATH set the sensor log file to PATH"));
112         puts(_("  --sensor-log-interval=S "
113                "set the sensor log interval to S (seconds)"));
114
115         puts("");
116         printf(_("Report bugs to: %s\n"), PACKAGE_BUGREPORT);
117         puts("");
118         printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
119 }
120
121 /*
122  * Returns the file path corresponding to a given URL
123  */
124 static char *get_path(const char *url, const char *www_dir)
125 {
126         const char *p;
127         char *res;
128
129         if (!strlen(url) || !strcmp(url, ".") || !strcmp(url, "/"))
130                 p = "/index.html";
131         else
132                 p = url;
133
134         res = malloc(strlen(www_dir)+strlen(p)+1);
135
136         strcpy(res, www_dir);
137         strcat(res, p);
138
139         return res;
140 }
141
142 #if MHD_VERSION >= 0x00090200
143 static ssize_t
144 file_reader(void *cls, uint64_t pos, char *buf, size_t max)
145 #else
146 static int
147 file_reader(void *cls, uint64_t pos, char *buf, int max)
148 #endif
149 {
150         FILE *file = cls;
151
152         fseek(file, pos, SEEK_SET);
153         return fread(buf, 1, max, file);
154 }
155
156 static struct MHD_Response *
157 create_response_api(const char *nurl, const char *method, unsigned int *rp_code)
158 {
159         struct MHD_Response *resp;
160         struct psensor *s;
161         char *page = NULL;
162
163         if (!strcmp(nurl, URL_BASE_API_1_0_SENSORS))  {
164                 page = sensors_to_json_string(server_data.sensors);
165 #ifdef HAVE_GTOP
166         } else if (!strcmp(nurl, URL_API_1_0_SYSINFO)) {
167                 page = sysinfo_to_json_string(&server_data.psysinfo);
168         } else if (!strcmp(nurl, URL_API_1_0_CPU_USAGE)) {
169                 page = sensor_to_json_string(server_data.cpu_usage);
170 #endif
171         } else if (!strncmp(nurl, URL_BASE_API_1_0_SENSORS,
172                             strlen(URL_BASE_API_1_0_SENSORS))
173                    && nurl[strlen(URL_BASE_API_1_0_SENSORS)] == '/') {
174
175                 const char *sid = nurl + strlen(URL_BASE_API_1_0_SENSORS) + 1;
176
177                 s = psensor_list_get_by_id(server_data.sensors, sid);
178
179                 if (s)
180                         page = sensor_to_json_string(s);
181
182         } else if (!strcmp(nurl, URL_API_1_0_SERVER_STOP)) {
183
184                 server_stop_requested = 1;
185                 page = strdup(HTML_STOP_REQUESTED);
186         }
187
188         if (page) {
189                 *rp_code = MHD_HTTP_OK;
190
191                 resp = MHD_create_response_from_data(strlen(page), page,
192                                                      MHD_YES, MHD_NO);
193
194                 MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
195                                         "application/json");
196
197                 return resp;
198         }
199
200         return NULL;
201 }
202
203 static struct MHD_Response *create_response_file(const char *nurl,
204                                                  const char *method,
205                                                  unsigned int *rp_code,
206                                                  const char *fpath)
207 {
208         struct stat st;
209         int ret;
210         FILE *file;
211
212         ret = stat(fpath, &st);
213
214         if (!ret && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
215                 file = fopen(fpath, "rb");
216
217                 if (file) {
218                         *rp_code = MHD_HTTP_OK;
219
220                         if (!st.st_size) {
221                                 fclose(file);
222                                 return MHD_create_response_from_data
223                                         (0, NULL, MHD_NO, MHD_NO);
224                         }
225
226                         return MHD_create_response_from_callback
227                                 (st.st_size,
228                                  32 * 1024,
229                                  &file_reader,
230                                  file,
231                                  (MHD_ContentReaderFreeCallback)&fclose);
232
233                 } else {
234                         log_err("Failed to open: %s.", fpath);
235                 }
236         }
237
238         return NULL;
239 }
240
241 static struct MHD_Response *
242 create_response(const char *nurl, const char *method, unsigned int *rp_code)
243 {
244         struct MHD_Response *resp = NULL;
245
246         if (!strncmp(nurl, URL_BASE_API_1_0, strlen(URL_BASE_API_1_0))) {
247                 resp = create_response_api(nurl, method, rp_code);
248         } else {
249                 char *fpath = get_path(nurl, server_data.www_dir);
250
251                 resp = create_response_file(nurl, method, rp_code, fpath);
252
253                 free(fpath);
254         }
255
256         if (resp) {
257                 return resp;
258         } else {
259                 char *page = strdup(PAGE_NOT_FOUND);
260                 *rp_code = MHD_HTTP_NOT_FOUND;
261
262                 return MHD_create_response_from_data
263                         (strlen(page), page, MHD_YES, MHD_NO);
264         }
265 }
266
267 static int cbk_http_request(void *cls,
268                             struct MHD_Connection *connection,
269                             const char *url,
270                             const char *method,
271                             const char *version,
272                             const char *upload_data,
273                             size_t *upload_data_size, void **ptr)
274 {
275         static int dummy;
276         struct MHD_Response *response;
277         int ret;
278         char *nurl;
279         unsigned int resp_code;
280
281         if (strcmp(method, "GET"))
282                 return MHD_NO;
283
284         if (&dummy != *ptr) {
285                 /* The first time only the headers are valid, do not
286                    respond in the first round... */
287                 *ptr = &dummy;
288                 return MHD_YES;
289         }
290
291         if (*upload_data_size)
292                 return MHD_NO;
293
294         *ptr = NULL;            /* clear context pointer */
295
296         log_debug(_("HTTP Request: %s"), url);
297
298         nurl = url_normalize(url);
299
300         pthread_mutex_lock(&mutex);
301         response = create_response(nurl, method, &resp_code);
302         pthread_mutex_unlock(&mutex);
303
304         ret = MHD_queue_response(connection, resp_code, response);
305         MHD_destroy_response(response);
306
307         free(nurl);
308
309         return ret;
310 }
311
312 int main(int argc, char *argv[])
313 {
314         struct MHD_Daemon *d;
315         int port, opti, optc, cmdok, ret, slog_interval;
316         char *log_file, *slog_file;
317
318         program_name = argv[0];
319
320         setlocale(LC_ALL, "");
321
322 #if ENABLE_NLS
323         bindtextdomain(PACKAGE, LOCALEDIR);
324         textdomain(PACKAGE);
325 #endif
326
327         server_data.www_dir = NULL;
328         server_data.psysinfo.interfaces = NULL;
329         log_file = NULL;
330         slog_file = NULL;
331         slog_interval = 300;
332         port = DEFAULT_PORT;
333         cmdok = 1;
334
335         while ((optc = getopt_long(argc,
336                                    argv,
337                                    "vhp:w:d:l:",
338                                    long_options,
339                                    &opti)) != -1) {
340                 switch (optc) {
341                 case 'w':
342                         if (optarg)
343                                 server_data.www_dir = strdup(optarg);
344                         break;
345                 case 'p':
346                         if (optarg)
347                                 port = atoi(optarg);
348                         break;
349                 case 'h':
350                         print_help();
351                         exit(EXIT_SUCCESS);
352                 case 'v':
353                         print_version();
354                         exit(EXIT_SUCCESS);
355                 case 'd':
356                         log_level = atoi(optarg);
357                         log_info(_("Enables debug mode: %d"), log_level);
358                         break;
359                 case 'l':
360                         if (optarg)
361                                 log_file = strdup(optarg);
362                         break;
363                 case 0:
364                         if (!strcmp(long_options[opti].name, "sensor-log-file"))
365                                 slog_file = strdup(optarg);
366                         else if (!strcmp(long_options[opti].name,
367                                          "sensor-log-interval"))
368                                 slog_interval = atoi(optarg);
369                         break;
370                 default:
371                         cmdok = 0;
372                         break;
373                 }
374         }
375
376         if (!cmdok || optind != argc) {
377                 fprintf(stderr, _("Try `%s --help' for more information.\n"),
378                         program_name);
379                 exit(EXIT_FAILURE);
380         }
381
382         if (!server_data.www_dir)
383                 server_data.www_dir = strdup(DEFAULT_WWW_DIR);
384
385         if (!log_file)
386                 log_file = strdup(DEFAULT_LOG_FILE);
387
388         log_open(log_file);
389
390         psensor_init();
391
392         server_data.sensors = get_all_sensors(0, 600);
393
394 #ifdef HAVE_GTOP
395         server_data.cpu_usage = create_cpu_usage_sensor(600);
396 #endif
397
398         if (!*server_data.sensors)
399                 log_err(_("No sensors detected."));
400
401         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
402                              port,
403                              NULL, NULL, &cbk_http_request, server_data.sensors,
404                              MHD_OPTION_END);
405         if (!d) {
406                 log_err(_("Failed to create Web server."));
407                 exit(EXIT_FAILURE);
408         }
409
410         log_info(_("Web server started on port: %d"), port);
411         log_info(_("WWW directory: %s"), server_data.www_dir);
412         log_info(_("URL: http://localhost:%d"), port);
413
414         if (slog_file) {
415                 if (slog_interval <= 0)
416                         slog_interval = 300;
417                 ret = slog_activate(slog_file,
418                                     server_data.sensors,
419                                     &mutex,
420                                     slog_interval);
421                 if (!ret)
422                         log_err(_("Failed to activate logging of sensors."));
423         }
424
425         while (!server_stop_requested) {
426                 pthread_mutex_lock(&mutex);
427
428 #ifdef HAVE_GTOP
429                 sysinfo_update(&server_data.psysinfo);
430                 cpu_usage_sensor_update(server_data.cpu_usage);
431 #endif
432                 psensor_list_update_measures(server_data.sensors);
433
434                 psensor_log_measures(server_data.sensors);
435
436                 pthread_mutex_unlock(&mutex);
437                 sleep(5);
438         }
439
440         slog_close();
441
442         MHD_stop_daemon(d);
443
444         /* sanity cleanup for valgrind */
445         psensor_list_free(server_data.sensors);
446 #ifdef HAVE_GTOP
447         psensor_free(server_data.cpu_usage);
448 #endif
449         free(server_data.www_dir);
450         sensors_cleanup();
451
452 #ifdef HAVE_GTOP
453         sysinfo_cleanup();
454         cpu_cleanup();
455 #endif
456
457         if (log_file != DEFAULT_LOG_FILE)
458                 free(log_file);
459
460         return EXIT_SUCCESS;
461 }