7 #include <sys/statvfs.h>
9 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || (__OpenBSD__) || defined(__DragonFly__)
10 #include <sys/param.h>
11 #include <sys/mount.h>
13 #include <yajl/yajl_gen.h>
14 #include <yajl/yajl_version.h>
18 #define TERABYTE (1024ULL * 1024 * 1024 * 1024)
19 #define GIGABYTE (1024ULL * 1024 * 1024)
20 #define MEGABYTE (1024ULL * 1024)
21 #define KILOBYTE (1024ULL)
24 * Prints the given amount of bytes in a human readable manner.
27 static int print_bytes_human(char *outwalk, uint64_t bytes) {
29 return sprintf(outwalk, "%.02f TB", (double)bytes / TERABYTE);
30 else if (bytes > GIGABYTE)
31 return sprintf(outwalk, "%.01f GB", (double)bytes / GIGABYTE);
32 else if (bytes > MEGABYTE)
33 return sprintf(outwalk, "%.01f MB", (double)bytes / MEGABYTE);
34 else if (bytes > KILOBYTE)
35 return sprintf(outwalk, "%.01f KB", (double)bytes / KILOBYTE);
37 return sprintf(outwalk, "%.01f B", (double)bytes);
42 * Does a statvfs and prints either free, used or total amounts of bytes in a
43 * human readable manner.
46 void print_disk_info(yajl_gen json_gen, char *buffer, const char *path, const char *format) {
48 char *outwalk = buffer;
52 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__DragonFly__)
55 if (statfs(path, &buf) == -1)
60 if (statvfs(path, &buf) == -1)
64 for (walk = format; *walk != '\0'; walk++) {
70 if (BEGINS_WITH(walk+1, "free")) {
71 outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * (uint64_t)buf.f_bfree);
72 walk += strlen("free");
75 if (BEGINS_WITH(walk+1, "used")) {
76 outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * ((uint64_t)buf.f_blocks - (uint64_t)buf.f_bfree));
77 walk += strlen("used");
80 if (BEGINS_WITH(walk+1, "total")) {
81 outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * (uint64_t)buf.f_blocks);
82 walk += strlen("total");
85 if (BEGINS_WITH(walk+1, "avail")) {
86 outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * (uint64_t)buf.f_bavail);
87 walk += strlen("avail");
90 if (BEGINS_WITH(walk+1, "percentage_free")) {
91 outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)buf.f_bfree / (double)buf.f_blocks);
92 walk += strlen("percentage_free");
95 if (BEGINS_WITH(walk+1, "percentage_used_of_avail")) {
96 outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)(buf.f_blocks - buf.f_bavail) / (double)buf.f_blocks);
97 walk += strlen("percentage_used_of_avail");
100 if (BEGINS_WITH(walk+1, "percentage_used")) {
101 outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)(buf.f_blocks - buf.f_bfree) / (double)buf.f_blocks);
102 walk += strlen("percentage_used");
105 if (BEGINS_WITH(walk+1, "percentage_avail")) {
106 outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)buf.f_bavail / (double)buf.f_blocks);
107 walk += strlen("percentage_avail");
112 OUTPUT_FULL_TEXT(buffer);