Updated connman to version 1.35
[platform/upstream/connman.git] / src / stats.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2010-2014  BMW Car IT GmbH.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #define _GNU_SOURCE
27 #include <errno.h>
28 #include <sys/mman.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/time.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <string.h>
35 #include <limits.h>
36 #include <sys/stat.h>
37
38 #include "connman.h"
39
40 #define MODE            (S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | \
41                         S_IXGRP | S_IROTH | S_IXOTH)
42
43 #ifdef TEMP_FAILURE_RETRY
44 #define TFR TEMP_FAILURE_RETRY
45 #else
46 #define TFR
47 #endif
48
49 #define MAGIC 0xFA00B916
50
51 /*
52  * Statistics counters are stored into a ring buffer which is stored
53  * into a file
54  *
55  * File properties:
56  *   The ring buffer is mmap to a file
57  *   Initialy only the smallest possible amount of disk space is allocated
58  *   The files grow to the configured maximal size
59  *   The grows by _SC_PAGESIZE step size
60  *   For each service a file is created
61  *   Each file has a header where the indexes are stored
62  *
63  * Entries properties:
64  *   Each entry has a timestamp
65  *   A flag to mark if the entry is either home (0) or roaming (1) entry
66  *   The entries are fixed sized (stats_record)
67  *
68  * Ring buffer properties:
69  *   There are to indexes 'begin', 'end', 'home' and 'roaming'
70  *   'begin' points to the oldest entry
71  *   'end' points to the newest/current entry
72  *   'home' points to the current home entry
73  *   'roaming' points to the current roaming entry
74  *   If 'begin' == 'end' then the buffer is empty
75  *   If 'end' + 1 == 'begin then it's full
76  *   The ring buffer is valid in the range (begin, end]
77  *   If 'home' has the value UINT_MAX', 'home' is invalid
78  *   if 'roaming' has the value UINT_MAX', 'roaming' is invalid
79  *   'first' points to the first entry in the ring buffer
80  *   'last' points to the last entry in the ring buffer
81  *
82  * History file:
83  *   Same format as the ring buffer file
84  *   For a period of at least 2 months dayly records are keept
85  *   If older, then only a monthly record is keept
86  */
87
88
89 struct stats_file_header {
90         unsigned int magic;
91         unsigned int begin;
92         unsigned int end;
93         unsigned int home;
94         unsigned int roaming;
95 };
96
97 struct stats_record {
98         time_t ts;
99         unsigned int roaming;
100         struct connman_stats_data data;
101 };
102
103 struct stats_file {
104         int fd;
105         char *name;
106         char *addr;
107         size_t len;
108         size_t max_len;
109
110         /* cached values */
111         struct stats_record *first;
112         struct stats_record *last;
113         struct stats_record *home;
114         struct stats_record *roaming;
115
116         /* history */
117         char *history_name;
118         int account_period_offset;
119 };
120
121 struct stats_iter {
122         struct stats_file *file;
123         struct stats_record *begin;
124         struct stats_record *end;
125         struct stats_record *it;
126 };
127
128 static GHashTable *stats_hash = NULL;
129
130 static struct stats_file_header *get_hdr(struct stats_file *file)
131 {
132         return (struct stats_file_header *)file->addr;
133 }
134
135 static struct stats_record *get_begin(struct stats_file *file)
136 {
137         unsigned int off = get_hdr(file)->begin;
138
139         return (struct stats_record *)(file->addr + off);
140 }
141
142 static struct stats_record *get_end(struct stats_file *file)
143 {
144         unsigned int off = get_hdr(file)->end;
145
146         return (struct stats_record *)(file->addr + off);
147 }
148
149 static struct stats_record *get_home(struct stats_file *file)
150 {
151         struct stats_file_header *hdr;
152
153         hdr = get_hdr(file);
154
155         if (hdr->home == UINT_MAX)
156                 return NULL;
157
158         return (struct stats_record *)(file->addr + hdr->home);
159 }
160
161 static struct stats_record *get_roaming(struct stats_file *file)
162 {
163         struct stats_file_header *hdr;
164
165         hdr = get_hdr(file);
166
167         if (hdr->roaming == UINT_MAX)
168                 return NULL;
169
170         return (struct stats_record *)(file->addr + hdr->roaming);
171 }
172
173 static void set_end(struct stats_file *file, struct stats_record *end)
174 {
175         struct stats_file_header *hdr;
176
177         hdr = get_hdr(file);
178         hdr->end = (char *)end - file->addr;
179 }
180
181 static void set_home(struct stats_file *file, struct stats_record *home)
182 {
183         struct stats_file_header *hdr;
184
185         hdr = get_hdr(file);
186         hdr->home = (char *)home - file->addr;
187 }
188
189 static void set_roaming(struct stats_file *file, struct stats_record *roaming)
190 {
191         struct stats_file_header *hdr;
192
193         hdr = get_hdr(file);
194         hdr->roaming = (char *)roaming - file->addr;
195 }
196
197 static struct stats_record *get_next(struct stats_file *file,
198                                         struct stats_record *cur)
199 {
200         cur++;
201
202         if (cur > file->last)
203                 cur = file->first;
204
205         return cur;
206 }
207
208 static struct stats_record *get_iterator_begin(struct stats_file *file)
209 {
210         return get_next(file, get_begin(file));
211 }
212
213 static struct stats_record *get_iterator_end(struct stats_file *file)
214 {
215         return get_next(file, get_end(file));
216 }
217
218 static void stats_free(gpointer user_data)
219 {
220         struct stats_file *file = user_data;
221
222         if (!file)
223                 return;
224
225         msync(file->addr, file->len, MS_SYNC);
226
227         munmap(file->addr, file->len);
228         file->addr = NULL;
229
230         close(file->fd);
231         file->fd = -1;
232
233         g_free(file->history_name);
234         file->history_name = NULL;
235
236         g_free(file->name);
237         file->name = NULL;
238
239         g_free(file);
240 }
241
242 static void update_first(struct stats_file *file)
243 {
244         file->first = (struct stats_record *)
245                         (file->addr + sizeof(struct stats_file_header));
246 }
247
248 static void update_last(struct stats_file *file)
249 {
250         unsigned int max_entries;
251
252         max_entries = (file->len - sizeof(struct stats_file_header)) /
253                         sizeof(struct stats_record);
254         file->last = file->first + max_entries - 1;
255 }
256
257 static void update_home(struct stats_file *file)
258 {
259         file->home = get_home(file);
260 }
261
262 static void update_roaming(struct stats_file *file)
263 {
264         file->roaming = get_roaming(file);
265 }
266
267 static void stats_file_update_cache(struct stats_file *file)
268 {
269         update_first(file);
270         update_last(file);
271         update_home(file);
272         update_roaming(file);
273 }
274
275 static int stats_file_remap(struct stats_file *file, size_t size)
276 {
277         size_t page_size, new_size;
278         void *addr;
279         int err;
280
281         DBG("file %p size %zu addr %p len %zu", file, size, file->addr,
282                 file->len);
283
284         page_size = sysconf(_SC_PAGESIZE);
285         new_size = (size + page_size - 1) & ~(page_size - 1);
286
287         err = ftruncate(file->fd, new_size);
288         if (err < 0) {
289                 connman_error("ftrunctate error %s for %s",
290                                 strerror(errno), file->name);
291                 return -errno;
292         }
293
294         if (!file->addr) {
295                 /*
296                  * Though the buffer is not shared between processes, we still
297                  * have to take MAP_SHARED because MAP_PRIVATE does not
298                  * guarantee that writes will hit the file without an explicit
299                  * call to munmap or msync. For more details please read the
300                  * mmap man pages.
301                  */
302                 addr = mmap(NULL, new_size, PROT_READ | PROT_WRITE,
303                                 MAP_SHARED, file->fd, 0);
304         } else {
305                 addr = mremap(file->addr, file->len, new_size, MREMAP_MAYMOVE);
306         }
307
308         if (addr == MAP_FAILED) {
309                 connman_error("mmap error %s for %s",
310                                 strerror(errno), file->name);
311                 if (errno == EINVAL) {
312                         connman_error("%s might be on a file system, such as "
313                                         "JFFS2, that does not allow shared "
314                                         "writable mappings.", file->name);
315                 }
316                 return -errno;
317         }
318
319         file->addr = addr;
320         file->len = new_size;
321
322         stats_file_update_cache(file);
323
324         return 0;
325 }
326
327 static int stats_open(struct stats_file *file,
328                         const char *name)
329 {
330         DBG("file %p name %s", file, name);
331
332         file->name = g_strdup(name);
333
334         file->fd = TFR(open(file->name, O_RDWR | O_CREAT | O_CLOEXEC, 0644));
335         if (file->fd < 0) {
336                 connman_error("open error %s for %s",
337                                 strerror(errno), file->name);
338                 g_free(file->name);
339                 file->name = NULL;
340                 return -errno;
341         }
342
343         return 0;
344 }
345
346 static int stats_open_temp(struct stats_file *file)
347 {
348         file->name = g_strdup_printf("%s/stats.XXXXXX.tmp",
349                                         STORAGEDIR);
350         file->fd = g_mkstemp_full(file->name, O_RDWR | O_CREAT, 0644);
351         if (file->fd < 0) {
352                 connman_error("create tempory file error %s for %s",
353                                 strerror(errno), file->name);
354                 g_free(file->name);
355                 file->name = NULL;
356                 return -errno;
357         }
358
359         return 0;
360 }
361
362 static int stats_file_setup(struct stats_file *file)
363 {
364         struct stats_file_header *hdr;
365         struct stat st;
366         size_t size = 0;
367         int err;
368
369         DBG("file %p fd %d name %s", file, file->fd, file->name);
370
371         err = fstat(file->fd, &st);
372         if (err < 0) {
373                 connman_error("fstat error %s for %s\n",
374                         strerror(errno), file->name);
375
376                 close(file->fd);
377                 file->fd = -1;
378                 g_free(file->name);
379                 file->name = NULL;
380
381                 return -errno;
382         }
383
384         size = (size_t)st.st_size;
385         file->max_len = STATS_MAX_FILE_SIZE;
386
387         if (size < (size_t)sysconf(_SC_PAGESIZE))
388                 size = sysconf(_SC_PAGESIZE);
389
390         err = stats_file_remap(file, size);
391         if (err < 0) {
392                 close(file->fd);
393                 file->fd = -1;
394                 g_free(file->name);
395                 file->name = NULL;
396
397                 return err;
398         }
399
400         hdr = get_hdr(file);
401
402         if (hdr->magic != MAGIC ||
403                         hdr->begin < sizeof(struct stats_file_header) ||
404                         hdr->end < sizeof(struct stats_file_header) ||
405                         hdr->home < sizeof(struct stats_file_header) ||
406                         hdr->roaming < sizeof(struct stats_file_header) ||
407                         hdr->begin > file->len ||
408                         hdr->end > file->len) {
409                 hdr->magic = MAGIC;
410                 hdr->begin = sizeof(struct stats_file_header);
411                 hdr->end = sizeof(struct stats_file_header);
412                 hdr->home = UINT_MAX;
413                 hdr->roaming = UINT_MAX;
414
415                 stats_file_update_cache(file);
416         }
417
418         return 0;
419 }
420
421
422 static struct stats_record *get_next_record(struct stats_iter *iter)
423 {
424         if (iter->it != iter->end) {
425                 struct stats_record *tmp;
426
427                 tmp = iter->it;
428                 iter->it = get_next(iter->file, iter->it);
429
430                 return tmp;
431         }
432
433         return NULL;
434 }
435
436 static int append_record(struct stats_file *file,
437                                 struct stats_record *rec)
438 {
439         struct stats_record *cur, *next;
440         int err;
441
442         if (file->last == get_end(file)) {
443                 err = stats_file_remap(file, file->len +
444                                         sysconf(_SC_PAGESIZE));
445                 if (err < 0)
446                         return err;
447
448                 stats_file_update_cache(file);
449         }
450
451         cur = get_end(file);
452         next = get_next(file, cur);
453
454         memcpy(next, rec, sizeof(struct stats_record));
455
456         set_end(file, next);
457
458         return 0;
459 }
460
461 static struct stats_record *process_file(struct stats_iter *iter,
462                                         struct stats_file *temp_file,
463                                         struct stats_record *cur,
464                                         GDate *date_change_step_size,
465                                         int account_period_offset)
466 {
467         struct stats_record *home, *roaming;
468         struct stats_record *next;
469
470         home = NULL;
471         roaming = NULL;
472
473         if (!cur)
474                 cur = get_next_record(iter);
475         next = get_next_record(iter);
476
477         while (next) {
478                 GDate date_cur;
479                 GDate date_next;
480                 bool append;
481
482                 append = false;
483
484                 if (cur->roaming)
485                         roaming = cur;
486                 else
487                         home = cur;
488
489                 g_date_set_time_t(&date_cur, cur->ts);
490                 g_date_set_time_t(&date_next, next->ts);
491
492                 if (g_date_compare(&date_cur, date_change_step_size) < 0) {
493                         /* month period size */
494                         GDateDay day_cur, day_next;
495                         GDateMonth month_cur, month_next;
496
497                         month_cur = g_date_get_month(&date_cur);
498                         month_next = g_date_get_month(&date_next);
499
500                         day_cur = g_date_get_day(&date_cur);
501                         day_next = g_date_get_day(&date_next);
502
503                         if (day_cur == day_next && month_cur != month_next) {
504                                 append = true;
505                         } else if (day_cur < account_period_offset &&
506                                         day_next >= account_period_offset) {
507                                 append = true;
508                         }
509                 } else {
510                         /* day period size */
511                         if (g_date_days_between(&date_cur, &date_next) > 0)
512                                 append = true;
513                 }
514
515                 if (append) {
516                         if (home) {
517                                 append_record(temp_file, home);
518                                 home = NULL;
519                         }
520
521                         if (roaming) {
522                                 append_record(temp_file, roaming);
523                                 roaming = NULL;
524                         }
525                 }
526
527                 cur = next;
528                 next = get_next_record(iter);
529         }
530
531         return cur;
532 }
533
534 static int summarize(struct stats_file *data_file,
535                         struct stats_file *history_file,
536                         struct stats_file *temp_file)
537 {
538         struct stats_iter data_iter;
539         struct stats_iter history_iter;
540         struct stats_record *cur, *next;
541
542         GDate today, date_change_step_size;
543
544         /*
545          * First calculate the date when switch from monthly
546          * accounting period size to daily size
547          */
548         g_date_set_time_t(&today, time(NULL));
549
550         date_change_step_size = today;
551         if (g_date_get_day(&today) - data_file->account_period_offset >= 0)
552                 g_date_subtract_months(&date_change_step_size, 2);
553         else
554                 g_date_subtract_months(&date_change_step_size, 3);
555
556         g_date_set_day(&date_change_step_size,
557                         data_file->account_period_offset);
558
559
560         /* Now process history file */
561         cur = NULL;
562
563         if (history_file) {
564                 history_iter.file = history_file;
565                 history_iter.begin = get_iterator_begin(history_iter.file);
566                 history_iter.end = get_iterator_end(history_iter.file);
567                 history_iter.it = history_iter.begin;
568
569                 cur = process_file(&history_iter, temp_file, NULL,
570                                         &date_change_step_size,
571                                         data_file->account_period_offset);
572         }
573
574         data_iter.file = data_file;
575         data_iter.begin = get_iterator_begin(data_iter.file);
576         data_iter.end = get_iterator_end(data_iter.file);
577         data_iter.it = data_iter.begin;
578
579         /*
580          * Ensure date_file records are newer than the history_file
581          * record
582          */
583         if (cur) {
584                 next = get_next_record(&data_iter);
585                 while (next && cur->ts > next->ts)
586                         next = get_next_record(&data_iter);
587         }
588
589         /* And finally process the new data records */
590         cur = process_file(&data_iter, temp_file, cur,
591                                 &date_change_step_size,
592                                 data_file->account_period_offset);
593
594         if (cur)
595                 append_record(temp_file, cur);
596
597         return 0;
598 }
599
600 static void stats_file_unmap(struct stats_file *file)
601 {
602         msync(file->addr, file->len, MS_SYNC);
603         munmap(file->addr, file->len);
604         file->addr = NULL;
605 }
606
607 static void stats_file_cleanup(struct stats_file *file)
608 {
609         file->fd = -1;
610         g_free(file->name);
611         file->name = NULL;
612 }
613
614 static int stats_file_close_swap(struct stats_file *history_file,
615                                         struct stats_file *temp_file)
616 {
617         int err;
618
619         stats_file_unmap(history_file);
620         stats_file_unmap(temp_file);
621
622         close(temp_file->fd);
623
624         unlink(history_file->name);
625
626         err = link(temp_file->name, history_file->name);
627
628         unlink(temp_file->name);
629
630         close(history_file->fd);
631
632         stats_file_cleanup(history_file);
633         stats_file_cleanup(temp_file);
634
635         return err;
636 }
637
638 static int stats_file_history_update(struct stats_file *data_file)
639 {
640         struct stats_file _history_file, *history_file;
641         struct stats_file _temp_file, *temp_file;
642         int err;
643
644         history_file = &_history_file;
645         temp_file = &_temp_file;
646
647         bzero(history_file, sizeof(struct stats_file));
648         bzero(temp_file, sizeof(struct stats_file));
649
650         history_file->fd = -1;
651         temp_file->fd = -1;
652
653         err = stats_open(history_file, data_file->history_name);
654         if (err < 0)
655                 return err;
656         stats_file_setup(history_file);
657
658         err = stats_open_temp(temp_file);
659         if (err < 0) {
660                 stats_free(history_file);
661                 return err;
662         }
663         stats_file_setup(temp_file);
664
665         summarize(data_file, history_file, temp_file);
666
667         err = stats_file_close_swap(history_file, temp_file);
668
669         return err;
670 }
671
672 int __connman_stats_service_register(struct connman_service *service)
673 {
674         struct stats_file *file;
675         char *name, *dir;
676         int err;
677
678         DBG("service %p", service);
679
680         dir = g_strdup_printf("%s/%s", STORAGEDIR,
681                                 __connman_service_get_ident(service));
682
683         /* If the dir doesn't exist, create it */
684         if (!g_file_test(dir, G_FILE_TEST_IS_DIR)) {
685                 if (mkdir(dir, MODE) < 0) {
686                         if (errno != EEXIST) {
687                                 g_free(dir);
688
689                                 err = -errno;
690                                 goto err;
691                         }
692                 }
693         }
694
695         g_free(dir);
696         file = g_hash_table_lookup(stats_hash, service);
697         if (!file) {
698                 file = g_try_new0(struct stats_file, 1);
699                 if (!file)
700                         return -ENOMEM;
701
702                 file->fd = -1;
703
704                 g_hash_table_insert(stats_hash, service, file);
705         } else {
706                 return -EALREADY;
707         }
708
709         name = g_strdup_printf("%s/%s/data", STORAGEDIR,
710                                 __connman_service_get_ident(service));
711         file->history_name = g_strdup_printf("%s/%s/history", STORAGEDIR,
712                                 __connman_service_get_ident(service));
713
714         /* TODO: Use a global config file instead of hard coded value. */
715         file->account_period_offset = 1;
716
717         err = stats_open(file, name);
718         g_free(name);
719         if (err < 0)
720                 goto err;
721
722         err = stats_file_setup(file);
723         if (err < 0)
724                 goto err;
725
726         return 0;
727
728 err:
729         g_hash_table_remove(stats_hash, service);
730
731         return err;
732 }
733
734 void __connman_stats_service_unregister(struct connman_service *service)
735 {
736         DBG("service %p", service);
737
738         g_hash_table_remove(stats_hash, service);
739 }
740
741 int  __connman_stats_update(struct connman_service *service,
742                                 bool roaming,
743                                 struct connman_stats_data *data)
744 {
745         struct stats_file *file;
746         struct stats_record *next;
747         int err;
748
749         file = g_hash_table_lookup(stats_hash, service);
750         if (!file)
751                 return -EEXIST;
752
753         if (file->len < file->max_len &&
754                         file->last == get_end(file)) {
755                 DBG("grow file %s", file->name);
756
757                 err = stats_file_remap(file, file->len + sysconf(_SC_PAGESIZE));
758                 if (err < 0)
759                         return err;
760         }
761
762         next = get_next(file, get_end(file));
763
764         if (next == get_begin(file)) {
765                 DBG("ring buffer is full, update history file");
766
767                 if (stats_file_history_update(file) < 0) {
768                         connman_warn("history file update failed %s",
769                                         file->history_name);
770                 }
771         }
772
773         next->ts = time(NULL);
774         next->roaming = roaming;
775         memcpy(&next->data, data, sizeof(struct connman_stats_data));
776
777         if (!roaming)
778                 set_home(file, next);
779         else
780                 set_roaming(file, next);
781
782         set_end(file, next);
783
784         return 0;
785 }
786
787 int __connman_stats_get(struct connman_service *service,
788                                 bool roaming,
789                                 struct connman_stats_data *data)
790 {
791         struct stats_file *file;
792         struct stats_record *rec;
793
794         file = g_hash_table_lookup(stats_hash, service);
795         if (!file)
796                 return -EEXIST;
797
798         if (!roaming)
799                 rec = file->home;
800         else
801                 rec = file->roaming;
802
803         if (rec) {
804                 memcpy(data, &rec->data,
805                         sizeof(struct connman_stats_data));
806         }
807
808         return 0;
809 }
810
811 int __connman_stats_init(void)
812 {
813         DBG("");
814
815         stats_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal,
816                                                         NULL, stats_free);
817
818         return 0;
819 }
820
821 void __connman_stats_cleanup(void)
822 {
823         DBG("");
824
825         g_hash_table_destroy(stats_hash);
826         stats_hash = NULL;
827 }