adding logging of sensors
[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 #define 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, 's'},
70         {0, 0, 0, 0}
71 };
72
73 static struct server_data server_data;
74
75 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
76
77 static int server_stop_requested;
78
79 void print_version()
80 {
81         printf("psensor-server %s\n", VERSION);
82         printf(_("Copyright (C) %s jeanfi@gmail.com\n"
83                  "License GPLv2: GNU GPL version 2 or later "
84                  "<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n"
85                  "This is free software: you are free to change and redistribute it.\n"
86                  "There is NO WARRANTY, to the extent permitted by law.\n"),
87                "2010-2012");
88 }
89
90 void print_help()
91 {
92         printf(_("Usage: %s [OPTION]...\n"), program_name);
93
94         puts(_("psensor-server is an HTTP server for monitoring hardware "
95                "sensors remotely."));
96
97         puts("");
98         puts("Options:");
99         puts(_("  -h, --help            display this help and exit\n"
100                "  -v, --version         display version information and exit"));
101
102         puts("");
103         puts(_("  -p,--port=PORT        webserver port\n"
104                "  -w,--wdir=DIR         directory containing webserver pages"));
105
106         puts("");
107         puts(_("  -d, --debug=LEVEL     "
108                "set the debug level, integer between 0 and 3"));
109         puts(_("  -l, --log-file=PATH   set the log file to PATH"));
110         puts(_("  -s, --sensor-log-file=PATH set the sensor log file to PATH"));
111
112         puts("");
113         printf(_("Report bugs to: %s\n"), PACKAGE_BUGREPORT);
114         puts("");
115         printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
116 }
117
118 /*
119   Returns the file path corresponding to a given URL
120 */
121 char *get_path(const char *url, const char *www_dir)
122 {
123         const char *p;
124         char *res;
125
126         if (!strlen(url) || !strcmp(url, ".") || !strcmp(url, "/"))
127                 p = "/index.html";
128         else
129                 p = url;
130
131         res = malloc(strlen(www_dir)+strlen(p)+1);
132
133         strcpy(res, www_dir);
134         strcat(res, p);
135
136         return res;
137 }
138
139 #if MHD_VERSION >= 0x00090200
140 static ssize_t
141 file_reader(void *cls, uint64_t pos, char *buf, size_t max)
142 #else
143 static int
144 file_reader(void *cls, uint64_t pos, char *buf, int max)
145 #endif
146 {
147         FILE *file = cls;
148
149         fseek(file, pos, SEEK_SET);
150         return fread(buf, 1, max, file);
151 }
152
153 struct MHD_Response *
154 create_response_api(const char *nurl,
155                     const char *method,
156                     unsigned int *rp_code)
157 {
158         struct MHD_Response *resp;
159         struct psensor *s;
160         char *page = NULL;
161
162         if (!strcmp(nurl, URL_BASE_API_1_0_SENSORS))  {
163                 page = sensors_to_json_string(server_data.sensors);
164 #ifdef HAVE_GTOP
165         } else if (!strcmp(nurl, URL_API_1_0_SYSINFO)) {
166                 page = sysinfo_to_json_string(&server_data.psysinfo);
167         } else if (!strcmp(nurl, URL_API_1_0_CPU_USAGE)) {
168                 page = sensor_to_json_string(server_data.cpu_usage);
169 #endif
170         } else if (!strncmp(nurl, URL_BASE_API_1_0_SENSORS,
171                             strlen(URL_BASE_API_1_0_SENSORS))
172                    && nurl[strlen(URL_BASE_API_1_0_SENSORS)] == '/') {
173
174                 const char *sid = nurl + strlen(URL_BASE_API_1_0_SENSORS) + 1;
175
176                 s = psensor_list_get_by_id(server_data.sensors, sid);
177
178                 if (s)
179                         page = sensor_to_json_string(s);
180
181         } else if (!strcmp(nurl, URL_API_1_0_SERVER_STOP)) {
182
183                 server_stop_requested = 1;
184                 page = strdup(HTML_STOP_REQUESTED);
185         }
186
187         if (page) {
188                 *rp_code = MHD_HTTP_OK;
189
190                 resp = MHD_create_response_from_data(strlen(page), page,
191                                                      MHD_YES, MHD_NO);
192
193                 MHD_add_response_header(resp, MHD_HTTP_HEADER_CONTENT_TYPE,
194                                         "application/json");
195
196                 return resp;
197         }
198
199         return NULL;
200 }
201
202 struct MHD_Response *
203 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 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
268 cbk_http_request(void *cls,
269                  struct MHD_Connection *connection,
270                  const char *url,
271                  const char *method,
272                  const char *version,
273                  const char *upload_data,
274                  size_t *upload_data_size, void **ptr)
275 {
276         static int dummy;
277         struct MHD_Response *response;
278         int ret;
279         char *nurl;
280         unsigned int resp_code;
281
282         if (strcmp(method, "GET"))
283                 return MHD_NO;
284
285         if (&dummy != *ptr) {
286                 /* The first time only the headers are valid, do not
287                    respond in the first round... */
288                 *ptr = &dummy;
289                 return MHD_YES;
290         }
291
292         if (*upload_data_size)
293                 return MHD_NO;
294
295         *ptr = NULL;            /* clear context pointer */
296
297         log_debug(_("HTTP Request: %s"), url);
298
299         nurl = url_normalize(url);
300
301         pthread_mutex_lock(&mutex);
302         response = create_response(nurl, method, &resp_code);
303         pthread_mutex_unlock(&mutex);
304
305         ret = MHD_queue_response(connection, resp_code, response);
306         MHD_destroy_response(response);
307
308         free(nurl);
309
310         return ret;
311 }
312
313 int main(int argc, char *argv[])
314 {
315         struct MHD_Daemon *d;
316         int port = DEFAULT_PORT;
317         int optc;
318         int cmdok = 1;
319         char *log_file, *slog_file;
320
321         program_name = argv[0];
322
323         setlocale(LC_ALL, "");
324
325 #if ENABLE_NLS
326         bindtextdomain(PACKAGE, LOCALEDIR);
327         textdomain(PACKAGE);
328 #endif
329
330         server_data.www_dir = NULL;
331         server_data.psysinfo.interfaces = NULL;
332         log_file = NULL;
333         slog_file = NULL;
334
335         while ((optc = getopt_long(argc, argv,
336                                    "vhp:w:d:l:s:", long_options, NULL)) != -1) {
337                 switch (optc) {
338                 case 'w':
339                         if (optarg)
340                                 server_data.www_dir = strdup(optarg);
341                         break;
342                 case 'p':
343                         if (optarg)
344                                 port = atoi(optarg);
345                         break;
346                 case 'h':
347                         print_help();
348                         exit(EXIT_SUCCESS);
349                 case 'v':
350                         print_version();
351                         exit(EXIT_SUCCESS);
352                 case 'd':
353                         log_level = atoi(optarg);
354                         log_info(_("Enables debug mode: %d"), log_level);
355                         break;
356                 case 'l':
357                         if (optarg)
358                                 log_file = strdup(optarg);
359                         break;
360                 case 's':
361                         if (optarg)
362                                 slog_file = strdup(optarg);
363                         break;
364                 default:
365                         cmdok = 0;
366                         break;
367                 }
368         }
369
370         if (!server_data.www_dir)
371                 server_data.www_dir = strdup(DEFAULT_WWW_DIR);
372
373         if (!log_file)
374                 log_file = strdup(DEFAULT_LOG_FILE);
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         log_open(log_file);
383
384         psensor_init();
385
386         server_data.sensors = get_all_sensors(0, 600);
387
388 #ifdef HAVE_GTOP
389         server_data.cpu_usage = create_cpu_usage_sensor(600);
390 #endif
391
392         if (!*server_data.sensors)
393                 log_err(_("No sensors detected."));
394
395         d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION,
396                              port,
397                              NULL, NULL, &cbk_http_request, server_data.sensors,
398                              MHD_OPTION_END);
399         if (!d) {
400                 log_err(_("Failed to create Web server."));
401                 exit(EXIT_FAILURE);
402         }
403
404         log_info(_("Web server started on port: %d"), port);
405         log_info(_("WWW directory: %s"), server_data.www_dir);
406         log_info(_("URL: http://localhost:%d"), port);
407
408         if (slog_file)
409                 slog_init(slog_file, server_data.sensors);
410
411         while (!server_stop_requested) {
412                 pthread_mutex_lock(&mutex);
413
414 #ifdef HAVE_GTOP
415                 sysinfo_update(&server_data.psysinfo);
416                 cpu_usage_sensor_update(server_data.cpu_usage);
417 #endif
418                 psensor_list_update_measures(server_data.sensors);
419
420                 psensor_log_measures(server_data.sensors);
421
422                 slog_write_sensors(server_data.sensors);
423
424                 pthread_mutex_unlock(&mutex);
425                 sleep(5);
426         }
427
428         slog_close();
429
430         MHD_stop_daemon(d);
431
432         /* sanity cleanup for valgrind */
433         psensor_list_free(server_data.sensors);
434 #ifdef HAVE_GTOP
435         psensor_free(server_data.cpu_usage);
436 #endif
437         free(server_data.www_dir);
438         sensors_cleanup();
439
440 #ifdef HAVE_GTOP
441         sysinfo_cleanup();
442         cpu_cleanup();
443 #endif
444
445         if (log_file != DEFAULT_LOG_FILE)
446                 free(log_file);
447
448         return EXIT_SUCCESS;
449 }