blob: 42bf77d5813a0eb5bcfe76c3d228e959743cf8a8 [file] [log] [blame]
Vijay Khemkae2795302020-07-15 17:28:45 -07001#include "config.h"
2
3#include "healthMonitor.hpp"
4
5#include <phosphor-logging/log.hpp>
6#include <sdeventplus/event.hpp>
7
8#include <fstream>
9#include <iostream>
Vijay Khemka15537762020-07-22 11:44:56 -070010#include <numeric>
11#include <sstream>
12
13extern "C"
14{
15#include <sys/sysinfo.h>
16}
Vijay Khemkae2795302020-07-15 17:28:45 -070017
18static constexpr bool DEBUG = false;
19
20namespace phosphor
21{
22namespace health
23{
24
25using namespace phosphor::logging;
26
Vijay Khemka15537762020-07-22 11:44:56 -070027enum CPUStatesTime
28{
29 USER_IDX = 0,
30 NICE_IDX,
31 SYSTEM_IDX,
32 IDLE_IDX,
33 IOWAIT_IDX,
34 IRQ_IDX,
35 SOFTIRQ_IDX,
36 STEAL_IDX,
37 GUEST_USER_IDX,
38 GUEST_NICE_IDX,
39 NUM_CPU_STATES_TIME
40};
41
42double readCPUUtilization()
43{
44 std::ifstream fileStat("/proc/stat");
45 if (!fileStat.is_open())
46 {
47 log<level::ERR>("cpu file not available",
48 entry("FILENAME = /proc/stat"));
49 return -1;
50 }
51
52 std::string firstLine, labelName;
53 std::size_t timeData[NUM_CPU_STATES_TIME];
54
55 std::getline(fileStat, firstLine);
56 std::stringstream ss(firstLine);
57 ss >> labelName;
58
59 if (DEBUG)
60 std::cout << "CPU stats first Line is " << firstLine << "\n";
61
62 if (labelName.compare("cpu"))
63 {
64 log<level::ERR>("CPU data not available");
65 return -1;
66 }
67
68 int i;
69 for (i = 0; i < NUM_CPU_STATES_TIME; i++)
70 {
71 if (!(ss >> timeData[i]))
72 break;
73 }
74
75 if (i != NUM_CPU_STATES_TIME)
76 {
77 log<level::ERR>("CPU data not correct");
78 return -1;
79 }
80
81 static double preActiveTime = 0, preIdleTime = 0;
82 double activeTime, activeTimeDiff, idleTime, idleTimeDiff, totalTime,
83 activePercValue;
84
85 idleTime = timeData[IDLE_IDX] + timeData[IOWAIT_IDX];
86 activeTime = timeData[USER_IDX] + timeData[NICE_IDX] +
87 timeData[SYSTEM_IDX] + timeData[IRQ_IDX] +
88 timeData[SOFTIRQ_IDX] + timeData[STEAL_IDX] +
89 timeData[GUEST_USER_IDX] + timeData[GUEST_NICE_IDX];
90
91 idleTimeDiff = idleTime - preIdleTime;
92 activeTimeDiff = activeTime - preActiveTime;
93
94 /* Store current idle and active time for next calculation */
95 preIdleTime = idleTime;
96 preActiveTime = activeTime;
97
98 totalTime = idleTimeDiff + activeTimeDiff;
99
100 activePercValue = activeTimeDiff / totalTime * 100;
101
102 if (DEBUG)
103 std::cout << "CPU Utilization is " << activePercValue << "\n";
104
105 return activePercValue;
106}
107
108double readMemoryUtilization()
109{
110 struct sysinfo s_info;
111
112 sysinfo(&s_info);
113 double usedRam = s_info.totalram - s_info.freeram;
114 double memUsePerc = usedRam / s_info.totalram * 100;
115
116 if (DEBUG)
117 {
118 std::cout << "Memory Utilization is " << memUsePerc << "\n";
119
120 std::cout << "TotalRam: " << s_info.totalram
121 << " FreeRam: " << s_info.freeram << "\n";
122 std::cout << "UseRam: " << usedRam << "\n";
123 }
124
125 return memUsePerc;
126}
127
128/** Map of read function for each health sensors supported */
129std::map<std::string, std::function<double()>> readSensors = {
130 {"CPU", readCPUUtilization}, {"Memory", readMemoryUtilization}};
131
132void HealthSensor::setSensorThreshold(double criticalHigh, double warningHigh)
Vijay Khemkae2795302020-07-15 17:28:45 -0700133{
134 CriticalInterface::criticalHigh(criticalHigh);
135 WarningInterface::warningHigh(warningHigh);
136}
137
Vijay Khemka15537762020-07-22 11:44:56 -0700138void HealthSensor::setSensorValueToDbus(const double value)
Vijay Khemkae2795302020-07-15 17:28:45 -0700139{
140 ValueIface::value(value);
141}
142
Vijay Khemka15537762020-07-22 11:44:56 -0700143void HealthSensor::initHealthSensor()
144{
145 std::string logMsg = sensorConfig.name + " Health Sensor initialized";
146 log<level::INFO>(logMsg.c_str());
147
148 /* Look for sensor read functions */
149 if (readSensors.find(sensorConfig.name) == readSensors.end())
150 {
151 log<level::ERR>("Sensor read function not available");
152 return;
153 }
154
155 /* Read Sensor values */
156 auto value = readSensors[sensorConfig.name]();
157
158 if (value < 0)
159 {
160 log<level::ERR>("Reading Sensor Utilization failed",
161 entry("NAME = %s", sensorConfig.name.c_str()));
162 return;
163 }
164
165 /* Initialize value queue with initail sensor reading */
166 for (int i = 0; i < sensorConfig.windowSize; i++)
167 {
168 valQueue.push_back(value);
169 }
170 setSensorValueToDbus(value);
Vijay Khemkab38fd582020-07-23 13:21:23 -0700171
172 /* Start the timer for reading sensor data at regular interval */
173 readTimer.restart(std::chrono::milliseconds(sensorConfig.freq * 1000));
174}
175
176void HealthSensor::readHealthSensor()
177{
178 /* Read current sensor value */
179 double value = readSensors[sensorConfig.name]();
180 if (value < 0)
181 {
182 log<level::ERR>("Reading Sensor Utilization failed",
183 entry("NAME = %s", sensorConfig.name.c_str()));
184 return;
185 }
186
187 /* Remove first item from the queue */
188 valQueue.pop_front();
189 /* Add new item at the back */
190 valQueue.push_back(value);
191
192 /* Calculate average values for the given window size */
193 double avgValue = 0;
194 avgValue = accumulate(valQueue.begin(), valQueue.end(), avgValue);
195 avgValue = avgValue / sensorConfig.windowSize;
196
197 /* Set this new value to dbus */
198 setSensorValueToDbus(avgValue);
Vijay Khemka15537762020-07-22 11:44:56 -0700199}
200
201void printConfig(HealthConfig& cfg)
202{
203 std::cout << "Name: " << cfg.name << "\n";
204 std::cout << "Freq: " << (int)cfg.freq << "\n";
205 std::cout << "Window Size: " << (int)cfg.windowSize << "\n";
206 std::cout << "Critical value: " << (int)cfg.criticalHigh << "\n";
207 std::cout << "warning value: " << (int)cfg.warningHigh << "\n";
208 std::cout << "Critical log: " << (int)cfg.criticalLog << "\n";
209 std::cout << "Warning log: " << (int)cfg.warningLog << "\n";
210 std::cout << "Critical Target: " << cfg.criticalTgt << "\n";
211 std::cout << "Warning Target: " << cfg.warningTgt << "\n\n";
212}
213
Vijay Khemkae2795302020-07-15 17:28:45 -0700214/* Create dbus utilization sensor object for each configured sensors */
215void HealthMon::createHealthSensors()
216{
217 for (auto& cfg : sensorConfigs)
218 {
219 std::string objPath = std::string(HEALTH_SENSOR_PATH) + cfg.name;
220 auto healthSensor =
Vijay Khemka15537762020-07-22 11:44:56 -0700221 std::make_shared<HealthSensor>(bus, objPath.c_str(), cfg);
Vijay Khemkae2795302020-07-15 17:28:45 -0700222 healthSensors.emplace(cfg.name, healthSensor);
223
224 std::string logMsg = cfg.name + " Health Sensor created";
225 log<level::INFO>(logMsg.c_str(), entry("NAME = %s", cfg.name.c_str()));
226
227 /* Set configured values of crtical and warning high to dbus */
228 healthSensor->setSensorThreshold(cfg.criticalHigh, cfg.warningHigh);
229 }
230}
231
232/** @brief Parsing Health config JSON file */
233Json HealthMon::parseConfigFile(std::string configFile)
234{
235 std::ifstream jsonFile(configFile);
236 if (!jsonFile.is_open())
237 {
238 log<level::ERR>("config JSON file not found",
239 entry("FILENAME = %s", configFile.c_str()));
240 }
241
242 auto data = Json::parse(jsonFile, nullptr, false);
243 if (data.is_discarded())
244 {
245 log<level::ERR>("config readings JSON parser failure",
246 entry("FILENAME = %s", configFile.c_str()));
247 }
248
249 return data;
250}
251
Vijay Khemkae2795302020-07-15 17:28:45 -0700252void HealthMon::getConfigData(Json& data, HealthConfig& cfg)
253{
254
255 static const Json empty{};
256
Vijay Khemka15537762020-07-22 11:44:56 -0700257 /* Default frerquency of sensor polling is 1 second */
258 cfg.freq = data.value("Frequency", 1);
259
260 /* Default window size sensor queue is 1 */
261 cfg.windowSize = data.value("Window_size", 1);
262
Vijay Khemkae2795302020-07-15 17:28:45 -0700263 auto threshold = data.value("Threshold", empty);
264 if (!threshold.empty())
265 {
266 auto criticalData = threshold.value("Critical", empty);
267 if (!criticalData.empty())
268 {
269 cfg.criticalHigh = criticalData.value("Value", 0);
270 cfg.criticalLog = criticalData.value("Log", true);
271 cfg.criticalTgt = criticalData.value("Target", "");
272 }
273 auto warningData = threshold.value("Warning", empty);
274 if (!warningData.empty())
275 {
276 cfg.warningHigh = warningData.value("Value", 0);
277 cfg.warningLog = warningData.value("Log", true);
278 cfg.warningTgt = warningData.value("Target", "");
279 }
280 }
281}
282
Vijay Khemka15537762020-07-22 11:44:56 -0700283std::vector<HealthConfig> HealthMon::getHealthConfig()
Vijay Khemkae2795302020-07-15 17:28:45 -0700284{
285
286 std::vector<HealthConfig> cfgs;
287 HealthConfig cfg;
288 auto data = parseConfigFile(HEALTH_CONFIG_FILE);
289
290 // print values
291 if (DEBUG)
292 std::cout << "Config json data:\n" << data << "\n\n";
293
294 /* Get CPU config data */
295 for (auto& j : data.items())
296 {
297 auto key = j.key();
Vijay Khemka15537762020-07-22 11:44:56 -0700298 if (readSensors.find(key) != readSensors.end())
Vijay Khemkae2795302020-07-15 17:28:45 -0700299 {
300 HealthConfig cfg = HealthConfig();
301 cfg.name = j.key();
302 getConfigData(j.value(), cfg);
303 cfgs.push_back(cfg);
304 if (DEBUG)
305 printConfig(cfg);
306 }
307 else
308 {
309 std::string logMsg = key + " Health Sensor not supported";
310 log<level::ERR>(logMsg.c_str(), entry("NAME = %s", key.c_str()));
311 }
312 }
313 return cfgs;
314}
315
316} // namespace health
317} // namespace phosphor
318
319/**
320 * @brief Main
321 */
322int main()
323{
324
325 // Get a default event loop
326 auto event = sdeventplus::Event::get_default();
327
328 // Get a handle to system dbus
329 auto bus = sdbusplus::bus::new_default();
330
331 // Create an health monitor object
332 phosphor::health::HealthMon healthMon(bus);
333
334 // Request service bus name
335 bus.request_name(HEALTH_BUS_NAME);
336
337 // Attach the bus to sd_event to service user requests
338 bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
339 event.loop();
340
341 return 0;
342}