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