blob: af69ecb689c1b7e24903b5c129dd2bfe3dded84b [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);
171}
172
173void printConfig(HealthConfig& cfg)
174{
175 std::cout << "Name: " << cfg.name << "\n";
176 std::cout << "Freq: " << (int)cfg.freq << "\n";
177 std::cout << "Window Size: " << (int)cfg.windowSize << "\n";
178 std::cout << "Critical value: " << (int)cfg.criticalHigh << "\n";
179 std::cout << "warning value: " << (int)cfg.warningHigh << "\n";
180 std::cout << "Critical log: " << (int)cfg.criticalLog << "\n";
181 std::cout << "Warning log: " << (int)cfg.warningLog << "\n";
182 std::cout << "Critical Target: " << cfg.criticalTgt << "\n";
183 std::cout << "Warning Target: " << cfg.warningTgt << "\n\n";
184}
185
Vijay Khemkae2795302020-07-15 17:28:45 -0700186/* Create dbus utilization sensor object for each configured sensors */
187void HealthMon::createHealthSensors()
188{
189 for (auto& cfg : sensorConfigs)
190 {
191 std::string objPath = std::string(HEALTH_SENSOR_PATH) + cfg.name;
192 auto healthSensor =
Vijay Khemka15537762020-07-22 11:44:56 -0700193 std::make_shared<HealthSensor>(bus, objPath.c_str(), cfg);
Vijay Khemkae2795302020-07-15 17:28:45 -0700194 healthSensors.emplace(cfg.name, healthSensor);
195
196 std::string logMsg = cfg.name + " Health Sensor created";
197 log<level::INFO>(logMsg.c_str(), entry("NAME = %s", cfg.name.c_str()));
198
199 /* Set configured values of crtical and warning high to dbus */
200 healthSensor->setSensorThreshold(cfg.criticalHigh, cfg.warningHigh);
201 }
202}
203
204/** @brief Parsing Health config JSON file */
205Json HealthMon::parseConfigFile(std::string configFile)
206{
207 std::ifstream jsonFile(configFile);
208 if (!jsonFile.is_open())
209 {
210 log<level::ERR>("config JSON file not found",
211 entry("FILENAME = %s", configFile.c_str()));
212 }
213
214 auto data = Json::parse(jsonFile, nullptr, false);
215 if (data.is_discarded())
216 {
217 log<level::ERR>("config readings JSON parser failure",
218 entry("FILENAME = %s", configFile.c_str()));
219 }
220
221 return data;
222}
223
Vijay Khemkae2795302020-07-15 17:28:45 -0700224void HealthMon::getConfigData(Json& data, HealthConfig& cfg)
225{
226
227 static const Json empty{};
228
Vijay Khemka15537762020-07-22 11:44:56 -0700229 /* Default frerquency of sensor polling is 1 second */
230 cfg.freq = data.value("Frequency", 1);
231
232 /* Default window size sensor queue is 1 */
233 cfg.windowSize = data.value("Window_size", 1);
234
Vijay Khemkae2795302020-07-15 17:28:45 -0700235 auto threshold = data.value("Threshold", empty);
236 if (!threshold.empty())
237 {
238 auto criticalData = threshold.value("Critical", empty);
239 if (!criticalData.empty())
240 {
241 cfg.criticalHigh = criticalData.value("Value", 0);
242 cfg.criticalLog = criticalData.value("Log", true);
243 cfg.criticalTgt = criticalData.value("Target", "");
244 }
245 auto warningData = threshold.value("Warning", empty);
246 if (!warningData.empty())
247 {
248 cfg.warningHigh = warningData.value("Value", 0);
249 cfg.warningLog = warningData.value("Log", true);
250 cfg.warningTgt = warningData.value("Target", "");
251 }
252 }
253}
254
Vijay Khemka15537762020-07-22 11:44:56 -0700255std::vector<HealthConfig> HealthMon::getHealthConfig()
Vijay Khemkae2795302020-07-15 17:28:45 -0700256{
257
258 std::vector<HealthConfig> cfgs;
259 HealthConfig cfg;
260 auto data = parseConfigFile(HEALTH_CONFIG_FILE);
261
262 // print values
263 if (DEBUG)
264 std::cout << "Config json data:\n" << data << "\n\n";
265
266 /* Get CPU config data */
267 for (auto& j : data.items())
268 {
269 auto key = j.key();
Vijay Khemka15537762020-07-22 11:44:56 -0700270 if (readSensors.find(key) != readSensors.end())
Vijay Khemkae2795302020-07-15 17:28:45 -0700271 {
272 HealthConfig cfg = HealthConfig();
273 cfg.name = j.key();
274 getConfigData(j.value(), cfg);
275 cfgs.push_back(cfg);
276 if (DEBUG)
277 printConfig(cfg);
278 }
279 else
280 {
281 std::string logMsg = key + " Health Sensor not supported";
282 log<level::ERR>(logMsg.c_str(), entry("NAME = %s", key.c_str()));
283 }
284 }
285 return cfgs;
286}
287
288} // namespace health
289} // namespace phosphor
290
291/**
292 * @brief Main
293 */
294int main()
295{
296
297 // Get a default event loop
298 auto event = sdeventplus::Event::get_default();
299
300 // Get a handle to system dbus
301 auto bus = sdbusplus::bus::new_default();
302
303 // Create an health monitor object
304 phosphor::health::HealthMon healthMon(bus);
305
306 // Request service bus name
307 bus.request_name(HEALTH_BUS_NAME);
308
309 // Attach the bus to sd_event to service user requests
310 bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
311 event.loop();
312
313 return 0;
314}