summaryrefslogtreecommitdiffhomepage
path: root/plugins/statistics/statistics.cpp
blob: 415369dd956dd5d5e3adb9e076aca32aef03075b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#include "statistics.h"

#include "libcommon/file.h"
#include "libcommon/tempfile.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/coroutine2/coroutine.hpp>
#include <boost/process.hpp>

#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>

using namespace std::string_literals;
namespace bp = boost::process;
namespace fs = std::filesystem;

namespace {

 // Used to return errors by generating response page and HTTP status code
 std::string HttpStatus(std::string status, std::string message, std::function<plugin_interface_setter_type>& SetResponseHeader)
 {
  SetResponseHeader("status", status);
  SetResponseHeader("content_type", "text/html");

  return status + " " + message;
 }

 std::string statsPng(std::function<std::string(const std::string& key)>& GetServerParam,
                      std::function<plugin_interface_setter_type>& SetResponseHeader)
 {
  // Create PNG statistics via Gnuplot
  std::string statistics{GetServerParam("statistics")};

  Tempfile tempStats{".txt"}; // input data
  File::setFile(tempStats.GetPath(), statistics);
  
  Tempfile tempPng{".png"}; // output
  
  Tempfile tempGnuplot{".gnuplot"};
  std::stringstream s;
  s << "set terminal png truecolor\n";
  s << "set output " << tempPng.GetPath() << "\n"; // quotes added automatically for paths
  s << "set title \"Webserver Throughput\"\n";
  s << "set xlabel \"Time\"\n";
  s << "set timefmt \"%s\"\n";
  s << "set format x \"%Y-%m-%d\"\n";
  s << "set xdata time\n";
  s << "set xtics rotate by 45 right\n";
  s << "set ylabel \"Bytes\"\n";
  s << "set datafile separator \",\"\n";
  s << "set grid\n";
  s << "set style fill solid\n";
  s << "plot " << tempStats.GetPath() << " using 1:($4+$5) with boxes title \"Bytes I/O\" lt rgb \"#1132A7\"\n";
  File::setFile(tempGnuplot.GetPath(), s.str());

  int exit_code{system(("gnuplot "s + tempGnuplot.GetPath().generic_string()).c_str())};
  if (exit_code) {
   std::cerr << "Error: gnuplot returned " << std::to_string(exit_code) << std::endl;
   return HttpStatus("500", "Statistics error"s, SetResponseHeader);
  }
  
  SetResponseHeader("content_type", "image/png");
  return File::getFile(tempPng.GetPath());
 }

 // returns sum over specified column
 uint64_t getSum(const std::string& stats, size_t column)
 {
  uint64_t result{0};

  std::istringstream is{stats};
  std::string line;

  while (std::getline(is, line) && !is.eof()) {

   std::vector<std::string> elements;
   boost::algorithm::split(elements, line, [](char c){ return c == ','; });

   if (column >= elements.size()) {
    std::cerr << "Error: No column " << column << " found." << std::endl;
    return 0;
   }

   try {
    result += stoull(elements[column]);
   } catch(...) {
    std::cerr << "Error: Stats value " << elements[column] << " malformed." << std::endl;
   }
  }

  return result;
 }

} // anonymous namespace

std::string statistics_plugin::name()
{
 return "statistics";
}

statistics_plugin::statistics_plugin()
{
 //std::cout << "Plugin constructor" << std::endl;
}

statistics_plugin::~statistics_plugin()
{
 //std::cout << "Plugin destructor" << std::endl;
}

std::string statistics_plugin::generate_page(
  std::function<std::string(const std::string& key)>& GetServerParam,
  std::function<std::string(const std::string& key)>& GetRequestParam, // request including body (POST...)
  std::function<void(const std::string& key, const std::string& value)>& SetResponseHeader // to be added to result string
)
{
 try {
  // Request path must not contain "..".
  std::string rel_target{GetRequestParam("rel_target")};
  size_t query_pos{rel_target.find("?")};
  if (query_pos != rel_target.npos)
   rel_target = rel_target.substr(0, query_pos);

  std::string target{GetRequestParam("target")};
  if (rel_target.find("..") != std::string::npos) {
   return HttpStatus("400", "Illegal request: "s + target, SetResponseHeader);
  }

  // Build the path to the requested file
  std::string doc_root{GetRequestParam("doc_root")};
  fs::path path {fs::path{doc_root} / rel_target};
  if (target.size() && target.back() != '/' && fs::is_directory(path)) {
   std::string location{GetRequestParam("location") + "/"s};
   SetResponseHeader("location", location);
   return HttpStatus("301", "Correcting directory path", SetResponseHeader); // 301 Moved Permanently
  }

  if (path.filename() == "stats.png")
   return statsPng(GetServerParam, SetResponseHeader);

  try {
   SetResponseHeader("content_type", "text/html");

   std::string header {"<!DOCTYPE html><html><head>"
             "<meta charset=\"utf-8\"/>"
             "<title>Webserver Statistics</title>"
             "</head><body>"};
   std::string footer{"<br/><br/><br/></body></html>"};

   std::string result{header};

   std::string statistics{GetServerParam("statistics")};
   double ipv6_fraction_by_requests {double(getSum(statistics, 5)) / getSum(statistics, 1)};
   double ipv6_fraction_by_bytes {double(getSum(statistics, 7) + getSum(statistics, 8)) / (getSum(statistics, 3) + getSum(statistics, 4))};
   double https_fraction_by_requests {double(getSum(statistics, 9)) / getSum(statistics, 1)};
   double https_fraction_by_bytes {double(getSum(statistics, 11) + getSum(statistics, 12)) / (getSum(statistics, 3) + getSum(statistics, 4))};

   result += "<h1>Webserver Statistics</h1>";
   result += "<p>Host uptime: "s + GetServerParam("uptime_host") + "</p>";
   result += "<p>Webserver uptime: "s + GetServerParam("uptime_webserver") + "</p>";
   result += "<p>IPv6 fraction by requests: "s + std::to_string(ipv6_fraction_by_requests * 100) + "%</p>";
   result += "<p>IPv6 fraction by bytes: "s + std::to_string(ipv6_fraction_by_bytes * 100) + "%</p>";
   result += "<p>HTTPS fraction by requests: "s + std::to_string(https_fraction_by_requests * 100) + "%</p>";
   result += "<p>HTTPS fraction by bytes: "s + std::to_string(https_fraction_by_bytes * 100) + "%</p>";
   result += "<p><img src=\"stats.png\"/></p>";
   result += "<pre>"s + statistics + "</pre>"s;

   result += footer;
   
   return result;
  } catch (const std::exception& ex) {
   return HttpStatus("500", "Statistics error: "s + ex.what(), SetResponseHeader);
  }

 } catch (const std::exception& ex) {
  return HttpStatus("500", "Unknown Error: "s + ex.what(), SetResponseHeader);
 }
}

bool statistics_plugin::has_own_authentication()
{
 return false;
}