mirror of
https://github.com/Telecominfraproject/wlan-cloud-analytics.git
synced 2025-11-03 03:48:01 +00:00
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
This commit is contained in:
519
src/APStats.cpp
519
src/APStats.cpp
@@ -3,9 +3,9 @@
|
||||
//
|
||||
|
||||
#include "APStats.h"
|
||||
#include "dict_ssid.h"
|
||||
#include "StorageService.h"
|
||||
#include "WifiClientCache.h"
|
||||
#include "dict_ssid.h"
|
||||
#include "fmt/format.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
@@ -13,23 +13,27 @@ namespace OpenWifi {
|
||||
|
||||
static std::string mac_filter(const std::string &m) {
|
||||
std::string r;
|
||||
for(const auto &c:m)
|
||||
if(c!=':' && c!='-') r += c;
|
||||
for (const auto &c : m)
|
||||
if (c != ':' && c != '-')
|
||||
r += c;
|
||||
return r;
|
||||
}
|
||||
|
||||
template <typename T> void GetJSON(const char *field, const nlohmann::json & doc, T & v , const T & def ) {
|
||||
if(doc.contains(field) && !doc[field].is_null()) {
|
||||
template <typename T>
|
||||
void GetJSON(const char *field, const nlohmann::json &doc, T &v, const T &def) {
|
||||
if (doc.contains(field) && !doc[field].is_null()) {
|
||||
v = doc[field].get<T>();
|
||||
return;
|
||||
}
|
||||
v = def;
|
||||
}
|
||||
|
||||
template <typename T> void GetJSON(const char *field1, const char *field2, const nlohmann::json & doc, T & v , const T & def ) {
|
||||
if(doc.contains(field1) && !doc[field1].is_null()) {
|
||||
template <typename T>
|
||||
void GetJSON(const char *field1, const char *field2, const nlohmann::json &doc, T &v,
|
||||
const T &def) {
|
||||
if (doc.contains(field1) && !doc[field1].is_null()) {
|
||||
auto subDoc = doc[field1];
|
||||
if(subDoc.contains(field2) && !subDoc[field2].is_null()) {
|
||||
if (subDoc.contains(field2) && !subDoc[field2].is_null()) {
|
||||
v = subDoc[field2].get<T>();
|
||||
return;
|
||||
}
|
||||
@@ -37,22 +41,24 @@ namespace OpenWifi {
|
||||
v = def;
|
||||
}
|
||||
|
||||
inline double safe_div(uint64_t a , uint64_t b) {
|
||||
if(b==0)
|
||||
inline double safe_div(uint64_t a, uint64_t b) {
|
||||
if (b == 0)
|
||||
return 0.0;
|
||||
return (double)a/ (double) b;
|
||||
return (double)a / (double)b;
|
||||
}
|
||||
|
||||
inline double safe_pct(uint64_t a , uint64_t b) {
|
||||
if(b==0)
|
||||
inline double safe_pct(uint64_t a, uint64_t b) {
|
||||
if (b == 0)
|
||||
return 0.0;
|
||||
return (100.0) * (double) a/ (double) b;
|
||||
return (100.0) * (double)a / (double)b;
|
||||
}
|
||||
|
||||
inline bool find_ue(const std::string &station, const std::vector<AnalyticsObjects::SSIDTimePoint> &tps, AnalyticsObjects::UETimePoint &ue_tp) {
|
||||
for(const auto &ssid:tps) {
|
||||
for(const auto &association:ssid.associations) {
|
||||
if(association.station==station) {
|
||||
inline bool find_ue(const std::string &station,
|
||||
const std::vector<AnalyticsObjects::SSIDTimePoint> &tps,
|
||||
AnalyticsObjects::UETimePoint &ue_tp) {
|
||||
for (const auto &ssid : tps) {
|
||||
for (const auto &association : ssid.associations) {
|
||||
if (association.station == station) {
|
||||
ue_tp = association;
|
||||
return true;
|
||||
}
|
||||
@@ -61,26 +67,27 @@ namespace OpenWifi {
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename X, typename M> double Average( X T, const std::vector<M> &Values ) {
|
||||
template <typename X, typename M> double Average(X T, const std::vector<M> &Values) {
|
||||
double result = 0.0;
|
||||
|
||||
if(!Values.empty()) {
|
||||
if (!Values.empty()) {
|
||||
double sum = 0.0;
|
||||
|
||||
for(const auto &v:Values) {
|
||||
for (const auto &v : Values) {
|
||||
sum += (v.*T);
|
||||
}
|
||||
|
||||
result = sum / (double) Values.size();
|
||||
result = sum / (double)Values.size();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// This is used to detect a new association VS an existing one. This may happen when a device is connected, disconnects, and
|
||||
// reconnects in between 2 samples.
|
||||
static bool new_connection(const AnalyticsObjects::UETimePoint &Existing_UE, const AnalyticsObjects::UETimePoint &new_association) {
|
||||
if( new_association.tx_packets < Existing_UE.tx_packets ||
|
||||
// This is used to detect a new association VS an existing one. This may happen when a device
|
||||
// is connected, disconnects, and reconnects in between 2 samples.
|
||||
static bool new_connection(const AnalyticsObjects::UETimePoint &Existing_UE,
|
||||
const AnalyticsObjects::UETimePoint &new_association) {
|
||||
if (new_association.tx_packets < Existing_UE.tx_packets ||
|
||||
new_association.rx_packets < Existing_UE.rx_packets ||
|
||||
new_association.tx_bytes < Existing_UE.tx_bytes ||
|
||||
new_association.rx_bytes < Existing_UE.rx_bytes ||
|
||||
@@ -91,32 +98,35 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
static int BandToInt(const std::string &band) {
|
||||
if(band=="2G") return 2;
|
||||
if(band=="5G") return 5;
|
||||
if(band=="6G") return 6;
|
||||
if (band == "2G")
|
||||
return 2;
|
||||
if (band == "5G")
|
||||
return 5;
|
||||
if (band == "6G")
|
||||
return 6;
|
||||
return 2;
|
||||
}
|
||||
|
||||
void AP::UpdateStats(const std::shared_ptr<nlohmann::json> &State) {
|
||||
DI_.states++;
|
||||
DI_.connected =true;
|
||||
DI_.connected = true;
|
||||
|
||||
AnalyticsObjects::DeviceTimePoint DTP;
|
||||
poco_information(Logger(),fmt::format("{}: stats message.", DI_.serialNumber));
|
||||
poco_information(Logger(), fmt::format("{}: stats message.", DI_.serialNumber));
|
||||
|
||||
// find radios first to get associations.
|
||||
try {
|
||||
if(State->contains("unit")) {
|
||||
if (State->contains("unit")) {
|
||||
auto unit = (*State)["unit"];
|
||||
GetJSON("localtime", unit, DI_.lastState, (uint64_t) 0);
|
||||
GetJSON("uptime", unit, DI_.uptime, (uint64_t) 0);
|
||||
if(unit.contains("memory")) {
|
||||
GetJSON("localtime", unit, DI_.lastState, (uint64_t)0);
|
||||
GetJSON("uptime", unit, DI_.uptime, (uint64_t)0);
|
||||
if (unit.contains("memory")) {
|
||||
auto memory = unit["memory"];
|
||||
uint64_t free_mem, total_mem;
|
||||
GetJSON("free", memory, free_mem, (uint64_t) 0);
|
||||
GetJSON("total", memory, total_mem, (uint64_t) 0);
|
||||
if(total_mem) {
|
||||
DI_.memory = ((double) (total_mem - free_mem) / (double)total_mem) * 100.0;
|
||||
GetJSON("free", memory, free_mem, (uint64_t)0);
|
||||
GetJSON("total", memory, total_mem, (uint64_t)0);
|
||||
if (total_mem) {
|
||||
DI_.memory = ((double)(total_mem - free_mem) / (double)total_mem) * 100.0;
|
||||
} else {
|
||||
DI_.memory = 0.0;
|
||||
}
|
||||
@@ -125,45 +135,46 @@ namespace OpenWifi {
|
||||
|
||||
DTP.timestamp = DI_.lastState;
|
||||
|
||||
std::map<uint, std::pair<uint,uint> > radio_map;
|
||||
if(State->contains("radios") && (*State)["radios"].is_array()) {
|
||||
std::map<uint, std::pair<uint, uint>> radio_map;
|
||||
if (State->contains("radios") && (*State)["radios"].is_array()) {
|
||||
auto radios = (*State)["radios"];
|
||||
uint radio_index = 0;
|
||||
for (const auto &radio: radios) {
|
||||
for (const auto &radio : radios) {
|
||||
if (radio.contains("channel")) {
|
||||
AnalyticsObjects::RadioTimePoint RTP;
|
||||
GetJSON("channel", radio, RTP.channel, (uint64_t) 2);
|
||||
if(radio.contains("band") && radio["band"].is_array()) {
|
||||
GetJSON("channel", radio, RTP.channel, (uint64_t)2);
|
||||
if (radio.contains("band") && radio["band"].is_array()) {
|
||||
auto BandArray = radio["band"];
|
||||
RTP.band = BandToInt(BandArray[0]);
|
||||
// std::cout << "BAND (radio): " << BandToInt(BandArray[0]) << std::endl;
|
||||
// std::cout << "BAND (radio): " << BandToInt(BandArray[0]) <<
|
||||
// std::endl;
|
||||
} else {
|
||||
RTP.band = RTP.channel <= 16 ? 2 : 5;
|
||||
}
|
||||
radio_map[radio_index++] = std::make_pair(RTP.band, RTP.channel);
|
||||
GetJSON("busy_ms", radio, RTP.busy_ms, (uint64_t) 0);
|
||||
GetJSON("receive_ms", radio, RTP.receive_ms, (uint64_t) 0);
|
||||
GetJSON("transmit_ms", radio, RTP.transmit_ms, (uint64_t) 0);
|
||||
GetJSON("active_ms", radio, RTP.active_ms, (uint64_t) 0);
|
||||
GetJSON("tx_power", radio, RTP.tx_power, (uint64_t) 0);
|
||||
GetJSON("active_ms", radio, RTP.active_ms, (uint64_t) 0);
|
||||
GetJSON("channel", radio, RTP.channel, (uint64_t) 0);
|
||||
GetJSON("temperature", radio, RTP.temperature, (int64_t) 20);
|
||||
GetJSON("busy_ms", radio, RTP.busy_ms, (uint64_t)0);
|
||||
GetJSON("receive_ms", radio, RTP.receive_ms, (uint64_t)0);
|
||||
GetJSON("transmit_ms", radio, RTP.transmit_ms, (uint64_t)0);
|
||||
GetJSON("active_ms", radio, RTP.active_ms, (uint64_t)0);
|
||||
GetJSON("tx_power", radio, RTP.tx_power, (uint64_t)0);
|
||||
GetJSON("active_ms", radio, RTP.active_ms, (uint64_t)0);
|
||||
GetJSON("channel", radio, RTP.channel, (uint64_t)0);
|
||||
GetJSON("temperature", radio, RTP.temperature, (int64_t)20);
|
||||
if (radio.contains("channel_width") && !radio["channel_width"].is_null()) {
|
||||
if(radio["channel_width"].is_string()) {
|
||||
if (radio["channel_width"].is_string()) {
|
||||
std::string C = radio["channel_width"];
|
||||
RTP.channel_width = std::strtoull(C.c_str(), nullptr,10);
|
||||
} else if(radio["channel_width"].is_number_integer()) {
|
||||
RTP.channel_width = std::strtoull(C.c_str(), nullptr, 10);
|
||||
} else if (radio["channel_width"].is_number_integer()) {
|
||||
RTP.channel_width = radio["channel_width"];
|
||||
} else {
|
||||
RTP.channel_width = 20;
|
||||
}
|
||||
}
|
||||
if(RTP.temperature==0)
|
||||
if (RTP.temperature == 0)
|
||||
RTP.temperature = 20;
|
||||
GetJSON("noise", radio, RTP.noise, (int64_t) -90);
|
||||
if(RTP.noise==0)
|
||||
RTP.noise=-90;
|
||||
GetJSON("noise", radio, RTP.noise, (int64_t)-90);
|
||||
if (RTP.noise == 0)
|
||||
RTP.noise = -90;
|
||||
DTP.radio_data.push_back(RTP);
|
||||
}
|
||||
}
|
||||
@@ -172,36 +183,40 @@ namespace OpenWifi {
|
||||
// now that we know the radio bands, look for associations
|
||||
auto interfaces = (*State)["interfaces"];
|
||||
DI_.associations_2g = DI_.associations_5g = DI_.associations_6g = 0;
|
||||
for(const auto &interface:interfaces) {
|
||||
std::string InterfaceName = fmt::format("{}: {}", DI_.serialNumber, interface.contains("name") ? to_string(interface["name"]) : "unknown");
|
||||
if(interface.contains("counters")) {
|
||||
for (const auto &interface : interfaces) {
|
||||
std::string InterfaceName = fmt::format(
|
||||
"{}: {}", DI_.serialNumber,
|
||||
interface.contains("name") ? to_string(interface["name"]) : "unknown");
|
||||
if (interface.contains("counters")) {
|
||||
auto counters = interface["counters"];
|
||||
GetJSON("collisions", counters, DTP.ap_data.collisions, (uint64_t) 0);
|
||||
GetJSON("multicast", counters, DTP.ap_data.multicast, (uint64_t) 0);
|
||||
GetJSON("rx_bytes", counters, DTP.ap_data.rx_bytes, (uint64_t) 0);
|
||||
GetJSON("rx_dropped", counters, DTP.ap_data.rx_dropped, (uint64_t) 0);
|
||||
GetJSON("rx_errors", counters, DTP.ap_data.rx_errors, (uint64_t) 0);
|
||||
GetJSON("rx_packets", counters, DTP.ap_data.rx_packets, (uint64_t) 0);
|
||||
GetJSON("tx_bytes", counters, DTP.ap_data.tx_bytes, (uint64_t) 0);
|
||||
GetJSON("tx_dropped", counters, DTP.ap_data.tx_dropped, (uint64_t) 0);
|
||||
GetJSON("tx_errors", counters, DTP.ap_data.tx_errors, (uint64_t) 0);
|
||||
GetJSON("tx_packets", counters, DTP.ap_data.tx_packets, (uint64_t) 0);
|
||||
GetJSON("collisions", counters, DTP.ap_data.collisions, (uint64_t)0);
|
||||
GetJSON("multicast", counters, DTP.ap_data.multicast, (uint64_t)0);
|
||||
GetJSON("rx_bytes", counters, DTP.ap_data.rx_bytes, (uint64_t)0);
|
||||
GetJSON("rx_dropped", counters, DTP.ap_data.rx_dropped, (uint64_t)0);
|
||||
GetJSON("rx_errors", counters, DTP.ap_data.rx_errors, (uint64_t)0);
|
||||
GetJSON("rx_packets", counters, DTP.ap_data.rx_packets, (uint64_t)0);
|
||||
GetJSON("tx_bytes", counters, DTP.ap_data.tx_bytes, (uint64_t)0);
|
||||
GetJSON("tx_dropped", counters, DTP.ap_data.tx_dropped, (uint64_t)0);
|
||||
GetJSON("tx_errors", counters, DTP.ap_data.tx_errors, (uint64_t)0);
|
||||
GetJSON("tx_packets", counters, DTP.ap_data.tx_packets, (uint64_t)0);
|
||||
}
|
||||
|
||||
InterfaceClientEntryMap_t ICEM;
|
||||
if(interface.contains("clients") && interface["clients"].is_array()) {
|
||||
if (interface.contains("clients") && interface["clients"].is_array()) {
|
||||
try {
|
||||
auto Clients = interface["clients"];
|
||||
for(const auto & client: Clients) {
|
||||
if(client.contains("mac") && client["mac"].is_string()) {
|
||||
for (const auto &client : Clients) {
|
||||
if (client.contains("mac") && client["mac"].is_string()) {
|
||||
InterfaceClientEntry E;
|
||||
if(client.contains("ipv4_addresses") && client["ipv4_addresses"].is_array()) {
|
||||
for(const auto &ip:client["ipv4_addresses"]) {
|
||||
if (client.contains("ipv4_addresses") &&
|
||||
client["ipv4_addresses"].is_array()) {
|
||||
for (const auto &ip : client["ipv4_addresses"]) {
|
||||
E.ipv4_addresses.push_back(ip);
|
||||
}
|
||||
}
|
||||
if(client.contains("ipv6_addresses") && client["ipv6_addresses"].is_array()) {
|
||||
for(const auto &ip:client["ipv6_addresses"]) {
|
||||
if (client.contains("ipv6_addresses") &&
|
||||
client["ipv6_addresses"].is_array()) {
|
||||
for (const auto &ip : client["ipv6_addresses"]) {
|
||||
E.ipv6_addresses.push_back(ip);
|
||||
}
|
||||
}
|
||||
@@ -209,56 +224,59 @@ namespace OpenWifi {
|
||||
ICEM[M] = E;
|
||||
}
|
||||
}
|
||||
} catch(...) {
|
||||
std::cout << "Exception while parsing clients: " << InterfaceName << std::endl;
|
||||
} catch (...) {
|
||||
std::cout << "Exception while parsing clients: " << InterfaceName
|
||||
<< std::endl;
|
||||
}
|
||||
} else {
|
||||
// std::cout <<"Interface: No clients: " << InterfaceName << std::endl;
|
||||
}
|
||||
|
||||
if(interface.contains("ssids")) {
|
||||
if (interface.contains("ssids")) {
|
||||
auto ssids = interface["ssids"];
|
||||
for (const auto &ssid: ssids) {
|
||||
for (const auto &ssid : ssids) {
|
||||
AnalyticsObjects::SSIDTimePoint SSIDTP;
|
||||
uint radio_location=0;
|
||||
uint radio_location = 0;
|
||||
SSIDTP.band = 2;
|
||||
|
||||
if(ssid.contains("band")) {
|
||||
if (ssid.contains("band")) {
|
||||
std::string Band = ssid["band"];
|
||||
SSIDTP.band = BandToInt(Band);
|
||||
// std::cout << "BAND (ssid): " << SSIDTP.band << std::endl;
|
||||
auto radio = ssid["radio"];
|
||||
if(radio.contains("$ref")) {
|
||||
if (radio.contains("$ref")) {
|
||||
auto ref = radio["$ref"];
|
||||
auto radio_parts = Poco::StringTokenizer(ref, "/");
|
||||
if(radio_parts.count()==3) {
|
||||
radio_location = std::strtol(radio_parts[2].c_str(), nullptr, 10);
|
||||
if(radio_map.find(radio_location)!=radio_map.end()) {
|
||||
if (radio_parts.count() == 3) {
|
||||
radio_location =
|
||||
std::strtol(radio_parts[2].c_str(), nullptr, 10);
|
||||
if (radio_map.find(radio_location) != radio_map.end()) {
|
||||
SSIDTP.channel = radio_map[radio_location].second;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if(ssid.contains("radio")) {
|
||||
} else if (ssid.contains("radio")) {
|
||||
auto radio = ssid["radio"];
|
||||
if(radio.contains("$ref")) {
|
||||
if (radio.contains("$ref")) {
|
||||
auto ref = radio["$ref"];
|
||||
auto radio_parts = Poco::StringTokenizer(ref, "/");
|
||||
if(radio_parts.count()==3) {
|
||||
radio_location = std::strtol(radio_parts[2].c_str(), nullptr, 10);
|
||||
if(radio_map.find(radio_location)!=radio_map.end()) {
|
||||
if (radio_parts.count() == 3) {
|
||||
radio_location =
|
||||
std::strtol(radio_parts[2].c_str(), nullptr, 10);
|
||||
if (radio_map.find(radio_location) != radio_map.end()) {
|
||||
SSIDTP.band = radio_map[radio_location].first;
|
||||
SSIDTP.channel = radio_map[radio_location].second;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
GetJSON("bssid",ssid,SSIDTP.bssid, std::string{""});
|
||||
GetJSON("mode",ssid,SSIDTP.mode, std::string{""} );
|
||||
GetJSON("ssid",ssid,SSIDTP.ssid, std::string{""} );
|
||||
GetJSON("bssid", ssid, SSIDTP.bssid, std::string{""});
|
||||
GetJSON("mode", ssid, SSIDTP.mode, std::string{""});
|
||||
GetJSON("ssid", ssid, SSIDTP.ssid, std::string{""});
|
||||
if (ssid.contains("associations") && ssid["associations"].is_array()) {
|
||||
auto associations = ssid["associations"];
|
||||
auto radio_it = radio_map.find(radio_location);
|
||||
if(radio_it!=radio_map.end()) {
|
||||
if (radio_it != radio_map.end()) {
|
||||
auto the_radio = radio_it->second.first;
|
||||
if (the_radio == 2)
|
||||
DI_.associations_2g += associations.size();
|
||||
@@ -267,58 +285,66 @@ namespace OpenWifi {
|
||||
else if (the_radio == 6)
|
||||
DI_.associations_6g += associations.size();
|
||||
}
|
||||
for(const auto &association:associations) {
|
||||
for (const auto &association : associations) {
|
||||
AnalyticsObjects::UETimePoint TP;
|
||||
GetJSON("station",association,TP.station, std::string{} );
|
||||
GetJSON("rssi",association,TP.rssi, (int64_t)0 );
|
||||
GetJSON("tx_bytes",association,TP.tx_bytes, (uint64_t)0 );
|
||||
GetJSON("rx_bytes",association,TP.rx_bytes, (uint64_t)0 );
|
||||
GetJSON("tx_duration",association,TP.tx_duration, (uint64_t)0 );
|
||||
GetJSON("rx_packets",association,TP.rx_packets, (uint64_t)0 );
|
||||
GetJSON("tx_packets",association,TP.tx_packets, (uint64_t)0 );
|
||||
GetJSON("tx_retries",association,TP.tx_retries, (uint64_t)0 );
|
||||
GetJSON("tx_failed",association,TP.tx_failed, (uint64_t)0 );
|
||||
GetJSON("connected",association,TP.connected, (uint64_t)0 );
|
||||
GetJSON("inactive",association,TP.inactive, (uint64_t)0 );
|
||||
GetJSON("station", association, TP.station, std::string{});
|
||||
GetJSON("rssi", association, TP.rssi, (int64_t)0);
|
||||
GetJSON("tx_bytes", association, TP.tx_bytes, (uint64_t)0);
|
||||
GetJSON("rx_bytes", association, TP.rx_bytes, (uint64_t)0);
|
||||
GetJSON("tx_duration", association, TP.tx_duration, (uint64_t)0);
|
||||
GetJSON("rx_packets", association, TP.rx_packets, (uint64_t)0);
|
||||
GetJSON("tx_packets", association, TP.tx_packets, (uint64_t)0);
|
||||
GetJSON("tx_retries", association, TP.tx_retries, (uint64_t)0);
|
||||
GetJSON("tx_failed", association, TP.tx_failed, (uint64_t)0);
|
||||
GetJSON("connected", association, TP.connected, (uint64_t)0);
|
||||
GetJSON("inactive", association, TP.inactive, (uint64_t)0);
|
||||
|
||||
AnalyticsObjects::WifiClientHistory WFH;
|
||||
WFH.station_id = mac_filter(TP.station);
|
||||
WFH.bssid = mac_filter(SSIDTP.bssid);
|
||||
WFH.ssid = SSIDTP.ssid;
|
||||
WFH.rssi = TP.rssi;
|
||||
GetJSON("rx_rate","bitrate",association,WFH.rx_bitrate,(uint32_t)0);
|
||||
GetJSON("rx_rate","chwidth",association,WFH.rx_chwidth,(uint32_t)0);
|
||||
GetJSON("rx_rate","mcs",association,WFH.rx_mcs,(uint16_t)0);
|
||||
GetJSON("rx_rate","nss",association,WFH.rx_nss,(uint16_t)0);
|
||||
GetJSON("rx_rate","vht",association,WFH.rx_vht,false);
|
||||
GetJSON("tx_rate","bitrate",association,WFH.tx_bitrate,(uint32_t)0);
|
||||
GetJSON("tx_rate","chwidth",association,WFH.tx_chwidth,(uint32_t)0);
|
||||
GetJSON("tx_rate","mcs",association,WFH.tx_mcs,(uint16_t)0);
|
||||
GetJSON("tx_rate","nss",association,WFH.tx_nss,(uint16_t)0);
|
||||
GetJSON("tx_rate","vht",association,WFH.tx_vht,false);
|
||||
GetJSON("rx_bytes",association,WFH.rx_bytes,(uint64_t)0);
|
||||
GetJSON("tx_bytes",association,WFH.tx_bytes,(uint64_t)0);
|
||||
GetJSON("rx_duration",association,WFH.rx_duration,(uint64_t)0);
|
||||
GetJSON("tx_duration",association,WFH.tx_duration,(uint64_t)0);
|
||||
GetJSON("rx_packets",association,WFH.rx_packets,(uint64_t)0);
|
||||
GetJSON("tx_packets",association,WFH.tx_packets,(uint64_t)0);
|
||||
GetJSON("rx_rate", "bitrate", association, WFH.rx_bitrate,
|
||||
(uint32_t)0);
|
||||
GetJSON("rx_rate", "chwidth", association, WFH.rx_chwidth,
|
||||
(uint32_t)0);
|
||||
GetJSON("rx_rate", "mcs", association, WFH.rx_mcs, (uint16_t)0);
|
||||
GetJSON("rx_rate", "nss", association, WFH.rx_nss, (uint16_t)0);
|
||||
GetJSON("rx_rate", "vht", association, WFH.rx_vht, false);
|
||||
GetJSON("tx_rate", "bitrate", association, WFH.tx_bitrate,
|
||||
(uint32_t)0);
|
||||
GetJSON("tx_rate", "chwidth", association, WFH.tx_chwidth,
|
||||
(uint32_t)0);
|
||||
GetJSON("tx_rate", "mcs", association, WFH.tx_mcs, (uint16_t)0);
|
||||
GetJSON("tx_rate", "nss", association, WFH.tx_nss, (uint16_t)0);
|
||||
GetJSON("tx_rate", "vht", association, WFH.tx_vht, false);
|
||||
GetJSON("rx_bytes", association, WFH.rx_bytes, (uint64_t)0);
|
||||
GetJSON("tx_bytes", association, WFH.tx_bytes, (uint64_t)0);
|
||||
GetJSON("rx_duration", association, WFH.rx_duration, (uint64_t)0);
|
||||
GetJSON("tx_duration", association, WFH.tx_duration, (uint64_t)0);
|
||||
GetJSON("rx_packets", association, WFH.rx_packets, (uint64_t)0);
|
||||
GetJSON("tx_packets", association, WFH.tx_packets, (uint64_t)0);
|
||||
|
||||
// try to locate the IP addresses
|
||||
auto ClientInfo = ICEM.find(WFH.station_id);
|
||||
if(ClientInfo!=end(ICEM)) {
|
||||
if(!ClientInfo->second.ipv4_addresses.empty()) {
|
||||
if (ClientInfo != end(ICEM)) {
|
||||
if (!ClientInfo->second.ipv4_addresses.empty()) {
|
||||
WFH.ipv4 = ClientInfo->second.ipv4_addresses[0];
|
||||
}
|
||||
if(!ClientInfo->second.ipv6_addresses.empty()) {
|
||||
if (!ClientInfo->second.ipv6_addresses.empty()) {
|
||||
WFH.ipv6 = ClientInfo->second.ipv6_addresses[0];
|
||||
}
|
||||
// std::cout << __LINE__ << ": " << InterfaceName << " Mac Found: " << ICEM.size() << " entries. " << WFH.station_id << std::endl;
|
||||
// std::cout << __LINE__ << ": " << InterfaceName << " Mac
|
||||
// Found: " << ICEM.size() << " entries. " << WFH.station_id <<
|
||||
// std::endl;
|
||||
} else {
|
||||
// std::cout << __LINE__ << ": " << InterfaceName << " Mac NOT found: " << ICEM.size() << " entries. " << WFH.station_id << std::endl;
|
||||
// std::cout << __LINE__ << ": " << InterfaceName << " Mac NOT
|
||||
// found: " << ICEM.size() << " entries. " << WFH.station_id <<
|
||||
// std::endl;
|
||||
}
|
||||
|
||||
for(const auto &rd:DTP.radio_data) {
|
||||
if(rd.band == SSIDTP.band) {
|
||||
for (const auto &rd : DTP.radio_data) {
|
||||
if (rd.band == SSIDTP.band) {
|
||||
WFH.channel_width = rd.channel_width;
|
||||
WFH.noise = rd.noise;
|
||||
WFH.tx_power = rd.tx_power;
|
||||
@@ -331,46 +357,50 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
WFH.mode = SSIDTP.mode;
|
||||
GetJSON("ack_signal",association,WFH.ack_signal,(int64_t)0);
|
||||
GetJSON("ack_signal_avg",association,WFH.ack_signal_avg,(int64_t)0);
|
||||
GetJSON("connected",association,WFH.connected,(uint64_t)0);
|
||||
GetJSON("inactive",association,WFH.inactive,(uint64_t)0);
|
||||
GetJSON("tx_retries",association,WFH.tx_retries,(uint64_t)0);
|
||||
GetJSON("ack_signal", association, WFH.ack_signal, (int64_t)0);
|
||||
GetJSON("ack_signal_avg", association, WFH.ack_signal_avg,
|
||||
(int64_t)0);
|
||||
GetJSON("connected", association, WFH.connected, (uint64_t)0);
|
||||
GetJSON("inactive", association, WFH.inactive, (uint64_t)0);
|
||||
GetJSON("tx_retries", association, WFH.tx_retries, (uint64_t)0);
|
||||
|
||||
WifiClientCache()->AddSerialNumber(venue_id_,WFH.station_id);
|
||||
WifiClientCache()->AddSerialNumber(venue_id_, WFH.station_id);
|
||||
WFH.venue_id = venue_id_;
|
||||
StorageService()->WifiClientHistoryDB().CreateRecord(WFH);
|
||||
|
||||
if(association.contains("tid_stats") && association["tid_stats"].is_array()) {
|
||||
if (association.contains("tid_stats") &&
|
||||
association["tid_stats"].is_array()) {
|
||||
auto tid_stats = association["tid_stats"];
|
||||
for(const auto &tid_stat:tid_stats) {
|
||||
for (const auto &tid_stat : tid_stats) {
|
||||
AnalyticsObjects::TIDstat_entry E;
|
||||
GetJSON("rx_msdu",tid_stat,E.rx_msdu, (uint64_t)0 );
|
||||
GetJSON("tx_msdu",tid_stat,E.tx_msdu, (uint64_t)0 );
|
||||
GetJSON("tx_msdu_failed",tid_stat,E.tx_msdu_failed, (uint64_t)0 );
|
||||
GetJSON("tx_msdu_retries",tid_stat,E.tx_msdu_retries, (uint64_t)0 );
|
||||
GetJSON("rx_msdu", tid_stat, E.rx_msdu, (uint64_t)0);
|
||||
GetJSON("tx_msdu", tid_stat, E.tx_msdu, (uint64_t)0);
|
||||
GetJSON("tx_msdu_failed", tid_stat, E.tx_msdu_failed,
|
||||
(uint64_t)0);
|
||||
GetJSON("tx_msdu_retries", tid_stat, E.tx_msdu_retries,
|
||||
(uint64_t)0);
|
||||
TP.tidstats.push_back(E);
|
||||
}
|
||||
}
|
||||
|
||||
if(association.contains("tx_rate")) {
|
||||
if (association.contains("tx_rate")) {
|
||||
auto tx_rate = association["tx_rate"];
|
||||
GetJSON("bitrate",tx_rate,TP.tx_rate.bitrate, (uint64_t)0 );
|
||||
GetJSON("mcs",tx_rate,TP.tx_rate.mcs, (uint64_t)0 );
|
||||
GetJSON("nss",tx_rate,TP.tx_rate.nss, (uint64_t)0 );
|
||||
GetJSON("chwidth",tx_rate,TP.tx_rate.chwidth, (uint64_t)0 );
|
||||
GetJSON("ht",tx_rate,TP.tx_rate.ht, false );
|
||||
GetJSON("sgi",tx_rate,TP.tx_rate.sgi, false );
|
||||
GetJSON("bitrate", tx_rate, TP.tx_rate.bitrate, (uint64_t)0);
|
||||
GetJSON("mcs", tx_rate, TP.tx_rate.mcs, (uint64_t)0);
|
||||
GetJSON("nss", tx_rate, TP.tx_rate.nss, (uint64_t)0);
|
||||
GetJSON("chwidth", tx_rate, TP.tx_rate.chwidth, (uint64_t)0);
|
||||
GetJSON("ht", tx_rate, TP.tx_rate.ht, false);
|
||||
GetJSON("sgi", tx_rate, TP.tx_rate.sgi, false);
|
||||
}
|
||||
|
||||
if(association.contains("rx_rate")) {
|
||||
if (association.contains("rx_rate")) {
|
||||
auto rx_rate = association["rx_rate"];
|
||||
GetJSON("bitrate",rx_rate,TP.rx_rate.bitrate, (uint64_t)0 );
|
||||
GetJSON("mcs",rx_rate,TP.rx_rate.mcs, (uint64_t)0 );
|
||||
GetJSON("nss",rx_rate,TP.rx_rate.nss, (uint64_t)0 );
|
||||
GetJSON("chwidth",rx_rate,TP.rx_rate.chwidth, (uint64_t)0 );
|
||||
GetJSON("ht",rx_rate,TP.rx_rate.ht, false );
|
||||
GetJSON("sgi",rx_rate,TP.rx_rate.sgi, false );
|
||||
GetJSON("bitrate", rx_rate, TP.rx_rate.bitrate, (uint64_t)0);
|
||||
GetJSON("mcs", rx_rate, TP.rx_rate.mcs, (uint64_t)0);
|
||||
GetJSON("nss", rx_rate, TP.rx_rate.nss, (uint64_t)0);
|
||||
GetJSON("chwidth", rx_rate, TP.rx_rate.chwidth, (uint64_t)0);
|
||||
GetJSON("ht", rx_rate, TP.rx_rate.ht, false);
|
||||
GetJSON("sgi", rx_rate, TP.rx_rate.sgi, false);
|
||||
}
|
||||
SSIDTP.associations.push_back(TP);
|
||||
}
|
||||
@@ -378,52 +408,64 @@ namespace OpenWifi {
|
||||
DTP.ssid_data.push_back(SSIDTP);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
DTP.device_info = DI_;
|
||||
} catch (...) {
|
||||
poco_information(Logger(),fmt::format("{}: stats failed parsing.", DI_.serialNumber));
|
||||
poco_information(Logger(), fmt::format("{}: stats failed parsing.", DI_.serialNumber));
|
||||
}
|
||||
|
||||
if(got_base) {
|
||||
if (got_base) {
|
||||
// calculate new point based on base, save new point, move DTP into base...
|
||||
AnalyticsObjects::DeviceTimePoint db_DTP = DTP;
|
||||
|
||||
auto time_lapse = DTP.timestamp - tp_base_.timestamp;
|
||||
if(time_lapse==0) time_lapse = 1;
|
||||
if (time_lapse == 0)
|
||||
time_lapse = 1;
|
||||
|
||||
db_DTP.ap_data.tx_bytes_delta = db_DTP.ap_data.tx_bytes - tp_base_.ap_data.tx_bytes;
|
||||
db_DTP.ap_data.rx_bytes_delta = db_DTP.ap_data.rx_bytes - tp_base_.ap_data.rx_bytes;
|
||||
db_DTP.ap_data.tx_packets_delta = db_DTP.ap_data.tx_packets - tp_base_.ap_data.tx_packets;
|
||||
db_DTP.ap_data.rx_packets_delta = db_DTP.ap_data.rx_packets - tp_base_.ap_data.rx_packets;
|
||||
db_DTP.ap_data.tx_dropped_delta = db_DTP.ap_data.tx_dropped - tp_base_.ap_data.tx_dropped;
|
||||
db_DTP.ap_data.rx_dropped_delta = db_DTP.ap_data.rx_dropped - tp_base_.ap_data.rx_dropped;
|
||||
db_DTP.ap_data.tx_packets_delta =
|
||||
db_DTP.ap_data.tx_packets - tp_base_.ap_data.tx_packets;
|
||||
db_DTP.ap_data.rx_packets_delta =
|
||||
db_DTP.ap_data.rx_packets - tp_base_.ap_data.rx_packets;
|
||||
db_DTP.ap_data.tx_dropped_delta =
|
||||
db_DTP.ap_data.tx_dropped - tp_base_.ap_data.tx_dropped;
|
||||
db_DTP.ap_data.rx_dropped_delta =
|
||||
db_DTP.ap_data.rx_dropped - tp_base_.ap_data.rx_dropped;
|
||||
db_DTP.ap_data.tx_errors_delta = db_DTP.ap_data.tx_errors - tp_base_.ap_data.tx_errors;
|
||||
db_DTP.ap_data.rx_errors_delta = db_DTP.ap_data.rx_errors - tp_base_.ap_data.rx_errors;
|
||||
|
||||
db_DTP.ap_data.tx_bytes_bw = safe_div(db_DTP.ap_data.tx_bytes_delta, time_lapse);
|
||||
db_DTP.ap_data.rx_bytes_bw = safe_div(db_DTP.ap_data.rx_bytes_delta , time_lapse);
|
||||
db_DTP.ap_data.rx_bytes_bw = safe_div(db_DTP.ap_data.rx_bytes_delta, time_lapse);
|
||||
db_DTP.ap_data.tx_packets_bw = safe_div(db_DTP.ap_data.tx_packets_delta, time_lapse);
|
||||
db_DTP.ap_data.rx_packets_bw = safe_div(db_DTP.ap_data.rx_packets_delta, time_lapse);
|
||||
db_DTP.ap_data.tx_dropped_pct = safe_pct(db_DTP.ap_data.tx_dropped_delta, db_DTP.ap_data.tx_packets);
|
||||
db_DTP.ap_data.rx_dropped_pct = safe_pct(db_DTP.ap_data.rx_dropped_delta, db_DTP.ap_data.rx_packets);
|
||||
db_DTP.ap_data.tx_errors_pct = safe_pct(db_DTP.ap_data.tx_errors_delta, db_DTP.ap_data.tx_packets);
|
||||
db_DTP.ap_data.rx_errors_pct = safe_pct(db_DTP.ap_data.rx_errors_delta, db_DTP.ap_data.rx_packets);
|
||||
db_DTP.ap_data.tx_dropped_pct =
|
||||
safe_pct(db_DTP.ap_data.tx_dropped_delta, db_DTP.ap_data.tx_packets);
|
||||
db_DTP.ap_data.rx_dropped_pct =
|
||||
safe_pct(db_DTP.ap_data.rx_dropped_delta, db_DTP.ap_data.rx_packets);
|
||||
db_DTP.ap_data.tx_errors_pct =
|
||||
safe_pct(db_DTP.ap_data.tx_errors_delta, db_DTP.ap_data.tx_packets);
|
||||
db_DTP.ap_data.rx_errors_pct =
|
||||
safe_pct(db_DTP.ap_data.rx_errors_delta, db_DTP.ap_data.rx_packets);
|
||||
|
||||
for(auto &radio:db_DTP.radio_data) {
|
||||
bool found=false;
|
||||
for(const auto &base_radio:tp_base_.radio_data) {
|
||||
for (auto &radio : db_DTP.radio_data) {
|
||||
bool found = false;
|
||||
for (const auto &base_radio : tp_base_.radio_data) {
|
||||
|
||||
if(radio.channel==base_radio.channel) {
|
||||
if (radio.channel == base_radio.channel) {
|
||||
found = true;
|
||||
radio.active_pct = safe_pct( (radio.active_ms - base_radio.active_ms) / 1000 , time_lapse);
|
||||
radio.busy_pct = safe_pct( (radio.busy_ms - base_radio.busy_ms) / 1000 , time_lapse);
|
||||
radio.receive_pct = safe_pct( (radio.receive_ms - base_radio.receive_ms) / 1000 , time_lapse);
|
||||
radio.transmit_pct = safe_pct( (radio.transmit_ms - base_radio.transmit_ms) / 1000 ,time_lapse);
|
||||
radio.active_pct =
|
||||
safe_pct((radio.active_ms - base_radio.active_ms) / 1000, time_lapse);
|
||||
radio.busy_pct =
|
||||
safe_pct((radio.busy_ms - base_radio.busy_ms) / 1000, time_lapse);
|
||||
radio.receive_pct =
|
||||
safe_pct((radio.receive_ms - base_radio.receive_ms) / 1000, time_lapse);
|
||||
radio.transmit_pct = safe_pct(
|
||||
(radio.transmit_ms - base_radio.transmit_ms) / 1000, time_lapse);
|
||||
}
|
||||
}
|
||||
|
||||
if(!found) {
|
||||
if (!found) {
|
||||
radio.active_pct = safe_pct(radio.active_ms / 1000, time_lapse);
|
||||
radio.busy_pct = safe_pct(radio.busy_ms / 1000, time_lapse);
|
||||
radio.receive_pct = safe_pct(radio.receive_ms / 1000, time_lapse);
|
||||
@@ -431,10 +473,11 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
for(auto &ssid:db_DTP.ssid_data) {
|
||||
for(auto &association:ssid.associations) {
|
||||
for (auto &ssid : db_DTP.ssid_data) {
|
||||
for (auto &association : ssid.associations) {
|
||||
AnalyticsObjects::UETimePoint ue_tp;
|
||||
if(find_ue(association.station, tp_base_.ssid_data, ue_tp) && !new_connection(ue_tp,association)) {
|
||||
if (find_ue(association.station, tp_base_.ssid_data, ue_tp) &&
|
||||
!new_connection(ue_tp, association)) {
|
||||
association.tx_bytes_delta = association.tx_bytes - ue_tp.tx_bytes;
|
||||
association.rx_bytes_delta = association.rx_bytes - ue_tp.rx_bytes;
|
||||
association.tx_packets_delta = association.tx_packets - ue_tp.tx_packets;
|
||||
@@ -452,22 +495,31 @@ namespace OpenWifi {
|
||||
association.tx_duration_delta = association.tx_duration;
|
||||
}
|
||||
|
||||
association.tx_bytes_bw = safe_div( association.tx_bytes_delta , time_lapse );
|
||||
association.rx_bytes_bw = safe_div( association.rx_bytes_delta , time_lapse );
|
||||
association.tx_packets_bw = safe_div( association.tx_packets_delta , time_lapse );
|
||||
association.rx_packets_bw = safe_div( association.rx_packets_delta , time_lapse );
|
||||
association.tx_failed_pct = safe_pct( association.tx_failed_delta, association.tx_packets);
|
||||
association.tx_retries_pct = safe_pct( association.tx_retries_delta, association.tx_packets);
|
||||
association.tx_duration_pct = safe_pct( (association.tx_duration_delta) / 1000000 , time_lapse );
|
||||
association.tx_bytes_bw = safe_div(association.tx_bytes_delta, time_lapse);
|
||||
association.rx_bytes_bw = safe_div(association.rx_bytes_delta, time_lapse);
|
||||
association.tx_packets_bw = safe_div(association.tx_packets_delta, time_lapse);
|
||||
association.rx_packets_bw = safe_div(association.rx_packets_delta, time_lapse);
|
||||
association.tx_failed_pct =
|
||||
safe_pct(association.tx_failed_delta, association.tx_packets);
|
||||
association.tx_retries_pct =
|
||||
safe_pct(association.tx_retries_delta, association.tx_packets);
|
||||
association.tx_duration_pct =
|
||||
safe_pct((association.tx_duration_delta) / 1000000, time_lapse);
|
||||
|
||||
ssid.tx_failed_pct.max = std::max(ssid.tx_failed_pct.max, association.tx_failed_pct);
|
||||
ssid.tx_failed_pct.min = std::min(ssid.tx_failed_pct.min, association.tx_failed_pct);
|
||||
ssid.tx_failed_pct.max =
|
||||
std::max(ssid.tx_failed_pct.max, association.tx_failed_pct);
|
||||
ssid.tx_failed_pct.min =
|
||||
std::min(ssid.tx_failed_pct.min, association.tx_failed_pct);
|
||||
|
||||
ssid.tx_retries_pct.max = std::max(ssid.tx_retries_pct.max, association.tx_retries_pct);
|
||||
ssid.tx_retries_pct.min = std::min(ssid.tx_retries_pct.min, association.tx_retries_pct);
|
||||
ssid.tx_retries_pct.max =
|
||||
std::max(ssid.tx_retries_pct.max, association.tx_retries_pct);
|
||||
ssid.tx_retries_pct.min =
|
||||
std::min(ssid.tx_retries_pct.min, association.tx_retries_pct);
|
||||
|
||||
ssid.tx_duration_pct.max = std::max(ssid.tx_duration_pct.max, association.tx_duration_pct);
|
||||
ssid.tx_duration_pct.min = std::min(ssid.tx_duration_pct.min, association.tx_duration_pct);
|
||||
ssid.tx_duration_pct.max =
|
||||
std::max(ssid.tx_duration_pct.max, association.tx_duration_pct);
|
||||
ssid.tx_duration_pct.min =
|
||||
std::min(ssid.tx_duration_pct.min, association.tx_duration_pct);
|
||||
|
||||
ssid.tx_bytes_bw.max = std::max(ssid.tx_bytes_bw.max, association.tx_bytes_bw);
|
||||
ssid.tx_bytes_bw.min = std::min(ssid.tx_bytes_bw.min, association.tx_bytes_bw);
|
||||
@@ -475,20 +527,31 @@ namespace OpenWifi {
|
||||
ssid.rx_bytes_bw.max = std::max(ssid.rx_bytes_bw.max, association.rx_bytes_bw);
|
||||
ssid.rx_bytes_bw.min = std::min(ssid.rx_bytes_bw.min, association.rx_bytes_bw);
|
||||
|
||||
ssid.tx_packets_bw.max = std::max(ssid.tx_packets_bw.max, association.tx_packets_bw);
|
||||
ssid.tx_packets_bw.min = std::min(ssid.tx_packets_bw.min, association.tx_packets_bw);
|
||||
ssid.tx_packets_bw.max =
|
||||
std::max(ssid.tx_packets_bw.max, association.tx_packets_bw);
|
||||
ssid.tx_packets_bw.min =
|
||||
std::min(ssid.tx_packets_bw.min, association.tx_packets_bw);
|
||||
|
||||
ssid.rx_packets_bw.max = std::max(ssid.rx_packets_bw.max, association.rx_packets_bw);
|
||||
ssid.rx_packets_bw.min = std::min(ssid.rx_packets_bw.min, association.rx_packets_bw);
|
||||
ssid.rx_packets_bw.max =
|
||||
std::max(ssid.rx_packets_bw.max, association.rx_packets_bw);
|
||||
ssid.rx_packets_bw.min =
|
||||
std::min(ssid.rx_packets_bw.min, association.rx_packets_bw);
|
||||
}
|
||||
|
||||
ssid.tx_bytes_bw.avg = Average(&AnalyticsObjects::UETimePoint::tx_bytes_bw,ssid.associations);
|
||||
ssid.rx_bytes_bw.avg = Average(&AnalyticsObjects::UETimePoint::rx_bytes_bw,ssid.associations);
|
||||
ssid.tx_packets_bw.avg = Average(&AnalyticsObjects::UETimePoint::tx_packets_bw,ssid.associations);
|
||||
ssid.rx_packets_bw.avg = Average(&AnalyticsObjects::UETimePoint::rx_packets_bw,ssid.associations);
|
||||
ssid.tx_failed_pct.avg = Average(&AnalyticsObjects::UETimePoint::tx_failed_pct,ssid.associations);
|
||||
ssid.tx_retries_pct.avg = Average(&AnalyticsObjects::UETimePoint::tx_retries_pct,ssid.associations);
|
||||
ssid.tx_duration_pct.avg = Average(&AnalyticsObjects::UETimePoint::tx_duration_pct,ssid.associations);
|
||||
ssid.tx_bytes_bw.avg =
|
||||
Average(&AnalyticsObjects::UETimePoint::tx_bytes_bw, ssid.associations);
|
||||
ssid.rx_bytes_bw.avg =
|
||||
Average(&AnalyticsObjects::UETimePoint::rx_bytes_bw, ssid.associations);
|
||||
ssid.tx_packets_bw.avg =
|
||||
Average(&AnalyticsObjects::UETimePoint::tx_packets_bw, ssid.associations);
|
||||
ssid.rx_packets_bw.avg =
|
||||
Average(&AnalyticsObjects::UETimePoint::rx_packets_bw, ssid.associations);
|
||||
ssid.tx_failed_pct.avg =
|
||||
Average(&AnalyticsObjects::UETimePoint::tx_failed_pct, ssid.associations);
|
||||
ssid.tx_retries_pct.avg =
|
||||
Average(&AnalyticsObjects::UETimePoint::tx_retries_pct, ssid.associations);
|
||||
ssid.tx_duration_pct.avg =
|
||||
Average(&AnalyticsObjects::UETimePoint::tx_duration_pct, ssid.associations);
|
||||
}
|
||||
|
||||
if (got_connection && got_health) {
|
||||
@@ -510,14 +573,14 @@ namespace OpenWifi {
|
||||
try {
|
||||
if (Connection->contains("ping")) {
|
||||
got_connection = true;
|
||||
poco_debug(Logger(),fmt::format("{}: ping message.", DI_.serialNumber));
|
||||
poco_debug(Logger(), fmt::format("{}: ping message.", DI_.serialNumber));
|
||||
DI_.connected = true;
|
||||
DI_.lastPing = Utils::Now();
|
||||
auto ping = (*Connection)["ping"];
|
||||
GetJSON("compatible", ping, DI_.deviceType, std::string{} );
|
||||
GetJSON("connectionIp", ping, DI_.connectionIp, std::string{} );
|
||||
GetJSON("locale", ping, DI_.locale, std::string{} );
|
||||
GetJSON("timestamp", ping, DI_.lastConnection, (uint64_t) Utils::Now() );
|
||||
GetJSON("compatible", ping, DI_.deviceType, std::string{});
|
||||
GetJSON("connectionIp", ping, DI_.connectionIp, std::string{});
|
||||
GetJSON("locale", ping, DI_.locale, std::string{});
|
||||
GetJSON("timestamp", ping, DI_.lastConnection, (uint64_t)Utils::Now());
|
||||
if (ping.contains("firmware")) {
|
||||
auto NewFirmware = ping["firmware"];
|
||||
if (NewFirmware != DI_.lastFirmware) {
|
||||
@@ -526,13 +589,13 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
} else if (Connection->contains("disconnection")) {
|
||||
poco_debug(Logger(),fmt::format("{}: disconnection message.", DI_.serialNumber));
|
||||
poco_debug(Logger(), fmt::format("{}: disconnection message.", DI_.serialNumber));
|
||||
auto Disconnection = (*Connection)["disconnection"];
|
||||
GetJSON("timestamp", Disconnection, DI_.lastDisconnection, (uint64_t)0 );
|
||||
GetJSON("timestamp", Disconnection, DI_.lastDisconnection, (uint64_t)0);
|
||||
got_base = got_health = got_connection = false;
|
||||
DI_.connected = false;
|
||||
} else if (Connection->contains("capabilities")) {
|
||||
poco_debug(Logger(),fmt::format("{}: connection message.", DI_.serialNumber));
|
||||
poco_debug(Logger(), fmt::format("{}: connection message.", DI_.serialNumber));
|
||||
got_connection = true;
|
||||
DI_.connected = true;
|
||||
DI_.lastConnection = Utils::Now();
|
||||
@@ -544,22 +607,24 @@ namespace OpenWifi {
|
||||
DI_.lastFirmwareUpdate = Utils::Now();
|
||||
}
|
||||
}
|
||||
GetJSON("connectionIp", ConnectionData, DI_.connectionIp, std::string{} );
|
||||
GetJSON("locale", ConnectionData, DI_.locale, std::string{} );
|
||||
GetJSON("connectionIp", ConnectionData, DI_.connectionIp, std::string{});
|
||||
GetJSON("locale", ConnectionData, DI_.locale, std::string{});
|
||||
}
|
||||
} catch (...) {
|
||||
poco_information(Logger(),fmt::format("{}: error parsing connection message.", DI_.serialNumber));
|
||||
poco_information(
|
||||
Logger(), fmt::format("{}: error parsing connection message.", DI_.serialNumber));
|
||||
}
|
||||
}
|
||||
|
||||
void AP::UpdateHealth(const std::shared_ptr<nlohmann::json> & Health) {
|
||||
void AP::UpdateHealth(const std::shared_ptr<nlohmann::json> &Health) {
|
||||
try {
|
||||
got_health = true;
|
||||
GetJSON("timestamp", *Health, DI_.lastHealth, (uint64_t)0 );
|
||||
GetJSON("sanity", *Health, DI_.health, (uint64_t)0 );
|
||||
poco_debug(Logger(),fmt::format("{}: health message.", DI_.serialNumber));
|
||||
} catch(...) {
|
||||
poco_information(Logger(),fmt::format("{}: error parsing health message.", DI_.serialNumber));
|
||||
GetJSON("timestamp", *Health, DI_.lastHealth, (uint64_t)0);
|
||||
GetJSON("sanity", *Health, DI_.health, (uint64_t)0);
|
||||
poco_debug(Logger(), fmt::format("{}: health message.", DI_.serialNumber));
|
||||
} catch (...) {
|
||||
poco_information(Logger(),
|
||||
fmt::format("{}: error parsing health message.", DI_.serialNumber));
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,11 +4,11 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <mutex>
|
||||
#include "nlohmann/json.hpp"
|
||||
#include "Poco/Logger.h"
|
||||
#include "RESTObjects/RESTAPI_AnalyticsObjects.h"
|
||||
#include "framework/utils.h"
|
||||
#include "Poco/Logger.h"
|
||||
#include "nlohmann/json.hpp"
|
||||
#include <mutex>
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
@@ -17,32 +17,29 @@ namespace OpenWifi {
|
||||
std::vector<std::string> ipv6_addresses;
|
||||
};
|
||||
|
||||
using InterfaceClientEntryMap_t = std::map<std::string,InterfaceClientEntry>;
|
||||
using InterfaceClientEntryMap_t = std::map<std::string, InterfaceClientEntry>;
|
||||
|
||||
class AP {
|
||||
public:
|
||||
explicit AP(uint64_t mac, const std::string &venue_id, const std::string &BoardId, Poco::Logger &L) :
|
||||
venue_id_(venue_id),
|
||||
boardId_(BoardId),
|
||||
Logger_(L)
|
||||
{
|
||||
explicit AP(uint64_t mac, const std::string &venue_id, const std::string &BoardId,
|
||||
Poco::Logger &L)
|
||||
: venue_id_(venue_id), boardId_(BoardId), Logger_(L) {
|
||||
DI_.serialNumber = Utils::IntToSerialNumber(mac);
|
||||
}
|
||||
|
||||
void UpdateStats(const std::shared_ptr<nlohmann::json> & State);
|
||||
void UpdateConnection(const std::shared_ptr<nlohmann::json> & Connection);
|
||||
void UpdateHealth(const std::shared_ptr<nlohmann::json> & Health);
|
||||
void UpdateStats(const std::shared_ptr<nlohmann::json> &State);
|
||||
void UpdateConnection(const std::shared_ptr<nlohmann::json> &Connection);
|
||||
void UpdateHealth(const std::shared_ptr<nlohmann::json> &Health);
|
||||
|
||||
[[nodiscard]] const AnalyticsObjects::DeviceInfo &Info() const { return DI_; }
|
||||
|
||||
[[nodiscard]] const AnalyticsObjects::DeviceInfo & Info() const { return DI_; }
|
||||
private:
|
||||
std::string venue_id_;
|
||||
std::string boardId_;
|
||||
AnalyticsObjects::DeviceInfo DI_;
|
||||
AnalyticsObjects::DeviceTimePoint tp_base_;
|
||||
bool got_health = false,
|
||||
got_connection = false,
|
||||
got_base = false;
|
||||
bool got_health = false, got_connection = false, got_base = false;
|
||||
Poco::Logger &Logger_;
|
||||
inline Poco::Logger & Logger() { return Logger_; }
|
||||
inline Poco::Logger &Logger() { return Logger_; }
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -8,17 +8,17 @@
|
||||
|
||||
#include "Daemon.h"
|
||||
|
||||
#include "Poco/Util/Application.h"
|
||||
#include "Poco/Util/Option.h"
|
||||
#include "Poco/Environment.h"
|
||||
#include "Poco/Net/SSLManager.h"
|
||||
#include "Poco/Util/Application.h"
|
||||
#include "Poco/Util/Option.h"
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
|
||||
#include "StorageService.h"
|
||||
#include "VenueCoordinator.h"
|
||||
#include "StateReceiver.h"
|
||||
#include "DeviceStatusReceiver.h"
|
||||
#include "HealthReceiver.h"
|
||||
#include "StateReceiver.h"
|
||||
#include "StorageService.h"
|
||||
#include "VenueCoordinator.h"
|
||||
#include "WifiClientCache.h"
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
|
||||
@@ -27,31 +27,22 @@ namespace OpenWifi {
|
||||
|
||||
class Daemon *Daemon::instance() {
|
||||
if (instance_ == nullptr) {
|
||||
instance_ = new Daemon(vDAEMON_PROPERTIES_FILENAME,
|
||||
vDAEMON_ROOT_ENV_VAR,
|
||||
vDAEMON_CONFIG_ENV_VAR,
|
||||
vDAEMON_APP_NAME,
|
||||
vDAEMON_BUS_TIMER,
|
||||
SubSystemVec{
|
||||
OpenWifi::StorageService(),
|
||||
StateReceiver(),
|
||||
DeviceStatusReceiver(),
|
||||
HealthReceiver(),
|
||||
VenueCoordinator(),
|
||||
WifiClientCache(),
|
||||
UI_WebSocketClientServer()
|
||||
});
|
||||
instance_ = new Daemon(vDAEMON_PROPERTIES_FILENAME, vDAEMON_ROOT_ENV_VAR,
|
||||
vDAEMON_CONFIG_ENV_VAR, vDAEMON_APP_NAME, vDAEMON_BUS_TIMER,
|
||||
SubSystemVec{OpenWifi::StorageService(), StateReceiver(),
|
||||
DeviceStatusReceiver(), HealthReceiver(),
|
||||
VenueCoordinator(), WifiClientCache(),
|
||||
UI_WebSocketClientServer()});
|
||||
}
|
||||
return instance_;
|
||||
}
|
||||
|
||||
void Daemon::PostInitialization([[maybe_unused]] Poco::Util::Application &self) {
|
||||
}
|
||||
void Daemon::PostInitialization([[maybe_unused]] Poco::Util::Application &self) {}
|
||||
|
||||
void DaemonPostInitialization(Poco::Util::Application &self) {
|
||||
Daemon()->PostInitialization(self);
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int ExitCode;
|
||||
|
||||
36
src/Daemon.h
36
src/Daemon.h
@@ -9,45 +9,43 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <vector>
|
||||
|
||||
#include "Dashboard.h"
|
||||
#include "RESTObjects/RESTAPI_AnalyticsObjects.h"
|
||||
#include "framework/MicroService.h"
|
||||
#include "framework/MicroServiceNames.h"
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
#include "RESTObjects/RESTAPI_AnalyticsObjects.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
[[maybe_unused]] inline static const char * vDAEMON_PROPERTIES_FILENAME = "owanalytics.properties";
|
||||
[[maybe_unused]] inline static const char * vDAEMON_ROOT_ENV_VAR = "OWANALYTICS_ROOT";
|
||||
[[maybe_unused]] inline static const char * vDAEMON_CONFIG_ENV_VAR = "OWANALYTICS_CONFIG";
|
||||
[[maybe_unused]] inline static const char * vDAEMON_APP_NAME = uSERVICE_ANALYTICS.c_str() ;
|
||||
[[maybe_unused]] inline static const char *vDAEMON_PROPERTIES_FILENAME =
|
||||
"owanalytics.properties";
|
||||
[[maybe_unused]] inline static const char *vDAEMON_ROOT_ENV_VAR = "OWANALYTICS_ROOT";
|
||||
[[maybe_unused]] inline static const char *vDAEMON_CONFIG_ENV_VAR = "OWANALYTICS_CONFIG";
|
||||
[[maybe_unused]] inline static const char *vDAEMON_APP_NAME = uSERVICE_ANALYTICS.c_str();
|
||||
[[maybe_unused]] inline static const uint64_t vDAEMON_BUS_TIMER = 10000;
|
||||
|
||||
class Daemon : public MicroService {
|
||||
public:
|
||||
explicit Daemon(const std::string & PropFile,
|
||||
const std::string & RootEnv,
|
||||
const std::string & ConfigEnv,
|
||||
const std::string & AppName,
|
||||
uint64_t BusTimer,
|
||||
const SubSystemVec & SubSystems) :
|
||||
MicroService( PropFile, RootEnv, ConfigEnv, AppName, BusTimer, SubSystems) {};
|
||||
explicit Daemon(const std::string &PropFile, const std::string &RootEnv,
|
||||
const std::string &ConfigEnv, const std::string &AppName, uint64_t BusTimer,
|
||||
const SubSystemVec &SubSystems)
|
||||
: MicroService(PropFile, RootEnv, ConfigEnv, AppName, BusTimer, SubSystems){};
|
||||
|
||||
void PostInitialization(Poco::Util::Application &self);
|
||||
static Daemon *instance();
|
||||
inline OpenWifi::AnalyticsDashboard & GetDashboard() { return DB_; }
|
||||
Poco::Logger & Log() { return Poco::Logger::get(AppName()); }
|
||||
inline OpenWifi::AnalyticsDashboard &GetDashboard() { return DB_; }
|
||||
Poco::Logger &Log() { return Poco::Logger::get(AppName()); }
|
||||
|
||||
private:
|
||||
static Daemon *instance_;
|
||||
OpenWifi::AnalyticsDashboard DB_{};
|
||||
};
|
||||
|
||||
inline Daemon * Daemon() { return Daemon::instance(); }
|
||||
inline Daemon *Daemon() { return Daemon::instance(); }
|
||||
void DaemonPostInitialization(Poco::Util::Application &self);
|
||||
}
|
||||
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -12,10 +12,10 @@
|
||||
namespace OpenWifi {
|
||||
void AnalyticsDashboard::Create() {
|
||||
uint64_t Now = Utils::Now();
|
||||
if(LastRun_==0 || (Now-LastRun_)>120) {
|
||||
if (LastRun_ == 0 || (Now - LastRun_) > 120) {
|
||||
DB_.reset();
|
||||
// Todo: call dashboard creation code.
|
||||
LastRun_ = Now;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -7,18 +7,21 @@
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
#include "RESTObjects/RESTAPI_AnalyticsObjects.h"
|
||||
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
class AnalyticsDashboard {
|
||||
public:
|
||||
void Create();
|
||||
[[nodiscard]] const AnalyticsObjects::Report & Report() const { return DB_;}
|
||||
inline void Reset() { LastRun_=0; DB_.reset(); }
|
||||
[[nodiscard]] const AnalyticsObjects::Report &Report() const { return DB_; }
|
||||
inline void Reset() {
|
||||
LastRun_ = 0;
|
||||
DB_.reset();
|
||||
}
|
||||
|
||||
private:
|
||||
AnalyticsObjects::Report DB_{};
|
||||
uint64_t LastRun_=0;
|
||||
uint64_t LastRun_ = 0;
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -5,13 +5,15 @@
|
||||
#include "DeviceStatusReceiver.h"
|
||||
#include "VenueWatcher.h"
|
||||
#include "fmt/core.h"
|
||||
#include "framework/KafkaTopics.h"
|
||||
#include "framework/KafkaManager.h"
|
||||
#include "framework/KafkaTopics.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
int DeviceStatusReceiver::Start() {
|
||||
Running_ = true;
|
||||
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) { this->DeviceStatusReceived(Key,Payload); };
|
||||
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) {
|
||||
this->DeviceStatusReceived(Key, Payload);
|
||||
};
|
||||
DeviceStateWatcherId_ = KafkaManager()->RegisterTopicWatcher(KafkaTopics::CONNECTION, F);
|
||||
Worker_.start(*this);
|
||||
return 0;
|
||||
@@ -27,9 +29,9 @@ namespace OpenWifi {
|
||||
void DeviceStatusReceiver::run() {
|
||||
Utils::SetThreadName("dev-status");
|
||||
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
|
||||
while(Note && Running_) {
|
||||
while (Note && Running_) {
|
||||
auto Msg = dynamic_cast<DeviceStatusMessage *>(Note.get());
|
||||
if(Msg!= nullptr) {
|
||||
if (Msg != nullptr) {
|
||||
try {
|
||||
nlohmann::json msg = nlohmann::json::parse(Msg->Payload());
|
||||
if (msg.contains(uCentralProtocol::PAYLOAD)) {
|
||||
@@ -38,8 +40,8 @@ namespace OpenWifi {
|
||||
uint64_t SerialNumber = Utils::SerialNumberToInt(Msg->Key());
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
for(const auto &[venue,devices]:Notifiers_) {
|
||||
if(devices.find(SerialNumber)!=cend(devices)) {
|
||||
for (const auto &[venue, devices] : Notifiers_) {
|
||||
if (devices.find(SerialNumber) != cend(devices)) {
|
||||
auto connection_data = std::make_shared<nlohmann::json>(payload);
|
||||
venue->PostConnection(SerialNumber, connection_data);
|
||||
break;
|
||||
@@ -49,23 +51,23 @@ namespace OpenWifi {
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger().log(E);
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
} else {
|
||||
|
||||
}
|
||||
Note = Queue_.waitDequeueNotification();
|
||||
}
|
||||
}
|
||||
|
||||
void DeviceStatusReceiver::Register(const std::vector <uint64_t> &SerialNumber, VenueWatcher *VW) {
|
||||
void DeviceStatusReceiver::Register(const std::vector<uint64_t> &SerialNumber,
|
||||
VenueWatcher *VW) {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
std::set<uint64_t> NewSerialNumbers;
|
||||
std::copy(SerialNumber.begin(),SerialNumber.end(),std::inserter(NewSerialNumbers,NewSerialNumbers.begin()));
|
||||
std::copy(SerialNumber.begin(), SerialNumber.end(),
|
||||
std::inserter(NewSerialNumbers, NewSerialNumbers.begin()));
|
||||
auto it = Notifiers_.find(VW);
|
||||
if(it==end(Notifiers_))
|
||||
Notifiers_[VW]=NewSerialNumbers;
|
||||
if (it == end(Notifiers_))
|
||||
Notifiers_[VW] = NewSerialNumbers;
|
||||
else
|
||||
it->second = NewSerialNumbers;
|
||||
}
|
||||
@@ -75,9 +77,10 @@ namespace OpenWifi {
|
||||
Notifiers_.erase(VW);
|
||||
}
|
||||
|
||||
void DeviceStatusReceiver::DeviceStatusReceived(const std::string &Key, const std::string &Payload) {
|
||||
void DeviceStatusReceiver::DeviceStatusReceived(const std::string &Key,
|
||||
const std::string &Payload) {
|
||||
std::lock_guard G(Mutex_);
|
||||
poco_debug(Logger(),fmt::format("Device({}): Connection/Ping message.", Key));
|
||||
Queue_.enqueueNotification( new DeviceStatusMessage(Key,Payload));
|
||||
poco_debug(Logger(), fmt::format("Device({}): Connection/Ping message.", Key));
|
||||
Queue_.enqueueNotification(new DeviceStatusMessage(Key, Payload));
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,18 +4,18 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "Poco/NotificationQueue.h"
|
||||
#include "Poco/Notification.h"
|
||||
#include "Poco/NotificationQueue.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
class DeviceStatusMessage : public Poco::Notification {
|
||||
public:
|
||||
explicit DeviceStatusMessage(const std::string &Key, const std::string &Payload ) :
|
||||
Key_(Key),
|
||||
Payload_(Payload) {}
|
||||
const std::string & Key() { return Key_; }
|
||||
const std::string & Payload() { return Payload_; }
|
||||
explicit DeviceStatusMessage(const std::string &Key, const std::string &Payload)
|
||||
: Key_(Key), Payload_(Payload) {}
|
||||
const std::string &Key() { return Key_; }
|
||||
const std::string &Payload() { return Payload_; }
|
||||
|
||||
private:
|
||||
std::string Key_;
|
||||
std::string Payload_;
|
||||
@@ -25,7 +25,6 @@ namespace OpenWifi {
|
||||
|
||||
class DeviceStatusReceiver : public SubSystemServer, Poco::Runnable {
|
||||
public:
|
||||
|
||||
static auto instance() {
|
||||
static auto instance_ = new DeviceStatusReceiver;
|
||||
return instance_;
|
||||
@@ -34,24 +33,22 @@ namespace OpenWifi {
|
||||
int Start() override;
|
||||
void Stop() override;
|
||||
void run() override;
|
||||
void DeviceStatusReceived( const std::string & Key, const std::string & Payload);
|
||||
void Register(const std::vector<uint64_t> & SerialNumber, VenueWatcher *VW);
|
||||
void DeviceStatusReceived(const std::string &Key, const std::string &Payload);
|
||||
void Register(const std::vector<uint64_t> &SerialNumber, VenueWatcher *VW);
|
||||
void DeRegister(VenueWatcher *VW);
|
||||
|
||||
private:
|
||||
// map of mac(as int), list of (id,func)
|
||||
std::map<VenueWatcher *, std::set<uint64_t>> Notifiers_;
|
||||
uint64_t DeviceStateWatcherId_=0;
|
||||
uint64_t DeviceStateWatcherId_ = 0;
|
||||
Poco::NotificationQueue Queue_;
|
||||
Poco::Thread Worker_;
|
||||
std::atomic_bool Running_=false;
|
||||
std::atomic_bool Running_ = false;
|
||||
|
||||
DeviceStatusReceiver() noexcept:
|
||||
SubSystemServer("DeviceStatus", "DEV-STATUS-RECEIVER", "devicestatus.receiver")
|
||||
{
|
||||
}
|
||||
DeviceStatusReceiver() noexcept
|
||||
: SubSystemServer("DeviceStatus", "DEV-STATUS-RECEIVER", "devicestatus.receiver") {}
|
||||
};
|
||||
|
||||
inline auto DeviceStatusReceiver() { return DeviceStatusReceiver::instance(); }
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,14 +4,16 @@
|
||||
|
||||
#include "HealthReceiver.h"
|
||||
#include "VenueWatcher.h"
|
||||
#include "fmt/core.h"
|
||||
#include "framework/KafkaManager.h"
|
||||
#include "framework/KafkaTopics.h"
|
||||
#include "fmt/core.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
int HealthReceiver::Start() {
|
||||
Running_ = true;
|
||||
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) { this->HealthReceived(Key,Payload); };
|
||||
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) {
|
||||
this->HealthReceived(Key, Payload);
|
||||
};
|
||||
HealthWatcherId_ = KafkaManager()->RegisterTopicWatcher(KafkaTopics::HEALTHCHECK, F);
|
||||
Worker_.start(*this);
|
||||
return 0;
|
||||
@@ -27,9 +29,9 @@ namespace OpenWifi {
|
||||
void HealthReceiver::run() {
|
||||
Utils::SetThreadName("dev-health");
|
||||
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
|
||||
while(Note && Running_) {
|
||||
while (Note && Running_) {
|
||||
auto Msg = dynamic_cast<HealthMessage *>(Note.get());
|
||||
if(Msg!= nullptr) {
|
||||
if (Msg != nullptr) {
|
||||
try {
|
||||
nlohmann::json msg = nlohmann::json::parse(Msg->Payload());
|
||||
if (msg.contains(uCentralProtocol::PAYLOAD)) {
|
||||
@@ -38,8 +40,8 @@ namespace OpenWifi {
|
||||
uint64_t SerialNumber = Utils::SerialNumberToInt(Msg->Key());
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
for(const auto &[venue,devices]:Notifiers_) {
|
||||
if(devices.find(SerialNumber)!=cend(devices)) {
|
||||
for (const auto &[venue, devices] : Notifiers_) {
|
||||
if (devices.find(SerialNumber) != cend(devices)) {
|
||||
auto health_data = std::make_shared<nlohmann::json>(payload);
|
||||
venue->PostHealth(SerialNumber, health_data);
|
||||
break;
|
||||
@@ -49,23 +51,22 @@ namespace OpenWifi {
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger().log(E);
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
} else {
|
||||
|
||||
}
|
||||
Note = Queue_.waitDequeueNotification();
|
||||
}
|
||||
}
|
||||
|
||||
void HealthReceiver::Register(const std::vector <uint64_t> &SerialNumber, VenueWatcher *VW) {
|
||||
void HealthReceiver::Register(const std::vector<uint64_t> &SerialNumber, VenueWatcher *VW) {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
std::set<uint64_t> NewSerialNumbers;
|
||||
std::copy(SerialNumber.begin(),SerialNumber.end(),std::inserter(NewSerialNumbers,NewSerialNumbers.begin()));
|
||||
std::copy(SerialNumber.begin(), SerialNumber.end(),
|
||||
std::inserter(NewSerialNumbers, NewSerialNumbers.begin()));
|
||||
auto it = Notifiers_.find(VW);
|
||||
if(it==end(Notifiers_))
|
||||
Notifiers_[VW]=NewSerialNumbers;
|
||||
if (it == end(Notifiers_))
|
||||
Notifiers_[VW] = NewSerialNumbers;
|
||||
else
|
||||
it->second = NewSerialNumbers;
|
||||
}
|
||||
@@ -77,7 +78,7 @@ namespace OpenWifi {
|
||||
|
||||
void HealthReceiver::HealthReceived(const std::string &Key, const std::string &Payload) {
|
||||
std::lock_guard G(Mutex_);
|
||||
poco_debug(Logger(),fmt::format("Device({}): Health message.", Key));
|
||||
Queue_.enqueueNotification( new HealthMessage(Key,Payload));
|
||||
poco_debug(Logger(), fmt::format("Device({}): Health message.", Key));
|
||||
Queue_.enqueueNotification(new HealthMessage(Key, Payload));
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,18 +4,18 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "Poco/Notification.h"
|
||||
#include "Poco/NotificationQueue.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
class HealthMessage : public Poco::Notification {
|
||||
public:
|
||||
explicit HealthMessage(const std::string &Key, const std::string &Payload ) :
|
||||
Key_(Key),
|
||||
Payload_(Payload) {}
|
||||
const std::string & Key() { return Key_; }
|
||||
const std::string & Payload() { return Payload_; }
|
||||
explicit HealthMessage(const std::string &Key, const std::string &Payload)
|
||||
: Key_(Key), Payload_(Payload) {}
|
||||
const std::string &Key() { return Key_; }
|
||||
const std::string &Payload() { return Payload_; }
|
||||
|
||||
private:
|
||||
std::string Key_;
|
||||
std::string Payload_;
|
||||
@@ -25,7 +25,6 @@ namespace OpenWifi {
|
||||
|
||||
class HealthReceiver : public SubSystemServer, Poco::Runnable {
|
||||
public:
|
||||
|
||||
static auto instance() {
|
||||
static auto instance_ = new HealthReceiver;
|
||||
return instance_;
|
||||
@@ -34,24 +33,22 @@ namespace OpenWifi {
|
||||
int Start() override;
|
||||
void Stop() override;
|
||||
void run() override;
|
||||
void HealthReceived( const std::string & Key, const std::string & Payload);
|
||||
void Register(const std::vector<uint64_t> & SerialNumber, VenueWatcher *VW);
|
||||
void HealthReceived(const std::string &Key, const std::string &Payload);
|
||||
void Register(const std::vector<uint64_t> &SerialNumber, VenueWatcher *VW);
|
||||
void DeRegister(VenueWatcher *VW);
|
||||
|
||||
private:
|
||||
// map of mac(as int), list of (id,func)
|
||||
std::map<VenueWatcher *, std::set<uint64_t>> Notifiers_;
|
||||
uint64_t HealthWatcherId_=0;
|
||||
uint64_t HealthWatcherId_ = 0;
|
||||
Poco::NotificationQueue Queue_;
|
||||
Poco::Thread Worker_;
|
||||
std::atomic_bool Running_=false;
|
||||
std::atomic_bool Running_ = false;
|
||||
|
||||
HealthReceiver() noexcept:
|
||||
SubSystemServer("HealthReceiver", "HEALTH-RECEIVER", "health.receiver")
|
||||
{
|
||||
}
|
||||
HealthReceiver() noexcept
|
||||
: SubSystemServer("HealthReceiver", "HEALTH-RECEIVER", "health.receiver") {}
|
||||
};
|
||||
|
||||
inline auto HealthReceiver() { return HealthReceiver::instance(); }
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -10,11 +10,12 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
template <typename DB> void ReturnRecordList(const char *ArrayName,DB & DBInstance, RESTAPIHandler & R) {
|
||||
template <typename DB>
|
||||
void ReturnRecordList(const char *ArrayName, DB &DBInstance, RESTAPIHandler &R) {
|
||||
Poco::JSON::Array ObjArr;
|
||||
for(const auto &i:R.SelectedRecords()) {
|
||||
for (const auto &i : R.SelectedRecords()) {
|
||||
typename DB::RecordName Rec;
|
||||
if(DBInstance.GetRecord("id",i,Rec)) {
|
||||
if (DBInstance.GetRecord("id", i, Rec)) {
|
||||
Poco::JSON::Object Obj;
|
||||
Rec.to_json(Obj);
|
||||
ObjArr.add(Obj);
|
||||
@@ -27,19 +28,20 @@ namespace OpenWifi {
|
||||
return R.ReturnObject(Answer);
|
||||
}
|
||||
|
||||
template <typename T> void MakeJSONObjectArray(const char * ArrayName, const std::vector<T> & V, RESTAPIHandler & R) {
|
||||
template <typename T>
|
||||
void MakeJSONObjectArray(const char *ArrayName, const std::vector<T> &V, RESTAPIHandler &R) {
|
||||
Poco::JSON::Array ObjArray;
|
||||
for(const auto &i:V) {
|
||||
for (const auto &i : V) {
|
||||
Poco::JSON::Object Obj;
|
||||
i.to_json(Obj);
|
||||
ObjArray.add(Obj);
|
||||
}
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set(ArrayName,ObjArray);
|
||||
Answer.set(ArrayName, ObjArray);
|
||||
return R.ReturnObject(Answer);
|
||||
}
|
||||
|
||||
template<typename DB>
|
||||
template <typename DB>
|
||||
void ListHandler(const char *BlockName, DB &DBInstance, RESTAPIHandler &R) {
|
||||
|
||||
typedef typename DB::RecordVec RecVec;
|
||||
@@ -57,12 +59,12 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
template <typename DBType> void ReturnFieldList(DBType & DB, RESTAPIHandler &H) {
|
||||
template <typename DBType> void ReturnFieldList(DBType &DB, RESTAPIHandler &H) {
|
||||
Types::StringVec Fields;
|
||||
DB.GetFieldNames(Fields);
|
||||
Poco::JSON::Object Answer;
|
||||
RESTAPI_utils::field_to_json(Answer,"list",Fields);
|
||||
RESTAPI_utils::field_to_json(Answer, "list", Fields);
|
||||
return H.ReturnObject(Answer);
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -9,22 +9,22 @@
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_board_devices_handler::DoGet() {
|
||||
|
||||
auto id = GetBinding("id","");
|
||||
auto id = GetBinding("id", "");
|
||||
|
||||
if(id.empty()) {
|
||||
if (id.empty()) {
|
||||
return BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
}
|
||||
|
||||
AnalyticsObjects::BoardInfo BI;
|
||||
if(!StorageService()->BoardsDB().GetRecord("id",id,BI)) {
|
||||
if (!StorageService()->BoardsDB().GetRecord("id", id, BI)) {
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
AnalyticsObjects::DeviceInfoList DIL;
|
||||
VenueCoordinator()->GetDevices(id,DIL);
|
||||
VenueCoordinator()->GetDevices(id, DIL);
|
||||
|
||||
Poco::JSON::Object Answer;
|
||||
DIL.to_json(Answer);
|
||||
return ReturnObject(Answer);
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,29 +4,28 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
#include "StorageService.h"
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class RESTAPI_board_devices_handler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_board_devices_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
|
||||
RESTAPI_board_devices_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
|
||||
RESTAPI_GenericServerAccounting &Server,
|
||||
uint64_t TransactionId, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>{
|
||||
Poco::Net::HTTPRequest::HTTP_GET,
|
||||
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
TransactionId,
|
||||
Internal){}
|
||||
Server, TransactionId, Internal) {}
|
||||
|
||||
static auto PathName() { return std::list<std::string>{"/api/v1/board/{id}/devices"}; };
|
||||
|
||||
private:
|
||||
BoardsDB & DB_=StorageService()->BoardsDB();
|
||||
BoardsDB &DB_ = StorageService()->BoardsDB();
|
||||
void DoGet() final;
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
void DoDelete() final {};
|
||||
void DoPost() final{};
|
||||
void DoPut() final{};
|
||||
void DoDelete() final{};
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -7,13 +7,13 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_board_handler::DoGet() {
|
||||
auto id = GetBinding("id","");
|
||||
if(id.empty()) {
|
||||
auto id = GetBinding("id", "");
|
||||
if (id.empty()) {
|
||||
return BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
}
|
||||
|
||||
AnalyticsObjects::BoardInfo B;
|
||||
if(!StorageService()->BoardsDB().GetRecord("id",id,B)) {
|
||||
if (!StorageService()->BoardsDB().GetRecord("id", id, B)) {
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
@@ -23,39 +23,39 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void RESTAPI_board_handler::DoDelete() {
|
||||
auto id = GetBinding("id","");
|
||||
if(id.empty()) {
|
||||
auto id = GetBinding("id", "");
|
||||
if (id.empty()) {
|
||||
return BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
}
|
||||
|
||||
AnalyticsObjects::BoardInfo B;
|
||||
if(!StorageService()->BoardsDB().GetRecord("id",id,B)) {
|
||||
if (!StorageService()->BoardsDB().GetRecord("id", id, B)) {
|
||||
return NotFound();
|
||||
}
|
||||
VenueCoordinator()->StopBoard(id);
|
||||
StorageService()->BoardsDB().DeleteRecord("id",id);
|
||||
StorageService()->BoardsDB().DeleteRecord("id", id);
|
||||
StorageService()->TimePointsDB().DeleteBoard(id);
|
||||
return OK();
|
||||
}
|
||||
|
||||
void RESTAPI_board_handler::DoPost() {
|
||||
auto id= GetBinding("id","");
|
||||
if(id.empty()) {
|
||||
auto id = GetBinding("id", "");
|
||||
if (id.empty()) {
|
||||
return BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
}
|
||||
|
||||
const auto & RawObject = ParsedBody_;
|
||||
const auto &RawObject = ParsedBody_;
|
||||
AnalyticsObjects::BoardInfo NewObject;
|
||||
if(!NewObject.from_json(RawObject)) {
|
||||
if (!NewObject.from_json(RawObject)) {
|
||||
return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
|
||||
}
|
||||
|
||||
ProvObjects::CreateObjectInfo(RawObject,UserInfo_.userinfo,NewObject.info);
|
||||
ProvObjects::CreateObjectInfo(RawObject, UserInfo_.userinfo, NewObject.info);
|
||||
|
||||
if(StorageService()->BoardsDB().CreateRecord(NewObject)) {
|
||||
if (StorageService()->BoardsDB().CreateRecord(NewObject)) {
|
||||
VenueCoordinator()->AddBoard(NewObject.info.id);
|
||||
AnalyticsObjects::BoardInfo NewBoard;
|
||||
StorageService()->BoardsDB().GetRecord("id",NewObject.info.id,NewBoard);
|
||||
StorageService()->BoardsDB().GetRecord("id", NewObject.info.id, NewBoard);
|
||||
Poco::JSON::Object Answer;
|
||||
NewBoard.to_json(Answer);
|
||||
return ReturnObject(Answer);
|
||||
@@ -64,39 +64,39 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void RESTAPI_board_handler::DoPut() {
|
||||
auto id= GetBinding("id","");
|
||||
if(id.empty()) {
|
||||
auto id = GetBinding("id", "");
|
||||
if (id.empty()) {
|
||||
return BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
}
|
||||
|
||||
AnalyticsObjects::BoardInfo Existing;
|
||||
if(!StorageService()->BoardsDB().GetRecord("id",id,Existing)) {
|
||||
if (!StorageService()->BoardsDB().GetRecord("id", id, Existing)) {
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
const auto & RawObject = ParsedBody_;
|
||||
const auto &RawObject = ParsedBody_;
|
||||
AnalyticsObjects::BoardInfo NewObject;
|
||||
if(!NewObject.from_json(RawObject)) {
|
||||
if (!NewObject.from_json(RawObject)) {
|
||||
return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
|
||||
}
|
||||
|
||||
ProvObjects::UpdateObjectInfo(RawObject,UserInfo_.userinfo,Existing.info);
|
||||
ProvObjects::UpdateObjectInfo(RawObject, UserInfo_.userinfo, Existing.info);
|
||||
|
||||
if(RawObject->has("venueList")) {
|
||||
if(NewObject.venueList.empty()) {
|
||||
if (RawObject->has("venueList")) {
|
||||
if (NewObject.venueList.empty()) {
|
||||
return BadRequest(RESTAPI::Errors::VenueMustExist);
|
||||
}
|
||||
Existing.venueList = NewObject.venueList;
|
||||
}
|
||||
|
||||
if(StorageService()->BoardsDB().UpdateRecord("id",Existing.info.id,Existing)) {
|
||||
if (StorageService()->BoardsDB().UpdateRecord("id", Existing.info.id, Existing)) {
|
||||
VenueCoordinator()->UpdateBoard(Existing.info.id);
|
||||
AnalyticsObjects::BoardInfo NewBoard;
|
||||
StorageService()->BoardsDB().GetRecord("id",Existing.info.id,NewBoard);
|
||||
StorageService()->BoardsDB().GetRecord("id", Existing.info.id, NewBoard);
|
||||
Poco::JSON::Object Answer;
|
||||
NewBoard.to_json(Answer);
|
||||
return ReturnObject(Answer);
|
||||
}
|
||||
return InternalError(RESTAPI::Errors::RecordNotUpdated);
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,32 +4,31 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
#include "StorageService.h"
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class RESTAPI_board_handler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_board_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
|
||||
RESTAPI_board_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
|
||||
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
|
||||
bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>{
|
||||
Poco::Net::HTTPRequest::HTTP_GET,
|
||||
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_POST,
|
||||
Poco::Net::HTTPRequest::HTTP_PUT,
|
||||
Poco::Net::HTTPRequest::HTTP_DELETE,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
TransactionId,
|
||||
Internal){}
|
||||
Server, TransactionId, Internal) {}
|
||||
|
||||
static auto PathName() { return std::list<std::string>{"/api/v1/board/{id}"}; };
|
||||
|
||||
private:
|
||||
BoardsDB & DB_=StorageService()->BoardsDB();
|
||||
BoardsDB &DB_ = StorageService()->BoardsDB();
|
||||
void DoGet() final;
|
||||
void DoPost() final;
|
||||
void DoPut() final;
|
||||
void DoDelete() final;
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -3,19 +3,19 @@
|
||||
//
|
||||
|
||||
#include "RESTAPI_board_list_handler.h"
|
||||
#include "StorageService.h"
|
||||
#include "RESTAPI/RESTAPI_analytics_db_helpers.h"
|
||||
#include "StorageService.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
void RESTAPI_board_list_handler::DoGet() {
|
||||
auto forVenue = GetParameter("forVenue","");
|
||||
auto forVenue = GetParameter("forVenue", "");
|
||||
|
||||
if(!forVenue.empty()) {
|
||||
if (!forVenue.empty()) {
|
||||
std::vector<AnalyticsObjects::BoardInfo> Boards;
|
||||
auto F = [&](const AnalyticsObjects::BoardInfo &B) -> bool {
|
||||
if(!B.venueList.empty()) {
|
||||
for(const auto &venue:B.venueList) {
|
||||
if(venue.id == forVenue) {
|
||||
if (!B.venueList.empty()) {
|
||||
for (const auto &venue : B.venueList) {
|
||||
if (venue.id == forVenue) {
|
||||
Boards.emplace_back(B);
|
||||
break;
|
||||
}
|
||||
@@ -24,10 +24,10 @@ namespace OpenWifi {
|
||||
return true;
|
||||
};
|
||||
DB_.Iterate(F);
|
||||
return ReturnObject("boards",Boards);
|
||||
return ReturnObject("boards", Boards);
|
||||
}
|
||||
|
||||
return ListHandler<BoardsDB>("boards", DB_, *this);
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,29 +4,28 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
#include "StorageService.h"
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class RESTAPI_board_list_handler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_board_list_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
|
||||
RESTAPI_board_list_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
|
||||
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
|
||||
bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>{
|
||||
Poco::Net::HTTPRequest::HTTP_GET,
|
||||
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
TransactionId,
|
||||
Internal){}
|
||||
Server, TransactionId, Internal) {}
|
||||
|
||||
static auto PathName() { return std::list<std::string>{"/api/v1/boards"}; };
|
||||
|
||||
private:
|
||||
BoardsDB & DB_=StorageService()->BoardsDB();
|
||||
BoardsDB &DB_ = StorageService()->BoardsDB();
|
||||
void DoGet() final;
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
void DoDelete() final {};
|
||||
void DoPost() final{};
|
||||
void DoPut() final{};
|
||||
void DoDelete() final{};
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -8,72 +8,77 @@
|
||||
#include <algorithm>
|
||||
|
||||
namespace OpenWifi {
|
||||
typedef std::vector<std::pair<std::uint64_t , std::uint64_t >> bucket_timespans;
|
||||
typedef std::vector< std::vector<AnalyticsObjects::DeviceTimePoint>> split_points;
|
||||
typedef std::vector<std::pair<std::uint64_t, std::uint64_t>> bucket_timespans;
|
||||
typedef std::vector<std::vector<AnalyticsObjects::DeviceTimePoint>> split_points;
|
||||
|
||||
template <typename X, typename M> void AverageAPData( X T, const std::vector<M> &Values, AnalyticsObjects::AveragePoint &P) {
|
||||
if(Values.empty())
|
||||
template <typename X, typename M>
|
||||
void AverageAPData(X T, const std::vector<M> &Values, AnalyticsObjects::AveragePoint &P) {
|
||||
if (Values.empty())
|
||||
return;
|
||||
double sum = 0.0;
|
||||
for(const auto &v:Values) {
|
||||
for (const auto &v : Values) {
|
||||
sum += (v.ap_data.*T);
|
||||
if((v.ap_data.*T)!=0) {
|
||||
if ((v.ap_data.*T) != 0) {
|
||||
P.min = std::min(P.min, (v.ap_data.*T));
|
||||
}
|
||||
P.max = std::min(P.max,(v.ap_data.*T));
|
||||
P.max = std::min(P.max, (v.ap_data.*T));
|
||||
}
|
||||
P.avg = sum / (double) Values.size();
|
||||
P.avg = sum / (double)Values.size();
|
||||
}
|
||||
|
||||
template <typename X, typename M> void AverageRadioData( X T, const std::vector<M> &Values, AnalyticsObjects::AveragePoint &P) {
|
||||
if(Values.empty())
|
||||
template <typename X, typename M>
|
||||
void AverageRadioData(X T, const std::vector<M> &Values, AnalyticsObjects::AveragePoint &P) {
|
||||
if (Values.empty())
|
||||
return;
|
||||
double sum = 0.0;
|
||||
uint32_t num_values = 0;
|
||||
for(const auto &value:Values) {
|
||||
for(const auto &radio:value.radio_data) {
|
||||
for (const auto &value : Values) {
|
||||
for (const auto &radio : value.radio_data) {
|
||||
num_values++;
|
||||
sum += (radio.*T);
|
||||
if((radio.*T)!=0) {
|
||||
P.min = std::min((double) P.min, (double) (radio.*T));
|
||||
if ((radio.*T) != 0) {
|
||||
P.min = std::min((double)P.min, (double)(radio.*T));
|
||||
}
|
||||
P.max = std::max((double)P.max, (double)(radio.*T));
|
||||
}
|
||||
}
|
||||
if(num_values)
|
||||
P.avg = sum / (double) num_values;
|
||||
if (num_values)
|
||||
P.avg = sum / (double)num_values;
|
||||
else
|
||||
P.avg = 0.0;
|
||||
}
|
||||
|
||||
static void NewSort(const AnalyticsObjects::DeviceTimePointList &l,split_points &sp) {
|
||||
static void NewSort(const AnalyticsObjects::DeviceTimePointList &l, split_points &sp) {
|
||||
|
||||
struct {
|
||||
bool operator()(const AnalyticsObjects::DeviceTimePoint &lhs, const AnalyticsObjects::DeviceTimePoint &rhs) const {
|
||||
if (lhs.device_info.serialNumber < rhs.device_info.serialNumber) return true;
|
||||
if (lhs.device_info.serialNumber > rhs.device_info.serialNumber) return false;
|
||||
bool operator()(const AnalyticsObjects::DeviceTimePoint &lhs,
|
||||
const AnalyticsObjects::DeviceTimePoint &rhs) const {
|
||||
if (lhs.device_info.serialNumber < rhs.device_info.serialNumber)
|
||||
return true;
|
||||
if (lhs.device_info.serialNumber > rhs.device_info.serialNumber)
|
||||
return false;
|
||||
return lhs.timestamp < rhs.timestamp;
|
||||
}
|
||||
} sort_serial_ts;
|
||||
|
||||
// attempt at finding an interval
|
||||
AnalyticsObjects::DeviceTimePointList tmp{l};
|
||||
std::sort(tmp.points.begin(),tmp.points.end(),sort_serial_ts);
|
||||
std::sort(tmp.points.begin(), tmp.points.end(), sort_serial_ts);
|
||||
|
||||
std::string cur_ser;
|
||||
std::uint64_t cur_int=0,start_val, last_val, first_val = 0;
|
||||
for(const auto &point:tmp.points) {
|
||||
if(cur_ser.empty()) {
|
||||
std::uint64_t cur_int = 0, start_val, last_val, first_val = 0;
|
||||
for (const auto &point : tmp.points) {
|
||||
if (cur_ser.empty()) {
|
||||
start_val = point.timestamp;
|
||||
cur_ser = point.serialNumber;
|
||||
first_val = point.timestamp;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(cur_ser==point.serialNumber) {
|
||||
if (cur_ser == point.serialNumber) {
|
||||
auto this_int = point.timestamp - start_val;
|
||||
if(cur_int) {
|
||||
if(this_int<cur_int) {
|
||||
if (cur_int) {
|
||||
if (this_int < cur_int) {
|
||||
cur_int = this_int;
|
||||
}
|
||||
} else {
|
||||
@@ -89,17 +94,16 @@ namespace OpenWifi {
|
||||
|
||||
// std::cout << "Intervals: " << cur_int << std::endl;
|
||||
|
||||
std::vector<std::pair<std::uint64_t,std::uint64_t>> time_slots; // timeslot 0 has <t1,t2>
|
||||
std::vector<std::pair<std::uint64_t, std::uint64_t>> time_slots; // timeslot 0 has <t1,t2>
|
||||
std::vector<std::set<std::string>> serial_numbers; // serial number already in a timeslot.
|
||||
|
||||
|
||||
std::uint64_t cur_first=first_val,cur_end=0;
|
||||
std::uint64_t cur_first = first_val, cur_end = 0;
|
||||
sp.clear();
|
||||
while(cur_end<last_val) {
|
||||
std::pair<std::uint64_t,std::uint64_t> e;
|
||||
while (cur_end < last_val) {
|
||||
std::pair<std::uint64_t, std::uint64_t> e;
|
||||
e.first = cur_first;
|
||||
e.second = e.first + cur_int-1;
|
||||
cur_first = e.second+1;
|
||||
e.second = e.first + cur_int - 1;
|
||||
cur_first = e.second + 1;
|
||||
cur_end = e.second;
|
||||
time_slots.emplace_back(e);
|
||||
std::set<std::string> q;
|
||||
@@ -108,100 +112,115 @@ namespace OpenWifi {
|
||||
sp.emplace_back(qq);
|
||||
}
|
||||
|
||||
for(const auto &point:tmp.points) {
|
||||
std::uint64_t slot_index=0;
|
||||
for(const auto &slot:time_slots) {
|
||||
if(point.timestamp >= slot.first && point.timestamp <= slot.second) {
|
||||
for (const auto &point : tmp.points) {
|
||||
std::uint64_t slot_index = 0;
|
||||
for (const auto &slot : time_slots) {
|
||||
if (point.timestamp >= slot.first && point.timestamp <= slot.second) {
|
||||
serial_numbers[slot_index].insert(point.serialNumber);
|
||||
sp[slot_index].emplace_back(point);
|
||||
}
|
||||
slot_index++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void RESTAPI_board_timepoint_handler::DoGet() {
|
||||
auto id = GetBinding("id","");
|
||||
if(id.empty() || !Utils::ValidUUID(id)) {
|
||||
auto id = GetBinding("id", "");
|
||||
if (id.empty() || !Utils::ValidUUID(id)) {
|
||||
return BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
}
|
||||
|
||||
AnalyticsObjects::BoardInfo B;
|
||||
if(!StorageService()->BoardsDB().GetRecord("id",id,B)) {
|
||||
if (!StorageService()->BoardsDB().GetRecord("id", id, B)) {
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
auto fromDate = GetParameter("fromDate",0);
|
||||
auto endDate = GetParameter("endDate",0);
|
||||
auto fromDate = GetParameter("fromDate", 0);
|
||||
auto endDate = GetParameter("endDate", 0);
|
||||
std::uint64_t maxRecords;
|
||||
if(Request->has("limit"))
|
||||
if (Request->has("limit"))
|
||||
maxRecords = QB_.Limit;
|
||||
else
|
||||
maxRecords = GetParameter("maxRecords",1000);
|
||||
maxRecords = GetParameter("maxRecords", 1000);
|
||||
|
||||
auto statsOnly = GetBoolParameter("statsOnly");
|
||||
auto pointsOnly = GetBoolParameter("pointsOnly");
|
||||
auto pointsStatsOnly = GetBoolParameter("pointsStatsOnly");
|
||||
|
||||
if(statsOnly) {
|
||||
if (statsOnly) {
|
||||
AnalyticsObjects::DeviceTimePointStats DTPS;
|
||||
Poco::JSON::Object Answer;
|
||||
DB_.GetStats(id,DTPS);
|
||||
DB_.GetStats(id, DTPS);
|
||||
DTPS.to_json(Answer);
|
||||
return ReturnObject(Answer);
|
||||
}
|
||||
|
||||
AnalyticsObjects::DeviceTimePointList Points;
|
||||
StorageService()->TimePointsDB().SelectRecords(id,fromDate, endDate, maxRecords, Points.points);
|
||||
std::cout << "1 MaxRecords=" << maxRecords << " retrieved=" << Points.points.size() << std::endl;
|
||||
StorageService()->TimePointsDB().SelectRecords(id, fromDate, endDate, maxRecords,
|
||||
Points.points);
|
||||
std::cout << "1 MaxRecords=" << maxRecords << " retrieved=" << Points.points.size()
|
||||
<< std::endl;
|
||||
|
||||
split_points sp;
|
||||
|
||||
NewSort(Points,sp);
|
||||
NewSort(Points, sp);
|
||||
std::cout << __LINE__ << std::endl;
|
||||
|
||||
Poco::JSON::Object Answer;
|
||||
if(!pointsStatsOnly) {
|
||||
if (!pointsStatsOnly) {
|
||||
Poco::JSON::Array Points_OuterArray;
|
||||
for (const auto &point_list:sp) {
|
||||
for (const auto &point_list : sp) {
|
||||
Poco::JSON::Array Points_InnerArray;
|
||||
for (const auto &point: point_list) {
|
||||
for (const auto &point : point_list) {
|
||||
Poco::JSON::Object O;
|
||||
point.to_json(O);
|
||||
Points_InnerArray.add(O);
|
||||
}
|
||||
Points_OuterArray.add(Points_InnerArray);
|
||||
}
|
||||
Answer.set("points",Points_OuterArray);
|
||||
Answer.set("points", Points_OuterArray);
|
||||
}
|
||||
|
||||
// calculate the stats for each time slot
|
||||
if(!pointsOnly) {
|
||||
if (!pointsOnly) {
|
||||
Poco::JSON::Array Stats_Array;
|
||||
for (const auto &point_list:sp) {
|
||||
for (const auto &point_list : sp) {
|
||||
AnalyticsObjects::DeviceTimePointAnalysis DTPA;
|
||||
|
||||
if(point_list.empty())
|
||||
if (point_list.empty())
|
||||
continue;
|
||||
|
||||
DTPA.timestamp = point_list[0].timestamp;
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::tx_bytes_bw, point_list, DTPA.tx_bytes_bw);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::rx_bytes_bw, point_list, DTPA.rx_bytes_bw);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::rx_dropped_pct, point_list, DTPA.rx_dropped_pct);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::tx_dropped_pct, point_list, DTPA.tx_dropped_pct);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::rx_packets_bw, point_list, DTPA.rx_packets_bw);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::tx_packets_bw, point_list, DTPA.tx_packets_bw);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::rx_errors_pct, point_list, DTPA.rx_errors_pct);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::tx_errors_pct, point_list, DTPA.tx_errors_pct);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::tx_bytes_bw, point_list,
|
||||
DTPA.tx_bytes_bw);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::rx_bytes_bw, point_list,
|
||||
DTPA.rx_bytes_bw);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::rx_dropped_pct, point_list,
|
||||
DTPA.rx_dropped_pct);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::tx_dropped_pct, point_list,
|
||||
DTPA.tx_dropped_pct);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::rx_packets_bw, point_list,
|
||||
DTPA.rx_packets_bw);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::tx_packets_bw, point_list,
|
||||
DTPA.tx_packets_bw);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::rx_errors_pct, point_list,
|
||||
DTPA.rx_errors_pct);
|
||||
AverageAPData(&AnalyticsObjects::APTimePoint::tx_errors_pct, point_list,
|
||||
DTPA.tx_errors_pct);
|
||||
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::noise, point_list, DTPA.noise);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::temperature, point_list, DTPA.temperature);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::tx_power, point_list, DTPA.tx_power);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::active_pct, point_list, DTPA.active_pct);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::busy_pct, point_list, DTPA.busy_pct);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::receive_pct, point_list, DTPA.receive_pct);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::transmit_pct, point_list, DTPA.transmit_pct);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::temperature, point_list,
|
||||
DTPA.temperature);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::tx_power, point_list,
|
||||
DTPA.tx_power);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::active_pct, point_list,
|
||||
DTPA.active_pct);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::busy_pct, point_list,
|
||||
DTPA.busy_pct);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::receive_pct, point_list,
|
||||
DTPA.receive_pct);
|
||||
AverageRadioData(&AnalyticsObjects::RadioTimePoint::transmit_pct, point_list,
|
||||
DTPA.transmit_pct);
|
||||
|
||||
Poco::JSON::Object Stats_point;
|
||||
DTPA.to_json(Stats_point);
|
||||
@@ -214,21 +233,21 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void RESTAPI_board_timepoint_handler::DoDelete() {
|
||||
auto id = GetBinding("id","");
|
||||
if(id.empty() || !Utils::ValidUUID(id)) {
|
||||
auto id = GetBinding("id", "");
|
||||
if (id.empty() || !Utils::ValidUUID(id)) {
|
||||
return BadRequest(RESTAPI::Errors::MissingUUID);
|
||||
}
|
||||
|
||||
AnalyticsObjects::BoardInfo B;
|
||||
if(!StorageService()->BoardsDB().GetRecord("id",id,B)) {
|
||||
if (!StorageService()->BoardsDB().GetRecord("id", id, B)) {
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
auto fromDate = GetParameter("fromDate",0);
|
||||
auto endDate = GetParameter("endDate",0);
|
||||
auto fromDate = GetParameter("fromDate", 0);
|
||||
auto endDate = GetParameter("endDate", 0);
|
||||
|
||||
StorageService()->TimePointsDB().DeleteTimeLine(id,fromDate,endDate);
|
||||
StorageService()->TimePointsDB().DeleteTimeLine(id, fromDate, endDate);
|
||||
return OK();
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,30 +4,29 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
#include "StorageService.h"
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class RESTAPI_board_timepoint_handler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_board_timepoint_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
|
||||
RESTAPI_board_timepoint_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
|
||||
RESTAPI_GenericServerAccounting &Server,
|
||||
uint64_t TransactionId, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>{
|
||||
Poco::Net::HTTPRequest::HTTP_GET,
|
||||
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_DELETE,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
TransactionId,
|
||||
Internal){}
|
||||
Server, TransactionId, Internal) {}
|
||||
|
||||
static auto PathName() { return std::list<std::string>{"/api/v1/board/{id}/timepoints"}; };
|
||||
|
||||
private:
|
||||
TimePointDB & DB_=StorageService()->TimePointsDB();
|
||||
TimePointDB &DB_ = StorageService()->TimePointsDB();
|
||||
void DoGet() final;
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
void DoPost() final{};
|
||||
void DoPut() final{};
|
||||
void DoDelete() final;
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// Created by stephane bourque on 2021-10-23.
|
||||
//
|
||||
|
||||
#include "RESTAPI/RESTAPI_board_list_handler.h"
|
||||
#include "RESTAPI/RESTAPI_board_handler.h"
|
||||
#include "RESTAPI/RESTAPI_board_devices_handler.h"
|
||||
#include "RESTAPI/RESTAPI_board_handler.h"
|
||||
#include "RESTAPI/RESTAPI_board_list_handler.h"
|
||||
#include "RESTAPI/RESTAPI_board_timepoint_handler.h"
|
||||
#include "RESTAPI/RESTAPI_wificlienthistory_handler.h"
|
||||
#include "framework/RESTAPI_SystemCommand.h"
|
||||
@@ -12,31 +12,22 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
Poco::Net::HTTPRequestHandler * RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger & L, RESTAPI_GenericServerAccounting & S,
|
||||
uint64_t TransactionId) {
|
||||
return RESTAPI_Router<
|
||||
RESTAPI_system_command,
|
||||
RESTAPI_board_devices_handler,
|
||||
RESTAPI_board_timepoint_handler,
|
||||
RESTAPI_board_handler,
|
||||
RESTAPI_board_list_handler,
|
||||
RESTAPI_wificlienthistory_handler,
|
||||
RESTAPI_webSocketServer
|
||||
>(Path,Bindings,L, S, TransactionId);
|
||||
Poco::Net::HTTPRequestHandler *
|
||||
RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t TransactionId) {
|
||||
return RESTAPI_Router<RESTAPI_system_command, RESTAPI_board_devices_handler,
|
||||
RESTAPI_board_timepoint_handler, RESTAPI_board_handler,
|
||||
RESTAPI_board_list_handler, RESTAPI_wificlienthistory_handler,
|
||||
RESTAPI_webSocketServer>(Path, Bindings, L, S, TransactionId);
|
||||
}
|
||||
|
||||
Poco::Net::HTTPRequestHandler * RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger & L, RESTAPI_GenericServerAccounting & S,
|
||||
uint64_t TransactionId) {
|
||||
return RESTAPI_Router_I<
|
||||
RESTAPI_system_command,
|
||||
RESTAPI_board_devices_handler,
|
||||
RESTAPI_board_timepoint_handler,
|
||||
RESTAPI_board_handler,
|
||||
RESTAPI_board_list_handler,
|
||||
RESTAPI_wificlienthistory_handler
|
||||
>(Path, Bindings, L, S, TransactionId);
|
||||
Poco::Net::HTTPRequestHandler *
|
||||
RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t TransactionId) {
|
||||
return RESTAPI_Router_I<RESTAPI_system_command, RESTAPI_board_devices_handler,
|
||||
RESTAPI_board_timepoint_handler, RESTAPI_board_handler,
|
||||
RESTAPI_board_list_handler, RESTAPI_wificlienthistory_handler>(
|
||||
Path, Bindings, L, S, TransactionId);
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -3,28 +3,28 @@
|
||||
//
|
||||
|
||||
#include "RESTAPI_wificlienthistory_handler.h"
|
||||
#include "WifiClientCache.h"
|
||||
#include "RESTAPI_analytics_db_helpers.h"
|
||||
#include "WifiClientCache.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
void RESTAPI_wificlienthistory_handler::DoGet() {
|
||||
|
||||
if(GetBoolParameter("orderSpec")) {
|
||||
return ReturnFieldList(DB_,*this);
|
||||
if (GetBoolParameter("orderSpec")) {
|
||||
return ReturnFieldList(DB_, *this);
|
||||
}
|
||||
|
||||
auto venue = ORM::Escape(GetParameter("venue",""));
|
||||
if(venue.empty()) {
|
||||
auto venue = ORM::Escape(GetParameter("venue", ""));
|
||||
if (venue.empty()) {
|
||||
return BadRequest(RESTAPI::Errors::VenueMustExist);
|
||||
}
|
||||
|
||||
if(GetBoolParameter("macsOnly")) {
|
||||
auto macFilter = GetParameter("macFilter","");
|
||||
if (GetBoolParameter("macsOnly")) {
|
||||
auto macFilter = GetParameter("macFilter", "");
|
||||
std::vector<uint64_t> Macs;
|
||||
WifiClientCache()->FindNumbers(venue,macFilter,QB_.Offset, QB_.Limit, Macs);
|
||||
WifiClientCache()->FindNumbers(venue, macFilter, QB_.Offset, QB_.Limit, Macs);
|
||||
Poco::JSON::Array Arr;
|
||||
for(const auto &mac: Macs)
|
||||
for (const auto &mac : Macs)
|
||||
Arr.add(Utils::IntToSerialNumber(mac));
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set("entries", Arr);
|
||||
@@ -32,75 +32,85 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
auto stationId = GetBinding("client");
|
||||
if(!Utils::ValidSerialNumber(stationId)) {
|
||||
if (!Utils::ValidSerialNumber(stationId)) {
|
||||
return BadRequest(RESTAPI::Errors::InvalidSerialNumber);
|
||||
}
|
||||
|
||||
std::string OrderBy{" ORDER BY timestamp DESC "}, Arg;
|
||||
if(HasParameter("orderBy",Arg)) {
|
||||
if(!DB_.PrepareOrderBy(Arg,OrderBy)) {
|
||||
if (HasParameter("orderBy", Arg)) {
|
||||
if (!DB_.PrepareOrderBy(Arg, OrderBy)) {
|
||||
return BadRequest(RESTAPI::Errors::InvalidLOrderBy);
|
||||
}
|
||||
}
|
||||
|
||||
auto fromDate = GetParameter("fromDate",0);
|
||||
auto endDate = GetParameter("endDate",0);
|
||||
auto fromDate = GetParameter("fromDate", 0);
|
||||
auto endDate = GetParameter("endDate", 0);
|
||||
|
||||
WifiClientHistoryDB::RecordVec Results;
|
||||
std::string Where;
|
||||
if(fromDate!=0 && endDate!=0)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp>={} and timestamp<={} ", venue, stationId, fromDate, endDate);
|
||||
else if(fromDate!=0 && endDate==0)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp>={} ", venue, stationId, fromDate);
|
||||
else if(fromDate==0 && endDate!=0)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp<={} ", venue, stationId, endDate);
|
||||
if (fromDate != 0 && endDate != 0)
|
||||
Where = fmt::format(
|
||||
" venue_id='{}' and station_id='{}' and timestamp>={} and timestamp<={} ", venue,
|
||||
stationId, fromDate, endDate);
|
||||
else if (fromDate != 0 && endDate == 0)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp>={} ", venue,
|
||||
stationId, fromDate);
|
||||
else if (fromDate == 0 && endDate != 0)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp<={} ", venue,
|
||||
stationId, endDate);
|
||||
else
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' ", venue, stationId);
|
||||
|
||||
if(GetBoolParameter("countOnly")) {
|
||||
if (GetBoolParameter("countOnly")) {
|
||||
auto Count = DB_.Count(Where);
|
||||
return ReturnCountOnly(Count);
|
||||
}
|
||||
|
||||
StorageService()->WifiClientHistoryDB().GetRecords(QB_.Offset,QB_.Limit, Results, Where, OrderBy);
|
||||
return ReturnObject("entries",Results);
|
||||
StorageService()->WifiClientHistoryDB().GetRecords(QB_.Offset, QB_.Limit, Results, Where,
|
||||
OrderBy);
|
||||
return ReturnObject("entries", Results);
|
||||
}
|
||||
|
||||
void RESTAPI_wificlienthistory_handler::DoDelete() {
|
||||
|
||||
if(UserInfo_.userinfo.userRole!=SecurityObjects::ADMIN && UserInfo_.userinfo.userRole!=SecurityObjects::ROOT) {
|
||||
if (UserInfo_.userinfo.userRole != SecurityObjects::ADMIN &&
|
||||
UserInfo_.userinfo.userRole != SecurityObjects::ROOT) {
|
||||
return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED);
|
||||
}
|
||||
|
||||
auto venue = ORM::Escape(GetParameter("venue",""));
|
||||
if(venue.empty()) {
|
||||
auto venue = ORM::Escape(GetParameter("venue", ""));
|
||||
if (venue.empty()) {
|
||||
return BadRequest(RESTAPI::Errors::VenueMustExist);
|
||||
}
|
||||
|
||||
auto stationId = GetBinding("client");
|
||||
if(!Utils::ValidSerialNumber(stationId)) {
|
||||
if (!Utils::ValidSerialNumber(stationId)) {
|
||||
return BadRequest(RESTAPI::Errors::InvalidSerialNumber);
|
||||
}
|
||||
|
||||
auto fromDate = GetParameter("fromDate",0);
|
||||
auto endDate = GetParameter("endDate",0);
|
||||
auto fromDate = GetParameter("fromDate", 0);
|
||||
auto endDate = GetParameter("endDate", 0);
|
||||
|
||||
WifiClientHistoryDB::RecordVec Results;
|
||||
std::string Where;
|
||||
if(fromDate && endDate)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp>={} and timestamp<={} ", venue, stationId, fromDate, endDate);
|
||||
else if(fromDate && !endDate)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp>={} ", venue, stationId, fromDate);
|
||||
else if(!fromDate && endDate)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp<={} ", venue, stationId, endDate);
|
||||
if (fromDate && endDate)
|
||||
Where = fmt::format(
|
||||
" venue_id='{}' and station_id='{}' and timestamp>={} and timestamp<={} ", venue,
|
||||
stationId, fromDate, endDate);
|
||||
else if (fromDate && !endDate)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp>={} ", venue,
|
||||
stationId, fromDate);
|
||||
else if (!fromDate && endDate)
|
||||
Where = fmt::format(" venue_id='{}' and station_id='{}' and timestamp<={} ", venue,
|
||||
stationId, endDate);
|
||||
else
|
||||
Where = fmt::format("venue_id='{}' and station_id='{}' ", stationId);
|
||||
|
||||
if(StorageService()->WifiClientHistoryDB().DeleteRecords(Where)) {
|
||||
if (StorageService()->WifiClientHistoryDB().DeleteRecords(Where)) {
|
||||
return OK();
|
||||
}
|
||||
|
||||
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,30 +4,32 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
#include "StorageService.h"
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class RESTAPI_wificlienthistory_handler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_wificlienthistory_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
|
||||
RESTAPI_wificlienthistory_handler(const RESTAPIHandler::BindingMap &bindings,
|
||||
Poco::Logger &L, RESTAPI_GenericServerAccounting &Server,
|
||||
uint64_t TransactionId, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>{
|
||||
Poco::Net::HTTPRequest::HTTP_GET,
|
||||
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_DELETE,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
TransactionId,
|
||||
Internal){}
|
||||
Server, TransactionId, Internal) {}
|
||||
|
||||
static auto PathName() { return std::list<std::string>{"/api/v1/wifiClientHistory/{client}", "/api/v1/wifiClientHistory"}; };
|
||||
static auto PathName() {
|
||||
return std::list<std::string>{"/api/v1/wifiClientHistory/{client}",
|
||||
"/api/v1/wifiClientHistory"};
|
||||
};
|
||||
|
||||
private:
|
||||
OpenWifi::WifiClientHistoryDB & DB_=StorageService()->WifiClientHistoryDB();
|
||||
OpenWifi::WifiClientHistoryDB &DB_ = StorageService()->WifiClientHistoryDB();
|
||||
void DoGet() final;
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
void DoPost() final{};
|
||||
void DoPut() final{};
|
||||
void DoDelete() final;
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
File diff suppressed because it is too large
Load Diff
@@ -39,13 +39,9 @@ namespace OpenWifi {
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
|
||||
inline bool operator<(const BoardInfo &bb) const {
|
||||
return info.id < bb.info.id;
|
||||
}
|
||||
inline bool operator<(const BoardInfo &bb) const { return info.id < bb.info.id; }
|
||||
|
||||
inline bool operator==(const BoardInfo &bb) const {
|
||||
return info.id == bb.info.id;
|
||||
}
|
||||
inline bool operator==(const BoardInfo &bb) const { return info.id == bb.info.id; }
|
||||
};
|
||||
|
||||
struct DeviceInfo {
|
||||
@@ -53,7 +49,7 @@ namespace OpenWifi {
|
||||
std::string type;
|
||||
std::string serialNumber;
|
||||
std::string deviceType;
|
||||
uint64_t lastContact = 0 ;
|
||||
uint64_t lastContact = 0;
|
||||
uint64_t lastPing = 0;
|
||||
uint64_t lastState = 0;
|
||||
std::string lastFirmware;
|
||||
@@ -84,36 +80,29 @@ namespace OpenWifi {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
enum wifi_band {
|
||||
band_2g = 0, band_5g = 1, band_6g = 2
|
||||
};
|
||||
enum wifi_band { band_2g = 0, band_5g = 1, band_6g = 2 };
|
||||
|
||||
struct TIDstat_entry {
|
||||
uint64_t rx_msdu = 0,
|
||||
tx_msdu = 0,
|
||||
tx_msdu_failed = 0,
|
||||
tx_msdu_retries = 0;
|
||||
uint64_t rx_msdu = 0, tx_msdu = 0, tx_msdu_failed = 0, tx_msdu_retries = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
struct UE_rate {
|
||||
uint64_t bitrate=0;
|
||||
uint64_t mcs=0;
|
||||
uint64_t nss=0;
|
||||
bool ht=false;
|
||||
bool sgi=false;
|
||||
uint64_t chwidth=0;
|
||||
uint64_t bitrate = 0;
|
||||
uint64_t mcs = 0;
|
||||
uint64_t nss = 0;
|
||||
bool ht = false;
|
||||
bool sgi = false;
|
||||
uint64_t chwidth = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
struct AveragePoint {
|
||||
double min = 0.0,
|
||||
max = 0.0,
|
||||
avg = 0.0;
|
||||
double min = 0.0, max = 0.0, avg = 0.0;
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
@@ -121,49 +110,24 @@ namespace OpenWifi {
|
||||
struct UETimePoint {
|
||||
std::string station;
|
||||
int64_t rssi = 0;
|
||||
uint64_t tx_bytes = 0,
|
||||
rx_bytes = 0,
|
||||
tx_duration = 0,
|
||||
rx_packets = 0,
|
||||
tx_packets = 0,
|
||||
tx_retries = 0,
|
||||
tx_failed = 0,
|
||||
connected = 0,
|
||||
inactive = 0;
|
||||
uint64_t tx_bytes = 0, rx_bytes = 0, tx_duration = 0, rx_packets = 0, tx_packets = 0,
|
||||
tx_retries = 0, tx_failed = 0, connected = 0, inactive = 0;
|
||||
|
||||
double tx_bytes_bw = 0.0 ,
|
||||
rx_bytes_bw = 0.0 ,
|
||||
tx_packets_bw = 0.0 ,
|
||||
rx_packets_bw = 0.0 ,
|
||||
tx_failed_pct = 0.0 ,
|
||||
tx_retries_pct = 0.0 ,
|
||||
tx_duration_pct = 0.0;
|
||||
double tx_bytes_bw = 0.0, rx_bytes_bw = 0.0, tx_packets_bw = 0.0, rx_packets_bw = 0.0,
|
||||
tx_failed_pct = 0.0, tx_retries_pct = 0.0, tx_duration_pct = 0.0;
|
||||
|
||||
uint64_t tx_bytes_delta = 0,
|
||||
rx_bytes_delta = 0,
|
||||
tx_duration_delta = 0,
|
||||
rx_packets_delta = 0,
|
||||
tx_packets_delta = 0,
|
||||
tx_retries_delta = 0,
|
||||
uint64_t tx_bytes_delta = 0, rx_bytes_delta = 0, tx_duration_delta = 0,
|
||||
rx_packets_delta = 0, tx_packets_delta = 0, tx_retries_delta = 0,
|
||||
tx_failed_delta = 0;
|
||||
|
||||
UE_rate tx_rate,
|
||||
rx_rate;
|
||||
UE_rate tx_rate, rx_rate;
|
||||
std::vector<TIDstat_entry> tidstats;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
enum SSID_MODES {
|
||||
unknown = 0,
|
||||
ap,
|
||||
mesh,
|
||||
sta,
|
||||
wds_ap,
|
||||
wds_sta,
|
||||
wds_repeater
|
||||
};
|
||||
enum SSID_MODES { unknown = 0, ap, mesh, sta, wds_ap, wds_sta, wds_repeater };
|
||||
|
||||
inline SSID_MODES SSID_Mode(const std::string &m) {
|
||||
if (m == "ap")
|
||||
@@ -182,82 +146,45 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
struct SSIDTimePoint {
|
||||
std::string bssid,
|
||||
mode,
|
||||
ssid;
|
||||
uint64_t band=0,
|
||||
channel=0;
|
||||
std::string bssid, mode, ssid;
|
||||
uint64_t band = 0, channel = 0;
|
||||
std::vector<UETimePoint> associations;
|
||||
|
||||
AveragePoint tx_bytes_bw,
|
||||
rx_bytes_bw,
|
||||
tx_packets_bw,
|
||||
rx_packets_bw,
|
||||
tx_failed_pct,
|
||||
tx_retries_pct,
|
||||
tx_duration_pct;
|
||||
AveragePoint tx_bytes_bw, rx_bytes_bw, tx_packets_bw, rx_packets_bw, tx_failed_pct,
|
||||
tx_retries_pct, tx_duration_pct;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
|
||||
struct APTimePoint {
|
||||
uint64_t collisions = 0,
|
||||
multicast = 0,
|
||||
rx_bytes = 0,
|
||||
rx_dropped = 0,
|
||||
rx_errors = 0,
|
||||
rx_packets = 0,
|
||||
tx_bytes = 0,
|
||||
tx_dropped = 0,
|
||||
tx_errors = 0,
|
||||
tx_packets = 0;
|
||||
uint64_t collisions = 0, multicast = 0, rx_bytes = 0, rx_dropped = 0, rx_errors = 0,
|
||||
rx_packets = 0, tx_bytes = 0, tx_dropped = 0, tx_errors = 0, tx_packets = 0;
|
||||
|
||||
double tx_bytes_bw = 0.0 ,
|
||||
rx_bytes_bw = 0.0 ,
|
||||
rx_dropped_pct = 0.0,
|
||||
tx_dropped_pct = 0.0,
|
||||
rx_packets_bw = 0.0,
|
||||
tx_packets_bw = 0.0,
|
||||
rx_errors_pct = 0.0 ,
|
||||
double tx_bytes_bw = 0.0, rx_bytes_bw = 0.0, rx_dropped_pct = 0.0, tx_dropped_pct = 0.0,
|
||||
rx_packets_bw = 0.0, tx_packets_bw = 0.0, rx_errors_pct = 0.0,
|
||||
tx_errors_pct = 0.0;
|
||||
|
||||
uint64_t tx_bytes_delta = 0,
|
||||
rx_bytes_delta = 0 ,
|
||||
rx_dropped_delta = 0,
|
||||
tx_dropped_delta = 0,
|
||||
rx_packets_delta = 0,
|
||||
tx_packets_delta = 0,
|
||||
rx_errors_delta = 0,
|
||||
tx_errors_delta = 0;
|
||||
uint64_t tx_bytes_delta = 0, rx_bytes_delta = 0, rx_dropped_delta = 0,
|
||||
tx_dropped_delta = 0, rx_packets_delta = 0, tx_packets_delta = 0,
|
||||
rx_errors_delta = 0, tx_errors_delta = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
struct RadioTimePoint {
|
||||
uint64_t band = 0,
|
||||
channel_width = 0;
|
||||
uint64_t active_ms = 0,
|
||||
busy_ms = 0,
|
||||
receive_ms = 0,
|
||||
transmit_ms = 0,
|
||||
tx_power = 0,
|
||||
uint64_t band = 0, channel_width = 0;
|
||||
uint64_t active_ms = 0, busy_ms = 0, receive_ms = 0, transmit_ms = 0, tx_power = 0,
|
||||
channel = 0;
|
||||
int64_t temperature = 0,
|
||||
noise = 0;
|
||||
int64_t temperature = 0, noise = 0;
|
||||
|
||||
double active_pct = 0.0 ,
|
||||
busy_pct = 0.0,
|
||||
receive_pct = 0.0,
|
||||
transmit_pct = 0.0;
|
||||
double active_pct = 0.0, busy_pct = 0.0, receive_pct = 0.0, transmit_pct = 0.0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
|
||||
struct DeviceTimePoint {
|
||||
std::string id;
|
||||
std::string boardId;
|
||||
@@ -272,29 +199,29 @@ namespace OpenWifi {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
|
||||
inline bool operator<(const DeviceTimePoint &rhs) const {
|
||||
if(timestamp < rhs.timestamp)
|
||||
if (timestamp < rhs.timestamp)
|
||||
return true;
|
||||
if(timestamp > rhs.timestamp)
|
||||
if (timestamp > rhs.timestamp)
|
||||
return false;
|
||||
if(device_info.serialNumber < rhs.device_info.serialNumber)
|
||||
if (device_info.serialNumber < rhs.device_info.serialNumber)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool operator==(const DeviceTimePoint &rhs) const {
|
||||
return timestamp==rhs.timestamp && device_info.serialNumber==rhs.device_info.serialNumber;
|
||||
return timestamp == rhs.timestamp &&
|
||||
device_info.serialNumber == rhs.device_info.serialNumber;
|
||||
}
|
||||
|
||||
inline bool operator>(const DeviceTimePoint &rhs) const {
|
||||
if(timestamp > rhs.timestamp)
|
||||
if (timestamp > rhs.timestamp)
|
||||
return true;
|
||||
if(timestamp < rhs.timestamp)
|
||||
if (timestamp < rhs.timestamp)
|
||||
return false;
|
||||
if(device_info.serialNumber > rhs.device_info.serialNumber)
|
||||
if (device_info.serialNumber > rhs.device_info.serialNumber)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
struct DeviceTimePointAnalysis {
|
||||
@@ -319,7 +246,6 @@ namespace OpenWifi {
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
|
||||
};
|
||||
|
||||
struct DeviceTimePointList {
|
||||
@@ -331,93 +257,87 @@ namespace OpenWifi {
|
||||
|
||||
struct BandwidthAnalysisEntry {
|
||||
uint64_t timestamp = 0;
|
||||
|
||||
};
|
||||
|
||||
struct BandwidthAnalysis {
|
||||
|
||||
};
|
||||
struct BandwidthAnalysis {};
|
||||
|
||||
struct AverageValueSigned {
|
||||
int64_t peak=0, avg=0, low=0;
|
||||
int64_t peak = 0, avg = 0, low = 0;
|
||||
};
|
||||
|
||||
struct AverageValueUnsigned {
|
||||
uint64_t peak=0, avg=0, low=0;
|
||||
uint64_t peak = 0, avg = 0, low = 0;
|
||||
};
|
||||
|
||||
struct RadioAnalysis {
|
||||
uint64_t timestamp=0;
|
||||
uint64_t timestamp = 0;
|
||||
AverageValueSigned noise, temperature;
|
||||
AverageValueUnsigned active_ms,
|
||||
busy_ms,
|
||||
transmit_ms,
|
||||
receive_ms;
|
||||
AverageValueUnsigned active_ms, busy_ms, transmit_ms, receive_ms;
|
||||
};
|
||||
|
||||
struct DeviceTimePointStats {
|
||||
uint64_t firstPoint=0;
|
||||
uint64_t lastPoint=0;
|
||||
uint64_t count=0;
|
||||
uint64_t firstPoint = 0;
|
||||
uint64_t lastPoint = 0;
|
||||
uint64_t count = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
struct WifiClientRate {
|
||||
uint32_t bitrate=0;
|
||||
uint32_t chwidth=0;
|
||||
uint16_t mcs=0;
|
||||
uint16_t nss=0;
|
||||
bool vht=false;
|
||||
uint32_t bitrate = 0;
|
||||
uint32_t chwidth = 0;
|
||||
uint16_t mcs = 0;
|
||||
uint16_t nss = 0;
|
||||
bool vht = false;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
struct WifiClientHistory {
|
||||
uint64_t timestamp=Utils::Now();
|
||||
uint64_t timestamp = Utils::Now();
|
||||
std::string station_id;
|
||||
std::string bssid;
|
||||
std::string ssid;
|
||||
int64_t rssi=0;
|
||||
uint32_t rx_bitrate=0;
|
||||
uint32_t rx_chwidth=0;
|
||||
uint16_t rx_mcs=0;
|
||||
uint16_t rx_nss=0;
|
||||
bool rx_vht=false;
|
||||
uint32_t tx_bitrate=0;
|
||||
uint32_t tx_chwidth=0;
|
||||
uint16_t tx_mcs=0;
|
||||
uint16_t tx_nss=0;
|
||||
bool tx_vht=false;
|
||||
uint64_t rx_bytes=0;
|
||||
uint64_t tx_bytes=0;
|
||||
uint64_t rx_duration=0;
|
||||
uint64_t tx_duration=0;
|
||||
uint64_t rx_packets=0;
|
||||
uint64_t tx_packets=0;
|
||||
int64_t rssi = 0;
|
||||
uint32_t rx_bitrate = 0;
|
||||
uint32_t rx_chwidth = 0;
|
||||
uint16_t rx_mcs = 0;
|
||||
uint16_t rx_nss = 0;
|
||||
bool rx_vht = false;
|
||||
uint32_t tx_bitrate = 0;
|
||||
uint32_t tx_chwidth = 0;
|
||||
uint16_t tx_mcs = 0;
|
||||
uint16_t tx_nss = 0;
|
||||
bool tx_vht = false;
|
||||
uint64_t rx_bytes = 0;
|
||||
uint64_t tx_bytes = 0;
|
||||
uint64_t rx_duration = 0;
|
||||
uint64_t tx_duration = 0;
|
||||
uint64_t rx_packets = 0;
|
||||
uint64_t tx_packets = 0;
|
||||
std::string ipv4;
|
||||
std::string ipv6;
|
||||
uint64_t channel_width=0;
|
||||
int64_t noise=0;
|
||||
uint64_t tx_power=0;
|
||||
uint64_t channel=0;
|
||||
uint64_t active_ms=0;
|
||||
uint64_t busy_ms=0;
|
||||
uint64_t receive_ms=0;
|
||||
uint64_t channel_width = 0;
|
||||
int64_t noise = 0;
|
||||
uint64_t tx_power = 0;
|
||||
uint64_t channel = 0;
|
||||
uint64_t active_ms = 0;
|
||||
uint64_t busy_ms = 0;
|
||||
uint64_t receive_ms = 0;
|
||||
std::string mode;
|
||||
int64_t ack_signal=0;
|
||||
int64_t ack_signal_avg=0;
|
||||
uint64_t connected=0;
|
||||
uint64_t inactive=0;
|
||||
uint64_t tx_retries=0;
|
||||
int64_t ack_signal = 0;
|
||||
int64_t ack_signal_avg = 0;
|
||||
uint64_t connected = 0;
|
||||
uint64_t inactive = 0;
|
||||
uint64_t tx_retries = 0;
|
||||
std::string venue_id;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace AnalyticsObjects
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -5,57 +5,57 @@
|
||||
#include "RESTAPI_CertObjects.h"
|
||||
#include "framework/RESTAPI_utils.h"
|
||||
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
using OpenWifi::RESTAPI_utils::field_from_json;
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
|
||||
namespace OpenWifi::CertObjects {
|
||||
void CertificateEntry::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id", id);
|
||||
field_to_json(Obj,"entity", entity);
|
||||
field_to_json(Obj,"creator", creator);
|
||||
field_to_json(Obj,"type", type);
|
||||
field_to_json(Obj,"status", status);
|
||||
field_to_json(Obj,"certificate", certificate);
|
||||
field_to_json(Obj,"key", key);
|
||||
field_to_json(Obj,"devid", devid);
|
||||
field_to_json(Obj,"cas", cas);
|
||||
field_to_json(Obj,"manufacturer", manufacturer);
|
||||
field_to_json(Obj,"model", model);
|
||||
field_to_json(Obj,"redirector", redirector);
|
||||
field_to_json(Obj,"commonName", commonName);
|
||||
field_to_json(Obj,"certificateId", certificateId);
|
||||
field_to_json(Obj,"batch", batch);
|
||||
field_to_json(Obj,"created", created);
|
||||
field_to_json(Obj,"modified", modified);
|
||||
field_to_json(Obj,"revoked", revoked);
|
||||
field_to_json(Obj,"revokeCount", revokeCount);
|
||||
field_to_json(Obj,"synched", synched);
|
||||
field_to_json(Obj,"expiryDate", expiryDate);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "entity", entity);
|
||||
field_to_json(Obj, "creator", creator);
|
||||
field_to_json(Obj, "type", type);
|
||||
field_to_json(Obj, "status", status);
|
||||
field_to_json(Obj, "certificate", certificate);
|
||||
field_to_json(Obj, "key", key);
|
||||
field_to_json(Obj, "devid", devid);
|
||||
field_to_json(Obj, "cas", cas);
|
||||
field_to_json(Obj, "manufacturer", manufacturer);
|
||||
field_to_json(Obj, "model", model);
|
||||
field_to_json(Obj, "redirector", redirector);
|
||||
field_to_json(Obj, "commonName", commonName);
|
||||
field_to_json(Obj, "certificateId", certificateId);
|
||||
field_to_json(Obj, "batch", batch);
|
||||
field_to_json(Obj, "created", created);
|
||||
field_to_json(Obj, "modified", modified);
|
||||
field_to_json(Obj, "revoked", revoked);
|
||||
field_to_json(Obj, "revokeCount", revokeCount);
|
||||
field_to_json(Obj, "synched", synched);
|
||||
field_to_json(Obj, "expiryDate", expiryDate);
|
||||
}
|
||||
|
||||
bool CertificateEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id", id);
|
||||
field_from_json(Obj,"entity", entity);
|
||||
field_from_json(Obj,"creator", creator);
|
||||
field_from_json(Obj,"type", type);
|
||||
field_from_json(Obj,"status", status);
|
||||
field_from_json(Obj,"certificate", certificate);
|
||||
field_from_json(Obj,"key", key);
|
||||
field_from_json(Obj,"devid", devid);
|
||||
field_from_json(Obj,"cas", cas);
|
||||
field_from_json(Obj,"manufacturer", manufacturer);
|
||||
field_from_json(Obj,"model", model);
|
||||
field_from_json(Obj,"redirector", redirector);
|
||||
field_from_json(Obj,"commonName", commonName);
|
||||
field_from_json(Obj,"certificateId", certificateId);
|
||||
field_from_json(Obj,"batch", batch);
|
||||
field_from_json(Obj,"created", created);
|
||||
field_from_json(Obj,"modified", modified);
|
||||
field_from_json(Obj,"revoked", revoked);
|
||||
field_from_json(Obj,"revokeCount", revokeCount);
|
||||
field_from_json(Obj,"synched", synched);
|
||||
field_from_json(Obj,"expiryDate", expiryDate);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "entity", entity);
|
||||
field_from_json(Obj, "creator", creator);
|
||||
field_from_json(Obj, "type", type);
|
||||
field_from_json(Obj, "status", status);
|
||||
field_from_json(Obj, "certificate", certificate);
|
||||
field_from_json(Obj, "key", key);
|
||||
field_from_json(Obj, "devid", devid);
|
||||
field_from_json(Obj, "cas", cas);
|
||||
field_from_json(Obj, "manufacturer", manufacturer);
|
||||
field_from_json(Obj, "model", model);
|
||||
field_from_json(Obj, "redirector", redirector);
|
||||
field_from_json(Obj, "commonName", commonName);
|
||||
field_from_json(Obj, "certificateId", certificateId);
|
||||
field_from_json(Obj, "batch", batch);
|
||||
field_from_json(Obj, "created", created);
|
||||
field_from_json(Obj, "modified", modified);
|
||||
field_from_json(Obj, "revoked", revoked);
|
||||
field_from_json(Obj, "revokeCount", revokeCount);
|
||||
field_from_json(Obj, "synched", synched);
|
||||
field_from_json(Obj, "expiryDate", expiryDate);
|
||||
return true;
|
||||
} catch (...) {
|
||||
}
|
||||
@@ -63,38 +63,38 @@ namespace OpenWifi::CertObjects {
|
||||
}
|
||||
|
||||
void EntityEntry::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id", id);
|
||||
field_to_json(Obj,"creator", creator);
|
||||
field_to_json(Obj,"name", name);
|
||||
field_to_json(Obj,"description", description);
|
||||
field_to_json(Obj,"defaultRedirector", defaultRedirector);
|
||||
field_to_json(Obj,"apiKey", apiKey);
|
||||
field_to_json(Obj,"serverEnrollmentProfile", serverEnrollmentProfile);
|
||||
field_to_json(Obj,"clientEnrollmentProfile", clientEnrollmentProfile);
|
||||
field_to_json(Obj,"organization", organization);
|
||||
field_to_json(Obj,"created", created);
|
||||
field_to_json(Obj,"modified", modified);
|
||||
field_to_json(Obj,"suspended", suspended);
|
||||
field_to_json(Obj,"deleted", deleted);
|
||||
field_to_json(Obj,"notes", notes);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "creator", creator);
|
||||
field_to_json(Obj, "name", name);
|
||||
field_to_json(Obj, "description", description);
|
||||
field_to_json(Obj, "defaultRedirector", defaultRedirector);
|
||||
field_to_json(Obj, "apiKey", apiKey);
|
||||
field_to_json(Obj, "serverEnrollmentProfile", serverEnrollmentProfile);
|
||||
field_to_json(Obj, "clientEnrollmentProfile", clientEnrollmentProfile);
|
||||
field_to_json(Obj, "organization", organization);
|
||||
field_to_json(Obj, "created", created);
|
||||
field_to_json(Obj, "modified", modified);
|
||||
field_to_json(Obj, "suspended", suspended);
|
||||
field_to_json(Obj, "deleted", deleted);
|
||||
field_to_json(Obj, "notes", notes);
|
||||
}
|
||||
|
||||
bool EntityEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id", id);
|
||||
field_from_json(Obj,"creator", creator);
|
||||
field_from_json(Obj,"name", name);
|
||||
field_from_json(Obj,"description", description);
|
||||
field_from_json(Obj,"defaultRedirector", defaultRedirector);
|
||||
field_from_json(Obj,"apiKey", apiKey);
|
||||
field_from_json(Obj,"serverEnrollmentProfile", serverEnrollmentProfile);
|
||||
field_from_json(Obj,"clientEnrollmentProfile", clientEnrollmentProfile);
|
||||
field_from_json(Obj,"organization", organization);
|
||||
field_from_json(Obj,"created", created);
|
||||
field_from_json(Obj,"modified", modified);
|
||||
field_from_json(Obj,"suspended", suspended);
|
||||
field_from_json(Obj,"deleted", deleted);
|
||||
field_from_json(Obj,"notes", notes);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "creator", creator);
|
||||
field_from_json(Obj, "name", name);
|
||||
field_from_json(Obj, "description", description);
|
||||
field_from_json(Obj, "defaultRedirector", defaultRedirector);
|
||||
field_from_json(Obj, "apiKey", apiKey);
|
||||
field_from_json(Obj, "serverEnrollmentProfile", serverEnrollmentProfile);
|
||||
field_from_json(Obj, "clientEnrollmentProfile", clientEnrollmentProfile);
|
||||
field_from_json(Obj, "organization", organization);
|
||||
field_from_json(Obj, "created", created);
|
||||
field_from_json(Obj, "modified", modified);
|
||||
field_from_json(Obj, "suspended", suspended);
|
||||
field_from_json(Obj, "deleted", deleted);
|
||||
field_from_json(Obj, "notes", notes);
|
||||
return true;
|
||||
} catch (...) {
|
||||
}
|
||||
@@ -102,40 +102,40 @@ namespace OpenWifi::CertObjects {
|
||||
}
|
||||
|
||||
void BatchEntry::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id", id);
|
||||
field_to_json(Obj,"entity", entity);
|
||||
field_to_json(Obj,"creator", creator);
|
||||
field_to_json(Obj,"name", name);
|
||||
field_to_json(Obj,"description", description);
|
||||
field_to_json(Obj,"manufacturer", manufacturer);
|
||||
field_to_json(Obj,"model", model);
|
||||
field_to_json(Obj,"redirector", redirector);
|
||||
field_to_json(Obj,"commonNames", commonNames);
|
||||
field_to_json(Obj,"jobHistory", jobHistory);
|
||||
field_to_json(Obj,"notes", notes);
|
||||
field_to_json(Obj,"submitted", submitted);
|
||||
field_to_json(Obj,"started", started);
|
||||
field_to_json(Obj,"completed", completed);
|
||||
field_to_json(Obj,"modified", modified);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "entity", entity);
|
||||
field_to_json(Obj, "creator", creator);
|
||||
field_to_json(Obj, "name", name);
|
||||
field_to_json(Obj, "description", description);
|
||||
field_to_json(Obj, "manufacturer", manufacturer);
|
||||
field_to_json(Obj, "model", model);
|
||||
field_to_json(Obj, "redirector", redirector);
|
||||
field_to_json(Obj, "commonNames", commonNames);
|
||||
field_to_json(Obj, "jobHistory", jobHistory);
|
||||
field_to_json(Obj, "notes", notes);
|
||||
field_to_json(Obj, "submitted", submitted);
|
||||
field_to_json(Obj, "started", started);
|
||||
field_to_json(Obj, "completed", completed);
|
||||
field_to_json(Obj, "modified", modified);
|
||||
}
|
||||
|
||||
bool BatchEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id", id);
|
||||
field_from_json(Obj,"entity", entity);
|
||||
field_from_json(Obj,"creator", creator);
|
||||
field_from_json(Obj,"name", name);
|
||||
field_from_json(Obj,"description", description);
|
||||
field_from_json(Obj,"manufacturer", manufacturer);
|
||||
field_from_json(Obj,"model", model);
|
||||
field_from_json(Obj,"redirector", redirector);
|
||||
field_from_json(Obj,"commonNames", commonNames);
|
||||
field_from_json(Obj,"jobHistory", jobHistory);
|
||||
field_from_json(Obj,"notes", notes);
|
||||
field_from_json(Obj,"submitted", submitted);
|
||||
field_from_json(Obj,"started", started);
|
||||
field_from_json(Obj,"completed", completed);
|
||||
field_from_json(Obj,"modified", modified);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "entity", entity);
|
||||
field_from_json(Obj, "creator", creator);
|
||||
field_from_json(Obj, "name", name);
|
||||
field_from_json(Obj, "description", description);
|
||||
field_from_json(Obj, "manufacturer", manufacturer);
|
||||
field_from_json(Obj, "model", model);
|
||||
field_from_json(Obj, "redirector", redirector);
|
||||
field_from_json(Obj, "commonNames", commonNames);
|
||||
field_from_json(Obj, "jobHistory", jobHistory);
|
||||
field_from_json(Obj, "notes", notes);
|
||||
field_from_json(Obj, "submitted", submitted);
|
||||
field_from_json(Obj, "started", started);
|
||||
field_from_json(Obj, "completed", completed);
|
||||
field_from_json(Obj, "modified", modified);
|
||||
return true;
|
||||
} catch (...) {
|
||||
}
|
||||
@@ -143,38 +143,38 @@ namespace OpenWifi::CertObjects {
|
||||
}
|
||||
|
||||
void JobEntry::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id", id);
|
||||
field_to_json(Obj,"entity", entity);
|
||||
field_to_json(Obj,"creator", creator);
|
||||
field_to_json(Obj,"batch", batch);
|
||||
field_to_json(Obj,"commonNames", commonNames);
|
||||
field_to_json(Obj,"completedNames", completedNames);
|
||||
field_to_json(Obj,"errorNames", errorNames);
|
||||
field_to_json(Obj,"status", status);
|
||||
field_to_json(Obj,"command", command);
|
||||
field_to_json(Obj,"parameters", parameters);
|
||||
field_to_json(Obj,"submitted", submitted);
|
||||
field_to_json(Obj,"started", started);
|
||||
field_to_json(Obj,"completed", completed);
|
||||
field_to_json(Obj,"requesterUsername", requesterUsername);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "entity", entity);
|
||||
field_to_json(Obj, "creator", creator);
|
||||
field_to_json(Obj, "batch", batch);
|
||||
field_to_json(Obj, "commonNames", commonNames);
|
||||
field_to_json(Obj, "completedNames", completedNames);
|
||||
field_to_json(Obj, "errorNames", errorNames);
|
||||
field_to_json(Obj, "status", status);
|
||||
field_to_json(Obj, "command", command);
|
||||
field_to_json(Obj, "parameters", parameters);
|
||||
field_to_json(Obj, "submitted", submitted);
|
||||
field_to_json(Obj, "started", started);
|
||||
field_to_json(Obj, "completed", completed);
|
||||
field_to_json(Obj, "requesterUsername", requesterUsername);
|
||||
}
|
||||
|
||||
bool JobEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id", id);
|
||||
field_from_json(Obj,"entity", entity);
|
||||
field_from_json(Obj,"creator", creator);
|
||||
field_from_json(Obj,"batch", batch);
|
||||
field_from_json(Obj,"commonNames", commonNames);
|
||||
field_from_json(Obj,"completedNames", completedNames);
|
||||
field_from_json(Obj,"errorNames", errorNames);
|
||||
field_from_json(Obj,"status", status);
|
||||
field_from_json(Obj,"command", command);
|
||||
field_from_json(Obj,"parameters", parameters);
|
||||
field_from_json(Obj,"submitted", submitted);
|
||||
field_from_json(Obj,"started", started);
|
||||
field_from_json(Obj,"completed", completed);
|
||||
field_from_json(Obj,"requesterUsername", requesterUsername);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "entity", entity);
|
||||
field_from_json(Obj, "creator", creator);
|
||||
field_from_json(Obj, "batch", batch);
|
||||
field_from_json(Obj, "commonNames", commonNames);
|
||||
field_from_json(Obj, "completedNames", completedNames);
|
||||
field_from_json(Obj, "errorNames", errorNames);
|
||||
field_from_json(Obj, "status", status);
|
||||
field_from_json(Obj, "command", command);
|
||||
field_from_json(Obj, "parameters", parameters);
|
||||
field_from_json(Obj, "submitted", submitted);
|
||||
field_from_json(Obj, "started", started);
|
||||
field_from_json(Obj, "completed", completed);
|
||||
field_from_json(Obj, "requesterUsername", requesterUsername);
|
||||
return true;
|
||||
} catch (...) {
|
||||
}
|
||||
@@ -188,19 +188,19 @@ namespace OpenWifi::CertObjects {
|
||||
}
|
||||
|
||||
void Dashboard::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"snapshot", snapshot);
|
||||
field_to_json(Obj,"numberOfIssuedCerts", numberOfIssuedCerts);
|
||||
field_to_json(Obj,"numberOfRevokedCerts", numberOfRevokedCerts);
|
||||
field_to_json(Obj,"activeCertsPerOrganization", activeCertsPerOrganization);
|
||||
field_to_json(Obj,"revokedCertsPerOrganization", revokedCertsPerOrganization);
|
||||
field_to_json(Obj,"numberOfRedirectors", numberOfRedirectors);
|
||||
field_to_json(Obj,"deviceTypes", deviceTypes);
|
||||
field_to_json(Obj,"monthlyNumberOfCerts", monthlyNumberOfCerts);
|
||||
field_to_json(Obj,"monthlyNumberOfCertsPerOrgPerYear", monthlyNumberOfCertsPerOrgPerYear);
|
||||
field_to_json(Obj, "snapshot", snapshot);
|
||||
field_to_json(Obj, "numberOfIssuedCerts", numberOfIssuedCerts);
|
||||
field_to_json(Obj, "numberOfRevokedCerts", numberOfRevokedCerts);
|
||||
field_to_json(Obj, "activeCertsPerOrganization", activeCertsPerOrganization);
|
||||
field_to_json(Obj, "revokedCertsPerOrganization", revokedCertsPerOrganization);
|
||||
field_to_json(Obj, "numberOfRedirectors", numberOfRedirectors);
|
||||
field_to_json(Obj, "deviceTypes", deviceTypes);
|
||||
field_to_json(Obj, "monthlyNumberOfCerts", monthlyNumberOfCerts);
|
||||
field_to_json(Obj, "monthlyNumberOfCertsPerOrgPerYear", monthlyNumberOfCertsPerOrgPerYear);
|
||||
}
|
||||
|
||||
void Dashboard::reset() {
|
||||
snapshot=0;
|
||||
snapshot = 0;
|
||||
numberOfRevokedCerts = numberOfIssuedCerts = 0;
|
||||
activeCertsPerOrganization.clear();
|
||||
revokedCertsPerOrganization.clear();
|
||||
@@ -209,4 +209,4 @@ namespace OpenWifi::CertObjects {
|
||||
monthlyNumberOfCerts.clear();
|
||||
monthlyNumberOfCertsPerOrgPerYear.clear();
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi::CertObjects
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
#include "RESTObjects/RESTAPI_SecurityObjects.h"
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
#include <string>
|
||||
|
||||
namespace OpenWifi::CertObjects {
|
||||
|
||||
@@ -31,7 +31,7 @@ namespace OpenWifi::CertObjects {
|
||||
uint64_t revoked = 0;
|
||||
uint64_t revokeCount = 0;
|
||||
uint64_t synched = 0;
|
||||
uint64_t expiryDate = 0 ;
|
||||
uint64_t expiryDate = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -48,10 +48,10 @@ namespace OpenWifi::CertObjects {
|
||||
std::string clientEnrollmentProfile;
|
||||
std::string organization;
|
||||
SecurityObjects::NoteInfoVec notes;
|
||||
bool suspended=false;
|
||||
bool deleted=false;
|
||||
uint64_t created = 0 ;
|
||||
uint64_t modified = 0 ;
|
||||
bool suspended = false;
|
||||
bool deleted = false;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -69,10 +69,10 @@ namespace OpenWifi::CertObjects {
|
||||
std::vector<std::string> commonNames;
|
||||
std::vector<std::string> jobHistory;
|
||||
SecurityObjects::NoteInfoVec notes;
|
||||
uint64_t submitted = 0 ;
|
||||
uint64_t started = 0 ;
|
||||
uint64_t completed = 0 ;
|
||||
uint64_t modified = 0 ;
|
||||
uint64_t submitted = 0;
|
||||
uint64_t started = 0;
|
||||
uint64_t completed = 0;
|
||||
uint64_t modified = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -89,9 +89,9 @@ namespace OpenWifi::CertObjects {
|
||||
OpenWifi::Types::StringVec errorNames;
|
||||
Types::StringPairVec parameters;
|
||||
std::string status;
|
||||
uint64_t submitted=0;
|
||||
uint64_t started=0;
|
||||
uint64_t completed=0;
|
||||
uint64_t submitted = 0;
|
||||
uint64_t started = 0;
|
||||
uint64_t completed = 0;
|
||||
std::string requesterUsername;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -99,7 +99,7 @@ namespace OpenWifi::CertObjects {
|
||||
};
|
||||
|
||||
struct DashBoardYearlyStats {
|
||||
uint64_t year=0;
|
||||
uint64_t year = 0;
|
||||
OpenWifi::Types::Counted3DMapSII activeCerts;
|
||||
OpenWifi::Types::Counted3DMapSII revokedCerts;
|
||||
|
||||
@@ -107,9 +107,9 @@ namespace OpenWifi::CertObjects {
|
||||
};
|
||||
|
||||
struct Dashboard {
|
||||
uint64_t snapshot=0;
|
||||
uint64_t numberOfIssuedCerts=0;
|
||||
uint64_t numberOfRevokedCerts=0;
|
||||
uint64_t snapshot = 0;
|
||||
uint64_t numberOfIssuedCerts = 0;
|
||||
uint64_t numberOfRevokedCerts = 0;
|
||||
OpenWifi::Types::CountedMap activeCertsPerOrganization;
|
||||
OpenWifi::Types::CountedMap revokedCertsPerOrganization;
|
||||
OpenWifi::Types::CountedMap numberOfRedirectors;
|
||||
@@ -121,4 +121,4 @@ namespace OpenWifi::CertObjects {
|
||||
void reset();
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace OpenWifi::CertObjects
|
||||
@@ -6,8 +6,8 @@
|
||||
#include "framework/RESTAPI_utils.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
using OpenWifi::RESTAPI_utils::field_from_json;
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
|
||||
namespace OpenWifi::FMSObjects {
|
||||
|
||||
@@ -54,13 +54,12 @@ namespace OpenWifi::FMSObjects {
|
||||
field_from_json(Obj, "created", created);
|
||||
return true;
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void FirmwareList::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"firmwares",firmwares);
|
||||
field_to_json(Obj, "firmwares", firmwares);
|
||||
}
|
||||
|
||||
bool FirmwareList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
@@ -68,7 +67,6 @@ namespace OpenWifi::FMSObjects {
|
||||
field_from_json(Obj, "firmwares", firmwares);
|
||||
return true;
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -102,21 +100,19 @@ namespace OpenWifi::FMSObjects {
|
||||
field_from_json(Obj, "id", id);
|
||||
return true;
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void DeviceTypeList::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"deviceTypes", deviceTypes);
|
||||
field_to_json(Obj, "deviceTypes", deviceTypes);
|
||||
}
|
||||
|
||||
bool DeviceTypeList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"deviceTypes", deviceTypes);
|
||||
field_from_json(Obj, "deviceTypes", deviceTypes);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -141,48 +137,45 @@ namespace OpenWifi::FMSObjects {
|
||||
field_from_json(Obj, "revisionId", revisionId);
|
||||
field_from_json(Obj, "upgraded", upgraded);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void RevisionHistoryEntryList::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"deviceTypes", history);
|
||||
field_to_json(Obj, "deviceTypes", history);
|
||||
}
|
||||
|
||||
bool RevisionHistoryEntryList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"deviceTypes", history);
|
||||
field_from_json(Obj, "deviceTypes", history);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void FirmwareAgeDetails::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"latestId", latestId);
|
||||
field_to_json(Obj,"image", image);
|
||||
field_to_json(Obj,"imageDate", imageDate);
|
||||
field_to_json(Obj,"revision", revision);
|
||||
field_to_json(Obj,"uri", uri);
|
||||
field_to_json(Obj,"age", age);
|
||||
field_to_json(Obj,"latest",latest);
|
||||
field_to_json(Obj, "latestId", latestId);
|
||||
field_to_json(Obj, "image", image);
|
||||
field_to_json(Obj, "imageDate", imageDate);
|
||||
field_to_json(Obj, "revision", revision);
|
||||
field_to_json(Obj, "uri", uri);
|
||||
field_to_json(Obj, "age", age);
|
||||
field_to_json(Obj, "latest", latest);
|
||||
}
|
||||
|
||||
bool FirmwareAgeDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"latestId", latestId);
|
||||
field_from_json(Obj,"image", image);
|
||||
field_from_json(Obj,"imageDate", imageDate);
|
||||
field_from_json(Obj,"revision", revision);
|
||||
field_from_json(Obj,"uri", uri);
|
||||
field_from_json(Obj,"age", age);
|
||||
field_from_json(Obj,"latest", latest);
|
||||
field_from_json(Obj, "latestId", latestId);
|
||||
field_from_json(Obj, "image", image);
|
||||
field_from_json(Obj, "imageDate", imageDate);
|
||||
field_from_json(Obj, "revision", revision);
|
||||
field_from_json(Obj, "uri", uri);
|
||||
field_from_json(Obj, "age", age);
|
||||
field_from_json(Obj, "latest", latest);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -205,22 +198,21 @@ namespace OpenWifi::FMSObjects {
|
||||
field_from_json(Obj, "lastUpdate", lastUpdate);
|
||||
field_from_json(Obj, "status", status);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void DeviceReport::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj, "ouis",OUI_);
|
||||
field_to_json(Obj, "ouis", OUI_);
|
||||
field_to_json(Obj, "revisions", Revisions_);
|
||||
field_to_json(Obj, "deviceTypes", DeviceTypes_);
|
||||
field_to_json(Obj, "status", Status_);
|
||||
field_to_json(Obj, "endPoints", EndPoints_);
|
||||
field_to_json(Obj, "usingLatest", UsingLatest_);
|
||||
field_to_json(Obj, "unknownFirmwares", UnknownFirmwares_);
|
||||
field_to_json(Obj,"snapshot",snapshot);
|
||||
field_to_json(Obj,"numberOfDevices",numberOfDevices);
|
||||
field_to_json(Obj, "snapshot", snapshot);
|
||||
field_to_json(Obj, "numberOfDevices", numberOfDevices);
|
||||
field_to_json(Obj, "totalSecondsOld", totalSecondsOld_);
|
||||
}
|
||||
|
||||
@@ -233,7 +225,7 @@ namespace OpenWifi::FMSObjects {
|
||||
UsingLatest_.clear();
|
||||
UnknownFirmwares_.clear();
|
||||
totalSecondsOld_.clear();
|
||||
numberOfDevices = 0 ;
|
||||
numberOfDevices = 0;
|
||||
snapshot = Utils::Now();
|
||||
}
|
||||
|
||||
@@ -242,69 +234,65 @@ namespace OpenWifi::FMSObjects {
|
||||
|
||||
return true;
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void DeviceInformation::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj, "serialNumber",serialNumber);
|
||||
field_to_json(Obj, "serialNumber", serialNumber);
|
||||
field_to_json(Obj, "history", history);
|
||||
field_to_json(Obj, "currentFirmware", currentFirmware);
|
||||
field_to_json(Obj, "currentFirmwareDate", currentFirmwareDate);
|
||||
field_to_json(Obj, "latestFirmware", latestFirmware);
|
||||
field_to_json(Obj, "latestFirmwareDate", latestFirmwareDate);
|
||||
field_to_json(Obj, "latestFirmwareAvailable",latestFirmwareAvailable);
|
||||
field_to_json(Obj, "latestFirmwareURI",latestFirmwareURI);
|
||||
field_to_json(Obj, "latestFirmwareAvailable", latestFirmwareAvailable);
|
||||
field_to_json(Obj, "latestFirmwareURI", latestFirmwareURI);
|
||||
}
|
||||
|
||||
bool DeviceInformation::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj, "serialNumber",serialNumber);
|
||||
field_from_json(Obj, "serialNumber", serialNumber);
|
||||
field_from_json(Obj, "history", history);
|
||||
field_from_json(Obj, "currentFirmware", currentFirmware);
|
||||
field_from_json(Obj, "currentFirmwareDate", currentFirmwareDate);
|
||||
field_from_json(Obj, "latestFirmware", latestFirmware);
|
||||
field_from_json(Obj, "latestFirmwareDate", latestFirmwareDate);
|
||||
field_from_json(Obj, "latestFirmwareAvailable",latestFirmwareAvailable);
|
||||
field_from_json(Obj, "latestFirmwareURI",latestFirmwareURI);
|
||||
field_from_json(Obj, "latestFirmwareAvailable", latestFirmwareAvailable);
|
||||
field_from_json(Obj, "latestFirmwareURI", latestFirmwareURI);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void DeviceCurrentInfo::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj, "serialNumber",serialNumber);
|
||||
field_to_json(Obj, "serialNumber", serialNumber);
|
||||
field_to_json(Obj, "revision", revision);
|
||||
field_to_json(Obj, "upgraded", upgraded);
|
||||
}
|
||||
|
||||
bool DeviceCurrentInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj, "serialNumber",serialNumber);
|
||||
field_from_json(Obj, "serialNumber", serialNumber);
|
||||
field_from_json(Obj, "revision", revision);
|
||||
field_from_json(Obj, "upgraded", upgraded);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void DeviceCurrentInfoList::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj, "devices",devices);
|
||||
field_to_json(Obj, "devices", devices);
|
||||
}
|
||||
|
||||
bool DeviceCurrentInfoList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj, "devices",devices);
|
||||
field_from_json(Obj, "devices", devices);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi::FMSObjects
|
||||
|
||||
@@ -19,17 +19,17 @@ namespace OpenWifi::FMSObjects {
|
||||
std::string revision;
|
||||
std::string uri;
|
||||
std::string image;
|
||||
uint64_t imageDate=0;
|
||||
uint64_t size=0;
|
||||
uint64_t downloadCount=0;
|
||||
uint64_t imageDate = 0;
|
||||
uint64_t size = 0;
|
||||
uint64_t downloadCount = 0;
|
||||
std::string firmwareHash;
|
||||
std::string owner;
|
||||
std::string location;
|
||||
std::string uploader;
|
||||
std::string digest;
|
||||
bool latest=false;
|
||||
bool latest = false;
|
||||
SecurityObjects::NoteInfoVec notes;
|
||||
uint64_t created=0;
|
||||
uint64_t created = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -50,8 +50,8 @@ namespace OpenWifi::FMSObjects {
|
||||
std::string model;
|
||||
std::string policy;
|
||||
SecurityObjects::NoteInfoVec notes;
|
||||
uint64_t lastUpdate=0;
|
||||
uint64_t created=0;
|
||||
uint64_t lastUpdate = 0;
|
||||
uint64_t created = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -92,8 +92,8 @@ namespace OpenWifi::FMSObjects {
|
||||
uint64_t imageDate;
|
||||
std::string revision;
|
||||
std::string uri;
|
||||
uint64_t age=0;
|
||||
bool latest=true;
|
||||
uint64_t age = 0;
|
||||
bool latest = true;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -111,8 +111,8 @@ namespace OpenWifi::FMSObjects {
|
||||
};
|
||||
|
||||
struct DeviceReport {
|
||||
uint64_t snapshot=0;
|
||||
uint64_t numberOfDevices=0;
|
||||
uint64_t snapshot = 0;
|
||||
uint64_t numberOfDevices = 0;
|
||||
Types::CountedMap OUI_;
|
||||
Types::CountedMap Revisions_;
|
||||
Types::CountedMap DeviceTypes_;
|
||||
@@ -130,9 +130,9 @@ namespace OpenWifi::FMSObjects {
|
||||
std::string serialNumber;
|
||||
RevisionHistoryEntryList history;
|
||||
std::string currentFirmware;
|
||||
uint64_t currentFirmwareDate=0;
|
||||
uint64_t currentFirmwareDate = 0;
|
||||
std::string latestFirmware;
|
||||
uint64_t latestFirmwareDate=0;
|
||||
uint64_t latestFirmwareDate = 0;
|
||||
bool latestFirmwareAvailable;
|
||||
std::string latestFirmwareURI;
|
||||
|
||||
@@ -143,7 +143,7 @@ namespace OpenWifi::FMSObjects {
|
||||
struct DeviceCurrentInfo {
|
||||
std::string serialNumber;
|
||||
std::string revision;
|
||||
uint64_t upgraded=0;
|
||||
uint64_t upgraded = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -156,4 +156,4 @@ namespace OpenWifi::FMSObjects {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace OpenWifi::FMSObjects
|
||||
|
||||
@@ -19,41 +19,41 @@
|
||||
#include "framework/RESTAPI_utils.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
using OpenWifi::RESTAPI_utils::field_from_json;
|
||||
using OpenWifi::RESTAPI_utils::EmbedDocument;
|
||||
using OpenWifi::RESTAPI_utils::field_from_json;
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
|
||||
namespace OpenWifi::GWObjects {
|
||||
|
||||
void Device::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"serialNumber", SerialNumber);
|
||||
field_to_json(Obj, "serialNumber", SerialNumber);
|
||||
#ifdef TIP_GATEWAY_SERVICE
|
||||
field_to_json(Obj,"deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible));
|
||||
field_to_json(Obj, "deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible));
|
||||
#endif
|
||||
field_to_json(Obj,"macAddress", MACAddress);
|
||||
field_to_json(Obj,"manufacturer", Manufacturer);
|
||||
field_to_json(Obj,"UUID", UUID);
|
||||
field_to_json(Obj, "macAddress", MACAddress);
|
||||
field_to_json(Obj, "manufacturer", Manufacturer);
|
||||
field_to_json(Obj, "UUID", UUID);
|
||||
EmbedDocument("configuration", Obj, Configuration);
|
||||
field_to_json(Obj,"notes", Notes);
|
||||
field_to_json(Obj,"createdTimestamp", CreationTimestamp);
|
||||
field_to_json(Obj,"lastConfigurationChange", LastConfigurationChange);
|
||||
field_to_json(Obj,"lastConfigurationDownload", LastConfigurationDownload);
|
||||
field_to_json(Obj,"lastFWUpdate", LastFWUpdate);
|
||||
field_to_json(Obj,"owner", Owner);
|
||||
field_to_json(Obj,"location", Location);
|
||||
field_to_json(Obj,"venue", Venue);
|
||||
field_to_json(Obj,"firmware", Firmware);
|
||||
field_to_json(Obj,"compatible", Compatible);
|
||||
field_to_json(Obj,"fwUpdatePolicy", FWUpdatePolicy);
|
||||
field_to_json(Obj,"devicePassword", DevicePassword);
|
||||
field_to_json(Obj,"subscriber", subscriber);
|
||||
field_to_json(Obj,"entity", entity);
|
||||
field_to_json(Obj,"modified", modified);
|
||||
field_to_json(Obj,"locale", locale);
|
||||
field_to_json(Obj,"restrictedDevice", restrictedDevice);
|
||||
field_to_json(Obj,"pendingConfiguration", pendingConfiguration);
|
||||
field_to_json(Obj,"pendingConfigurationCmd", pendingConfigurationCmd);
|
||||
field_to_json(Obj,"restrictionDetails", restrictionDetails);
|
||||
field_to_json(Obj, "notes", Notes);
|
||||
field_to_json(Obj, "createdTimestamp", CreationTimestamp);
|
||||
field_to_json(Obj, "lastConfigurationChange", LastConfigurationChange);
|
||||
field_to_json(Obj, "lastConfigurationDownload", LastConfigurationDownload);
|
||||
field_to_json(Obj, "lastFWUpdate", LastFWUpdate);
|
||||
field_to_json(Obj, "owner", Owner);
|
||||
field_to_json(Obj, "location", Location);
|
||||
field_to_json(Obj, "venue", Venue);
|
||||
field_to_json(Obj, "firmware", Firmware);
|
||||
field_to_json(Obj, "compatible", Compatible);
|
||||
field_to_json(Obj, "fwUpdatePolicy", FWUpdatePolicy);
|
||||
field_to_json(Obj, "devicePassword", DevicePassword);
|
||||
field_to_json(Obj, "subscriber", subscriber);
|
||||
field_to_json(Obj, "entity", entity);
|
||||
field_to_json(Obj, "modified", modified);
|
||||
field_to_json(Obj, "locale", locale);
|
||||
field_to_json(Obj, "restrictedDevice", restrictedDevice);
|
||||
field_to_json(Obj, "pendingConfiguration", pendingConfiguration);
|
||||
field_to_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd);
|
||||
field_to_json(Obj, "restrictionDetails", restrictionDetails);
|
||||
}
|
||||
|
||||
void Device::to_json_with_status(Poco::JSON::Object &Obj) const {
|
||||
@@ -65,39 +65,39 @@ namespace OpenWifi::GWObjects {
|
||||
if (AP_WS_Server()->GetState(SerialNumber, ConState)) {
|
||||
ConState.to_json(Obj);
|
||||
} else {
|
||||
field_to_json(Obj,"ipAddress", "");
|
||||
field_to_json(Obj,"txBytes", (uint64_t) 0);
|
||||
field_to_json(Obj,"rxBytes", (uint64_t )0);
|
||||
field_to_json(Obj,"messageCount", (uint64_t )0);
|
||||
field_to_json(Obj,"connected", false);
|
||||
field_to_json(Obj,"lastContact", "");
|
||||
field_to_json(Obj,"verifiedCertificate", "NO_CERTIFICATE");
|
||||
field_to_json(Obj,"associations_2G", (uint64_t) 0);
|
||||
field_to_json(Obj,"associations_5G", (uint64_t) 0);
|
||||
field_to_json(Obj,"associations_6G", (uint64_t) 0);
|
||||
field_to_json(Obj, "ipAddress", "");
|
||||
field_to_json(Obj, "txBytes", (uint64_t)0);
|
||||
field_to_json(Obj, "rxBytes", (uint64_t)0);
|
||||
field_to_json(Obj, "messageCount", (uint64_t)0);
|
||||
field_to_json(Obj, "connected", false);
|
||||
field_to_json(Obj, "lastContact", "");
|
||||
field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
|
||||
field_to_json(Obj, "associations_2G", (uint64_t)0);
|
||||
field_to_json(Obj, "associations_5G", (uint64_t)0);
|
||||
field_to_json(Obj, "associations_6G", (uint64_t)0);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool Device::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"serialNumber",SerialNumber);
|
||||
field_from_json(Obj,"deviceType",DeviceType);
|
||||
field_from_json(Obj,"macAddress",MACAddress);
|
||||
field_from_json(Obj,"configuration",Configuration);
|
||||
field_from_json(Obj,"notes",Notes);
|
||||
field_from_json(Obj,"manufacturer",Manufacturer);
|
||||
field_from_json(Obj,"owner",Owner);
|
||||
field_from_json(Obj,"location",Location);
|
||||
field_from_json(Obj,"venue",Venue);
|
||||
field_from_json(Obj,"compatible",Compatible);
|
||||
field_from_json(Obj,"subscriber", subscriber);
|
||||
field_from_json(Obj,"entity", entity);
|
||||
field_from_json(Obj,"locale", locale);
|
||||
field_from_json(Obj,"restrictedDevice", restrictedDevice);
|
||||
field_from_json(Obj,"pendingConfiguration", pendingConfiguration);
|
||||
field_from_json(Obj,"pendingConfigurationCmd", pendingConfigurationCmd);
|
||||
field_from_json(Obj,"restrictionDetails", restrictionDetails);
|
||||
field_from_json(Obj, "serialNumber", SerialNumber);
|
||||
field_from_json(Obj, "deviceType", DeviceType);
|
||||
field_from_json(Obj, "macAddress", MACAddress);
|
||||
field_from_json(Obj, "configuration", Configuration);
|
||||
field_from_json(Obj, "notes", Notes);
|
||||
field_from_json(Obj, "manufacturer", Manufacturer);
|
||||
field_from_json(Obj, "owner", Owner);
|
||||
field_from_json(Obj, "location", Location);
|
||||
field_from_json(Obj, "venue", Venue);
|
||||
field_from_json(Obj, "compatible", Compatible);
|
||||
field_from_json(Obj, "subscriber", subscriber);
|
||||
field_from_json(Obj, "entity", entity);
|
||||
field_from_json(Obj, "locale", locale);
|
||||
field_from_json(Obj, "restrictedDevice", restrictedDevice);
|
||||
field_from_json(Obj, "pendingConfiguration", pendingConfiguration);
|
||||
field_from_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd);
|
||||
field_from_json(Obj, "restrictionDetails", restrictionDetails);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -105,73 +105,74 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void Device::Print() const {
|
||||
std::cout << "Device: " << SerialNumber << " DeviceType:" << DeviceType << " MACAddress:" << MACAddress << " Manufacturer:"
|
||||
<< Manufacturer << " " << Configuration << std::endl;
|
||||
std::cout << "Device: " << SerialNumber << " DeviceType:" << DeviceType
|
||||
<< " MACAddress:" << MACAddress << " Manufacturer:" << Manufacturer << " "
|
||||
<< Configuration << std::endl;
|
||||
}
|
||||
|
||||
void Statistics::to_json(Poco::JSON::Object &Obj) const {
|
||||
EmbedDocument("data", Obj, Data);
|
||||
field_to_json(Obj,"UUID", UUID);
|
||||
field_to_json(Obj,"recorded", Recorded);
|
||||
field_to_json(Obj, "UUID", UUID);
|
||||
field_to_json(Obj, "recorded", Recorded);
|
||||
}
|
||||
|
||||
void Capabilities::to_json(Poco::JSON::Object &Obj) const {
|
||||
EmbedDocument("capabilities", Obj, Capabilities);
|
||||
field_to_json(Obj,"firstUpdate", FirstUpdate);
|
||||
field_to_json(Obj,"lastUpdate", LastUpdate);
|
||||
field_to_json(Obj, "firstUpdate", FirstUpdate);
|
||||
field_to_json(Obj, "lastUpdate", LastUpdate);
|
||||
}
|
||||
|
||||
void DeviceLog::to_json(Poco::JSON::Object &Obj) const {
|
||||
EmbedDocument("data", Obj, Data);
|
||||
field_to_json(Obj,"log", Log);
|
||||
field_to_json(Obj,"severity", Severity);
|
||||
field_to_json(Obj,"recorded", Recorded);
|
||||
field_to_json(Obj,"logType", LogType);
|
||||
field_to_json(Obj,"UUID", UUID);
|
||||
field_to_json(Obj, "log", Log);
|
||||
field_to_json(Obj, "severity", Severity);
|
||||
field_to_json(Obj, "recorded", Recorded);
|
||||
field_to_json(Obj, "logType", LogType);
|
||||
field_to_json(Obj, "UUID", UUID);
|
||||
}
|
||||
|
||||
void HealthCheck::to_json(Poco::JSON::Object &Obj) const {
|
||||
EmbedDocument("values", Obj, Data);
|
||||
field_to_json(Obj,"UUID", UUID);
|
||||
field_to_json(Obj,"sanity", Sanity);
|
||||
field_to_json(Obj,"recorded", Recorded);
|
||||
field_to_json(Obj, "UUID", UUID);
|
||||
field_to_json(Obj, "sanity", Sanity);
|
||||
field_to_json(Obj, "recorded", Recorded);
|
||||
}
|
||||
|
||||
void DefaultConfiguration::to_json(Poco::JSON::Object &Obj) const {
|
||||
EmbedDocument("configuration", Obj, Configuration);
|
||||
field_to_json(Obj,"name", Name);
|
||||
field_to_json(Obj,"modelIds", Models);
|
||||
field_to_json(Obj,"description", Description);
|
||||
field_to_json(Obj,"created", Created);
|
||||
field_to_json(Obj,"lastModified", LastModified);
|
||||
field_to_json(Obj, "name", Name);
|
||||
field_to_json(Obj, "modelIds", Models);
|
||||
field_to_json(Obj, "description", Description);
|
||||
field_to_json(Obj, "created", Created);
|
||||
field_to_json(Obj, "lastModified", LastModified);
|
||||
}
|
||||
|
||||
void CommandDetails::to_json(Poco::JSON::Object &Obj) const {
|
||||
EmbedDocument("details", Obj, Details);
|
||||
EmbedDocument("results", Obj, Results);
|
||||
field_to_json(Obj,"UUID", UUID);
|
||||
field_to_json(Obj,"serialNumber", SerialNumber);
|
||||
field_to_json(Obj,"command", Command);
|
||||
field_to_json(Obj,"errorText", ErrorText);
|
||||
field_to_json(Obj,"submittedBy", SubmittedBy);
|
||||
field_to_json(Obj,"status", Status);
|
||||
field_to_json(Obj,"submitted", Submitted);
|
||||
field_to_json(Obj,"executed", Executed);
|
||||
field_to_json(Obj,"completed", Completed);
|
||||
field_to_json(Obj,"when", RunAt);
|
||||
field_to_json(Obj,"errorCode", ErrorCode);
|
||||
field_to_json(Obj,"custom", Custom);
|
||||
field_to_json(Obj,"waitingForFile", WaitingForFile);
|
||||
field_to_json(Obj,"attachFile", AttachDate);
|
||||
field_to_json(Obj,"executionTime", executionTime);
|
||||
field_to_json(Obj, "UUID", UUID);
|
||||
field_to_json(Obj, "serialNumber", SerialNumber);
|
||||
field_to_json(Obj, "command", Command);
|
||||
field_to_json(Obj, "errorText", ErrorText);
|
||||
field_to_json(Obj, "submittedBy", SubmittedBy);
|
||||
field_to_json(Obj, "status", Status);
|
||||
field_to_json(Obj, "submitted", Submitted);
|
||||
field_to_json(Obj, "executed", Executed);
|
||||
field_to_json(Obj, "completed", Completed);
|
||||
field_to_json(Obj, "when", RunAt);
|
||||
field_to_json(Obj, "errorCode", ErrorCode);
|
||||
field_to_json(Obj, "custom", Custom);
|
||||
field_to_json(Obj, "waitingForFile", WaitingForFile);
|
||||
field_to_json(Obj, "attachFile", AttachDate);
|
||||
field_to_json(Obj, "executionTime", executionTime);
|
||||
}
|
||||
|
||||
bool DefaultConfiguration::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"name",Name);
|
||||
field_from_json(Obj,"configuration",Configuration);
|
||||
field_from_json(Obj,"modelIds",Models);
|
||||
field_from_json(Obj,"description",Description);
|
||||
field_from_json(Obj, "name", Name);
|
||||
field_from_json(Obj, "configuration", Configuration);
|
||||
field_from_json(Obj, "modelIds", Models);
|
||||
field_from_json(Obj, "description", Description);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -179,18 +180,18 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void BlackListedDevice::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"serialNumber", serialNumber);
|
||||
field_to_json(Obj,"author", author);
|
||||
field_to_json(Obj,"reason", reason);
|
||||
field_to_json(Obj,"created", created);
|
||||
field_to_json(Obj, "serialNumber", serialNumber);
|
||||
field_to_json(Obj, "author", author);
|
||||
field_to_json(Obj, "reason", reason);
|
||||
field_to_json(Obj, "created", created);
|
||||
}
|
||||
|
||||
bool BlackListedDevice::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"serialNumber",serialNumber);
|
||||
field_from_json(Obj,"author",author);
|
||||
field_from_json(Obj,"reason",reason);
|
||||
field_from_json(Obj,"created",created);
|
||||
field_from_json(Obj, "serialNumber", serialNumber);
|
||||
field_from_json(Obj, "author", author);
|
||||
field_from_json(Obj, "reason", reason);
|
||||
field_from_json(Obj, "created", created);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -198,53 +199,58 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void ConnectionState::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"ipAddress", Address);
|
||||
field_to_json(Obj,"txBytes", TX);
|
||||
field_to_json(Obj,"rxBytes", RX);
|
||||
field_to_json(Obj,"messageCount", MessageCount);
|
||||
field_to_json(Obj,"UUID", UUID);
|
||||
field_to_json(Obj,"connected", Connected);
|
||||
field_to_json(Obj,"firmware", Firmware);
|
||||
field_to_json(Obj,"lastContact", LastContact);
|
||||
field_to_json(Obj,"associations_2G", Associations_2G);
|
||||
field_to_json(Obj,"associations_5G", Associations_5G);
|
||||
field_to_json(Obj,"associations_6G", Associations_6G);
|
||||
field_to_json(Obj,"webSocketClients", webSocketClients);
|
||||
field_to_json(Obj,"websocketPackets", websocketPackets);
|
||||
field_to_json(Obj,"kafkaClients", kafkaClients);
|
||||
field_to_json(Obj,"kafkaPackets", kafkaPackets);
|
||||
field_to_json(Obj,"locale", locale);
|
||||
field_to_json(Obj,"started", started);
|
||||
field_to_json(Obj,"sessionId", sessionId);
|
||||
field_to_json(Obj,"connectionCompletionTime", connectionCompletionTime);
|
||||
field_to_json(Obj,"totalConnectionTime", Utils::Now() - started);
|
||||
field_to_json(Obj,"certificateExpiryDate", certificateExpiryDate);
|
||||
field_to_json(Obj, "ipAddress", Address);
|
||||
field_to_json(Obj, "txBytes", TX);
|
||||
field_to_json(Obj, "rxBytes", RX);
|
||||
field_to_json(Obj, "messageCount", MessageCount);
|
||||
field_to_json(Obj, "UUID", UUID);
|
||||
field_to_json(Obj, "connected", Connected);
|
||||
field_to_json(Obj, "firmware", Firmware);
|
||||
field_to_json(Obj, "lastContact", LastContact);
|
||||
field_to_json(Obj, "associations_2G", Associations_2G);
|
||||
field_to_json(Obj, "associations_5G", Associations_5G);
|
||||
field_to_json(Obj, "associations_6G", Associations_6G);
|
||||
field_to_json(Obj, "webSocketClients", webSocketClients);
|
||||
field_to_json(Obj, "websocketPackets", websocketPackets);
|
||||
field_to_json(Obj, "kafkaClients", kafkaClients);
|
||||
field_to_json(Obj, "kafkaPackets", kafkaPackets);
|
||||
field_to_json(Obj, "locale", locale);
|
||||
field_to_json(Obj, "started", started);
|
||||
field_to_json(Obj, "sessionId", sessionId);
|
||||
field_to_json(Obj, "connectionCompletionTime", connectionCompletionTime);
|
||||
field_to_json(Obj, "totalConnectionTime", Utils::Now() - started);
|
||||
field_to_json(Obj, "certificateExpiryDate", certificateExpiryDate);
|
||||
|
||||
switch(VerifiedCertificate) {
|
||||
switch (VerifiedCertificate) {
|
||||
case NO_CERTIFICATE:
|
||||
field_to_json(Obj,"verifiedCertificate", "NO_CERTIFICATE"); break;
|
||||
field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
|
||||
break;
|
||||
case VALID_CERTIFICATE:
|
||||
field_to_json(Obj,"verifiedCertificate", "VALID_CERTIFICATE"); break;
|
||||
field_to_json(Obj, "verifiedCertificate", "VALID_CERTIFICATE");
|
||||
break;
|
||||
case MISMATCH_SERIAL:
|
||||
field_to_json(Obj,"verifiedCertificate", "MISMATCH_SERIAL"); break;
|
||||
field_to_json(Obj, "verifiedCertificate", "MISMATCH_SERIAL");
|
||||
break;
|
||||
case VERIFIED:
|
||||
field_to_json(Obj,"verifiedCertificate", "VERIFIED"); break;
|
||||
field_to_json(Obj, "verifiedCertificate", "VERIFIED");
|
||||
break;
|
||||
default:
|
||||
field_to_json(Obj,"verifiedCertificate", "NO_CERTIFICATE"); break;
|
||||
field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void DeviceConnectionStatistics::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"averageConnectionTime", averageConnectionTime);
|
||||
field_to_json(Obj,"connectedDevices", connectedDevices );
|
||||
field_to_json(Obj,"connectingDevices", connectingDevices );
|
||||
field_to_json(Obj, "averageConnectionTime", averageConnectionTime);
|
||||
field_to_json(Obj, "connectedDevices", connectedDevices);
|
||||
field_to_json(Obj, "connectingDevices", connectingDevices);
|
||||
}
|
||||
|
||||
bool DeviceConnectionStatistics::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"averageConnectionTime", averageConnectionTime);
|
||||
field_from_json(Obj,"connectedDevices", connectedDevices );
|
||||
field_from_json(Obj,"connectingDevices", connectingDevices );
|
||||
field_from_json(Obj, "averageConnectionTime", averageConnectionTime);
|
||||
field_from_json(Obj, "connectedDevices", connectedDevices);
|
||||
field_from_json(Obj, "connectingDevices", connectingDevices);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -252,34 +258,34 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void RttySessionDetails::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"serialNumber", SerialNumber);
|
||||
field_to_json(Obj,"server", Server);
|
||||
field_to_json(Obj,"port", Port);
|
||||
field_to_json(Obj,"token",Token);
|
||||
field_to_json(Obj,"timeout", TimeOut);
|
||||
field_to_json(Obj,"connectionId",ConnectionId);
|
||||
field_to_json(Obj,"commandUUID",CommandUUID);
|
||||
field_to_json(Obj,"started", Started);
|
||||
field_to_json(Obj,"viewport",ViewPort);
|
||||
field_to_json(Obj,"password",DevicePassword);
|
||||
field_to_json(Obj, "serialNumber", SerialNumber);
|
||||
field_to_json(Obj, "server", Server);
|
||||
field_to_json(Obj, "port", Port);
|
||||
field_to_json(Obj, "token", Token);
|
||||
field_to_json(Obj, "timeout", TimeOut);
|
||||
field_to_json(Obj, "connectionId", ConnectionId);
|
||||
field_to_json(Obj, "commandUUID", CommandUUID);
|
||||
field_to_json(Obj, "started", Started);
|
||||
field_to_json(Obj, "viewport", ViewPort);
|
||||
field_to_json(Obj, "password", DevicePassword);
|
||||
}
|
||||
|
||||
void Dashboard::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"commands",commands);
|
||||
field_to_json(Obj,"upTimes",upTimes);
|
||||
field_to_json(Obj,"memoryUsed",memoryUsed);
|
||||
field_to_json(Obj,"load1",load1);
|
||||
field_to_json(Obj,"load5",load5);
|
||||
field_to_json(Obj,"load15",load15);
|
||||
field_to_json(Obj,"vendors",vendors);
|
||||
field_to_json(Obj,"status",status);
|
||||
field_to_json(Obj,"deviceType",deviceType);
|
||||
field_to_json(Obj,"healths",healths);
|
||||
field_to_json(Obj,"certificates",certificates);
|
||||
field_to_json(Obj,"lastContact",lastContact);
|
||||
field_to_json(Obj,"associations",associations);
|
||||
field_to_json(Obj,"snapshot",snapshot);
|
||||
field_to_json(Obj,"numberOfDevices",numberOfDevices);
|
||||
field_to_json(Obj, "commands", commands);
|
||||
field_to_json(Obj, "upTimes", upTimes);
|
||||
field_to_json(Obj, "memoryUsed", memoryUsed);
|
||||
field_to_json(Obj, "load1", load1);
|
||||
field_to_json(Obj, "load5", load5);
|
||||
field_to_json(Obj, "load15", load15);
|
||||
field_to_json(Obj, "vendors", vendors);
|
||||
field_to_json(Obj, "status", status);
|
||||
field_to_json(Obj, "deviceType", deviceType);
|
||||
field_to_json(Obj, "healths", healths);
|
||||
field_to_json(Obj, "certificates", certificates);
|
||||
field_to_json(Obj, "lastContact", lastContact);
|
||||
field_to_json(Obj, "associations", associations);
|
||||
field_to_json(Obj, "snapshot", snapshot);
|
||||
field_to_json(Obj, "numberOfDevices", numberOfDevices);
|
||||
}
|
||||
|
||||
void Dashboard::reset() {
|
||||
@@ -296,38 +302,38 @@ namespace OpenWifi::GWObjects {
|
||||
certificates.clear();
|
||||
lastContact.clear();
|
||||
associations.clear();
|
||||
numberOfDevices = 0 ;
|
||||
numberOfDevices = 0;
|
||||
snapshot = Utils::Now();
|
||||
}
|
||||
|
||||
void CapabilitiesModel::to_json(Poco::JSON::Object &Obj) const{
|
||||
field_to_json(Obj,"deviceType", deviceType);
|
||||
field_to_json(Obj,"capabilities", capabilities);
|
||||
void CapabilitiesModel::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj, "deviceType", deviceType);
|
||||
field_to_json(Obj, "capabilities", capabilities);
|
||||
};
|
||||
|
||||
void ScriptRequest::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"serialNumber",serialNumber);
|
||||
field_to_json(Obj,"timeout",timeout);
|
||||
field_to_json(Obj,"type",type);
|
||||
field_to_json(Obj,"scriptId",scriptId);
|
||||
field_to_json(Obj,"script",script);
|
||||
field_to_json(Obj,"when",when);
|
||||
field_to_json(Obj,"signature", signature);
|
||||
field_to_json(Obj,"deferred", deferred);
|
||||
field_to_json(Obj,"uri", uri);
|
||||
field_to_json(Obj, "serialNumber", serialNumber);
|
||||
field_to_json(Obj, "timeout", timeout);
|
||||
field_to_json(Obj, "type", type);
|
||||
field_to_json(Obj, "scriptId", scriptId);
|
||||
field_to_json(Obj, "script", script);
|
||||
field_to_json(Obj, "when", when);
|
||||
field_to_json(Obj, "signature", signature);
|
||||
field_to_json(Obj, "deferred", deferred);
|
||||
field_to_json(Obj, "uri", uri);
|
||||
}
|
||||
|
||||
bool ScriptRequest::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"serialNumber",serialNumber);
|
||||
field_from_json(Obj,"timeout",timeout);
|
||||
field_from_json(Obj,"type",type);
|
||||
field_from_json(Obj,"script",script);
|
||||
field_from_json(Obj,"scriptId",scriptId);
|
||||
field_from_json(Obj,"when",when);
|
||||
field_from_json(Obj,"signature", signature);
|
||||
field_from_json(Obj,"deferred", deferred);
|
||||
field_from_json(Obj,"uri", uri);
|
||||
field_from_json(Obj, "serialNumber", serialNumber);
|
||||
field_from_json(Obj, "timeout", timeout);
|
||||
field_from_json(Obj, "type", type);
|
||||
field_from_json(Obj, "script", script);
|
||||
field_from_json(Obj, "scriptId", scriptId);
|
||||
field_from_json(Obj, "when", when);
|
||||
field_from_json(Obj, "signature", signature);
|
||||
field_from_json(Obj, "deferred", deferred);
|
||||
field_from_json(Obj, "uri", uri);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -335,12 +341,12 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void RadiusProxyPoolList::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"pools",pools);
|
||||
field_to_json(Obj, "pools", pools);
|
||||
}
|
||||
|
||||
bool RadiusProxyPoolList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"pools",pools);
|
||||
field_from_json(Obj, "pools", pools);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -348,22 +354,22 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void RadiusProxyPool::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"name",name);
|
||||
field_to_json(Obj,"description",description);
|
||||
field_to_json(Obj,"authConfig",authConfig);
|
||||
field_to_json(Obj,"acctConfig",acctConfig);
|
||||
field_to_json(Obj,"coaConfig",coaConfig);
|
||||
field_to_json(Obj,"useByDefault",useByDefault);
|
||||
field_to_json(Obj, "name", name);
|
||||
field_to_json(Obj, "description", description);
|
||||
field_to_json(Obj, "authConfig", authConfig);
|
||||
field_to_json(Obj, "acctConfig", acctConfig);
|
||||
field_to_json(Obj, "coaConfig", coaConfig);
|
||||
field_to_json(Obj, "useByDefault", useByDefault);
|
||||
}
|
||||
|
||||
bool RadiusProxyPool::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"name",name);
|
||||
field_from_json(Obj,"description",description);
|
||||
field_from_json(Obj,"authConfig",authConfig);
|
||||
field_from_json(Obj,"acctConfig",acctConfig);
|
||||
field_from_json(Obj,"coaConfig",coaConfig);
|
||||
field_from_json(Obj,"useByDefault",useByDefault);
|
||||
field_from_json(Obj, "name", name);
|
||||
field_from_json(Obj, "description", description);
|
||||
field_from_json(Obj, "authConfig", authConfig);
|
||||
field_from_json(Obj, "acctConfig", acctConfig);
|
||||
field_from_json(Obj, "coaConfig", coaConfig);
|
||||
field_from_json(Obj, "useByDefault", useByDefault);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -371,20 +377,20 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void RadiusProxyServerConfig::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"strategy",strategy);
|
||||
field_to_json(Obj,"monitor",monitor);
|
||||
field_to_json(Obj,"monitorMethod",monitorMethod);
|
||||
field_to_json(Obj,"methodParameters",methodParameters);
|
||||
field_to_json(Obj,"servers",servers);
|
||||
field_to_json(Obj, "strategy", strategy);
|
||||
field_to_json(Obj, "monitor", monitor);
|
||||
field_to_json(Obj, "monitorMethod", monitorMethod);
|
||||
field_to_json(Obj, "methodParameters", methodParameters);
|
||||
field_to_json(Obj, "servers", servers);
|
||||
}
|
||||
|
||||
bool RadiusProxyServerConfig::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"strategy",strategy);
|
||||
field_from_json(Obj,"monitor",monitor);
|
||||
field_from_json(Obj,"monitorMethod",monitorMethod);
|
||||
field_from_json(Obj,"methodParameters",methodParameters);
|
||||
field_from_json(Obj,"servers",servers);
|
||||
field_from_json(Obj, "strategy", strategy);
|
||||
field_from_json(Obj, "monitor", monitor);
|
||||
field_from_json(Obj, "monitorMethod", monitorMethod);
|
||||
field_from_json(Obj, "methodParameters", methodParameters);
|
||||
field_from_json(Obj, "servers", servers);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -392,40 +398,40 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void RadiusProxyServerEntry::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"name",name);
|
||||
field_to_json(Obj,"ip",ip);
|
||||
field_to_json(Obj,"port",port);
|
||||
field_to_json(Obj,"weight",weight);
|
||||
field_to_json(Obj,"secret",secret);
|
||||
field_to_json(Obj,"certificate",certificate);
|
||||
field_to_json(Obj,"radsec",radsec);
|
||||
field_to_json(Obj,"allowSelfSigned",allowSelfSigned);
|
||||
field_to_json(Obj,"radsecPort",radsecPort);
|
||||
field_to_json(Obj,"radsecSecret",radsecSecret);
|
||||
field_to_json(Obj,"radsecCacerts",radsecCacerts);
|
||||
field_to_json(Obj,"radsecCert",radsecCert);
|
||||
field_to_json(Obj,"radsecKey",radsecKey);
|
||||
field_to_json(Obj,"radsecRealms",radsecRealms);
|
||||
field_to_json(Obj,"ignore",ignore);
|
||||
field_to_json(Obj, "name", name);
|
||||
field_to_json(Obj, "ip", ip);
|
||||
field_to_json(Obj, "port", port);
|
||||
field_to_json(Obj, "weight", weight);
|
||||
field_to_json(Obj, "secret", secret);
|
||||
field_to_json(Obj, "certificate", certificate);
|
||||
field_to_json(Obj, "radsec", radsec);
|
||||
field_to_json(Obj, "allowSelfSigned", allowSelfSigned);
|
||||
field_to_json(Obj, "radsecPort", radsecPort);
|
||||
field_to_json(Obj, "radsecSecret", radsecSecret);
|
||||
field_to_json(Obj, "radsecCacerts", radsecCacerts);
|
||||
field_to_json(Obj, "radsecCert", radsecCert);
|
||||
field_to_json(Obj, "radsecKey", radsecKey);
|
||||
field_to_json(Obj, "radsecRealms", radsecRealms);
|
||||
field_to_json(Obj, "ignore", ignore);
|
||||
}
|
||||
|
||||
bool RadiusProxyServerEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"name",name);
|
||||
field_from_json(Obj,"ip",ip);
|
||||
field_from_json(Obj,"port",port);
|
||||
field_from_json(Obj,"weight",weight);
|
||||
field_from_json(Obj,"secret",secret);
|
||||
field_from_json(Obj,"certificate",certificate);
|
||||
field_from_json(Obj,"radsec",radsec);
|
||||
field_from_json(Obj,"allowSelfSigned",allowSelfSigned);
|
||||
field_from_json(Obj,"radsecSecret",radsecSecret);
|
||||
field_from_json(Obj,"radsecPort",radsecPort);
|
||||
field_from_json(Obj,"radsecCacerts",radsecCacerts);
|
||||
field_from_json(Obj,"radsecCert",radsecCert);
|
||||
field_from_json(Obj,"radsecKey",radsecKey);
|
||||
field_from_json(Obj,"radsecRealms",radsecRealms);
|
||||
field_from_json(Obj,"ignore",ignore);
|
||||
field_from_json(Obj, "name", name);
|
||||
field_from_json(Obj, "ip", ip);
|
||||
field_from_json(Obj, "port", port);
|
||||
field_from_json(Obj, "weight", weight);
|
||||
field_from_json(Obj, "secret", secret);
|
||||
field_from_json(Obj, "certificate", certificate);
|
||||
field_from_json(Obj, "radsec", radsec);
|
||||
field_from_json(Obj, "allowSelfSigned", allowSelfSigned);
|
||||
field_from_json(Obj, "radsecSecret", radsecSecret);
|
||||
field_from_json(Obj, "radsecPort", radsecPort);
|
||||
field_from_json(Obj, "radsecCacerts", radsecCacerts);
|
||||
field_from_json(Obj, "radsecCert", radsecCert);
|
||||
field_from_json(Obj, "radsecKey", radsecKey);
|
||||
field_from_json(Obj, "radsecRealms", radsecRealms);
|
||||
field_from_json(Obj, "ignore", ignore);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -433,38 +439,38 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void ScriptEntry::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id", id);
|
||||
field_to_json(Obj,"name", name);
|
||||
field_to_json(Obj,"description", description);
|
||||
field_to_json(Obj,"uri", uri);
|
||||
field_to_json(Obj,"content", content);
|
||||
field_to_json(Obj,"version", version);
|
||||
field_to_json(Obj,"type", type);
|
||||
field_to_json(Obj,"created", created);
|
||||
field_to_json(Obj,"modified", modified);
|
||||
field_to_json(Obj,"author", author);
|
||||
field_to_json(Obj,"restricted", restricted);
|
||||
field_to_json(Obj,"deferred", deferred);
|
||||
field_to_json(Obj,"timeout", timeout);
|
||||
field_to_json(Obj,"defaultUploadURI", defaultUploadURI);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "name", name);
|
||||
field_to_json(Obj, "description", description);
|
||||
field_to_json(Obj, "uri", uri);
|
||||
field_to_json(Obj, "content", content);
|
||||
field_to_json(Obj, "version", version);
|
||||
field_to_json(Obj, "type", type);
|
||||
field_to_json(Obj, "created", created);
|
||||
field_to_json(Obj, "modified", modified);
|
||||
field_to_json(Obj, "author", author);
|
||||
field_to_json(Obj, "restricted", restricted);
|
||||
field_to_json(Obj, "deferred", deferred);
|
||||
field_to_json(Obj, "timeout", timeout);
|
||||
field_to_json(Obj, "defaultUploadURI", defaultUploadURI);
|
||||
}
|
||||
|
||||
bool ScriptEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id", id);
|
||||
field_from_json(Obj,"name", name);
|
||||
field_from_json(Obj,"description", description);
|
||||
field_from_json(Obj,"uri", uri);
|
||||
field_from_json(Obj,"content", content);
|
||||
field_from_json(Obj,"version", version);
|
||||
field_from_json(Obj,"type", type);
|
||||
field_from_json(Obj,"created", created);
|
||||
field_from_json(Obj,"modified", modified);
|
||||
field_from_json(Obj,"author", author);
|
||||
field_from_json(Obj,"restricted", restricted);
|
||||
field_from_json(Obj,"deferred", deferred);
|
||||
field_from_json(Obj,"timeout", timeout);
|
||||
field_from_json(Obj,"defaultUploadURI", defaultUploadURI);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "name", name);
|
||||
field_from_json(Obj, "description", description);
|
||||
field_from_json(Obj, "uri", uri);
|
||||
field_from_json(Obj, "content", content);
|
||||
field_from_json(Obj, "version", version);
|
||||
field_from_json(Obj, "type", type);
|
||||
field_from_json(Obj, "created", created);
|
||||
field_from_json(Obj, "modified", modified);
|
||||
field_from_json(Obj, "author", author);
|
||||
field_from_json(Obj, "restricted", restricted);
|
||||
field_from_json(Obj, "deferred", deferred);
|
||||
field_from_json(Obj, "timeout", timeout);
|
||||
field_from_json(Obj, "defaultUploadURI", defaultUploadURI);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -472,12 +478,12 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void ScriptEntryList::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"scripts",scripts);
|
||||
field_to_json(Obj, "scripts", scripts);
|
||||
}
|
||||
|
||||
bool ScriptEntryList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"scripts",scripts);
|
||||
field_from_json(Obj, "scripts", scripts);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
@@ -485,63 +491,57 @@ namespace OpenWifi::GWObjects {
|
||||
}
|
||||
|
||||
void DeviceRestrictionsKeyInfo::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"vendor", vendor);
|
||||
field_to_json(Obj,"algo", algo);
|
||||
field_to_json(Obj, "vendor", vendor);
|
||||
field_to_json(Obj, "algo", algo);
|
||||
}
|
||||
|
||||
bool DeviceRestrictionsKeyInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"vendor", vendor);
|
||||
field_from_json(Obj,"algo", algo);
|
||||
field_from_json(Obj, "vendor", vendor);
|
||||
field_from_json(Obj, "algo", algo);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
void DeviceRestrictions::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"dfs", dfs);
|
||||
field_to_json(Obj,"ssh", ssh);
|
||||
field_to_json(Obj,"rtty", rtty);
|
||||
field_to_json(Obj,"tty", tty);
|
||||
field_to_json(Obj,"developer", developer);
|
||||
field_to_json(Obj,"upgrade", upgrade);
|
||||
field_to_json(Obj,"commands", commands);
|
||||
field_to_json(Obj,"country", country);
|
||||
field_to_json(Obj,"key_info", key_info);
|
||||
field_to_json(Obj, "dfs", dfs);
|
||||
field_to_json(Obj, "ssh", ssh);
|
||||
field_to_json(Obj, "rtty", rtty);
|
||||
field_to_json(Obj, "tty", tty);
|
||||
field_to_json(Obj, "developer", developer);
|
||||
field_to_json(Obj, "upgrade", upgrade);
|
||||
field_to_json(Obj, "commands", commands);
|
||||
field_to_json(Obj, "country", country);
|
||||
field_to_json(Obj, "key_info", key_info);
|
||||
}
|
||||
|
||||
bool DeviceRestrictions::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"dfs", dfs);
|
||||
field_from_json(Obj,"ssh", ssh);
|
||||
field_from_json(Obj,"rtty", rtty);
|
||||
field_from_json(Obj,"tty", tty);
|
||||
field_from_json(Obj,"developer", developer);
|
||||
field_from_json(Obj,"upgrade", upgrade);
|
||||
field_from_json(Obj,"commands", commands);
|
||||
field_from_json(Obj,"country", country);
|
||||
field_from_json(Obj,"key_info", key_info);
|
||||
field_from_json(Obj, "dfs", dfs);
|
||||
field_from_json(Obj, "ssh", ssh);
|
||||
field_from_json(Obj, "rtty", rtty);
|
||||
field_from_json(Obj, "tty", tty);
|
||||
field_from_json(Obj, "developer", developer);
|
||||
field_from_json(Obj, "upgrade", upgrade);
|
||||
field_from_json(Obj, "commands", commands);
|
||||
field_from_json(Obj, "country", country);
|
||||
field_from_json(Obj, "key_info", key_info);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DeviceRestrictionsKeyInfo::operator!=(const OpenWifi::GWObjects::DeviceRestrictionsKeyInfo &T) const {
|
||||
return (T.algo!=algo) || (T.vendor!=vendor);
|
||||
bool DeviceRestrictionsKeyInfo::operator!=(
|
||||
const OpenWifi::GWObjects::DeviceRestrictionsKeyInfo &T) const {
|
||||
return (T.algo != algo) || (T.vendor != vendor);
|
||||
}
|
||||
|
||||
bool DeviceRestrictions::operator!=(const OpenWifi::GWObjects::DeviceRestrictions &T) const {
|
||||
return ( (T.dfs!=dfs) ||
|
||||
(T.rtty!=rtty) ||
|
||||
(T.upgrade!=upgrade) ||
|
||||
(T.commands != commands) ||
|
||||
(T.developer != developer) ||
|
||||
(T.ssh !=ssh) ||
|
||||
(T.key_info != key_info) ||
|
||||
(T.country != country) );
|
||||
return ((T.dfs != dfs) || (T.rtty != rtty) || (T.upgrade != upgrade) ||
|
||||
(T.commands != commands) || (T.developer != developer) || (T.ssh != ssh) ||
|
||||
(T.key_info != key_info) || (T.country != country));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace OpenWifi::GWObjects
|
||||
|
||||
@@ -13,36 +13,31 @@
|
||||
|
||||
namespace OpenWifi::GWObjects {
|
||||
|
||||
enum CertificateValidation {
|
||||
NO_CERTIFICATE,
|
||||
VALID_CERTIFICATE,
|
||||
MISMATCH_SERIAL,
|
||||
VERIFIED
|
||||
};
|
||||
enum CertificateValidation { NO_CERTIFICATE, VALID_CERTIFICATE, MISMATCH_SERIAL, VERIFIED };
|
||||
|
||||
struct ConnectionState {
|
||||
uint64_t MessageCount = 0 ;
|
||||
uint64_t MessageCount = 0;
|
||||
std::string Address;
|
||||
uint64_t UUID = 0 ;
|
||||
uint64_t PendingUUID = 0 ;
|
||||
uint64_t UUID = 0;
|
||||
uint64_t PendingUUID = 0;
|
||||
uint64_t TX = 0, RX = 0;
|
||||
uint64_t Associations_2G=0;
|
||||
uint64_t Associations_5G=0;
|
||||
uint64_t Associations_6G=0;
|
||||
uint64_t Associations_2G = 0;
|
||||
uint64_t Associations_5G = 0;
|
||||
uint64_t Associations_6G = 0;
|
||||
bool Connected = false;
|
||||
uint64_t LastContact=0;
|
||||
uint64_t LastContact = 0;
|
||||
std::string Firmware;
|
||||
CertificateValidation VerifiedCertificate = NO_CERTIFICATE;
|
||||
std::string Compatible;
|
||||
uint64_t kafkaClients=0;
|
||||
uint64_t webSocketClients=0;
|
||||
uint64_t kafkaPackets=0;
|
||||
uint64_t websocketPackets=0;
|
||||
uint64_t kafkaClients = 0;
|
||||
uint64_t webSocketClients = 0;
|
||||
uint64_t kafkaPackets = 0;
|
||||
uint64_t websocketPackets = 0;
|
||||
std::string locale;
|
||||
uint64_t started=0;
|
||||
uint64_t sessionId=0;
|
||||
double connectionCompletionTime=0.0;
|
||||
std::uint64_t certificateExpiryDate=0;
|
||||
uint64_t started = 0;
|
||||
uint64_t sessionId = 0;
|
||||
double connectionCompletionTime = 0.0;
|
||||
std::uint64_t certificateExpiryDate = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
};
|
||||
@@ -51,7 +46,7 @@ namespace OpenWifi::GWObjects {
|
||||
std::string vendor;
|
||||
std::string algo;
|
||||
|
||||
bool operator !=(const DeviceRestrictionsKeyInfo &b) const;
|
||||
bool operator!=(const DeviceRestrictionsKeyInfo &b) const;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -68,7 +63,7 @@ namespace OpenWifi::GWObjects {
|
||||
std::vector<std::string> country;
|
||||
DeviceRestrictionsKeyInfo key_info;
|
||||
|
||||
bool operator !=(const DeviceRestrictions &D) const;
|
||||
bool operator!=(const DeviceRestrictions &D) const;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -86,18 +81,18 @@ namespace OpenWifi::GWObjects {
|
||||
std::string Firmware;
|
||||
std::string Compatible;
|
||||
std::string FWUpdatePolicy;
|
||||
uint64_t UUID = 0 ;
|
||||
uint64_t CreationTimestamp = 0 ;
|
||||
uint64_t LastConfigurationChange = 0 ;
|
||||
uint64_t LastConfigurationDownload = 0 ;
|
||||
uint64_t LastFWUpdate = 0 ;
|
||||
uint64_t UUID = 0;
|
||||
uint64_t CreationTimestamp = 0;
|
||||
uint64_t LastConfigurationChange = 0;
|
||||
uint64_t LastConfigurationDownload = 0;
|
||||
uint64_t LastFWUpdate = 0;
|
||||
std::string Venue;
|
||||
std::string DevicePassword;
|
||||
std::string subscriber;
|
||||
std::string entity;
|
||||
uint64_t modified=0;
|
||||
uint64_t modified = 0;
|
||||
std::string locale;
|
||||
bool restrictedDevice=false;
|
||||
bool restrictedDevice = false;
|
||||
std::string pendingConfiguration;
|
||||
std::string pendingConfigurationCmd;
|
||||
DeviceRestrictions restrictionDetails;
|
||||
@@ -119,7 +114,7 @@ namespace OpenWifi::GWObjects {
|
||||
|
||||
struct Statistics {
|
||||
std::string SerialNumber;
|
||||
uint64_t UUID = 0 ;
|
||||
uint64_t UUID = 0;
|
||||
std::string Data;
|
||||
uint64_t Recorded = 0;
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -127,17 +122,17 @@ namespace OpenWifi::GWObjects {
|
||||
|
||||
struct HealthCheck {
|
||||
std::string SerialNumber;
|
||||
uint64_t UUID = 0 ;
|
||||
uint64_t UUID = 0;
|
||||
std::string Data;
|
||||
uint64_t Recorded = 0 ;
|
||||
uint64_t Sanity = 0 ;
|
||||
uint64_t Recorded = 0;
|
||||
uint64_t Sanity = 0;
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
};
|
||||
|
||||
struct Capabilities {
|
||||
std::string Capabilities;
|
||||
uint64_t FirstUpdate = 0 ;
|
||||
uint64_t LastUpdate = 0 ;
|
||||
uint64_t FirstUpdate = 0;
|
||||
uint64_t LastUpdate = 0;
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
};
|
||||
|
||||
@@ -155,10 +150,10 @@ namespace OpenWifi::GWObjects {
|
||||
std::string SerialNumber;
|
||||
std::string Log;
|
||||
std::string Data;
|
||||
uint64_t Severity = 0 ;
|
||||
uint64_t Recorded = 0 ;
|
||||
uint64_t LogType = 0 ;
|
||||
uint64_t UUID = 0 ;
|
||||
uint64_t Severity = 0;
|
||||
uint64_t Recorded = 0;
|
||||
uint64_t LogType = 0;
|
||||
uint64_t UUID = 0;
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
};
|
||||
|
||||
@@ -184,13 +179,13 @@ namespace OpenWifi::GWObjects {
|
||||
std::string ErrorText;
|
||||
uint64_t Submitted = time(nullptr);
|
||||
uint64_t Executed = 0;
|
||||
uint64_t Completed = 0 ;
|
||||
uint64_t RunAt = 0 ;
|
||||
uint64_t ErrorCode = 0 ;
|
||||
uint64_t Custom = 0 ;
|
||||
uint64_t WaitingForFile = 0 ;
|
||||
uint64_t AttachDate = 0 ;
|
||||
uint64_t AttachSize = 0 ;
|
||||
uint64_t Completed = 0;
|
||||
uint64_t RunAt = 0;
|
||||
uint64_t ErrorCode = 0;
|
||||
uint64_t Custom = 0;
|
||||
uint64_t WaitingForFile = 0;
|
||||
uint64_t AttachDate = 0;
|
||||
uint64_t AttachSize = 0;
|
||||
std::string AttachType;
|
||||
double executionTime = 0.0;
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -208,20 +203,20 @@ namespace OpenWifi::GWObjects {
|
||||
struct RttySessionDetails {
|
||||
std::string SerialNumber;
|
||||
std::string Server;
|
||||
uint64_t Port = 0 ;
|
||||
uint64_t Port = 0;
|
||||
std::string Token;
|
||||
uint64_t TimeOut = 0 ;
|
||||
uint64_t TimeOut = 0;
|
||||
std::string ConnectionId;
|
||||
uint64_t Started = 0 ;
|
||||
uint64_t Started = 0;
|
||||
std::string CommandUUID;
|
||||
uint64_t ViewPort = 0 ;
|
||||
uint64_t ViewPort = 0;
|
||||
std::string DevicePassword;
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
};
|
||||
|
||||
struct Dashboard {
|
||||
uint64_t snapshot = 0 ;
|
||||
uint64_t numberOfDevices = 0 ;
|
||||
uint64_t snapshot = 0;
|
||||
uint64_t numberOfDevices = 0;
|
||||
Types::CountedMap commands;
|
||||
Types::CountedMap upTimes;
|
||||
Types::CountedMap memoryUsed;
|
||||
@@ -258,8 +253,8 @@ namespace OpenWifi::GWObjects {
|
||||
std::uint64_t modified;
|
||||
std::string author;
|
||||
Types::StringVec restricted;
|
||||
bool deferred=false;
|
||||
std::uint64_t timeout=30;
|
||||
bool deferred = false;
|
||||
std::uint64_t timeout = 30;
|
||||
std::string defaultUploadURI;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -275,7 +270,7 @@ namespace OpenWifi::GWObjects {
|
||||
|
||||
struct ScriptRequest {
|
||||
std::string serialNumber;
|
||||
uint64_t timeout=30;
|
||||
uint64_t timeout = 30;
|
||||
std::string type;
|
||||
std::string script;
|
||||
std::string scriptId;
|
||||
@@ -291,19 +286,19 @@ namespace OpenWifi::GWObjects {
|
||||
struct RadiusProxyServerEntry {
|
||||
std::string name;
|
||||
std::string ip;
|
||||
uint16_t port=0;
|
||||
uint64_t weight=0;
|
||||
uint16_t port = 0;
|
||||
uint64_t weight = 0;
|
||||
std::string secret;
|
||||
std::string certificate;
|
||||
bool radsec=false;
|
||||
bool allowSelfSigned=false;
|
||||
uint16_t radsecPort=2083;
|
||||
bool radsec = false;
|
||||
bool allowSelfSigned = false;
|
||||
uint16_t radsecPort = 2083;
|
||||
std::string radsecSecret;
|
||||
std::string radsecKey;
|
||||
std::string radsecCert;
|
||||
std::vector<std::string> radsecCacerts;
|
||||
std::vector<std::string> radsecRealms;
|
||||
bool ignore=false;
|
||||
bool ignore = false;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -311,7 +306,7 @@ namespace OpenWifi::GWObjects {
|
||||
|
||||
struct RadiusProxyServerConfig {
|
||||
std::string strategy;
|
||||
bool monitor=false;
|
||||
bool monitor = false;
|
||||
std::string monitorMethod;
|
||||
std::vector<std::string> methodParameters;
|
||||
std::vector<RadiusProxyServerEntry> servers;
|
||||
@@ -326,7 +321,7 @@ namespace OpenWifi::GWObjects {
|
||||
RadiusProxyServerConfig authConfig;
|
||||
RadiusProxyServerConfig acctConfig;
|
||||
RadiusProxyServerConfig coaConfig;
|
||||
bool useByDefault=false;
|
||||
bool useByDefault = false;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -339,4 +334,4 @@ namespace OpenWifi::GWObjects {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace OpenWifi::GWObjects
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
#include "framework/RESTAPI_utils.h"
|
||||
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
using OpenWifi::RESTAPI_utils::field_from_json;
|
||||
using OpenWifi::RESTAPI_utils::EmbedDocument;
|
||||
using OpenWifi::RESTAPI_utils::field_from_json;
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
|
||||
#include "RESTAPI_OWLSobjects.h"
|
||||
|
||||
@@ -15,96 +15,88 @@ using OpenWifi::RESTAPI_utils::EmbedDocument;
|
||||
namespace OpenWifi::OWLSObjects {
|
||||
|
||||
void SimulationDetails::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id", id);
|
||||
field_to_json(Obj,"name", name);
|
||||
field_to_json(Obj,"gateway", gateway);
|
||||
field_to_json(Obj,"certificate", certificate);
|
||||
field_to_json(Obj,"key", key);
|
||||
field_to_json(Obj,"macPrefix", macPrefix);
|
||||
field_to_json(Obj,"deviceType", deviceType);
|
||||
field_to_json(Obj,"devices", devices);
|
||||
field_to_json(Obj,"healthCheckInterval", healthCheckInterval);
|
||||
field_to_json(Obj,"stateInterval", stateInterval);
|
||||
field_to_json(Obj,"minAssociations", minAssociations);
|
||||
field_to_json(Obj,"maxAssociations", maxAssociations);
|
||||
field_to_json(Obj,"minClients", minClients);
|
||||
field_to_json(Obj,"maxClients", maxClients);
|
||||
field_to_json(Obj,"simulationLength", simulationLength);
|
||||
field_to_json(Obj,"threads", threads);
|
||||
field_to_json(Obj,"clientInterval", clientInterval);
|
||||
field_to_json(Obj,"keepAlive", keepAlive);
|
||||
field_to_json(Obj,"reconnectInterval", reconnectInterval);
|
||||
field_to_json(Obj,"concurrentDevices", concurrentDevices);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "name", name);
|
||||
field_to_json(Obj, "gateway", gateway);
|
||||
field_to_json(Obj, "certificate", certificate);
|
||||
field_to_json(Obj, "key", key);
|
||||
field_to_json(Obj, "macPrefix", macPrefix);
|
||||
field_to_json(Obj, "deviceType", deviceType);
|
||||
field_to_json(Obj, "devices", devices);
|
||||
field_to_json(Obj, "healthCheckInterval", healthCheckInterval);
|
||||
field_to_json(Obj, "stateInterval", stateInterval);
|
||||
field_to_json(Obj, "minAssociations", minAssociations);
|
||||
field_to_json(Obj, "maxAssociations", maxAssociations);
|
||||
field_to_json(Obj, "minClients", minClients);
|
||||
field_to_json(Obj, "maxClients", maxClients);
|
||||
field_to_json(Obj, "simulationLength", simulationLength);
|
||||
field_to_json(Obj, "threads", threads);
|
||||
field_to_json(Obj, "clientInterval", clientInterval);
|
||||
field_to_json(Obj, "keepAlive", keepAlive);
|
||||
field_to_json(Obj, "reconnectInterval", reconnectInterval);
|
||||
field_to_json(Obj, "concurrentDevices", concurrentDevices);
|
||||
}
|
||||
|
||||
bool SimulationDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id", id);
|
||||
field_from_json(Obj,"name", name);
|
||||
field_from_json(Obj,"gateway", gateway);
|
||||
field_from_json(Obj,"certificate", certificate);
|
||||
field_from_json(Obj,"key", key);
|
||||
field_from_json(Obj,"macPrefix", macPrefix);
|
||||
field_from_json(Obj,"deviceType", deviceType);
|
||||
field_from_json(Obj,"devices", devices);
|
||||
field_from_json(Obj,"healthCheckInterval", healthCheckInterval);
|
||||
field_from_json(Obj,"stateInterval", stateInterval);
|
||||
field_from_json(Obj,"minAssociations", minAssociations);
|
||||
field_from_json(Obj,"maxAssociations", maxAssociations);
|
||||
field_from_json(Obj,"minClients", minClients);
|
||||
field_from_json(Obj,"maxClients", maxClients);
|
||||
field_from_json(Obj,"simulationLength", simulationLength);
|
||||
field_from_json(Obj,"threads", threads);
|
||||
field_from_json(Obj,"clientInterval", clientInterval);
|
||||
field_from_json(Obj,"keepAlive", keepAlive);
|
||||
field_from_json(Obj,"reconnectInterval", reconnectInterval);
|
||||
field_from_json(Obj,"concurrentDevices", concurrentDevices);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "name", name);
|
||||
field_from_json(Obj, "gateway", gateway);
|
||||
field_from_json(Obj, "certificate", certificate);
|
||||
field_from_json(Obj, "key", key);
|
||||
field_from_json(Obj, "macPrefix", macPrefix);
|
||||
field_from_json(Obj, "deviceType", deviceType);
|
||||
field_from_json(Obj, "devices", devices);
|
||||
field_from_json(Obj, "healthCheckInterval", healthCheckInterval);
|
||||
field_from_json(Obj, "stateInterval", stateInterval);
|
||||
field_from_json(Obj, "minAssociations", minAssociations);
|
||||
field_from_json(Obj, "maxAssociations", maxAssociations);
|
||||
field_from_json(Obj, "minClients", minClients);
|
||||
field_from_json(Obj, "maxClients", maxClients);
|
||||
field_from_json(Obj, "simulationLength", simulationLength);
|
||||
field_from_json(Obj, "threads", threads);
|
||||
field_from_json(Obj, "clientInterval", clientInterval);
|
||||
field_from_json(Obj, "keepAlive", keepAlive);
|
||||
field_from_json(Obj, "reconnectInterval", reconnectInterval);
|
||||
field_from_json(Obj, "concurrentDevices", concurrentDevices);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void SimulationDetailsList::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"list", list);
|
||||
field_to_json(Obj, "list", list);
|
||||
}
|
||||
|
||||
bool SimulationDetailsList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"list", list);
|
||||
field_from_json(Obj, "list", list);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void SimulationStatus::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id", id);
|
||||
field_to_json(Obj,"simulationId", simulationId);
|
||||
field_to_json(Obj,"state", state);
|
||||
field_to_json(Obj,"tx", tx);
|
||||
field_to_json(Obj,"rx", rx);
|
||||
field_to_json(Obj,"msgsTx", msgsTx);
|
||||
field_to_json(Obj,"msgsRx", msgsRx);
|
||||
field_to_json(Obj,"liveDevices", liveDevices);
|
||||
field_to_json(Obj,"timeToFullDevices", timeToFullDevices);
|
||||
field_to_json(Obj,"startTime", startTime);
|
||||
field_to_json(Obj,"endTime", endTime);
|
||||
field_to_json(Obj,"errorDevices", errorDevices);
|
||||
field_to_json(Obj,"owner", owner);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "simulationId", simulationId);
|
||||
field_to_json(Obj, "state", state);
|
||||
field_to_json(Obj, "tx", tx);
|
||||
field_to_json(Obj, "rx", rx);
|
||||
field_to_json(Obj, "msgsTx", msgsTx);
|
||||
field_to_json(Obj, "msgsRx", msgsRx);
|
||||
field_to_json(Obj, "liveDevices", liveDevices);
|
||||
field_to_json(Obj, "timeToFullDevices", timeToFullDevices);
|
||||
field_to_json(Obj, "startTime", startTime);
|
||||
field_to_json(Obj, "endTime", endTime);
|
||||
field_to_json(Obj, "errorDevices", errorDevices);
|
||||
field_to_json(Obj, "owner", owner);
|
||||
}
|
||||
|
||||
void Dashboard::to_json([[maybe_unused]] Poco::JSON::Object &Obj) const {
|
||||
void Dashboard::to_json([[maybe_unused]] Poco::JSON::Object &Obj) const {}
|
||||
|
||||
}
|
||||
bool Dashboard::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) { return true; }
|
||||
|
||||
bool Dashboard::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) {
|
||||
return true;
|
||||
}
|
||||
|
||||
void Dashboard::reset() {
|
||||
|
||||
}
|
||||
}
|
||||
void Dashboard::reset() {}
|
||||
} // namespace OpenWifi::OWLSObjects
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
#ifndef UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
|
||||
#define UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
|
||||
|
||||
#include <vector>
|
||||
#include "Poco/JSON/Object.h"
|
||||
#include <vector>
|
||||
|
||||
namespace OpenWifi::OWLSObjects {
|
||||
|
||||
@@ -20,16 +20,16 @@ namespace OpenWifi::OWLSObjects {
|
||||
std::string deviceType;
|
||||
uint64_t devices = 5;
|
||||
uint64_t healthCheckInterval = 60;
|
||||
uint64_t stateInterval = 60 ;
|
||||
uint64_t stateInterval = 60;
|
||||
uint64_t minAssociations = 1;
|
||||
uint64_t maxAssociations = 3;
|
||||
uint64_t minClients = 1 ;
|
||||
uint64_t minClients = 1;
|
||||
uint64_t maxClients = 3;
|
||||
uint64_t simulationLength = 60 * 60;
|
||||
uint64_t threads = 16;
|
||||
uint64_t clientInterval = 1;
|
||||
uint64_t keepAlive = 300;
|
||||
uint64_t reconnectInterval = 30 ;
|
||||
uint64_t reconnectInterval = 30;
|
||||
uint64_t concurrentDevices = 5;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -61,17 +61,14 @@ namespace OpenWifi::OWLSObjects {
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
};
|
||||
|
||||
|
||||
struct Dashboard {
|
||||
int O;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
void reset();
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace OpenWifi::OWLSObjects
|
||||
|
||||
|
||||
#endif //UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
|
||||
#endif // UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -24,8 +24,8 @@ namespace OpenWifi::ProvObjects {
|
||||
std::string name;
|
||||
std::string description;
|
||||
SecurityObjects::NoteInfoVec notes;
|
||||
uint64_t created=0;
|
||||
uint64_t modified=0;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
Types::TagList tags;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -167,37 +167,50 @@ namespace OpenWifi::ProvObjects {
|
||||
typedef std::vector<ManagementRole> ManagementRoleVec;
|
||||
|
||||
enum LocationType {
|
||||
LT_SERVICE, LT_EQUIPMENT, LT_AUTO, LT_MANUAL,
|
||||
LT_SPECIAL, LT_UNKNOWN, LT_CORPORATE
|
||||
LT_SERVICE,
|
||||
LT_EQUIPMENT,
|
||||
LT_AUTO,
|
||||
LT_MANUAL,
|
||||
LT_SPECIAL,
|
||||
LT_UNKNOWN,
|
||||
LT_CORPORATE
|
||||
};
|
||||
|
||||
inline std::string to_string(LocationType L) {
|
||||
switch(L) {
|
||||
case LT_SERVICE: return "SERVICE";
|
||||
case LT_EQUIPMENT: return "EQUIPMENT";
|
||||
case LT_AUTO: return "AUTO";
|
||||
case LT_MANUAL: return "MANUAL";
|
||||
case LT_SPECIAL: return "SPECIAL";
|
||||
case LT_UNKNOWN: return "UNKNOWN";
|
||||
case LT_CORPORATE: return "CORPORATE";
|
||||
default: return "UNKNOWN";
|
||||
switch (L) {
|
||||
case LT_SERVICE:
|
||||
return "SERVICE";
|
||||
case LT_EQUIPMENT:
|
||||
return "EQUIPMENT";
|
||||
case LT_AUTO:
|
||||
return "AUTO";
|
||||
case LT_MANUAL:
|
||||
return "MANUAL";
|
||||
case LT_SPECIAL:
|
||||
return "SPECIAL";
|
||||
case LT_UNKNOWN:
|
||||
return "UNKNOWN";
|
||||
case LT_CORPORATE:
|
||||
return "CORPORATE";
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
inline LocationType location_from_string(const std::string &S) {
|
||||
if(!Poco::icompare(S,"SERVICE"))
|
||||
if (!Poco::icompare(S, "SERVICE"))
|
||||
return LT_SERVICE;
|
||||
else if(!Poco::icompare(S,"EQUIPMENT"))
|
||||
else if (!Poco::icompare(S, "EQUIPMENT"))
|
||||
return LT_EQUIPMENT;
|
||||
else if(!Poco::icompare(S,"AUTO"))
|
||||
else if (!Poco::icompare(S, "AUTO"))
|
||||
return LT_AUTO;
|
||||
else if(!Poco::icompare(S,"MANUAL"))
|
||||
else if (!Poco::icompare(S, "MANUAL"))
|
||||
return LT_MANUAL;
|
||||
else if(!Poco::icompare(S,"SPECIAL"))
|
||||
else if (!Poco::icompare(S, "SPECIAL"))
|
||||
return LT_SPECIAL;
|
||||
else if(!Poco::icompare(S,"UNKNOWN"))
|
||||
else if (!Poco::icompare(S, "UNKNOWN"))
|
||||
return LT_UNKNOWN;
|
||||
else if(!Poco::icompare(S,"CORPORATE"))
|
||||
else if (!Poco::icompare(S, "CORPORATE"))
|
||||
return LT_CORPORATE;
|
||||
return LT_UNKNOWN;
|
||||
}
|
||||
@@ -267,50 +280,66 @@ namespace OpenWifi::ProvObjects {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
|
||||
enum ContactType {
|
||||
CT_SUBSCRIBER, CT_USER, CT_INSTALLER, CT_CSR, CT_MANAGER,
|
||||
CT_BUSINESSOWNER, CT_TECHNICIAN, CT_CORPORATE, CT_UNKNOWN
|
||||
CT_SUBSCRIBER,
|
||||
CT_USER,
|
||||
CT_INSTALLER,
|
||||
CT_CSR,
|
||||
CT_MANAGER,
|
||||
CT_BUSINESSOWNER,
|
||||
CT_TECHNICIAN,
|
||||
CT_CORPORATE,
|
||||
CT_UNKNOWN
|
||||
};
|
||||
|
||||
inline std::string to_string(ContactType L) {
|
||||
switch(L) {
|
||||
case CT_SUBSCRIBER: return "SUBSCRIBER";
|
||||
case CT_USER: return "USER";
|
||||
case CT_INSTALLER: return "INSTALLER";
|
||||
case CT_CSR: return "CSR";
|
||||
case CT_MANAGER: return "MANAGER";
|
||||
case CT_BUSINESSOWNER: return "BUSINESSOWNER";
|
||||
case CT_TECHNICIAN: return "TECHNICIAN";
|
||||
case CT_CORPORATE: return "CORPORATE";
|
||||
case CT_UNKNOWN: return "UNKNOWN";
|
||||
default: return "UNKNOWN";
|
||||
switch (L) {
|
||||
case CT_SUBSCRIBER:
|
||||
return "SUBSCRIBER";
|
||||
case CT_USER:
|
||||
return "USER";
|
||||
case CT_INSTALLER:
|
||||
return "INSTALLER";
|
||||
case CT_CSR:
|
||||
return "CSR";
|
||||
case CT_MANAGER:
|
||||
return "MANAGER";
|
||||
case CT_BUSINESSOWNER:
|
||||
return "BUSINESSOWNER";
|
||||
case CT_TECHNICIAN:
|
||||
return "TECHNICIAN";
|
||||
case CT_CORPORATE:
|
||||
return "CORPORATE";
|
||||
case CT_UNKNOWN:
|
||||
return "UNKNOWN";
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
inline ContactType contact_from_string(const std::string &S) {
|
||||
if(!Poco::icompare(S,"SUBSCRIBER"))
|
||||
if (!Poco::icompare(S, "SUBSCRIBER"))
|
||||
return CT_SUBSCRIBER;
|
||||
else if(!Poco::icompare(S,"USER"))
|
||||
else if (!Poco::icompare(S, "USER"))
|
||||
return CT_USER;
|
||||
else if(!Poco::icompare(S,"INSTALLER"))
|
||||
else if (!Poco::icompare(S, "INSTALLER"))
|
||||
return CT_INSTALLER;
|
||||
else if(!Poco::icompare(S,"CSR"))
|
||||
else if (!Poco::icompare(S, "CSR"))
|
||||
return CT_CSR;
|
||||
else if(!Poco::icompare(S,"BUSINESSOWNER"))
|
||||
else if (!Poco::icompare(S, "BUSINESSOWNER"))
|
||||
return CT_BUSINESSOWNER;
|
||||
else if(!Poco::icompare(S,"TECHNICIAN"))
|
||||
else if (!Poco::icompare(S, "TECHNICIAN"))
|
||||
return CT_TECHNICIAN;
|
||||
else if(!Poco::icompare(S,"CORPORATE"))
|
||||
else if (!Poco::icompare(S, "CORPORATE"))
|
||||
return CT_CORPORATE;
|
||||
else if(!Poco::icompare(S,"UNKNOWN"))
|
||||
else if (!Poco::icompare(S, "UNKNOWN"))
|
||||
return CT_UNKNOWN;
|
||||
return CT_UNKNOWN;
|
||||
}
|
||||
|
||||
struct Contact {
|
||||
ObjectInfo info;
|
||||
ContactType type=CT_USER;
|
||||
ContactType type = CT_USER;
|
||||
std::string title;
|
||||
std::string salutation;
|
||||
std::string firstname;
|
||||
@@ -399,7 +428,7 @@ namespace OpenWifi::ProvObjects {
|
||||
Types::StringVec inUse;
|
||||
Types::UUIDvec_t variables;
|
||||
DeviceRules deviceRules;
|
||||
bool subscriberOnly=false;
|
||||
bool subscriberOnly = false;
|
||||
std::string venue;
|
||||
std::string entity;
|
||||
std::string subscriber;
|
||||
@@ -409,7 +438,6 @@ namespace OpenWifi::ProvObjects {
|
||||
};
|
||||
typedef std::vector<DeviceConfiguration> DeviceConfigurationVec;
|
||||
|
||||
|
||||
struct InventoryTag {
|
||||
ObjectInfo info;
|
||||
std::string serialNumber;
|
||||
@@ -428,7 +456,7 @@ namespace OpenWifi::ProvObjects {
|
||||
std::string devClass;
|
||||
std::string locale;
|
||||
std::string realMacAddress;
|
||||
bool doNotAllowOverrides=false;
|
||||
bool doNotAllowOverrides = false;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -454,7 +482,7 @@ namespace OpenWifi::ProvObjects {
|
||||
};
|
||||
|
||||
struct Report {
|
||||
uint64_t snapShot=0;
|
||||
uint64_t snapShot = 0;
|
||||
Types::CountedMap tenants;
|
||||
|
||||
void reset();
|
||||
@@ -492,14 +520,12 @@ namespace OpenWifi::ProvObjects {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
enum ACLACCESS {
|
||||
NONE = 0, READ=1, MODIFY=2, CREATE=3, DELETE=4
|
||||
};
|
||||
enum ACLACCESS { NONE = 0, READ = 1, MODIFY = 2, CREATE = 3, DELETE = 4 };
|
||||
|
||||
struct ObjectACL {
|
||||
UuidList users;
|
||||
UuidList roles;
|
||||
uint64_t access = (uint64_t) NONE;
|
||||
uint64_t access = (uint64_t)NONE;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -534,7 +560,7 @@ namespace OpenWifi::ProvObjects {
|
||||
};
|
||||
|
||||
enum SignupStatusCodes {
|
||||
SignupCreated = 0 ,
|
||||
SignupCreated = 0,
|
||||
SignupWaitingForEmail,
|
||||
SignupWaitingForDevice,
|
||||
SignupSuccess,
|
||||
@@ -549,11 +575,11 @@ namespace OpenWifi::ProvObjects {
|
||||
std::string userId;
|
||||
std::string macAddress;
|
||||
std::string serialNumber;
|
||||
uint64_t submitted = 0 ;
|
||||
uint64_t completed = 0 ;
|
||||
uint64_t submitted = 0;
|
||||
uint64_t completed = 0;
|
||||
std::string status;
|
||||
uint64_t error=0;
|
||||
uint64_t statusCode=0;
|
||||
uint64_t error = 0;
|
||||
uint64_t statusCode = 0;
|
||||
std::string deviceID;
|
||||
std::string registrationId;
|
||||
std::string operatorId;
|
||||
@@ -564,7 +590,7 @@ namespace OpenWifi::ProvObjects {
|
||||
|
||||
struct Variable {
|
||||
std::string type;
|
||||
uint64_t weight=0;
|
||||
uint64_t weight = 0;
|
||||
std::string prefix;
|
||||
std::string value;
|
||||
|
||||
@@ -606,7 +632,7 @@ namespace OpenWifi::ProvObjects {
|
||||
Types::UUIDvec_t managementRoles;
|
||||
DeviceRules deviceRules;
|
||||
std::vector<Variable> variables;
|
||||
bool defaultOperator=false;
|
||||
bool defaultOperator = false;
|
||||
Types::StringVec sourceIP;
|
||||
std::string registrationId;
|
||||
|
||||
@@ -635,12 +661,12 @@ namespace OpenWifi::ProvObjects {
|
||||
ObjectInfo info;
|
||||
Types::UUID_t operatorId;
|
||||
Types::UUID_t managementPolicy;
|
||||
double cost=0.0;
|
||||
double cost = 0.0;
|
||||
std::string currency;
|
||||
std::string period;
|
||||
std::string billingCode;
|
||||
std::vector<Variable> variables;
|
||||
bool defaultService=false;
|
||||
bool defaultService = false;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -680,7 +706,7 @@ namespace OpenWifi::ProvObjects {
|
||||
std::string locale;
|
||||
std::string billingCode;
|
||||
DeviceConfigurationElementVec configuration;
|
||||
bool suspended=false;
|
||||
bool suspended = false;
|
||||
std::string realMacAddress;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -715,7 +741,9 @@ namespace OpenWifi::ProvObjects {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
bool UpdateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U, ObjectInfo &I);
|
||||
bool CreateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U, ObjectInfo &I);
|
||||
bool UpdateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U,
|
||||
ObjectInfo &I);
|
||||
bool CreateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U,
|
||||
ObjectInfo &I);
|
||||
bool CreateObjectInfo(const SecurityObjects::UserInfo &U, ObjectInfo &I);
|
||||
};
|
||||
}; // namespace OpenWifi::ProvObjects
|
||||
|
||||
@@ -9,54 +9,67 @@
|
||||
#include "Poco/JSON/Parser.h"
|
||||
#include "Poco/JSON/Stringifier.h"
|
||||
|
||||
#include "framework/RESTAPI_utils.h"
|
||||
#include "RESTAPI_SecurityObjects.h"
|
||||
#include "framework/RESTAPI_utils.h"
|
||||
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
using OpenWifi::RESTAPI_utils::field_from_json;
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
|
||||
namespace OpenWifi::SecurityObjects {
|
||||
|
||||
void AclTemplate::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"Read",Read_);
|
||||
field_to_json(Obj,"ReadWrite",ReadWrite_);
|
||||
field_to_json(Obj,"ReadWriteCreate",ReadWriteCreate_);
|
||||
field_to_json(Obj,"Delete",Delete_);
|
||||
field_to_json(Obj,"PortalLogin",PortalLogin_);
|
||||
field_to_json(Obj, "Read", Read_);
|
||||
field_to_json(Obj, "ReadWrite", ReadWrite_);
|
||||
field_to_json(Obj, "ReadWriteCreate", ReadWriteCreate_);
|
||||
field_to_json(Obj, "Delete", Delete_);
|
||||
field_to_json(Obj, "PortalLogin", PortalLogin_);
|
||||
}
|
||||
|
||||
ResourceAccessType ResourceAccessTypeFromString(const std::string &s) {
|
||||
if(!Poco::icompare(s,"READ")) return READ;
|
||||
if(!Poco::icompare(s,"MODIFY")) return MODIFY;
|
||||
if(!Poco::icompare(s,"DELETE")) return DELETE;
|
||||
if(!Poco::icompare(s,"CREATE")) return CREATE;
|
||||
if(!Poco::icompare(s,"TEST")) return TEST;
|
||||
if(!Poco::icompare(s,"MOVE")) return MOVE;
|
||||
if (!Poco::icompare(s, "READ"))
|
||||
return READ;
|
||||
if (!Poco::icompare(s, "MODIFY"))
|
||||
return MODIFY;
|
||||
if (!Poco::icompare(s, "DELETE"))
|
||||
return DELETE;
|
||||
if (!Poco::icompare(s, "CREATE"))
|
||||
return CREATE;
|
||||
if (!Poco::icompare(s, "TEST"))
|
||||
return TEST;
|
||||
if (!Poco::icompare(s, "MOVE"))
|
||||
return MOVE;
|
||||
return NONE;
|
||||
}
|
||||
|
||||
std::string ResourceAccessTypeToString(const ResourceAccessType & T) {
|
||||
switch(T) {
|
||||
case READ: return "READ";
|
||||
case MODIFY: return "MODIFY";
|
||||
case DELETE: return "DELETE";
|
||||
case CREATE: return "CREATE";
|
||||
case TEST: return "TEST";
|
||||
case MOVE: return "MOVE";
|
||||
default: return "NONE";
|
||||
std::string ResourceAccessTypeToString(const ResourceAccessType &T) {
|
||||
switch (T) {
|
||||
case READ:
|
||||
return "READ";
|
||||
case MODIFY:
|
||||
return "MODIFY";
|
||||
case DELETE:
|
||||
return "DELETE";
|
||||
case CREATE:
|
||||
return "CREATE";
|
||||
case TEST:
|
||||
return "TEST";
|
||||
case MOVE:
|
||||
return "MOVE";
|
||||
default:
|
||||
return "NONE";
|
||||
}
|
||||
}
|
||||
|
||||
USER_ROLE UserTypeFromString(const std::string &U) {
|
||||
if (!Poco::icompare(U,"root"))
|
||||
if (!Poco::icompare(U, "root"))
|
||||
return ROOT;
|
||||
else if (!Poco::icompare(U,"admin"))
|
||||
else if (!Poco::icompare(U, "admin"))
|
||||
return ADMIN;
|
||||
else if (!Poco::icompare(U,"subscriber"))
|
||||
else if (!Poco::icompare(U, "subscriber"))
|
||||
return SUBSCRIBER;
|
||||
else if (!Poco::icompare(U,"partner"))
|
||||
else if (!Poco::icompare(U, "partner"))
|
||||
return PARTNER;
|
||||
else if (!Poco::icompare(U,"csr"))
|
||||
else if (!Poco::icompare(U, "csr"))
|
||||
return CSR;
|
||||
else if (!Poco::icompare(U, "system"))
|
||||
return SYSTEM;
|
||||
@@ -70,16 +83,25 @@ namespace OpenWifi::SecurityObjects {
|
||||
}
|
||||
|
||||
std::string UserTypeToString(USER_ROLE U) {
|
||||
switch(U) {
|
||||
case ROOT: return "root";
|
||||
case ADMIN: return "admin";
|
||||
case SUBSCRIBER: return "subscriber";
|
||||
case PARTNER: return "partner";
|
||||
case CSR: return "csr";
|
||||
case SYSTEM: return "system";
|
||||
case INSTALLER: return "installer";
|
||||
case NOC: return "noc";
|
||||
case ACCOUNTING: return "accounting";
|
||||
switch (U) {
|
||||
case ROOT:
|
||||
return "root";
|
||||
case ADMIN:
|
||||
return "admin";
|
||||
case SUBSCRIBER:
|
||||
return "subscriber";
|
||||
case PARTNER:
|
||||
return "partner";
|
||||
case CSR:
|
||||
return "csr";
|
||||
case SYSTEM:
|
||||
return "system";
|
||||
case INSTALLER:
|
||||
return "installer";
|
||||
case NOC:
|
||||
return "noc";
|
||||
case ACCOUNTING:
|
||||
return "accounting";
|
||||
case UNKNOWN:
|
||||
default:
|
||||
return "unknown";
|
||||
@@ -94,27 +116,27 @@ namespace OpenWifi::SecurityObjects {
|
||||
field_from_json(Obj, "Delete", Delete_);
|
||||
field_from_json(Obj, "PortalLogin", PortalLogin_);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: AclTemplate" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void WebToken::to_json(Poco::JSON::Object & Obj) const {
|
||||
void WebToken::to_json(Poco::JSON::Object &Obj) const {
|
||||
Poco::JSON::Object AclTemplateObj;
|
||||
acl_template_.to_json(AclTemplateObj);
|
||||
field_to_json(Obj,"access_token",access_token_);
|
||||
field_to_json(Obj,"refresh_token",refresh_token_);
|
||||
field_to_json(Obj,"token_type",token_type_);
|
||||
field_to_json(Obj,"expires_in",expires_in_);
|
||||
field_to_json(Obj,"idle_timeout",idle_timeout_);
|
||||
field_to_json(Obj,"created",created_);
|
||||
field_to_json(Obj,"username",username_);
|
||||
field_to_json(Obj,"userMustChangePassword",userMustChangePassword);
|
||||
field_to_json(Obj,"errorCode", errorCode);
|
||||
Obj.set("aclTemplate",AclTemplateObj);
|
||||
field_to_json(Obj,"errorCode", errorCode);
|
||||
field_to_json(Obj,"lastRefresh", lastRefresh_);
|
||||
field_to_json(Obj, "access_token", access_token_);
|
||||
field_to_json(Obj, "refresh_token", refresh_token_);
|
||||
field_to_json(Obj, "token_type", token_type_);
|
||||
field_to_json(Obj, "expires_in", expires_in_);
|
||||
field_to_json(Obj, "idle_timeout", idle_timeout_);
|
||||
field_to_json(Obj, "created", created_);
|
||||
field_to_json(Obj, "username", username_);
|
||||
field_to_json(Obj, "userMustChangePassword", userMustChangePassword);
|
||||
field_to_json(Obj, "errorCode", errorCode);
|
||||
Obj.set("aclTemplate", AclTemplateObj);
|
||||
field_to_json(Obj, "errorCode", errorCode);
|
||||
field_to_json(Obj, "lastRefresh", lastRefresh_);
|
||||
}
|
||||
|
||||
bool WebToken::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
@@ -130,8 +152,8 @@ namespace OpenWifi::SecurityObjects {
|
||||
field_from_json(Obj, "idle_timeout", idle_timeout_);
|
||||
field_from_json(Obj, "created", created_);
|
||||
field_from_json(Obj, "username", username_);
|
||||
field_from_json(Obj, "userMustChangePassword",userMustChangePassword);
|
||||
field_from_json(Obj,"lastRefresh", lastRefresh_);
|
||||
field_from_json(Obj, "userMustChangePassword", userMustChangePassword);
|
||||
field_from_json(Obj, "lastRefresh", lastRefresh_);
|
||||
return true;
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: WebToken" << std::endl;
|
||||
@@ -140,16 +162,16 @@ namespace OpenWifi::SecurityObjects {
|
||||
}
|
||||
|
||||
void MobilePhoneNumber::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"number", number);
|
||||
field_to_json(Obj,"verified", verified);
|
||||
field_to_json(Obj,"primary", primary);
|
||||
field_to_json(Obj, "number", number);
|
||||
field_to_json(Obj, "verified", verified);
|
||||
field_to_json(Obj, "primary", primary);
|
||||
}
|
||||
|
||||
bool MobilePhoneNumber::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"number",number);
|
||||
field_from_json(Obj,"verified",verified);
|
||||
field_from_json(Obj,"primary",primary);
|
||||
field_from_json(Obj, "number", number);
|
||||
field_from_json(Obj, "verified", verified);
|
||||
field_from_json(Obj, "primary", primary);
|
||||
return true;
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: MobilePhoneNumber" << std::endl;
|
||||
@@ -158,14 +180,14 @@ namespace OpenWifi::SecurityObjects {
|
||||
};
|
||||
|
||||
void MfaAuthInfo::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"enabled", enabled);
|
||||
field_to_json(Obj,"method", method);
|
||||
field_to_json(Obj, "enabled", enabled);
|
||||
field_to_json(Obj, "method", method);
|
||||
}
|
||||
|
||||
bool MfaAuthInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"enabled",enabled);
|
||||
field_from_json(Obj,"method",method);
|
||||
field_from_json(Obj, "enabled", enabled);
|
||||
field_from_json(Obj, "method", method);
|
||||
return true;
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: MfaAuthInfo" << std::endl;
|
||||
@@ -181,8 +203,8 @@ namespace OpenWifi::SecurityObjects {
|
||||
|
||||
bool UserLoginLoginExtensions::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj, "mobiles",mobiles);
|
||||
field_from_json(Obj, "mfa",mfa);
|
||||
field_from_json(Obj, "mobiles", mobiles);
|
||||
field_from_json(Obj, "mfa", mfa);
|
||||
field_from_json(Obj, "authenticatorSecret", authenticatorSecret);
|
||||
return true;
|
||||
} catch (...) {
|
||||
@@ -200,10 +222,10 @@ namespace OpenWifi::SecurityObjects {
|
||||
|
||||
bool MFAChallengeRequest::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"uuid",uuid);
|
||||
field_from_json(Obj,"question",question);
|
||||
field_from_json(Obj,"created",created);
|
||||
field_from_json(Obj,"method",method);
|
||||
field_from_json(Obj, "uuid", uuid);
|
||||
field_from_json(Obj, "question", question);
|
||||
field_from_json(Obj, "created", created);
|
||||
field_from_json(Obj, "method", method);
|
||||
return true;
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: MFAChallengeRequest" << std::endl;
|
||||
@@ -218,85 +240,84 @@ namespace OpenWifi::SecurityObjects {
|
||||
|
||||
bool MFAChallengeResponse::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"uuid",uuid);
|
||||
field_from_json(Obj,"answer",answer);
|
||||
field_from_json(Obj, "uuid", uuid);
|
||||
field_from_json(Obj, "answer", answer);
|
||||
return true;
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: MFAChallengeResponse" << std::endl;
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
void UserInfo::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id",id);
|
||||
field_to_json(Obj,"name",name);
|
||||
field_to_json(Obj,"description", description);
|
||||
field_to_json(Obj,"avatar", avatar);
|
||||
field_to_json(Obj,"email", email);
|
||||
field_to_json(Obj,"validated", validated);
|
||||
field_to_json(Obj,"validationEmail", validationEmail);
|
||||
field_to_json(Obj,"validationDate", validationDate);
|
||||
field_to_json(Obj,"creationDate", creationDate);
|
||||
field_to_json(Obj,"validationURI", validationURI);
|
||||
field_to_json(Obj,"changePassword", changePassword);
|
||||
field_to_json(Obj,"lastLogin", lastLogin);
|
||||
field_to_json(Obj,"currentLoginURI", currentLoginURI);
|
||||
field_to_json(Obj,"lastPasswordChange", lastPasswordChange);
|
||||
field_to_json(Obj,"lastEmailCheck", lastEmailCheck);
|
||||
field_to_json(Obj,"waitingForEmailCheck", waitingForEmailCheck);
|
||||
field_to_json(Obj,"locale", locale);
|
||||
field_to_json(Obj,"notes", notes);
|
||||
field_to_json(Obj,"location", location);
|
||||
field_to_json(Obj,"owner", owner);
|
||||
field_to_json(Obj,"suspended", suspended);
|
||||
field_to_json(Obj,"blackListed", blackListed);
|
||||
field_to_json<USER_ROLE>(Obj,"userRole", userRole, UserTypeToString);
|
||||
field_to_json(Obj,"userTypeProprietaryInfo", userTypeProprietaryInfo);
|
||||
field_to_json(Obj,"securityPolicy", securityPolicy);
|
||||
field_to_json(Obj,"securityPolicyChange", securityPolicyChange);
|
||||
field_to_json(Obj,"currentPassword",currentPassword);
|
||||
field_to_json(Obj,"lastPasswords",lastPasswords);
|
||||
field_to_json(Obj,"oauthType",oauthType);
|
||||
field_to_json(Obj,"oauthUserInfo",oauthUserInfo);
|
||||
field_to_json(Obj,"modified",modified);
|
||||
field_to_json(Obj,"signingUp",signingUp);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "name", name);
|
||||
field_to_json(Obj, "description", description);
|
||||
field_to_json(Obj, "avatar", avatar);
|
||||
field_to_json(Obj, "email", email);
|
||||
field_to_json(Obj, "validated", validated);
|
||||
field_to_json(Obj, "validationEmail", validationEmail);
|
||||
field_to_json(Obj, "validationDate", validationDate);
|
||||
field_to_json(Obj, "creationDate", creationDate);
|
||||
field_to_json(Obj, "validationURI", validationURI);
|
||||
field_to_json(Obj, "changePassword", changePassword);
|
||||
field_to_json(Obj, "lastLogin", lastLogin);
|
||||
field_to_json(Obj, "currentLoginURI", currentLoginURI);
|
||||
field_to_json(Obj, "lastPasswordChange", lastPasswordChange);
|
||||
field_to_json(Obj, "lastEmailCheck", lastEmailCheck);
|
||||
field_to_json(Obj, "waitingForEmailCheck", waitingForEmailCheck);
|
||||
field_to_json(Obj, "locale", locale);
|
||||
field_to_json(Obj, "notes", notes);
|
||||
field_to_json(Obj, "location", location);
|
||||
field_to_json(Obj, "owner", owner);
|
||||
field_to_json(Obj, "suspended", suspended);
|
||||
field_to_json(Obj, "blackListed", blackListed);
|
||||
field_to_json<USER_ROLE>(Obj, "userRole", userRole, UserTypeToString);
|
||||
field_to_json(Obj, "userTypeProprietaryInfo", userTypeProprietaryInfo);
|
||||
field_to_json(Obj, "securityPolicy", securityPolicy);
|
||||
field_to_json(Obj, "securityPolicyChange", securityPolicyChange);
|
||||
field_to_json(Obj, "currentPassword", currentPassword);
|
||||
field_to_json(Obj, "lastPasswords", lastPasswords);
|
||||
field_to_json(Obj, "oauthType", oauthType);
|
||||
field_to_json(Obj, "oauthUserInfo", oauthUserInfo);
|
||||
field_to_json(Obj, "modified", modified);
|
||||
field_to_json(Obj, "signingUp", signingUp);
|
||||
};
|
||||
|
||||
bool UserInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id",id);
|
||||
field_from_json(Obj,"name",name);
|
||||
field_from_json(Obj,"description",description);
|
||||
field_from_json(Obj,"avatar",avatar);
|
||||
field_from_json(Obj,"email",email);
|
||||
field_from_json(Obj,"validationEmail",validationEmail);
|
||||
field_from_json(Obj,"validationURI",validationURI);
|
||||
field_from_json(Obj,"currentLoginURI",currentLoginURI);
|
||||
field_from_json(Obj,"locale",locale);
|
||||
field_from_json(Obj,"notes",notes);
|
||||
field_from_json(Obj,"location", location);
|
||||
field_from_json(Obj,"owner", owner);
|
||||
field_from_json<USER_ROLE>(Obj,"userRole",userRole, UserTypeFromString);
|
||||
field_from_json(Obj,"securityPolicy",securityPolicy);
|
||||
field_from_json(Obj,"userTypeProprietaryInfo",userTypeProprietaryInfo);
|
||||
field_from_json(Obj,"validationDate",validationDate);
|
||||
field_from_json(Obj,"creationDate",creationDate);
|
||||
field_from_json(Obj,"lastLogin",lastLogin);
|
||||
field_from_json(Obj,"lastPasswordChange",lastPasswordChange);
|
||||
field_from_json(Obj,"lastEmailCheck",lastEmailCheck);
|
||||
field_from_json(Obj,"securityPolicyChange",securityPolicyChange);
|
||||
field_from_json(Obj,"validated",validated);
|
||||
field_from_json(Obj,"changePassword",changePassword);
|
||||
field_from_json(Obj,"waitingForEmailCheck",waitingForEmailCheck);
|
||||
field_from_json(Obj,"suspended",suspended);
|
||||
field_from_json(Obj,"blackListed",blackListed);
|
||||
field_from_json(Obj,"currentPassword",currentPassword);
|
||||
field_from_json(Obj,"lastPasswords",lastPasswords);
|
||||
field_from_json(Obj,"oauthType",oauthType);
|
||||
field_from_json(Obj,"oauthUserInfo",oauthUserInfo);
|
||||
field_from_json(Obj,"modified",modified);
|
||||
field_from_json(Obj,"signingUp",signingUp);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "name", name);
|
||||
field_from_json(Obj, "description", description);
|
||||
field_from_json(Obj, "avatar", avatar);
|
||||
field_from_json(Obj, "email", email);
|
||||
field_from_json(Obj, "validationEmail", validationEmail);
|
||||
field_from_json(Obj, "validationURI", validationURI);
|
||||
field_from_json(Obj, "currentLoginURI", currentLoginURI);
|
||||
field_from_json(Obj, "locale", locale);
|
||||
field_from_json(Obj, "notes", notes);
|
||||
field_from_json(Obj, "location", location);
|
||||
field_from_json(Obj, "owner", owner);
|
||||
field_from_json<USER_ROLE>(Obj, "userRole", userRole, UserTypeFromString);
|
||||
field_from_json(Obj, "securityPolicy", securityPolicy);
|
||||
field_from_json(Obj, "userTypeProprietaryInfo", userTypeProprietaryInfo);
|
||||
field_from_json(Obj, "validationDate", validationDate);
|
||||
field_from_json(Obj, "creationDate", creationDate);
|
||||
field_from_json(Obj, "lastLogin", lastLogin);
|
||||
field_from_json(Obj, "lastPasswordChange", lastPasswordChange);
|
||||
field_from_json(Obj, "lastEmailCheck", lastEmailCheck);
|
||||
field_from_json(Obj, "securityPolicyChange", securityPolicyChange);
|
||||
field_from_json(Obj, "validated", validated);
|
||||
field_from_json(Obj, "changePassword", changePassword);
|
||||
field_from_json(Obj, "waitingForEmailCheck", waitingForEmailCheck);
|
||||
field_from_json(Obj, "suspended", suspended);
|
||||
field_from_json(Obj, "blackListed", blackListed);
|
||||
field_from_json(Obj, "currentPassword", currentPassword);
|
||||
field_from_json(Obj, "lastPasswords", lastPasswords);
|
||||
field_from_json(Obj, "oauthType", oauthType);
|
||||
field_from_json(Obj, "oauthUserInfo", oauthUserInfo);
|
||||
field_from_json(Obj, "modified", modified);
|
||||
field_from_json(Obj, "signingUp", signingUp);
|
||||
return true;
|
||||
} catch (const Poco::Exception &E) {
|
||||
std::cout << "Cannot parse: UserInfo" << std::endl;
|
||||
@@ -305,12 +326,12 @@ namespace OpenWifi::SecurityObjects {
|
||||
};
|
||||
|
||||
void UserInfoList::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"users",users);
|
||||
field_to_json(Obj, "users", users);
|
||||
}
|
||||
|
||||
bool UserInfoList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"users",users);
|
||||
field_from_json(Obj, "users", users);
|
||||
return true;
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: InternalServiceInfo" << std::endl;
|
||||
@@ -319,16 +340,16 @@ namespace OpenWifi::SecurityObjects {
|
||||
}
|
||||
|
||||
void InternalServiceInfo::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"privateURI",privateURI);
|
||||
field_to_json(Obj,"publicURI",publicURI);
|
||||
field_to_json(Obj,"token",token);
|
||||
field_to_json(Obj, "privateURI", privateURI);
|
||||
field_to_json(Obj, "publicURI", publicURI);
|
||||
field_to_json(Obj, "token", token);
|
||||
};
|
||||
|
||||
bool InternalServiceInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"privateURI",privateURI);
|
||||
field_from_json(Obj,"publicURI",publicURI);
|
||||
field_from_json(Obj,"token",token);
|
||||
field_from_json(Obj, "privateURI", privateURI);
|
||||
field_from_json(Obj, "publicURI", publicURI);
|
||||
field_from_json(Obj, "token", token);
|
||||
return true;
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: InternalServiceInfo" << std::endl;
|
||||
@@ -337,9 +358,9 @@ namespace OpenWifi::SecurityObjects {
|
||||
};
|
||||
|
||||
void InternalSystemServices::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"key",key);
|
||||
field_to_json(Obj,"version",version);
|
||||
field_to_json(Obj,"services",services);
|
||||
field_to_json(Obj, "key", key);
|
||||
field_to_json(Obj, "version", version);
|
||||
field_to_json(Obj, "services", services);
|
||||
};
|
||||
|
||||
bool InternalSystemServices::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
@@ -348,18 +369,18 @@ namespace OpenWifi::SecurityObjects {
|
||||
field_from_json(Obj, "version", version);
|
||||
field_from_json(Obj, "services", services);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: InternalSystemServices" << std::endl;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
void SystemEndpoint::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"type",type);
|
||||
field_to_json(Obj,"id",id);
|
||||
field_to_json(Obj,"vendor",vendor);
|
||||
field_to_json(Obj,"uri",uri);
|
||||
field_to_json(Obj,"authenticationType",authenticationType);
|
||||
field_to_json(Obj, "type", type);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "vendor", vendor);
|
||||
field_to_json(Obj, "uri", uri);
|
||||
field_to_json(Obj, "authenticationType", authenticationType);
|
||||
};
|
||||
|
||||
bool SystemEndpoint::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
@@ -377,7 +398,7 @@ namespace OpenWifi::SecurityObjects {
|
||||
};
|
||||
|
||||
void SystemEndpointList::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"endpoints",endpoints);
|
||||
field_to_json(Obj, "endpoints", endpoints);
|
||||
}
|
||||
|
||||
bool SystemEndpointList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
@@ -394,8 +415,8 @@ namespace OpenWifi::SecurityObjects {
|
||||
Poco::JSON::Object UI, TI;
|
||||
userinfo.to_json(UI);
|
||||
webtoken.to_json(TI);
|
||||
Obj.set("tokenInfo",TI);
|
||||
Obj.set("userInfo",UI);
|
||||
Obj.set("tokenInfo", TI);
|
||||
Obj.set("userInfo", UI);
|
||||
}
|
||||
|
||||
bool UserInfoAndPolicy::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
@@ -403,90 +424,96 @@ namespace OpenWifi::SecurityObjects {
|
||||
field_from_json(Obj, "tokenInfo", webtoken);
|
||||
field_from_json(Obj, "userInfo", userinfo);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: UserInfoAndPolicy" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void NoteInfo::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"created", created);
|
||||
field_to_json(Obj,"createdBy", createdBy);
|
||||
field_to_json(Obj,"note", note);
|
||||
field_to_json(Obj, "created", created);
|
||||
field_to_json(Obj, "createdBy", createdBy);
|
||||
field_to_json(Obj, "note", note);
|
||||
}
|
||||
|
||||
bool NoteInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"created",created);
|
||||
field_from_json(Obj,"createdBy",createdBy);
|
||||
field_from_json(Obj,"note", note);
|
||||
field_from_json(Obj, "created", created);
|
||||
field_from_json(Obj, "createdBy", createdBy);
|
||||
field_from_json(Obj, "note", note);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: NoteInfo" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool MergeNotes(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec & Notes) {
|
||||
bool MergeNotes(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec &Notes) {
|
||||
try {
|
||||
if(Obj->has("notes") && Obj->isArray("notes")) {
|
||||
if (Obj->has("notes") && Obj->isArray("notes")) {
|
||||
SecurityObjects::NoteInfoVec NIV;
|
||||
NIV = RESTAPI_utils::to_object_array<SecurityObjects::NoteInfo>(Obj->get("notes").toString());
|
||||
for(auto const &i:NIV) {
|
||||
SecurityObjects::NoteInfo ii{.created=(uint64_t)Utils::Now(), .createdBy=UInfo.email, .note=i.note};
|
||||
NIV = RESTAPI_utils::to_object_array<SecurityObjects::NoteInfo>(
|
||||
Obj->get("notes").toString());
|
||||
for (auto const &i : NIV) {
|
||||
SecurityObjects::NoteInfo ii{.created = (uint64_t)Utils::Now(),
|
||||
.createdBy = UInfo.email,
|
||||
.note = i.note};
|
||||
Notes.push_back(ii);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: MergeNotes" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool MergeNotes(const NoteInfoVec & NewNotes, const UserInfo &UInfo, NoteInfoVec & ExistingNotes) {
|
||||
for(auto const &i:NewNotes) {
|
||||
SecurityObjects::NoteInfo ii{.created=(uint64_t)Utils::Now(), .createdBy=UInfo.email, .note=i.note};
|
||||
bool MergeNotes(const NoteInfoVec &NewNotes, const UserInfo &UInfo,
|
||||
NoteInfoVec &ExistingNotes) {
|
||||
for (auto const &i : NewNotes) {
|
||||
SecurityObjects::NoteInfo ii{
|
||||
.created = (uint64_t)Utils::Now(), .createdBy = UInfo.email, .note = i.note};
|
||||
ExistingNotes.push_back(ii);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ProfileAction::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"resource", resource);
|
||||
field_to_json<ResourceAccessType>(Obj,"access", access, ResourceAccessTypeToString);
|
||||
field_to_json(Obj, "resource", resource);
|
||||
field_to_json<ResourceAccessType>(Obj, "access", access, ResourceAccessTypeToString);
|
||||
}
|
||||
|
||||
bool ProfileAction::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"resource",resource);
|
||||
field_from_json<ResourceAccessType>(Obj,"access",access,ResourceAccessTypeFromString );
|
||||
field_from_json(Obj, "resource", resource);
|
||||
field_from_json<ResourceAccessType>(Obj, "access", access,
|
||||
ResourceAccessTypeFromString);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: ProfileAction" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void SecurityProfile::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id", id);
|
||||
field_to_json(Obj,"name", name);
|
||||
field_to_json(Obj,"description", description);
|
||||
field_to_json(Obj,"policy", policy);
|
||||
field_to_json(Obj,"role", role);
|
||||
field_to_json(Obj,"notes", notes);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "name", name);
|
||||
field_to_json(Obj, "description", description);
|
||||
field_to_json(Obj, "policy", policy);
|
||||
field_to_json(Obj, "role", role);
|
||||
field_to_json(Obj, "notes", notes);
|
||||
}
|
||||
|
||||
bool SecurityProfile::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id",id);
|
||||
field_from_json(Obj,"name",name);
|
||||
field_from_json(Obj,"description",description);
|
||||
field_from_json(Obj,"policy",policy);
|
||||
field_from_json(Obj,"role",role);
|
||||
field_from_json(Obj,"notes",notes);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "name", name);
|
||||
field_from_json(Obj, "description", description);
|
||||
field_from_json(Obj, "policy", policy);
|
||||
field_from_json(Obj, "role", role);
|
||||
field_from_json(Obj, "notes", notes);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: SecurityProfile" << std::endl;
|
||||
}
|
||||
return false;
|
||||
@@ -498,126 +525,126 @@ namespace OpenWifi::SecurityObjects {
|
||||
|
||||
bool SecurityProfileList::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"profiles",profiles);
|
||||
field_from_json(Obj, "profiles", profiles);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: SecurityProfileList" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void ActionLink::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id",id);
|
||||
field_to_json(Obj,"action",action);
|
||||
field_to_json(Obj,"userId",userId);
|
||||
field_to_json(Obj,"actionTemplate",actionTemplate);
|
||||
field_to_json(Obj,"variables",variables);
|
||||
field_to_json(Obj,"locale",locale);
|
||||
field_to_json(Obj,"message",message);
|
||||
field_to_json(Obj,"sent",sent);
|
||||
field_to_json(Obj,"created",created);
|
||||
field_to_json(Obj,"expires",expires);
|
||||
field_to_json(Obj,"completed",completed);
|
||||
field_to_json(Obj,"canceled",canceled);
|
||||
field_to_json(Obj,"userAction",userAction);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "action", action);
|
||||
field_to_json(Obj, "userId", userId);
|
||||
field_to_json(Obj, "actionTemplate", actionTemplate);
|
||||
field_to_json(Obj, "variables", variables);
|
||||
field_to_json(Obj, "locale", locale);
|
||||
field_to_json(Obj, "message", message);
|
||||
field_to_json(Obj, "sent", sent);
|
||||
field_to_json(Obj, "created", created);
|
||||
field_to_json(Obj, "expires", expires);
|
||||
field_to_json(Obj, "completed", completed);
|
||||
field_to_json(Obj, "canceled", canceled);
|
||||
field_to_json(Obj, "userAction", userAction);
|
||||
}
|
||||
|
||||
bool ActionLink::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id",id);
|
||||
field_from_json(Obj,"action",action);
|
||||
field_from_json(Obj,"userId",userId);
|
||||
field_from_json(Obj,"actionTemplate",actionTemplate);
|
||||
field_from_json(Obj,"variables",variables);
|
||||
field_from_json(Obj,"locale",locale);
|
||||
field_from_json(Obj,"message",message);
|
||||
field_from_json(Obj,"sent",sent);
|
||||
field_from_json(Obj,"created",created);
|
||||
field_from_json(Obj,"expires",expires);
|
||||
field_from_json(Obj,"completed",completed);
|
||||
field_from_json(Obj,"canceled",canceled);
|
||||
field_from_json(Obj,"userAction",userAction);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "action", action);
|
||||
field_from_json(Obj, "userId", userId);
|
||||
field_from_json(Obj, "actionTemplate", actionTemplate);
|
||||
field_from_json(Obj, "variables", variables);
|
||||
field_from_json(Obj, "locale", locale);
|
||||
field_from_json(Obj, "message", message);
|
||||
field_from_json(Obj, "sent", sent);
|
||||
field_from_json(Obj, "created", created);
|
||||
field_from_json(Obj, "expires", expires);
|
||||
field_from_json(Obj, "completed", completed);
|
||||
field_from_json(Obj, "canceled", canceled);
|
||||
field_from_json(Obj, "userAction", userAction);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: ActionLink" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void Preferences::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id",id);
|
||||
field_to_json(Obj,"modified",modified);
|
||||
field_to_json(Obj,"data",data);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "modified", modified);
|
||||
field_to_json(Obj, "data", data);
|
||||
}
|
||||
|
||||
bool Preferences::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id",id);
|
||||
field_from_json(Obj,"modified",modified);
|
||||
field_from_json(Obj,"data",data);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "modified", modified);
|
||||
field_from_json(Obj, "data", data);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: Preferences" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void SubMfaConfig::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"id",id);
|
||||
field_to_json(Obj,"type",type);
|
||||
field_to_json(Obj,"sms",sms);
|
||||
field_to_json(Obj,"email",email);
|
||||
field_to_json(Obj, "id", id);
|
||||
field_to_json(Obj, "type", type);
|
||||
field_to_json(Obj, "sms", sms);
|
||||
field_to_json(Obj, "email", email);
|
||||
}
|
||||
|
||||
bool SubMfaConfig::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"id",id);
|
||||
field_from_json(Obj,"type",type);
|
||||
field_from_json(Obj,"sms",sms);
|
||||
field_from_json(Obj,"email",email);
|
||||
field_from_json(Obj, "id", id);
|
||||
field_from_json(Obj, "type", type);
|
||||
field_from_json(Obj, "sms", sms);
|
||||
field_from_json(Obj, "email", email);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: SubMfaConfig" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void Token::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"token",token);
|
||||
field_to_json(Obj,"refreshToken",refreshToken);
|
||||
field_to_json(Obj,"tokenType",tokenType);
|
||||
field_to_json(Obj,"userName",userName);
|
||||
field_to_json(Obj,"created",created);
|
||||
field_to_json(Obj,"expires",expires);
|
||||
field_to_json(Obj,"idleTimeout",idleTimeout);
|
||||
field_to_json(Obj,"revocationDate",revocationDate);
|
||||
field_to_json(Obj,"lastRefresh", lastRefresh);
|
||||
field_to_json(Obj, "token", token);
|
||||
field_to_json(Obj, "refreshToken", refreshToken);
|
||||
field_to_json(Obj, "tokenType", tokenType);
|
||||
field_to_json(Obj, "userName", userName);
|
||||
field_to_json(Obj, "created", created);
|
||||
field_to_json(Obj, "expires", expires);
|
||||
field_to_json(Obj, "idleTimeout", idleTimeout);
|
||||
field_to_json(Obj, "revocationDate", revocationDate);
|
||||
field_to_json(Obj, "lastRefresh", lastRefresh);
|
||||
}
|
||||
|
||||
bool Token::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
field_from_json(Obj,"token",token);
|
||||
field_from_json(Obj,"refreshToken",refreshToken);
|
||||
field_from_json(Obj,"tokenType",tokenType);
|
||||
field_from_json(Obj,"userName",userName);
|
||||
field_from_json(Obj,"created",created);
|
||||
field_from_json(Obj,"expires",expires);
|
||||
field_from_json(Obj,"idleTimeout",idleTimeout);
|
||||
field_from_json(Obj,"revocationDate",revocationDate);
|
||||
field_from_json(Obj,"lastRefresh", lastRefresh);
|
||||
field_from_json(Obj, "token", token);
|
||||
field_from_json(Obj, "refreshToken", refreshToken);
|
||||
field_from_json(Obj, "tokenType", tokenType);
|
||||
field_from_json(Obj, "userName", userName);
|
||||
field_from_json(Obj, "created", created);
|
||||
field_from_json(Obj, "expires", expires);
|
||||
field_from_json(Obj, "idleTimeout", idleTimeout);
|
||||
field_from_json(Obj, "revocationDate", revocationDate);
|
||||
field_from_json(Obj, "lastRefresh", lastRefresh);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: Token" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void LoginRecordInfo::to_json(Poco::JSON::Object &Obj) const {
|
||||
field_to_json(Obj,"sessionId",sessionId);
|
||||
field_to_json(Obj,"userId",userId);
|
||||
field_to_json(Obj,"email",email);
|
||||
field_to_json(Obj,"login",login);
|
||||
field_to_json(Obj,"logout",logout);
|
||||
field_to_json(Obj, "sessionId", sessionId);
|
||||
field_to_json(Obj, "userId", userId);
|
||||
field_to_json(Obj, "email", email);
|
||||
field_to_json(Obj, "login", login);
|
||||
field_to_json(Obj, "logout", logout);
|
||||
}
|
||||
|
||||
void ApiKeyAccessRight::to_json(Poco::JSON::Object &Obj) const {
|
||||
@@ -630,7 +657,7 @@ namespace OpenWifi::SecurityObjects {
|
||||
field_from_json(Obj, "service", service);
|
||||
field_from_json(Obj, "access", access);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: Token" << std::endl;
|
||||
}
|
||||
return false;
|
||||
@@ -644,7 +671,7 @@ namespace OpenWifi::SecurityObjects {
|
||||
try {
|
||||
field_from_json(Obj, "acls", acls);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: Token" << std::endl;
|
||||
}
|
||||
return false;
|
||||
@@ -674,7 +701,7 @@ namespace OpenWifi::SecurityObjects {
|
||||
field_from_json(Obj, "rights", rights);
|
||||
field_from_json(Obj, "lastUse", lastUse);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: Token" << std::endl;
|
||||
}
|
||||
return false;
|
||||
@@ -688,11 +715,10 @@ namespace OpenWifi::SecurityObjects {
|
||||
try {
|
||||
field_from_json(Obj, "apiKeys", apiKeys);
|
||||
return true;
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot parse: Token" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} // namespace OpenWifi::SecurityObjects
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
#include "Poco/JSON/Object.h"
|
||||
#include "Poco/Data/LOB.h"
|
||||
#include "Poco/Data/LOBStream.h"
|
||||
#include "Poco/JSON/Object.h"
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
#include "framework/utils.h"
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
namespace OpenWifi {
|
||||
uint64_t Now();
|
||||
@@ -35,7 +35,7 @@ namespace OpenWifi {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
static_assert( std::is_nothrow_move_constructible_v<AclTemplate> );
|
||||
static_assert(std::is_nothrow_move_constructible_v<AclTemplate>);
|
||||
|
||||
struct WebToken {
|
||||
std::string access_token_;
|
||||
@@ -43,27 +43,36 @@ namespace OpenWifi {
|
||||
std::string id_token_;
|
||||
std::string token_type_;
|
||||
std::string username_;
|
||||
bool userMustChangePassword=false;
|
||||
uint64_t errorCode=0;
|
||||
uint64_t expires_in_=0;
|
||||
uint64_t idle_timeout_=0;
|
||||
bool userMustChangePassword = false;
|
||||
uint64_t errorCode = 0;
|
||||
uint64_t expires_in_ = 0;
|
||||
uint64_t idle_timeout_ = 0;
|
||||
AclTemplate acl_template_;
|
||||
uint64_t created_=0;
|
||||
uint64_t lastRefresh_=0;
|
||||
uint64_t created_ = 0;
|
||||
uint64_t lastRefresh_ = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
enum USER_ROLE {
|
||||
UNKNOWN, ROOT, ADMIN, SUBSCRIBER, CSR, SYSTEM, INSTALLER, NOC, ACCOUNTING, PARTNER
|
||||
UNKNOWN,
|
||||
ROOT,
|
||||
ADMIN,
|
||||
SUBSCRIBER,
|
||||
CSR,
|
||||
SYSTEM,
|
||||
INSTALLER,
|
||||
NOC,
|
||||
ACCOUNTING,
|
||||
PARTNER
|
||||
};
|
||||
|
||||
USER_ROLE UserTypeFromString(const std::string &U);
|
||||
std::string UserTypeToString(USER_ROLE U);
|
||||
|
||||
struct NoteInfo {
|
||||
uint64_t created=0; // = Utils::Now();
|
||||
uint64_t created = 0; // = Utils::Now();
|
||||
std::string createdBy;
|
||||
std::string note;
|
||||
|
||||
@@ -142,7 +151,7 @@ namespace OpenWifi {
|
||||
USER_ROLE userRole;
|
||||
UserLoginLoginExtensions userTypeProprietaryInfo;
|
||||
std::string securityPolicy;
|
||||
uint64_t securityPolicyChange = 0 ;
|
||||
uint64_t securityPolicyChange = 0;
|
||||
std::string currentPassword;
|
||||
OpenWifi::Types::StringVec lastPasswords;
|
||||
std::string oauthType;
|
||||
@@ -162,9 +171,11 @@ namespace OpenWifi {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
// bool append_from_json(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec & Notes);
|
||||
bool MergeNotes(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec & Notes);
|
||||
bool MergeNotes(const NoteInfoVec & NewNotes, const UserInfo &UInfo, NoteInfoVec & ExistingNotes);
|
||||
// bool append_from_json(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec &
|
||||
// Notes);
|
||||
bool MergeNotes(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec &Notes);
|
||||
bool MergeNotes(const NoteInfoVec &NewNotes, const UserInfo &UInfo,
|
||||
NoteInfoVec &ExistingNotes);
|
||||
|
||||
struct InternalServiceInfo {
|
||||
std::string privateURI;
|
||||
@@ -206,20 +217,12 @@ namespace OpenWifi {
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
typedef std::map<std::string,SecurityObjects::UserInfoAndPolicy> UserInfoCache;
|
||||
typedef std::map<std::string, SecurityObjects::UserInfoAndPolicy> UserInfoCache;
|
||||
|
||||
enum ResourceAccessType {
|
||||
NONE,
|
||||
READ,
|
||||
MODIFY,
|
||||
DELETE,
|
||||
CREATE,
|
||||
TEST,
|
||||
MOVE
|
||||
};
|
||||
enum ResourceAccessType { NONE, READ, MODIFY, DELETE, CREATE, TEST, MOVE };
|
||||
|
||||
ResourceAccessType ResourceAccessTypeFromString(const std::string &s);
|
||||
std::string ResourceAccessTypeToString(const ResourceAccessType & T);
|
||||
std::string ResourceAccessTypeToString(const ResourceAccessType &T);
|
||||
|
||||
struct ProfileAction {
|
||||
std::string resource;
|
||||
@@ -230,7 +233,7 @@ namespace OpenWifi {
|
||||
typedef std::vector<ProfileAction> ProfileActionVec;
|
||||
|
||||
struct SecurityProfile {
|
||||
uint64_t id=0;
|
||||
uint64_t id = 0;
|
||||
std::string name;
|
||||
std::string description;
|
||||
ProfileActionVec policy;
|
||||
@@ -248,7 +251,7 @@ namespace OpenWifi {
|
||||
};
|
||||
|
||||
enum LinkActions {
|
||||
FORGOT_PASSWORD=1,
|
||||
FORGOT_PASSWORD = 1,
|
||||
VERIFY_EMAIL,
|
||||
SUB_FORGOT_PASSWORD,
|
||||
SUB_VERIFY_EMAIL,
|
||||
@@ -264,12 +267,12 @@ namespace OpenWifi {
|
||||
Types::StringPairVec variables;
|
||||
std::string locale;
|
||||
std::string message;
|
||||
uint64_t sent=0;
|
||||
uint64_t created=Utils::Now();
|
||||
uint64_t expires=0;
|
||||
uint64_t completed=0;
|
||||
uint64_t canceled=0;
|
||||
bool userAction=true;
|
||||
uint64_t sent = 0;
|
||||
uint64_t created = Utils::Now();
|
||||
uint64_t expires = 0;
|
||||
uint64_t completed = 0;
|
||||
uint64_t canceled = 0;
|
||||
bool userAction = true;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -298,11 +301,11 @@ namespace OpenWifi {
|
||||
std::string refreshToken;
|
||||
std::string tokenType;
|
||||
std::string userName;
|
||||
uint64_t created=0;
|
||||
uint64_t expires=0;
|
||||
uint64_t idleTimeout=0;
|
||||
uint64_t revocationDate=0;
|
||||
uint64_t lastRefresh=0;
|
||||
uint64_t created = 0;
|
||||
uint64_t expires = 0;
|
||||
uint64_t idleTimeout = 0;
|
||||
uint64_t revocationDate = 0;
|
||||
uint64_t lastRefresh = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -311,7 +314,7 @@ namespace OpenWifi {
|
||||
struct Avatar {
|
||||
std::string id;
|
||||
std::string type;
|
||||
uint64_t created=0;
|
||||
uint64_t created = 0;
|
||||
std::string name;
|
||||
Poco::Data::BLOB avatar;
|
||||
};
|
||||
@@ -320,8 +323,8 @@ namespace OpenWifi {
|
||||
std::string sessionId;
|
||||
std::string userId;
|
||||
std::string email;
|
||||
uint64_t login=0;
|
||||
uint64_t logout=0;
|
||||
uint64_t login = 0;
|
||||
uint64_t logout = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
};
|
||||
@@ -349,9 +352,9 @@ namespace OpenWifi {
|
||||
std::string apiKey;
|
||||
std::string salt;
|
||||
std::uint64_t created;
|
||||
std::uint64_t expiresOn=0;
|
||||
std::uint64_t expiresOn = 0;
|
||||
ApiKeyAccessRightList rights;
|
||||
std::uint64_t lastUse=0;
|
||||
std::uint64_t lastUse = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -364,5 +367,5 @@ namespace OpenWifi {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
} // namespace SecurityObjects
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
#include "RESTAPI_SubObjects.h"
|
||||
#include "framework/RESTAPI_utils.h"
|
||||
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
using OpenWifi::RESTAPI_utils::field_from_json;
|
||||
using OpenWifi::RESTAPI_utils::field_to_json;
|
||||
|
||||
namespace OpenWifi::SubObjects {
|
||||
|
||||
@@ -599,4 +599,4 @@ namespace OpenWifi::SubObjects {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi::SubObjects
|
||||
@@ -18,10 +18,10 @@ namespace OpenWifi::SubObjects {
|
||||
std::string subnetMask;
|
||||
std::string startIP;
|
||||
std::string endIP;
|
||||
uint64_t created = 0 ;
|
||||
uint64_t modified = 0 ;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
std::string subnetV6;
|
||||
int subnetMaskV6=0;
|
||||
int subnetMaskV6 = 0;
|
||||
std::string startIPV6;
|
||||
std::string endIPV6;
|
||||
std::string leaseTime;
|
||||
@@ -42,16 +42,16 @@ namespace OpenWifi::SubObjects {
|
||||
struct IPReservationList {
|
||||
std::string id;
|
||||
std::vector<IPReservation> reservations;
|
||||
uint64_t created = 0 ;
|
||||
uint64_t modified = 0 ;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
struct DnsConfiguration {
|
||||
bool ISP=false;
|
||||
bool custom=false;
|
||||
bool ISP = false;
|
||||
bool custom = false;
|
||||
std::string primary;
|
||||
std::string secondary;
|
||||
std::string primaryV6;
|
||||
@@ -71,11 +71,11 @@ namespace OpenWifi::SubObjects {
|
||||
bool sendHostname = true;
|
||||
std::string primaryDns;
|
||||
std::string secondaryDns;
|
||||
uint64_t created=0;
|
||||
uint64_t modified=0;
|
||||
bool ipV6Support=false;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
bool ipV6Support = false;
|
||||
std::string ipAddressV6;
|
||||
int subnetMaskV6=0;
|
||||
int subnetMaskV6 = 0;
|
||||
std::string defaultGatewayV6;
|
||||
std::string primaryDnsV6;
|
||||
std::string secondaryDnsV6;
|
||||
@@ -97,8 +97,8 @@ namespace OpenWifi::SubObjects {
|
||||
|
||||
struct WifiNetworkList {
|
||||
std::vector<WifiNetwork> wifiNetworks;
|
||||
uint64_t created=0;
|
||||
uint64_t modified=0;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -114,8 +114,8 @@ namespace OpenWifi::SubObjects {
|
||||
|
||||
struct AccessTimes {
|
||||
std::vector<AccessTime> schedule;
|
||||
uint64_t created=0;
|
||||
uint64_t modified=0;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -126,11 +126,11 @@ namespace OpenWifi::SubObjects {
|
||||
std::string description;
|
||||
std::string macAddress;
|
||||
std::string manufacturer;
|
||||
uint64_t firstContact=0;
|
||||
uint64_t lastContact=0;
|
||||
uint64_t firstContact = 0;
|
||||
uint64_t lastContact = 0;
|
||||
std::string group;
|
||||
std::string icon;
|
||||
bool suspended=false;
|
||||
bool suspended = false;
|
||||
std::string ip;
|
||||
std::vector<AccessTimes> schedule;
|
||||
|
||||
@@ -140,8 +140,8 @@ namespace OpenWifi::SubObjects {
|
||||
|
||||
struct SubscriberDeviceList {
|
||||
std::vector<SubscriberDevice> devices;
|
||||
uint64_t created=0;
|
||||
uint64_t modified=0;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -151,12 +151,12 @@ namespace OpenWifi::SubObjects {
|
||||
std::string name;
|
||||
std::string ssid;
|
||||
std::string macAddress;
|
||||
int rssi=0;
|
||||
int power=0;
|
||||
int rssi = 0;
|
||||
int power = 0;
|
||||
std::string ipv4;
|
||||
std::string ipv6;
|
||||
uint64_t tx=0;
|
||||
uint64_t rx=0;
|
||||
uint64_t tx = 0;
|
||||
uint64_t rx = 0;
|
||||
std::string manufacturer;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -165,8 +165,8 @@ namespace OpenWifi::SubObjects {
|
||||
|
||||
struct AssociationList {
|
||||
std::vector<Association> associations;
|
||||
uint64_t created=0;
|
||||
uint64_t modified=0;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -178,8 +178,8 @@ namespace OpenWifi::SubObjects {
|
||||
std::string mode;
|
||||
std::string ipv4;
|
||||
std::string ipv6;
|
||||
uint64_t tx=0;
|
||||
uint64_t rx=0;
|
||||
uint64_t tx = 0;
|
||||
uint64_t rx = 0;
|
||||
std::string manufacturer;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -188,8 +188,8 @@ namespace OpenWifi::SubObjects {
|
||||
|
||||
struct ClientList {
|
||||
std::vector<Client> clients;
|
||||
uint64_t created=0;
|
||||
uint64_t modified=0;
|
||||
uint64_t created = 0;
|
||||
uint64_t modified = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
@@ -229,19 +229,19 @@ namespace OpenWifi::SubObjects {
|
||||
struct RadioInformation {
|
||||
std::string band;
|
||||
uint64_t bandwidth;
|
||||
uint64_t channel = 0 ;
|
||||
uint64_t channel = 0;
|
||||
std::string country;
|
||||
std::string channelMode{"HE"};
|
||||
uint64_t channelWidth = 80;
|
||||
std::string requireMode;
|
||||
uint64_t txpower=0;
|
||||
uint64_t txpower = 0;
|
||||
bool legacyRates = false;
|
||||
uint64_t beaconInterval = 100;
|
||||
uint64_t dtimPeriod = 2;
|
||||
uint64_t maximumClients = 64;
|
||||
RadioRates rates;
|
||||
RadioHE he;
|
||||
bool allowDFS=false;
|
||||
bool allowDFS = false;
|
||||
std::string mimo;
|
||||
std::vector<std::string> rawInfo;
|
||||
|
||||
@@ -302,21 +302,21 @@ namespace OpenWifi::SubObjects {
|
||||
};
|
||||
|
||||
struct StatsEntry {
|
||||
uint64_t timestamp=0;
|
||||
uint64_t tx=0;
|
||||
uint64_t rx=0;
|
||||
uint64_t timestamp = 0;
|
||||
uint64_t tx = 0;
|
||||
uint64_t rx = 0;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
struct StatsBlock {
|
||||
uint64_t modified=0;
|
||||
uint64_t modified = 0;
|
||||
std::vector<StatsEntry> external, internal;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi::SubObjects
|
||||
|
||||
#endif //OWSUB_RESTAPI_SUBOBJECTS_H
|
||||
#endif // OWSUB_RESTAPI_SUBOBJECTS_H
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
@@ -18,60 +18,48 @@ namespace OpenWifi {
|
||||
|
||||
RelativeCounter() = default;
|
||||
|
||||
RelativeCounter & operator=(uint64_t v) {
|
||||
RelativeCounter &operator=(uint64_t v) {
|
||||
set(v);
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool operator==(uint64_t v) const {
|
||||
return v == Value;
|
||||
}
|
||||
bool operator>=(uint64_t v) const {
|
||||
return v >= Value;
|
||||
}
|
||||
bool operator>(uint64_t v) const {
|
||||
return v > Value;
|
||||
}
|
||||
bool operator<=(uint64_t v) const {
|
||||
return v <= Value;
|
||||
}
|
||||
bool operator<(uint64_t v) const {
|
||||
return v < Value;
|
||||
}
|
||||
bool operator==(uint64_t v) const { return v == Value; }
|
||||
bool operator>=(uint64_t v) const { return v >= Value; }
|
||||
bool operator>(uint64_t v) const { return v > Value; }
|
||||
bool operator<=(uint64_t v) const { return v <= Value; }
|
||||
bool operator<(uint64_t v) const { return v < Value; }
|
||||
|
||||
inline uint64_t set(uint64_t v) {
|
||||
if(!inited) {
|
||||
inited=true;
|
||||
LastValue=v;
|
||||
if (!inited) {
|
||||
inited = true;
|
||||
LastValue = v;
|
||||
return v;
|
||||
}
|
||||
|
||||
if(v>=LastValue) {
|
||||
Value = (v-LastValue);
|
||||
if (v >= LastValue) {
|
||||
Value = (v - LastValue);
|
||||
LastValue = v;
|
||||
return Value;
|
||||
} else {
|
||||
Value = v ;
|
||||
Value = v;
|
||||
LastValue = v;
|
||||
return Value;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] inline uint64_t get() const {
|
||||
return Value;
|
||||
}
|
||||
[[nodiscard]] inline uint64_t get() const { return Value; }
|
||||
|
||||
friend std::ostream& operator<<(std::ostream& os, const RelativeCounter& rc);
|
||||
friend std::ostream &operator<<(std::ostream &os, const RelativeCounter &rc);
|
||||
|
||||
private:
|
||||
uint64_t Value = 0 ;
|
||||
uint64_t Value = 0;
|
||||
bool inited = false;
|
||||
uint64_t LastValue=0;
|
||||
uint64_t LastValue = 0;
|
||||
};
|
||||
|
||||
std::ostream & operator<<(std::ostream &os, const RelativeCounter &rc) {
|
||||
os << rc.get() ;
|
||||
std::ostream &operator<<(std::ostream &os, const RelativeCounter &rc) {
|
||||
os << rc.get();
|
||||
return os;
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -5,14 +5,16 @@
|
||||
#include "StateReceiver.h"
|
||||
#include "VenueWatcher.h"
|
||||
#include "fmt/core.h"
|
||||
#include "framework/KafkaTopics.h"
|
||||
#include "framework/KafkaManager.h"
|
||||
#include "framework/KafkaTopics.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
int StateReceiver::Start() {
|
||||
Running_ = true;
|
||||
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) { this->StateReceived(Key,Payload); };
|
||||
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) {
|
||||
this->StateReceived(Key, Payload);
|
||||
};
|
||||
StateWatcherId_ = KafkaManager()->RegisterTopicWatcher(KafkaTopics::STATE, F);
|
||||
Worker_.start(*this);
|
||||
return 0;
|
||||
@@ -28,9 +30,9 @@ namespace OpenWifi {
|
||||
void StateReceiver::run() {
|
||||
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
|
||||
Utils::SetThreadName("dev-state");
|
||||
while(Note && Running_) {
|
||||
while (Note && Running_) {
|
||||
auto Msg = dynamic_cast<StateMessage *>(Note.get());
|
||||
if(Msg!= nullptr) {
|
||||
if (Msg != nullptr) {
|
||||
try {
|
||||
nlohmann::json msg = nlohmann::json::parse(Msg->Payload());
|
||||
if (msg.contains(uCentralProtocol::PAYLOAD)) {
|
||||
@@ -40,8 +42,8 @@ namespace OpenWifi {
|
||||
auto state = std::make_shared<nlohmann::json>(payload["state"]);
|
||||
std::lock_guard G(Mutex_);
|
||||
auto it = Notifiers_.find(Utils::SerialNumberToInt(serialNumber));
|
||||
if(it!=Notifiers_.end()) {
|
||||
for(const auto &i:it->second) {
|
||||
if (it != Notifiers_.end()) {
|
||||
for (const auto &i : it->second) {
|
||||
i->PostState(Utils::SerialNumberToInt(serialNumber), state);
|
||||
}
|
||||
}
|
||||
@@ -50,25 +52,23 @@ namespace OpenWifi {
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger().log(E);
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
} else {
|
||||
|
||||
}
|
||||
Note = Queue_.waitDequeueNotification();
|
||||
}
|
||||
}
|
||||
|
||||
void StateReceiver::StateReceived( const std::string & Key, const std::string & Payload) {
|
||||
void StateReceiver::StateReceived(const std::string &Key, const std::string &Payload) {
|
||||
std::lock_guard G(Mutex_);
|
||||
poco_debug(Logger(),fmt::format("Device({}): State message.", Key));
|
||||
Queue_.enqueueNotification( new StateMessage(Key,Payload));
|
||||
poco_debug(Logger(), fmt::format("Device({}): State message.", Key));
|
||||
Queue_.enqueueNotification(new StateMessage(Key, Payload));
|
||||
}
|
||||
|
||||
void StateReceiver::Register(uint64_t SerialNumber, VenueWatcher *VW) {
|
||||
std::lock_guard G(Mutex_);
|
||||
auto it = Notifiers_.find(SerialNumber);
|
||||
if(it == Notifiers_.end()) {
|
||||
if (it == Notifiers_.end()) {
|
||||
std::list<VenueWatcher *> L;
|
||||
L.push_back(VW);
|
||||
Notifiers_[SerialNumber] = L;
|
||||
@@ -80,16 +80,14 @@ namespace OpenWifi {
|
||||
void StateReceiver::DeRegister(uint64_t SerialNumber, VenueWatcher *VW) {
|
||||
std::lock_guard G(Mutex_);
|
||||
auto it = Notifiers_.find(SerialNumber);
|
||||
if(it==Notifiers_.end())
|
||||
if (it == Notifiers_.end())
|
||||
return;
|
||||
for(auto i=it->second.begin();i!=it->second.end();i++) {
|
||||
if(*i==VW) {
|
||||
for (auto i = it->second.begin(); i != it->second.end(); i++) {
|
||||
if (*i == VW) {
|
||||
it->second.erase(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -3,18 +3,18 @@
|
||||
//
|
||||
|
||||
#pragma once
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "Poco/Notification.h"
|
||||
#include "Poco/NotificationQueue.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
class StateMessage : public Poco::Notification {
|
||||
public:
|
||||
explicit StateMessage(const std::string &Key, const std::string &Payload ) :
|
||||
Key_(Key),
|
||||
Payload_(Payload) {}
|
||||
const std::string & Key() { return Key_; }
|
||||
const std::string & Payload() { return Payload_; }
|
||||
explicit StateMessage(const std::string &Key, const std::string &Payload)
|
||||
: Key_(Key), Payload_(Payload) {}
|
||||
const std::string &Key() { return Key_; }
|
||||
const std::string &Payload() { return Payload_; }
|
||||
|
||||
private:
|
||||
std::string Key_;
|
||||
std::string Payload_;
|
||||
@@ -24,7 +24,6 @@ namespace OpenWifi {
|
||||
|
||||
class StateReceiver : public SubSystemServer, Poco::Runnable {
|
||||
public:
|
||||
|
||||
static auto instance() {
|
||||
static auto instance_ = new StateReceiver;
|
||||
return instance_;
|
||||
@@ -32,25 +31,23 @@ namespace OpenWifi {
|
||||
|
||||
int Start() override;
|
||||
void Stop() override;
|
||||
void StateReceived( const std::string & Key, const std::string & Payload);
|
||||
void StateReceived(const std::string &Key, const std::string &Payload);
|
||||
void run() override;
|
||||
void Register(uint64_t SerialNumber, VenueWatcher *VW);
|
||||
void DeRegister(uint64_t SerialNumber, VenueWatcher *VW);
|
||||
|
||||
private:
|
||||
// map of mac(as int), list of (id,func)
|
||||
std::map<uint64_t , std::list< VenueWatcher * >> Notifiers_;
|
||||
uint64_t StateWatcherId_=0;
|
||||
std::map<uint64_t, std::list<VenueWatcher *>> Notifiers_;
|
||||
uint64_t StateWatcherId_ = 0;
|
||||
Poco::NotificationQueue Queue_;
|
||||
Poco::Thread Worker_;
|
||||
std::atomic_bool Running_=false;
|
||||
std::atomic_bool Running_ = false;
|
||||
|
||||
StateReceiver() noexcept:
|
||||
SubSystemServer("StatsReceiver", "STATS-RECEIVER", "stats.receiver")
|
||||
{
|
||||
}
|
||||
StateReceiver() noexcept
|
||||
: SubSystemServer("StatsReceiver", "STATS-RECEIVER", "stats.receiver") {}
|
||||
};
|
||||
|
||||
inline auto StateReceiver() { return StateReceiver::instance(); }
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -8,34 +8,35 @@
|
||||
|
||||
#include "StorageService.h"
|
||||
#include "RESTObjects/RESTAPI_ProvObjects.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "fmt/format.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
int Storage::Start() {
|
||||
poco_notice(Logger(),"Starting...");
|
||||
poco_notice(Logger(), "Starting...");
|
||||
std::lock_guard Guard(Mutex_);
|
||||
|
||||
StorageClass::Start();
|
||||
|
||||
BoardsDB_ = std::make_unique<OpenWifi::BoardsDB>(dbType_,*Pool_, Logger());
|
||||
TimePointsDB_ = std::make_unique<OpenWifi::TimePointDB>(dbType_,*Pool_, Logger());
|
||||
WifiClientHistoryDB_ = std::make_unique<OpenWifi::WifiClientHistoryDB>(dbType_,*Pool_, Logger());
|
||||
BoardsDB_ = std::make_unique<OpenWifi::BoardsDB>(dbType_, *Pool_, Logger());
|
||||
TimePointsDB_ = std::make_unique<OpenWifi::TimePointDB>(dbType_, *Pool_, Logger());
|
||||
WifiClientHistoryDB_ =
|
||||
std::make_unique<OpenWifi::WifiClientHistoryDB>(dbType_, *Pool_, Logger());
|
||||
|
||||
TimePointsDB_->Create();
|
||||
BoardsDB_->Create();
|
||||
WifiClientHistoryDB_->Create();
|
||||
|
||||
PeriodicCleanup_ = MicroServiceConfigGetInt("storage.cleanup.interval", 6*60*60);
|
||||
if(PeriodicCleanup_<1*60*60)
|
||||
PeriodicCleanup_ = 1*60*60;
|
||||
PeriodicCleanup_ = MicroServiceConfigGetInt("storage.cleanup.interval", 6 * 60 * 60);
|
||||
if (PeriodicCleanup_ < 1 * 60 * 60)
|
||||
PeriodicCleanup_ = 1 * 60 * 60;
|
||||
|
||||
Updater_.start(*this);
|
||||
|
||||
TimerCallback_ = std::make_unique<Poco::TimerCallback<Storage>>(*this,&Storage::onTimer);
|
||||
Timer_.setStartInterval( 60 * 1000); // first run in 20 seconds
|
||||
TimerCallback_ = std::make_unique<Poco::TimerCallback<Storage>>(*this, &Storage::onTimer);
|
||||
Timer_.setStartInterval(60 * 1000); // first run in 20 seconds
|
||||
Timer_.setPeriodicInterval((long)PeriodicCleanup_ * 1000); // 1 hours
|
||||
Timer_.start(*TimerCallback_);
|
||||
|
||||
@@ -44,40 +45,46 @@ namespace OpenWifi {
|
||||
|
||||
void Storage::onTimer([[maybe_unused]] Poco::Timer &timer) {
|
||||
BoardsDB::RecordVec BoardList;
|
||||
uint64_t start = 0 ;
|
||||
uint64_t start = 0;
|
||||
bool done = false;
|
||||
const uint64_t batch=100;
|
||||
poco_information(Logger(),"Starting cleanup of TimePoint Database");
|
||||
while(!done) {
|
||||
if(!BoardsDB().GetRecords(start,batch,BoardList)) {
|
||||
for(const auto &board:BoardList) {
|
||||
for(const auto &venue:board.venueList) {
|
||||
const uint64_t batch = 100;
|
||||
poco_information(Logger(), "Starting cleanup of TimePoint Database");
|
||||
while (!done) {
|
||||
if (!BoardsDB().GetRecords(start, batch, BoardList)) {
|
||||
for (const auto &board : BoardList) {
|
||||
for (const auto &venue : board.venueList) {
|
||||
auto now = Utils::Now();
|
||||
auto lower_bound = now - venue.retention;
|
||||
poco_information(Logger(),fmt::format("Removing old records for board '{}'",board.info.name));
|
||||
BoardsDB().DeleteRecords(fmt::format(" boardId='{}' and timestamp<{}", board.info.id, lower_bound));
|
||||
poco_information(
|
||||
Logger(),
|
||||
fmt::format("Removing old records for board '{}'", board.info.name));
|
||||
BoardsDB().DeleteRecords(fmt::format(" boardId='{}' and timestamp<{}",
|
||||
board.info.id, lower_bound));
|
||||
}
|
||||
}
|
||||
}
|
||||
done = (BoardList.size() < batch);
|
||||
}
|
||||
|
||||
auto MaxDays = MicroServiceConfigGetInt("wificlient.age.limit",14);
|
||||
auto LowerDate = Utils::Now() - (MaxDays*60*60*24);
|
||||
poco_information(Logger(),fmt::format("Removing WiFi Clients history older than {} days.", MaxDays));
|
||||
StorageService()->WifiClientHistoryDB().DeleteRecords(fmt::format(" timestamp<{} ", LowerDate));
|
||||
poco_information(Logger(),fmt::format("Done cleanup of databases. Next run in {} seconds.", PeriodicCleanup_));
|
||||
auto MaxDays = MicroServiceConfigGetInt("wificlient.age.limit", 14);
|
||||
auto LowerDate = Utils::Now() - (MaxDays * 60 * 60 * 24);
|
||||
poco_information(Logger(),
|
||||
fmt::format("Removing WiFi Clients history older than {} days.", MaxDays));
|
||||
StorageService()->WifiClientHistoryDB().DeleteRecords(
|
||||
fmt::format(" timestamp<{} ", LowerDate));
|
||||
poco_information(Logger(), fmt::format("Done cleanup of databases. Next run in {} seconds.",
|
||||
PeriodicCleanup_));
|
||||
}
|
||||
|
||||
void Storage::run() {
|
||||
Utils::SetThreadName("strg-updtr");
|
||||
Running_ = true ;
|
||||
bool FirstRun=true;
|
||||
Running_ = true;
|
||||
bool FirstRun = true;
|
||||
long Retry = 2000;
|
||||
while(Running_) {
|
||||
if(!FirstRun)
|
||||
while (Running_) {
|
||||
if (!FirstRun)
|
||||
Poco::Thread::trySleep(Retry);
|
||||
if(!Running_)
|
||||
if (!Running_)
|
||||
break;
|
||||
FirstRun = false;
|
||||
Retry = 2000;
|
||||
@@ -85,13 +92,13 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void Storage::Stop() {
|
||||
poco_notice(Logger(),"Stopping...");
|
||||
Running_=false;
|
||||
poco_notice(Logger(), "Stopping...");
|
||||
Running_ = false;
|
||||
Timer_.stop();
|
||||
Updater_.wakeUp();
|
||||
Updater_.join();
|
||||
poco_notice(Logger(),"Stopped...");
|
||||
poco_notice(Logger(), "Stopped...");
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
// namespace
|
||||
@@ -25,21 +25,20 @@ namespace OpenWifi {
|
||||
void Stop() override;
|
||||
|
||||
void run() final;
|
||||
auto & BoardsDB() { return *BoardsDB_; };
|
||||
auto & TimePointsDB() { return *TimePointsDB_; };
|
||||
auto & WifiClientHistoryDB() { return *WifiClientHistoryDB_; };
|
||||
void onTimer(Poco::Timer & timer);
|
||||
auto &BoardsDB() { return *BoardsDB_; };
|
||||
auto &TimePointsDB() { return *TimePointsDB_; };
|
||||
auto &WifiClientHistoryDB() { return *WifiClientHistoryDB_; };
|
||||
void onTimer(Poco::Timer &timer);
|
||||
|
||||
private:
|
||||
std::unique_ptr<OpenWifi::BoardsDB> BoardsDB_;
|
||||
std::unique_ptr<OpenWifi::TimePointDB> TimePointsDB_;
|
||||
std::unique_ptr<OpenWifi::WifiClientHistoryDB> WifiClientHistoryDB_;
|
||||
Poco::Thread Updater_;
|
||||
std::atomic_bool Running_=false;
|
||||
std::atomic_bool Running_ = false;
|
||||
Poco::Timer Timer_;
|
||||
std::unique_ptr<Poco::TimerCallback<Storage>> TimerCallback_;
|
||||
uint64_t PeriodicCleanup_=6*60*60;
|
||||
uint64_t PeriodicCleanup_ = 6 * 60 * 60;
|
||||
};
|
||||
inline auto StorageService() { return Storage::instance(); }
|
||||
} // namespace
|
||||
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -3,21 +3,22 @@
|
||||
//
|
||||
|
||||
#include "VenueCoordinator.h"
|
||||
#include "VenueWatcher.h"
|
||||
#include "StorageService.h"
|
||||
#include "sdks/SDK_prov.h"
|
||||
#include "VenueWatcher.h"
|
||||
#include "fmt/core.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "sdks/SDK_prov.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
int VenueCoordinator::Start() {
|
||||
poco_notice(Logger(),"Starting...");
|
||||
poco_notice(Logger(), "Starting...");
|
||||
GetBoardList();
|
||||
Worker_.start(*this);
|
||||
|
||||
ReconcileTimerCallback_ = std::make_unique<Poco::TimerCallback<VenueCoordinator>>(*this,&VenueCoordinator::onReconcileTimer);
|
||||
ReconcileTimerTimer_.setStartInterval( 3 * 60 * 1000 );
|
||||
ReconcileTimerCallback_ = std::make_unique<Poco::TimerCallback<VenueCoordinator>>(
|
||||
*this, &VenueCoordinator::onReconcileTimer);
|
||||
ReconcileTimerTimer_.setStartInterval(3 * 60 * 1000);
|
||||
ReconcileTimerTimer_.setPeriodicInterval(3 * 60 * 1000); // 1 hours
|
||||
ReconcileTimerTimer_.start(*ReconcileTimerCallback_, MicroServiceTimerPool());
|
||||
|
||||
@@ -28,17 +29,17 @@ namespace OpenWifi {
|
||||
std::lock_guard G(Mutex_);
|
||||
Utils::SetThreadName("brd-refresh");
|
||||
|
||||
poco_information(Logger(),"Starting to reconcile board information.");
|
||||
for(const auto &[board_id, watcher]:Watchers_) {
|
||||
poco_information(Logger(),fmt::format("Updating: {}", board_id));
|
||||
poco_information(Logger(), "Starting to reconcile board information.");
|
||||
for (const auto &[board_id, watcher] : Watchers_) {
|
||||
poco_information(Logger(), fmt::format("Updating: {}", board_id));
|
||||
UpdateBoard(board_id);
|
||||
}
|
||||
poco_information(Logger(),"Finished reconciling board information.");
|
||||
poco_information(Logger(), "Finished reconciling board information.");
|
||||
}
|
||||
|
||||
void VenueCoordinator::GetBoardList() {
|
||||
BoardsToWatch_.clear();
|
||||
auto F = [&](const AnalyticsObjects::BoardInfo &B) ->bool {
|
||||
auto F = [&](const AnalyticsObjects::BoardInfo &B) -> bool {
|
||||
BoardsToWatch_.insert(B);
|
||||
// poco_information(Logger(),fmt::format("Starting watch for {}.", B.info.name));
|
||||
return true;
|
||||
@@ -47,31 +48,33 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void VenueCoordinator::Stop() {
|
||||
poco_notice(Logger(),"Stopping...");
|
||||
Running_=false;
|
||||
poco_notice(Logger(), "Stopping...");
|
||||
Running_ = false;
|
||||
Worker_.wakeUp();
|
||||
Worker_.wakeUp();
|
||||
Worker_.join();
|
||||
poco_notice(Logger(),"Stopped...");
|
||||
poco_notice(Logger(), "Stopped...");
|
||||
}
|
||||
|
||||
void VenueCoordinator::run() {
|
||||
Utils::SetThreadName("venue-coord");
|
||||
Running_=true;
|
||||
while(Running_) {
|
||||
Running_ = true;
|
||||
while (Running_) {
|
||||
Poco::Thread::trySleep(20000);
|
||||
if(!Running_)
|
||||
if (!Running_)
|
||||
break;
|
||||
|
||||
std::lock_guard G(Mutex_);
|
||||
GetBoardList();
|
||||
|
||||
if(!BoardsToWatch_.empty()) {
|
||||
for(const auto &board_to_start:BoardsToWatch_) {
|
||||
if (!BoardsToWatch_.empty()) {
|
||||
for (const auto &board_to_start : BoardsToWatch_) {
|
||||
bool VenueExists = true;
|
||||
if(!Watching(board_to_start.info.id)) {
|
||||
if (!Watching(board_to_start.info.id)) {
|
||||
StartBoard(board_to_start);
|
||||
} else if(SDK::Prov::Venue::Exists(nullptr,board_to_start.venueList[0].id,VenueExists) && !VenueExists) {
|
||||
} else if (SDK::Prov::Venue::Exists(nullptr, board_to_start.venueList[0].id,
|
||||
VenueExists) &&
|
||||
!VenueExists) {
|
||||
RetireBoard(board_to_start);
|
||||
}
|
||||
}
|
||||
@@ -80,18 +83,22 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void VenueCoordinator::RetireBoard(const AnalyticsObjects::BoardInfo &B) {
|
||||
Logger().error(fmt::format("Venue board '{}' is no longer in the system. Retiring its associated board.", B.venueList[0].name));
|
||||
Logger().error(fmt::format(
|
||||
"Venue board '{}' is no longer in the system. Retiring its associated board.",
|
||||
B.venueList[0].name));
|
||||
StopBoard(B.info.id);
|
||||
StorageService()->BoardsDB().DeleteRecord("id",B.info.id);
|
||||
StorageService()->BoardsDB().DeleteRecord("id", B.info.id);
|
||||
StorageService()->TimePointsDB().DeleteRecords(fmt::format(" boardId='{}' ", B.info.id));
|
||||
}
|
||||
|
||||
bool VenueCoordinator::GetDevicesForBoard(const AnalyticsObjects::BoardInfo &B, std::vector<uint64_t> & Devices, bool & VenueExists) {
|
||||
bool VenueCoordinator::GetDevicesForBoard(const AnalyticsObjects::BoardInfo &B,
|
||||
std::vector<uint64_t> &Devices, bool &VenueExists) {
|
||||
ProvObjects::VenueDeviceList VDL;
|
||||
|
||||
if(SDK::Prov::Venue::GetDevices(nullptr,B.venueList[0].id,B.venueList[0].monitorSubVenues, VDL, VenueExists)) {
|
||||
if (SDK::Prov::Venue::GetDevices(nullptr, B.venueList[0].id,
|
||||
B.venueList[0].monitorSubVenues, VDL, VenueExists)) {
|
||||
Devices.clear();
|
||||
for (const auto &device: VDL.devices) {
|
||||
for (const auto &device : VDL.devices) {
|
||||
Devices.push_back(Utils::SerialNumberToInt(device));
|
||||
}
|
||||
std::sort(Devices.begin(), Devices.end());
|
||||
@@ -100,7 +107,7 @@ namespace OpenWifi {
|
||||
return true;
|
||||
}
|
||||
|
||||
if(!VenueExists) {
|
||||
if (!VenueExists) {
|
||||
RetireBoard(B);
|
||||
}
|
||||
|
||||
@@ -108,26 +115,28 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
bool VenueCoordinator::StartBoard(const AnalyticsObjects::BoardInfo &B) {
|
||||
if(B.venueList.empty())
|
||||
if (B.venueList.empty())
|
||||
return true;
|
||||
|
||||
bool VenueExists=true;
|
||||
bool VenueExists = true;
|
||||
std::vector<uint64_t> Devices;
|
||||
if(GetDevicesForBoard(B,Devices,VenueExists)) {
|
||||
if (GetDevicesForBoard(B, Devices, VenueExists)) {
|
||||
std::lock_guard G(Mutex_);
|
||||
ExistingBoards_[B.info.id] = Devices;
|
||||
Watchers_[B.info.id] = std::make_shared<VenueWatcher>(B.info.id, B.venueList[0].id, Logger(), Devices);
|
||||
Watchers_[B.info.id] =
|
||||
std::make_shared<VenueWatcher>(B.info.id, B.venueList[0].id, Logger(), Devices);
|
||||
Watchers_[B.info.id]->Start();
|
||||
poco_information(Logger(),fmt::format("Started board {} for venue {}", B.info.name,B.venueList[0].id ));
|
||||
poco_information(Logger(), fmt::format("Started board {} for venue {}", B.info.name,
|
||||
B.venueList[0].id));
|
||||
return true;
|
||||
}
|
||||
|
||||
if(!VenueExists) {
|
||||
if (!VenueExists) {
|
||||
RetireBoard(B);
|
||||
return false;
|
||||
}
|
||||
|
||||
poco_information(Logger(),fmt::format("Could not start board {}",B.info.name));
|
||||
poco_information(Logger(), fmt::format("Could not start board {}", B.info.name));
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -135,7 +144,7 @@ namespace OpenWifi {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
auto it = Watchers_.find(id);
|
||||
if(it!=Watchers_.end()) {
|
||||
if (it != Watchers_.end()) {
|
||||
it->second->Stop();
|
||||
Watchers_.erase(it);
|
||||
}
|
||||
@@ -143,33 +152,34 @@ namespace OpenWifi {
|
||||
|
||||
void VenueCoordinator::UpdateBoard(const std::string &id) {
|
||||
AnalyticsObjects::BoardInfo B;
|
||||
if(StorageService()->BoardsDB().GetRecord("id",id,B)) {
|
||||
if (StorageService()->BoardsDB().GetRecord("id", id, B)) {
|
||||
std::vector<uint64_t> Devices;
|
||||
bool VenueExists=true;
|
||||
if(GetDevicesForBoard(B,Devices,VenueExists)) {
|
||||
bool VenueExists = true;
|
||||
if (GetDevicesForBoard(B, Devices, VenueExists)) {
|
||||
std::lock_guard G(Mutex_);
|
||||
auto it = ExistingBoards_.find(id);
|
||||
if(it!=ExistingBoards_.end()) {
|
||||
if(it->second!=Devices) {
|
||||
if (it != ExistingBoards_.end()) {
|
||||
if (it->second != Devices) {
|
||||
auto it2 = Watchers_.find(id);
|
||||
if(it2!=Watchers_.end()) {
|
||||
if (it2 != Watchers_.end()) {
|
||||
it2->second->ModifySerialNumbers(Devices);
|
||||
}
|
||||
ExistingBoards_[id] = Devices;
|
||||
poco_information(Logger(),fmt::format("Modified board {}",B.info.name));
|
||||
poco_information(Logger(), fmt::format("Modified board {}", B.info.name));
|
||||
} else {
|
||||
poco_information(Logger(),fmt::format("No device changes in board {}",B.info.name));
|
||||
poco_information(Logger(),
|
||||
fmt::format("No device changes in board {}", B.info.name));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if(!VenueExists) {
|
||||
if (!VenueExists) {
|
||||
RetireBoard(B);
|
||||
return;
|
||||
}
|
||||
|
||||
poco_information(Logger(),fmt::format("Could not modify board {}",B.info.name));
|
||||
poco_information(Logger(), fmt::format("Could not modify board {}", B.info.name));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,18 +192,18 @@ namespace OpenWifi {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
AnalyticsObjects::BoardInfo B;
|
||||
if(StorageService()->BoardsDB().GetRecord("id",id,B))
|
||||
if (StorageService()->BoardsDB().GetRecord("id", id, B))
|
||||
BoardsToWatch_.insert(B);
|
||||
else
|
||||
poco_information(Logger(),fmt::format("Board {} does not seem to exist",id));
|
||||
poco_information(Logger(), fmt::format("Board {} does not seem to exist", id));
|
||||
}
|
||||
|
||||
void VenueCoordinator::GetDevices(std::string &id, AnalyticsObjects::DeviceInfoList &DIL) {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
auto it = Watchers_.find(id);
|
||||
if(it!=end(Watchers_)) {
|
||||
if (it != end(Watchers_)) {
|
||||
it->second->GetDevices(DIL.devices);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "VenueWatcher.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
#include "Poco/Timer.h"
|
||||
|
||||
@@ -13,7 +13,6 @@ namespace OpenWifi {
|
||||
|
||||
class VenueCoordinator : public SubSystemServer, Poco::Runnable {
|
||||
public:
|
||||
|
||||
static auto instance() {
|
||||
static auto instance_ = new VenueCoordinator;
|
||||
return instance_;
|
||||
@@ -27,32 +26,30 @@ namespace OpenWifi {
|
||||
void UpdateBoard(const std::string &id);
|
||||
void AddBoard(const std::string &id);
|
||||
|
||||
bool GetDevicesForBoard(const AnalyticsObjects::BoardInfo &B, std::vector<uint64_t> & Devices, bool & VenueExists);
|
||||
void GetDevices(std::string &id, AnalyticsObjects::DeviceInfoList & DIL);
|
||||
bool GetDevicesForBoard(const AnalyticsObjects::BoardInfo &B,
|
||||
std::vector<uint64_t> &Devices, bool &VenueExists);
|
||||
void GetDevices(std::string &id, AnalyticsObjects::DeviceInfoList &DIL);
|
||||
void GetBoardList();
|
||||
bool Watching(const std::string &id);
|
||||
void RetireBoard(const AnalyticsObjects::BoardInfo &B);
|
||||
|
||||
void onReconcileTimer(Poco::Timer & timer);
|
||||
void onReconcileTimer(Poco::Timer &timer);
|
||||
|
||||
private:
|
||||
Poco::Thread Worker_;
|
||||
std::atomic_bool Running_=false;
|
||||
std::atomic_bool Running_ = false;
|
||||
std::set<AnalyticsObjects::BoardInfo> BoardsToWatch_;
|
||||
std::map<std::string,std::shared_ptr<VenueWatcher>> Watchers_;
|
||||
std::map<std::string, std::shared_ptr<VenueWatcher>> Watchers_;
|
||||
std::unique_ptr<Poco::TimerCallback<VenueCoordinator>> ReconcileTimerCallback_;
|
||||
Poco::Timer ReconcileTimerTimer_;
|
||||
|
||||
std::map<std::string,std::vector<uint64_t>> ExistingBoards_;
|
||||
std::map<std::string, std::vector<uint64_t>> ExistingBoards_;
|
||||
|
||||
VenueCoordinator() noexcept:
|
||||
SubSystemServer("VenueCoordinator", "VENUE-COORD", "venue.coordinator")
|
||||
{
|
||||
}
|
||||
VenueCoordinator() noexcept
|
||||
: SubSystemServer("VenueCoordinator", "VENUE-COORD", "venue.coordinator") {}
|
||||
|
||||
bool StartBoard(const AnalyticsObjects::BoardInfo &B);
|
||||
|
||||
};
|
||||
inline auto VenueCoordinator() { return VenueCoordinator::instance(); }
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -3,59 +3,59 @@
|
||||
//
|
||||
|
||||
#include "VenueWatcher.h"
|
||||
#include "StateReceiver.h"
|
||||
#include "DeviceStatusReceiver.h"
|
||||
#include "HealthReceiver.h"
|
||||
#include "StateReceiver.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
void VenueWatcher::Start() {
|
||||
poco_notice(Logger(),"Starting...");
|
||||
for(const auto &mac:SerialNumbers_) {
|
||||
poco_notice(Logger(), "Starting...");
|
||||
for (const auto &mac : SerialNumbers_) {
|
||||
auto ap = std::make_shared<AP>(mac, venue_id_, boardId_, Logger());
|
||||
APs_[mac ] = ap;
|
||||
APs_[mac] = ap;
|
||||
}
|
||||
|
||||
for(const auto &i:SerialNumbers_)
|
||||
StateReceiver()->Register(i,this);
|
||||
for (const auto &i : SerialNumbers_)
|
||||
StateReceiver()->Register(i, this);
|
||||
|
||||
DeviceStatusReceiver()->Register(SerialNumbers_,this);
|
||||
HealthReceiver()->Register(SerialNumbers_,this);
|
||||
DeviceStatusReceiver()->Register(SerialNumbers_, this);
|
||||
HealthReceiver()->Register(SerialNumbers_, this);
|
||||
Worker_.start(*this);
|
||||
}
|
||||
|
||||
void VenueWatcher::Stop() {
|
||||
poco_notice(Logger(),"Stopping...");
|
||||
poco_notice(Logger(), "Stopping...");
|
||||
Running_ = false;
|
||||
Queue_.wakeUpAll();
|
||||
Worker_.join();
|
||||
for(const auto &i:SerialNumbers_)
|
||||
StateReceiver()->DeRegister(i,this);
|
||||
for (const auto &i : SerialNumbers_)
|
||||
StateReceiver()->DeRegister(i, this);
|
||||
DeviceStatusReceiver()->DeRegister(this);
|
||||
HealthReceiver()->DeRegister(this);
|
||||
poco_notice(Logger(),"Stopped...");
|
||||
poco_notice(Logger(), "Stopped...");
|
||||
}
|
||||
|
||||
void VenueWatcher::run() {
|
||||
Utils::SetThreadName("venue-watch");
|
||||
Running_ = true;
|
||||
Poco::AutoPtr<Poco::Notification> Msg(Queue_.waitDequeueNotification());
|
||||
while(Msg && Running_) {
|
||||
while (Msg && Running_) {
|
||||
auto MsgContent = dynamic_cast<VenueMessage *>(Msg.get());
|
||||
if(MsgContent!= nullptr) {
|
||||
if (MsgContent != nullptr) {
|
||||
try {
|
||||
auto State = MsgContent->Payload();
|
||||
if(MsgContent->Type()==VenueMessage::connection) {
|
||||
if (MsgContent->Type() == VenueMessage::connection) {
|
||||
auto It = APs_.find(MsgContent->SerialNumber());
|
||||
if(It!=end(APs_)) {
|
||||
if (It != end(APs_)) {
|
||||
It->second->UpdateConnection(MsgContent->Payload());
|
||||
}
|
||||
} else if(MsgContent->Type()==VenueMessage::state) {
|
||||
} else if (MsgContent->Type() == VenueMessage::state) {
|
||||
auto It = APs_.find(MsgContent->SerialNumber());
|
||||
if (It != end(APs_)) {
|
||||
It->second->UpdateStats(MsgContent->Payload());
|
||||
}
|
||||
} else if(MsgContent->Type()==VenueMessage::health) {
|
||||
} else if (MsgContent->Type() == VenueMessage::health) {
|
||||
auto It = APs_.find(MsgContent->SerialNumber());
|
||||
if (It != end(APs_)) {
|
||||
It->second->UpdateHealth(MsgContent->Payload());
|
||||
@@ -64,10 +64,8 @@ namespace OpenWifi {
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger().log(E);
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
} else {
|
||||
|
||||
}
|
||||
Msg = Queue_.waitDequeueNotification();
|
||||
}
|
||||
@@ -77,36 +75,37 @@ namespace OpenWifi {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
std::vector<uint64_t> Diff;
|
||||
std::set_symmetric_difference(SerialNumbers_.begin(),SerialNumbers_.end(),SerialNumbers.begin(),
|
||||
SerialNumbers.end(),std::inserter(Diff,Diff.begin()));
|
||||
std::set_symmetric_difference(SerialNumbers_.begin(), SerialNumbers_.end(),
|
||||
SerialNumbers.begin(), SerialNumbers.end(),
|
||||
std::inserter(Diff, Diff.begin()));
|
||||
|
||||
std::vector<uint64_t> ToRemove;
|
||||
std::set_intersection(SerialNumbers_.begin(),SerialNumbers_.end(),Diff.begin(),
|
||||
Diff.end(),std::inserter(ToRemove,ToRemove.begin()));
|
||||
std::set_intersection(SerialNumbers_.begin(), SerialNumbers_.end(), Diff.begin(),
|
||||
Diff.end(), std::inserter(ToRemove, ToRemove.begin()));
|
||||
|
||||
std::vector<uint64_t> ToAdd;
|
||||
std::set_intersection(SerialNumbers.begin(),SerialNumbers.end(),Diff.begin(),
|
||||
Diff.end(),std::inserter(ToAdd,ToAdd.begin()));
|
||||
std::set_intersection(SerialNumbers.begin(), SerialNumbers.end(), Diff.begin(), Diff.end(),
|
||||
std::inserter(ToAdd, ToAdd.begin()));
|
||||
|
||||
for(const auto &i:ToRemove) {
|
||||
for (const auto &i : ToRemove) {
|
||||
StateReceiver()->DeRegister(i, this);
|
||||
}
|
||||
for(const auto &i:ToAdd) {
|
||||
for (const auto &i : ToAdd) {
|
||||
StateReceiver()->Register(i, this);
|
||||
}
|
||||
|
||||
HealthReceiver()->Register(SerialNumbers,this);
|
||||
DeviceStatusReceiver()->Register(SerialNumbers,this);
|
||||
HealthReceiver()->Register(SerialNumbers, this);
|
||||
DeviceStatusReceiver()->Register(SerialNumbers, this);
|
||||
|
||||
SerialNumbers_ = SerialNumbers;
|
||||
}
|
||||
|
||||
void VenueWatcher::GetDevices(std::vector<AnalyticsObjects::DeviceInfo> & DIL) {
|
||||
void VenueWatcher::GetDevices(std::vector<AnalyticsObjects::DeviceInfo> &DIL) {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
DIL.reserve(APs_.size());
|
||||
for(const auto &[serialNumber,DI]:APs_)
|
||||
for (const auto &[serialNumber, DI] : APs_)
|
||||
DIL.push_back(DI->Info());
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,47 +4,39 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "APStats.h"
|
||||
#include "RESTObjects/RESTAPI_AnalyticsObjects.h"
|
||||
#include "Poco/NotificationQueue.h"
|
||||
#include "Poco/Notification.h"
|
||||
#include "Poco/NotificationQueue.h"
|
||||
#include "RESTObjects/RESTAPI_AnalyticsObjects.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class VenueMessage : public Poco::Notification {
|
||||
public:
|
||||
enum MsgType {
|
||||
connection,
|
||||
state,
|
||||
health
|
||||
};
|
||||
enum MsgType { connection, state, health };
|
||||
|
||||
explicit VenueMessage(uint64_t SerialNumber, MsgType Msg, std::shared_ptr<nlohmann::json> &M ) :
|
||||
Payload_(M),
|
||||
Type_(Msg),
|
||||
SerialNumber_(SerialNumber) {
|
||||
}
|
||||
inline std::shared_ptr<nlohmann::json> & Payload() { return Payload_; }
|
||||
explicit VenueMessage(uint64_t SerialNumber, MsgType Msg,
|
||||
std::shared_ptr<nlohmann::json> &M)
|
||||
: Payload_(M), Type_(Msg), SerialNumber_(SerialNumber) {}
|
||||
inline std::shared_ptr<nlohmann::json> &Payload() { return Payload_; }
|
||||
inline auto SerialNumber() { return SerialNumber_; }
|
||||
inline uint64_t Type() { return Type_; }
|
||||
|
||||
private:
|
||||
std::shared_ptr<nlohmann::json> Payload_;
|
||||
MsgType Type_;
|
||||
uint64_t SerialNumber_=0;
|
||||
uint64_t SerialNumber_ = 0;
|
||||
};
|
||||
|
||||
class VenueWatcher : public Poco::Runnable {
|
||||
public:
|
||||
explicit VenueWatcher(const std::string &boardId, const std::string &venue_id,Poco::Logger &L, const std::vector<uint64_t> & SerialNumbers) :
|
||||
boardId_(boardId),
|
||||
venue_id_(venue_id),
|
||||
Logger_(L),
|
||||
SerialNumbers_(SerialNumbers) {
|
||||
std::sort(SerialNumbers_.begin(),SerialNumbers_.end());
|
||||
auto last = std::unique(SerialNumbers_.begin(),SerialNumbers_.end());
|
||||
SerialNumbers_.erase(last,SerialNumbers_.end());
|
||||
explicit VenueWatcher(const std::string &boardId, const std::string &venue_id,
|
||||
Poco::Logger &L, const std::vector<uint64_t> &SerialNumbers)
|
||||
: boardId_(boardId), venue_id_(venue_id), Logger_(L), SerialNumbers_(SerialNumbers) {
|
||||
std::sort(SerialNumbers_.begin(), SerialNumbers_.end());
|
||||
auto last = std::unique(SerialNumbers_.begin(), SerialNumbers_.end());
|
||||
SerialNumbers_.erase(last, SerialNumbers_.end());
|
||||
}
|
||||
|
||||
inline void PostState(uint64_t SerialNumber, std::shared_ptr<nlohmann::json> &Msg) {
|
||||
@@ -54,7 +46,8 @@ namespace OpenWifi {
|
||||
|
||||
inline void PostConnection(uint64_t SerialNumber, std::shared_ptr<nlohmann::json> &Msg) {
|
||||
std::lock_guard G(Mutex_);
|
||||
Queue_.enqueueNotification(new VenueMessage(SerialNumber, VenueMessage::connection, Msg));
|
||||
Queue_.enqueueNotification(
|
||||
new VenueMessage(SerialNumber, VenueMessage::connection, Msg));
|
||||
}
|
||||
|
||||
inline void PostHealth(uint64_t SerialNumber, std::shared_ptr<nlohmann::json> &Msg) {
|
||||
@@ -66,14 +59,14 @@ namespace OpenWifi {
|
||||
void Stop();
|
||||
|
||||
void run() final;
|
||||
inline Poco::Logger & Logger() { return Logger_; }
|
||||
inline Poco::Logger &Logger() { return Logger_; }
|
||||
void ModifySerialNumbers(const std::vector<uint64_t> &SerialNumbers);
|
||||
void GetDevices(std::vector<AnalyticsObjects::DeviceInfo> & DI);
|
||||
void GetDevices(std::vector<AnalyticsObjects::DeviceInfo> &DI);
|
||||
|
||||
void GetBandwidth(uint64_t start, uint64_t end, uint64_t interval,
|
||||
AnalyticsObjects::BandwidthAnalysis &BW);
|
||||
inline std::string Venue() const { return venue_id_; }
|
||||
|
||||
void GetBandwidth(uint64_t start, uint64_t end, uint64_t interval , AnalyticsObjects::BandwidthAnalysis & BW);
|
||||
inline std::string Venue() const {
|
||||
return venue_id_;
|
||||
}
|
||||
private:
|
||||
std::mutex Mutex_;
|
||||
std::string boardId_;
|
||||
@@ -81,9 +74,9 @@ namespace OpenWifi {
|
||||
Poco::NotificationQueue Queue_;
|
||||
Poco::Logger &Logger_;
|
||||
Poco::Thread Worker_;
|
||||
std::atomic_bool Running_=false;
|
||||
std::atomic_bool Running_ = false;
|
||||
std::vector<uint64_t> SerialNumbers_;
|
||||
std::map<uint64_t, std::shared_ptr<AP>> APs_;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,59 +4,65 @@
|
||||
|
||||
#include <mutex>
|
||||
|
||||
#include "WifiClientCache.h"
|
||||
#include "StorageService.h"
|
||||
#include "WifiClientCache.h"
|
||||
#include "fmt/format.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
int WifiClientCache::Start() {
|
||||
poco_notice(Logger(),"Starting...");
|
||||
TimerCallback_ = std::make_unique<Poco::TimerCallback<WifiClientCache>>(*this,&WifiClientCache::onTimer);
|
||||
Timer_.setStartInterval( 30 * 1000); // first run in 20 seconds
|
||||
Timer_.setPeriodicInterval( 60 * 60 * 1000); // 1 hours
|
||||
poco_notice(Logger(), "Starting...");
|
||||
TimerCallback_ = std::make_unique<Poco::TimerCallback<WifiClientCache>>(
|
||||
*this, &WifiClientCache::onTimer);
|
||||
Timer_.setStartInterval(30 * 1000); // first run in 20 seconds
|
||||
Timer_.setPeriodicInterval(60 * 60 * 1000); // 1 hours
|
||||
Timer_.start(*TimerCallback_);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void WifiClientCache::Stop() {
|
||||
poco_notice(Logger(),"Stopping...");
|
||||
poco_notice(Logger(), "Stopping...");
|
||||
Timer_.stop();
|
||||
poco_notice(Logger(),"Stopped...");
|
||||
poco_notice(Logger(), "Stopped...");
|
||||
}
|
||||
|
||||
void WifiClientCache::onTimer([[maybe_unused]] Poco::Timer & timer) {
|
||||
std::vector<std::pair<std::string,std::string>> WifiClients;
|
||||
if(StorageService()->WifiClientHistoryDB().GetClientMacs(WifiClients)) {
|
||||
void WifiClientCache::onTimer([[maybe_unused]] Poco::Timer &timer) {
|
||||
std::vector<std::pair<std::string, std::string>> WifiClients;
|
||||
if (StorageService()->WifiClientHistoryDB().GetClientMacs(WifiClients)) {
|
||||
// Let's replace current cache...
|
||||
std::lock_guard G(Mutex_);
|
||||
Cache_.clear();
|
||||
for(const auto &mac:WifiClients)
|
||||
AddSerialNumber(mac.second,mac.first,G);
|
||||
for (const auto &mac : WifiClients)
|
||||
AddSerialNumber(mac.second, mac.first, G);
|
||||
}
|
||||
}
|
||||
|
||||
void WifiClientCache::AddSerialNumber(const std::string &venue_id, const std::string &S) {
|
||||
std::lock_guard G(Mutex_);
|
||||
AddSerialNumber(venue_id, S,G);
|
||||
AddSerialNumber(venue_id, S, G);
|
||||
}
|
||||
|
||||
void WifiClientCache::AddSerialNumber(const std::string &venue_id, const std::string &S, [[maybe_unused]] std::lock_guard<std::recursive_mutex> & G) {
|
||||
void
|
||||
WifiClientCache::AddSerialNumber(const std::string &venue_id, const std::string &S,
|
||||
[[maybe_unused]] std::lock_guard<std::recursive_mutex> &G) {
|
||||
auto VenueIt = Cache_.find(venue_id);
|
||||
if(VenueIt==Cache_.end()) {
|
||||
if (VenueIt == Cache_.end()) {
|
||||
Cache_.insert(std::pair(venue_id, Cache{}));
|
||||
VenueIt = Cache_.find(venue_id);
|
||||
}
|
||||
|
||||
uint64_t SN = std::stoull(S, nullptr, 16);
|
||||
if (std::find(std::begin(VenueIt->second.SNs_), std::end(VenueIt->second.SNs_), SN) == std::end(VenueIt->second.SNs_)) {
|
||||
auto insert_point = std::lower_bound(VenueIt->second.SNs_.begin(), VenueIt->second.SNs_.end(), SN);
|
||||
if (std::find(std::begin(VenueIt->second.SNs_), std::end(VenueIt->second.SNs_), SN) ==
|
||||
std::end(VenueIt->second.SNs_)) {
|
||||
auto insert_point =
|
||||
std::lower_bound(VenueIt->second.SNs_.begin(), VenueIt->second.SNs_.end(), SN);
|
||||
VenueIt->second.SNs_.insert(insert_point, SN);
|
||||
|
||||
auto R = ReverseSerialNumber(S);
|
||||
uint64_t RSN = std::stoull(R, nullptr, 16);
|
||||
auto rev_insert_point = std::lower_bound(VenueIt->second.Reverse_SNs_.begin(), VenueIt->second.Reverse_SNs_.end(), RSN);
|
||||
auto rev_insert_point = std::lower_bound(VenueIt->second.Reverse_SNs_.begin(),
|
||||
VenueIt->second.Reverse_SNs_.end(), RSN);
|
||||
VenueIt->second.Reverse_SNs_.insert(rev_insert_point, RSN);
|
||||
}
|
||||
}
|
||||
@@ -64,19 +70,20 @@ namespace OpenWifi {
|
||||
void WifiClientCache::DeleteSerialNumber(const std::string &venue_id, const std::string &S) {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
uint64_t SN = std::stoull(S,nullptr,16);
|
||||
uint64_t SN = std::stoull(S, nullptr, 16);
|
||||
|
||||
auto VenueIt = Cache_.find(venue_id);
|
||||
if(VenueIt==Cache_.end())
|
||||
if (VenueIt == Cache_.end())
|
||||
return;
|
||||
auto It = std::find(VenueIt->second.SNs_.begin(),VenueIt->second.SNs_.end(),SN);
|
||||
if(It != VenueIt->second.SNs_.end()) {
|
||||
auto It = std::find(VenueIt->second.SNs_.begin(), VenueIt->second.SNs_.end(), SN);
|
||||
if (It != VenueIt->second.SNs_.end()) {
|
||||
VenueIt->second.SNs_.erase(It);
|
||||
|
||||
auto R = ReverseSerialNumber(S);
|
||||
uint64_t RSN = std::stoull(R, nullptr, 16);
|
||||
auto RIt = std::find(VenueIt->second.Reverse_SNs_.begin(),VenueIt->second.Reverse_SNs_.end(),RSN);
|
||||
if(RIt != VenueIt->second.Reverse_SNs_.end()) {
|
||||
auto RIt = std::find(VenueIt->second.Reverse_SNs_.begin(),
|
||||
VenueIt->second.Reverse_SNs_.end(), RSN);
|
||||
if (RIt != VenueIt->second.Reverse_SNs_.end()) {
|
||||
VenueIt->second.Reverse_SNs_.erase(RIt);
|
||||
}
|
||||
}
|
||||
@@ -93,7 +100,9 @@ namespace OpenWifi {
|
||||
return Res;
|
||||
}
|
||||
|
||||
void WifiClientCache::ReturnNumbers(const std::string &S, uint HowMany, const std::vector<uint64_t> &SNArr, std::vector<uint64_t> &A, bool ReverseResult) {
|
||||
void WifiClientCache::ReturnNumbers(const std::string &S, uint HowMany,
|
||||
const std::vector<uint64_t> &SNArr,
|
||||
std::vector<uint64_t> &A, bool ReverseResult) {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
if (S.length() == 12) {
|
||||
@@ -109,9 +118,10 @@ namespace OpenWifi {
|
||||
auto LB = std::lower_bound(SNArr.begin(), SNArr.end(), SN);
|
||||
if (LB != SNArr.end()) {
|
||||
for (; LB != SNArr.end() && HowMany; ++LB, --HowMany) {
|
||||
if(ReverseResult) {
|
||||
const auto TSN = ReverseSerialNumber(Utils::IntToSerialNumber(Reverse(*LB)));
|
||||
if (S == TSN.substr(0,S.size())) {
|
||||
if (ReverseResult) {
|
||||
const auto TSN =
|
||||
ReverseSerialNumber(Utils::IntToSerialNumber(Reverse(*LB)));
|
||||
if (S == TSN.substr(0, S.size())) {
|
||||
A.emplace_back(Reverse(*LB));
|
||||
} else {
|
||||
break;
|
||||
@@ -129,19 +139,21 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
void WifiClientCache::FindNumbers(const std::string &venueId, const std::string &SerialNumber, std::uint64_t StartingOffset, std::uint64_t HowMany, std::vector<uint64_t> &A) {
|
||||
void WifiClientCache::FindNumbers(const std::string &venueId, const std::string &SerialNumber,
|
||||
std::uint64_t StartingOffset, std::uint64_t HowMany,
|
||||
std::vector<uint64_t> &A) {
|
||||
std::lock_guard G(Mutex_);
|
||||
|
||||
A.clear();
|
||||
auto VenueIt = Cache_.find(venueId);
|
||||
if(VenueIt==Cache_.end())
|
||||
if (VenueIt == Cache_.end())
|
||||
return;
|
||||
|
||||
if(SerialNumber.empty()) {
|
||||
if (SerialNumber.empty()) {
|
||||
auto Start = VenueIt->second.SNs_.begin();
|
||||
std::uint64_t Offset=0;
|
||||
while(HowMany && Start!=VenueIt->second.SNs_.end()) {
|
||||
if(Offset>=StartingOffset) {
|
||||
std::uint64_t Offset = 0;
|
||||
while (HowMany && Start != VenueIt->second.SNs_.end()) {
|
||||
if (Offset >= StartingOffset) {
|
||||
A.push_back(*Start);
|
||||
HowMany--;
|
||||
}
|
||||
@@ -153,12 +165,12 @@ namespace OpenWifi {
|
||||
|
||||
if (SerialNumber[0] == '*') {
|
||||
std::string Reversed;
|
||||
std::copy(rbegin(SerialNumber), rend(SerialNumber)-1, std::back_inserter(Reversed));
|
||||
if(Reversed.empty())
|
||||
std::copy(rbegin(SerialNumber), rend(SerialNumber) - 1, std::back_inserter(Reversed));
|
||||
if (Reversed.empty())
|
||||
return;
|
||||
return ReturnNumbers(Reversed, HowMany, VenueIt->second.Reverse_SNs_, A, true);
|
||||
} else {
|
||||
return ReturnNumbers(SerialNumber, HowMany, VenueIt->second.SNs_, A, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,13 +4,12 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "Poco/Timer.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
class WifiClientCache : public SubSystemServer {
|
||||
public:
|
||||
|
||||
static auto instance() {
|
||||
static auto instance_ = new WifiClientCache;
|
||||
return instance_;
|
||||
@@ -20,41 +19,43 @@ namespace OpenWifi {
|
||||
void Stop() override;
|
||||
void AddSerialNumber(const std::string &venueId, const std::string &SerialNumber);
|
||||
void DeleteSerialNumber(const std::string &venueId, const std::string &SerialNumber);
|
||||
void FindNumbers(const std::string &venueId, const std::string &SerialNumber, std::uint64_t start, std::uint64_t HowMany, std::vector<uint64_t> &A);
|
||||
void FindNumbers(const std::string &venueId, const std::string &SerialNumber,
|
||||
std::uint64_t start, std::uint64_t HowMany, std::vector<uint64_t> &A);
|
||||
inline bool NumberExists(const std::string &venueId, uint64_t SerialNumber) {
|
||||
std::lock_guard G(Mutex_);
|
||||
auto It = Cache_.find(venueId);
|
||||
if(It==Cache_.end())
|
||||
if (It == Cache_.end())
|
||||
return false;
|
||||
return std::find(It->second.SNs_.begin(),It->second.SNs_.end(),SerialNumber)!=It->second.SNs_.end();
|
||||
return std::find(It->second.SNs_.begin(), It->second.SNs_.end(), SerialNumber) !=
|
||||
It->second.SNs_.end();
|
||||
}
|
||||
|
||||
static inline std::string ReverseSerialNumber(const std::string &S) {
|
||||
std::string ReversedString;
|
||||
std::copy(rbegin(S),rend(S),std::back_inserter(ReversedString));
|
||||
std::copy(rbegin(S), rend(S), std::back_inserter(ReversedString));
|
||||
return ReversedString;
|
||||
}
|
||||
void onTimer(Poco::Timer & timer);
|
||||
void onTimer(Poco::Timer &timer);
|
||||
|
||||
private:
|
||||
struct Cache {
|
||||
std::vector<uint64_t> SNs_;
|
||||
std::vector<uint64_t> Reverse_SNs_;
|
||||
};
|
||||
std::map<std::string,Cache> Cache_;
|
||||
std::map<std::string, Cache> Cache_;
|
||||
Poco::Timer Timer_;
|
||||
std::unique_ptr<Poco::TimerCallback<WifiClientCache>> TimerCallback_;
|
||||
|
||||
void AddSerialNumber(const std::string &venueId, const std::string &S, std::lock_guard<std::recursive_mutex> & G);
|
||||
void AddSerialNumber(const std::string &venueId, const std::string &S,
|
||||
std::lock_guard<std::recursive_mutex> &G);
|
||||
|
||||
void ReturnNumbers(const std::string &S, uint HowMany, const std::vector<uint64_t> & SNArr, std::vector<uint64_t> &A, bool ReverseResult);
|
||||
void ReturnNumbers(const std::string &S, uint HowMany, const std::vector<uint64_t> &SNArr,
|
||||
std::vector<uint64_t> &A, bool ReverseResult);
|
||||
|
||||
WifiClientCache() noexcept:
|
||||
SubSystemServer("SerialNumberCache", "SNCACHE-SVR", "serialcache")
|
||||
{
|
||||
}
|
||||
WifiClientCache() noexcept
|
||||
: SubSystemServer("SerialNumberCache", "SNCACHE-SVR", "serialcache") {}
|
||||
};
|
||||
|
||||
inline auto WifiClientCache() { return WifiClientCache::instance(); }
|
||||
|
||||
} // namespace OpenWiFi
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <mutex>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
|
||||
namespace OpenWifi {
|
||||
class BSSID_DICT {
|
||||
@@ -18,9 +18,9 @@ namespace OpenWifi {
|
||||
inline uint32_t Get(uint64_t bssid) {
|
||||
std::lock_guard G(Mutex_);
|
||||
auto it = Dict_.find(bssid);
|
||||
if(it==end(Dict_)) {
|
||||
if (it == end(Dict_)) {
|
||||
auto I = Index_++;
|
||||
Dict_[bssid]=I;
|
||||
Dict_[bssid] = I;
|
||||
return I;
|
||||
} else {
|
||||
return it->second;
|
||||
@@ -33,9 +33,9 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
private:
|
||||
uint32_t Index_=1;
|
||||
uint32_t Index_ = 1;
|
||||
std::mutex Mutex_;
|
||||
std::map<uint64_t,uint32_t> Dict_;
|
||||
std::map<uint64_t, uint32_t> Dict_;
|
||||
};
|
||||
inline auto BSSID_DICT() { return BSSID_DICT::instance(); }
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -1,5 +1,5 @@
|
||||
#include <mutex>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
namespace OpenWifi {
|
||||
@@ -31,8 +31,8 @@ namespace OpenWifi {
|
||||
|
||||
inline std::string Get(uint64_t ssid_id) {
|
||||
std::lock_guard G(Mutex_);
|
||||
for(const auto &[name,id]:Dict_) {
|
||||
if(ssid_id==id)
|
||||
for (const auto &[name, id] : Dict_) {
|
||||
if (ssid_id == id)
|
||||
return name;
|
||||
}
|
||||
return "";
|
||||
@@ -40,9 +40,9 @@ namespace OpenWifi {
|
||||
|
||||
private:
|
||||
std::recursive_mutex Mutex_;
|
||||
uint64_t Index_=1;
|
||||
std::map<std::string,uint64_t> Dict_;
|
||||
uint64_t Index_ = 1;
|
||||
std::map<std::string, uint64_t> Dict_;
|
||||
};
|
||||
|
||||
inline auto SSID_DICT() { return SSID_DICT::instance(); }
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <mutex>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
@@ -46,4 +46,4 @@ namespace OpenWifi {
|
||||
};
|
||||
|
||||
inline auto UE_DICT() { return UE_DICT::instance(); }
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,17 +4,19 @@
|
||||
|
||||
#include "ALBserver.h"
|
||||
|
||||
#include "framework/utils.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "fmt/format.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) {
|
||||
void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) {
|
||||
Utils::SetThreadName("alb-request");
|
||||
try {
|
||||
if((id_ % 100) == 0) {
|
||||
Logger_.debug(fmt::format("ALB-REQUEST({}): ALB Request {}.", Request.clientAddress().toString(), id_));
|
||||
if ((id_ % 100) == 0) {
|
||||
Logger_.debug(fmt::format("ALB-REQUEST({}): ALB Request {}.",
|
||||
Request.clientAddress().toString(), id_));
|
||||
}
|
||||
Response.setChunkedTransferEncoding(true);
|
||||
Response.setContentType("text/html");
|
||||
@@ -26,31 +28,27 @@ namespace OpenWifi {
|
||||
std::ostream &Answer = Response.send();
|
||||
Answer << "process Alive and kicking!";
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger & L):
|
||||
Logger_(L) {
|
||||
}
|
||||
ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger &L) : Logger_(L) {}
|
||||
|
||||
ALBRequestHandler* ALBRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest& request) {
|
||||
ALBRequestHandler *
|
||||
ALBRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &request) {
|
||||
if (request.getURI() == "/")
|
||||
return new ALBRequestHandler(Logger_, req_id_++);
|
||||
else
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ALBHealthCheckServer::ALBHealthCheckServer() :
|
||||
SubSystemServer("ALBHealthCheckServer", "ALB-SVR", "alb")
|
||||
{
|
||||
}
|
||||
ALBHealthCheckServer::ALBHealthCheckServer()
|
||||
: SubSystemServer("ALBHealthCheckServer", "ALB-SVR", "alb") {}
|
||||
|
||||
int ALBHealthCheckServer::Start() {
|
||||
if(MicroServiceConfigGetBool("alb.enable",false)) {
|
||||
poco_information(Logger(),"Starting...");
|
||||
Running_=true;
|
||||
Port_ = (int)MicroServiceConfigGetInt("alb.port",15015);
|
||||
if (MicroServiceConfigGetBool("alb.enable", false)) {
|
||||
poco_information(Logger(), "Starting...");
|
||||
Running_ = true;
|
||||
Port_ = (int)MicroServiceConfigGetInt("alb.port", 15015);
|
||||
Poco::Net::IPAddress Addr(Poco::Net::IPAddress::wildcard(
|
||||
Poco::Net::Socket::supportsIPv6() ? Poco::Net::AddressFamily::IPv6
|
||||
: Poco::Net::AddressFamily::IPv4));
|
||||
@@ -60,7 +58,8 @@ namespace OpenWifi {
|
||||
Socket_ = std::make_unique<Poco::Net::ServerSocket>(SockAddr, Port_);
|
||||
auto Params = new Poco::Net::HTTPServerParams;
|
||||
Params->setName("ws:alb");
|
||||
Server_ = std::make_unique<Poco::Net::HTTPServer>(new ALBRequestHandlerFactory(Logger()), *Socket_, Params);
|
||||
Server_ = std::make_unique<Poco::Net::HTTPServer>(
|
||||
new ALBRequestHandlerFactory(Logger()), *Socket_, Params);
|
||||
Server_->start();
|
||||
}
|
||||
|
||||
@@ -68,10 +67,10 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void ALBHealthCheckServer::Stop() {
|
||||
poco_information(Logger(),"Stopping...");
|
||||
if(Running_)
|
||||
poco_information(Logger(), "Stopping...");
|
||||
if (Running_)
|
||||
Server_->stopAll(true);
|
||||
poco_information(Logger(),"Stopped...");
|
||||
poco_information(Logger(), "Stopped...");
|
||||
}
|
||||
|
||||
} // namespace OpenWifi
|
||||
@@ -7,35 +7,34 @@
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
#include "Poco/Net/HTTPRequestHandler.h"
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
#include "Poco/Net/HTTPServerResponse.h"
|
||||
#include "Poco/Net/HTTPRequestHandlerFactory.h"
|
||||
#include "Poco/Net/HTTPServer.h"
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
#include "Poco/Net/HTTPServerResponse.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class ALBRequestHandler: public Poco::Net::HTTPRequestHandler {
|
||||
class ALBRequestHandler : public Poco::Net::HTTPRequestHandler {
|
||||
public:
|
||||
explicit ALBRequestHandler(Poco::Logger & L, uint64_t id)
|
||||
: Logger_(L), id_(id) {
|
||||
}
|
||||
explicit ALBRequestHandler(Poco::Logger &L, uint64_t id) : Logger_(L), id_(id) {}
|
||||
|
||||
void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) override;
|
||||
|
||||
private:
|
||||
Poco::Logger & Logger_;
|
||||
uint64_t id_;
|
||||
};
|
||||
|
||||
class ALBRequestHandlerFactory: public Poco::Net::HTTPRequestHandlerFactory
|
||||
{
|
||||
public:
|
||||
explicit ALBRequestHandlerFactory(Poco::Logger & L);
|
||||
ALBRequestHandler* createRequestHandler(const Poco::Net::HTTPServerRequest& request) override;
|
||||
void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request,
|
||||
Poco::Net::HTTPServerResponse &Response) override;
|
||||
|
||||
private:
|
||||
Poco::Logger &Logger_;
|
||||
inline static std::atomic_uint64_t req_id_=1;
|
||||
uint64_t id_;
|
||||
};
|
||||
|
||||
class ALBRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
|
||||
public:
|
||||
explicit ALBRequestHandlerFactory(Poco::Logger &L);
|
||||
ALBRequestHandler *
|
||||
createRequestHandler(const Poco::Net::HTTPServerRequest &request) override;
|
||||
|
||||
private:
|
||||
Poco::Logger &Logger_;
|
||||
inline static std::atomic_uint64_t req_id_ = 1;
|
||||
};
|
||||
|
||||
class ALBHealthCheckServer : public SubSystemServer {
|
||||
@@ -54,10 +53,9 @@ namespace OpenWifi {
|
||||
std::unique_ptr<Poco::Net::HTTPServer> Server_;
|
||||
std::unique_ptr<Poco::Net::ServerSocket> Socket_;
|
||||
int Port_ = 0;
|
||||
mutable std::atomic_bool Running_=false;
|
||||
mutable std::atomic_bool Running_ = false;
|
||||
};
|
||||
|
||||
inline auto ALBHealthCheckServer() { return ALBHealthCheckServer::instance(); }
|
||||
|
||||
} // namespace OpenWifi
|
||||
|
||||
|
||||
@@ -4,25 +4,22 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Poco/Logger.h"
|
||||
#include "Poco/JSON/Parser.h"
|
||||
#include "Poco/Logger.h"
|
||||
#include "Poco/Net/HTTPSClientSession.h"
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
#include "Poco/Net/HTTPServerResponse.h"
|
||||
#include "Poco/Net/HTTPSClientSession.h"
|
||||
#include "Poco/URI.h"
|
||||
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
inline void API_Proxy( Poco::Logger &Logger,
|
||||
Poco::Net::HTTPServerRequest *Request,
|
||||
Poco::Net::HTTPServerResponse *Response,
|
||||
const char * ServiceType,
|
||||
const char * PathRewrite,
|
||||
uint64_t msTimeout_ = 10000 ) {
|
||||
inline void API_Proxy(Poco::Logger &Logger, Poco::Net::HTTPServerRequest *Request,
|
||||
Poco::Net::HTTPServerResponse *Response, const char *ServiceType,
|
||||
const char *PathRewrite, uint64_t msTimeout_ = 10000) {
|
||||
try {
|
||||
auto Services = MicroServiceGetServices(ServiceType);
|
||||
for(auto const &Svc:Services) {
|
||||
for (auto const &Svc : Services) {
|
||||
Poco::URI SourceURI(Request->getURI());
|
||||
Poco::URI DestinationURI(Svc.PrivateEndPoint);
|
||||
DestinationURI.setPath(PathRewrite);
|
||||
@@ -31,20 +28,21 @@ namespace OpenWifi {
|
||||
// std::cout << " Source: " << SourceURI.toString() << std::endl;
|
||||
// std::cout << "Destination: " << DestinationURI.toString() << std::endl;
|
||||
|
||||
Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(), DestinationURI.getPort());
|
||||
Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(),
|
||||
DestinationURI.getPort());
|
||||
Session.setKeepAlive(true);
|
||||
Session.setTimeout(Poco::Timespan(msTimeout_/1000, msTimeout_ % 1000));
|
||||
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
|
||||
Poco::Net::HTTPRequest ProxyRequest(Request->getMethod(),
|
||||
DestinationURI.getPathAndQuery(),
|
||||
Poco::Net::HTTPMessage::HTTP_1_1);
|
||||
if(Request->has("Authorization")) {
|
||||
if (Request->has("Authorization")) {
|
||||
ProxyRequest.add("Authorization", Request->get("Authorization"));
|
||||
} else {
|
||||
ProxyRequest.add("X-API-KEY", Svc.AccessKey);
|
||||
ProxyRequest.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
|
||||
}
|
||||
|
||||
if(Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE) {
|
||||
if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE) {
|
||||
Session.sendRequest(ProxyRequest);
|
||||
Poco::Net::HTTPResponse ProxyResponse;
|
||||
Session.receiveResponse(ProxyResponse);
|
||||
@@ -56,19 +54,19 @@ namespace OpenWifi {
|
||||
std::stringstream SS;
|
||||
try {
|
||||
auto Body = P.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>();
|
||||
Poco::JSON::Stringifier::condense(Body,SS);
|
||||
Poco::JSON::Stringifier::condense(Body, SS);
|
||||
SS << "\r\n\r\n";
|
||||
} catch(const Poco::Exception &E) {
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger.log(E);
|
||||
}
|
||||
|
||||
if(SS.str().empty()) {
|
||||
if (SS.str().empty()) {
|
||||
Session.sendRequest(ProxyRequest);
|
||||
} else {
|
||||
ProxyRequest.setContentType("application/json");
|
||||
ProxyRequest.setContentLength(SS.str().size());
|
||||
std::ostream & os = Session.sendRequest(ProxyRequest);
|
||||
os << SS.str() ;
|
||||
std::ostream &os = Session.sendRequest(ProxyRequest);
|
||||
os << SS.str();
|
||||
}
|
||||
|
||||
Poco::Net::HTTPResponse ProxyResponse;
|
||||
@@ -76,15 +74,15 @@ namespace OpenWifi {
|
||||
try {
|
||||
std::istream &ProxyResponseStream = Session.receiveResponse(ProxyResponse);
|
||||
Poco::JSON::Parser P2;
|
||||
auto ProxyResponseBody = P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>();
|
||||
Poco::JSON::Stringifier::condense(ProxyResponseBody,SSR);
|
||||
auto ProxyResponseBody =
|
||||
P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>();
|
||||
Poco::JSON::Stringifier::condense(ProxyResponseBody, SSR);
|
||||
Response->setContentType("application/json");
|
||||
Response->setContentLength(SSR.str().size());
|
||||
Response->setStatus(ProxyResponse.getStatus());
|
||||
Response->sendBuffer(SSR.str().c_str(),SSR.str().size());
|
||||
Response->sendBuffer(SSR.str().c_str(), SSR.str().size());
|
||||
return;
|
||||
} catch( const Poco::Exception & E) {
|
||||
|
||||
} catch (const Poco::Exception &E) {
|
||||
}
|
||||
Response->setStatus(ProxyResponse.getStatus());
|
||||
Response->send();
|
||||
@@ -96,4 +94,4 @@ namespace OpenWifi {
|
||||
Logger.log(E);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include "Poco/StreamCopier.h"
|
||||
#include "Poco/File.h"
|
||||
#include "Poco/StreamCopier.h"
|
||||
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
|
||||
class AppServiceRegistry {
|
||||
public:
|
||||
AppServiceRegistry() {
|
||||
@@ -26,7 +25,7 @@ namespace OpenWifi {
|
||||
Poco::File F(FileName);
|
||||
|
||||
try {
|
||||
if(F.exists()) {
|
||||
if (F.exists()) {
|
||||
std::ostringstream OS;
|
||||
std::ifstream IF(FileName);
|
||||
Poco::StreamCopier::copyStream(IF, OS);
|
||||
@@ -37,55 +36,53 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
static AppServiceRegistry & instance() {
|
||||
static auto instance_= new AppServiceRegistry;
|
||||
static AppServiceRegistry &instance() {
|
||||
static auto instance_ = new AppServiceRegistry;
|
||||
return *instance_;
|
||||
}
|
||||
|
||||
inline ~AppServiceRegistry() {
|
||||
Save();
|
||||
}
|
||||
inline ~AppServiceRegistry() { Save(); }
|
||||
|
||||
inline void Save() {
|
||||
std::istringstream IS( to_string(Registry_));
|
||||
std::istringstream IS(to_string(Registry_));
|
||||
std::ofstream OF;
|
||||
OF.open(FileName,std::ios::binary | std::ios::trunc);
|
||||
OF.open(FileName, std::ios::binary | std::ios::trunc);
|
||||
Poco::StreamCopier::copyStream(IS, OF);
|
||||
}
|
||||
|
||||
inline void Set(const char *Key, uint64_t Value ) {
|
||||
inline void Set(const char *Key, uint64_t Value) {
|
||||
Registry_[Key] = Value;
|
||||
Save();
|
||||
}
|
||||
|
||||
inline void Set(const char *Key, const std::string &Value ) {
|
||||
inline void Set(const char *Key, const std::string &Value) {
|
||||
Registry_[Key] = Value;
|
||||
Save();
|
||||
}
|
||||
|
||||
inline void Set(const char *Key, bool Value ) {
|
||||
inline void Set(const char *Key, bool Value) {
|
||||
Registry_[Key] = Value;
|
||||
Save();
|
||||
}
|
||||
|
||||
inline bool Get(const char *Key, bool & Value ) {
|
||||
if(Registry_[Key].is_boolean()) {
|
||||
inline bool Get(const char *Key, bool &Value) {
|
||||
if (Registry_[Key].is_boolean()) {
|
||||
Value = Registry_[Key].get<bool>();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool Get(const char *Key, uint64_t & Value ) {
|
||||
if(Registry_[Key].is_number_unsigned()) {
|
||||
inline bool Get(const char *Key, uint64_t &Value) {
|
||||
if (Registry_[Key].is_number_unsigned()) {
|
||||
Value = Registry_[Key].get<uint64_t>();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool Get(const char *Key, std::string & Value ) {
|
||||
if(Registry_[Key].is_string()) {
|
||||
inline bool Get(const char *Key, std::string &Value) {
|
||||
if (Registry_[Key].is_string()) {
|
||||
Value = Registry_[Key].get<std::string>();
|
||||
return true;
|
||||
}
|
||||
@@ -99,4 +96,4 @@ namespace OpenWifi {
|
||||
|
||||
inline auto AppServiceRegistry() { return AppServiceRegistry::instance(); }
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,41 +4,40 @@
|
||||
|
||||
#include "Poco/Net/HTTPServerResponse.h"
|
||||
|
||||
#include "fmt/format.h"
|
||||
#include "framework/AuthClient.h"
|
||||
#include "framework/MicroServiceNames.h"
|
||||
#include "framework/OpenAPIRequests.h"
|
||||
#include "framework/utils.h"
|
||||
#include "fmt/format.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
bool AuthClient::RetrieveTokenInformation(const std::string & SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy & UInfo,
|
||||
std::uint64_t TID,
|
||||
bool & Expired, bool & Contacted, bool Sub) {
|
||||
bool AuthClient::RetrieveTokenInformation(const std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy &UInfo,
|
||||
std::uint64_t TID, bool &Expired, bool &Contacted,
|
||||
bool Sub) {
|
||||
try {
|
||||
Types::StringPairVec QueryData;
|
||||
QueryData.push_back(std::make_pair("token",SessionToken));
|
||||
std::string AlternateURIForLogging = fmt::format("{}?token={}", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", Utils::SanitizeToken(SessionToken));
|
||||
OpenAPIRequestGet Req( uSERVICE_SECURITY,
|
||||
QueryData.push_back(std::make_pair("token", SessionToken));
|
||||
std::string AlternateURIForLogging = fmt::format(
|
||||
"{}?token={}", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken",
|
||||
Utils::SanitizeToken(SessionToken));
|
||||
OpenAPIRequestGet Req(uSERVICE_SECURITY,
|
||||
Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken",
|
||||
QueryData,
|
||||
10000,
|
||||
AlternateURIForLogging
|
||||
);
|
||||
QueryData, 10000, AlternateURIForLogging);
|
||||
Poco::JSON::Object::Ptr Response;
|
||||
|
||||
auto StatusCode = Req.Do(Response);
|
||||
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
|
||||
if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
|
||||
Contacted = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
Contacted = true;
|
||||
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_OK) {
|
||||
if(Response->has("tokenInfo") && Response->has("userInfo")) {
|
||||
if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) {
|
||||
if (Response->has("tokenInfo") && Response->has("userInfo")) {
|
||||
UInfo.from_json(Response);
|
||||
if(IsTokenExpired(UInfo.webtoken)) {
|
||||
if (IsTokenExpired(UInfo.webtoken)) {
|
||||
Expired = true;
|
||||
return false;
|
||||
}
|
||||
@@ -50,18 +49,19 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
} catch (...) {
|
||||
poco_error(Logger(),fmt::format("Failed to retrieve token={} for TID={}", Utils::SanitizeToken(SessionToken), TID));
|
||||
poco_error(Logger(), fmt::format("Failed to retrieve token={} for TID={}",
|
||||
Utils::SanitizeToken(SessionToken), TID));
|
||||
}
|
||||
Expired = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool AuthClient::IsAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo,
|
||||
std::uint64_t TID,
|
||||
bool & Expired, bool & Contacted, bool Sub) {
|
||||
bool AuthClient::IsAuthorized(const std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
|
||||
bool &Expired, bool &Contacted, bool Sub) {
|
||||
auto User = Cache_.get(SessionToken);
|
||||
if(!User.isNull()) {
|
||||
if(IsTokenExpired(User->webtoken)) {
|
||||
if (!User.isNull()) {
|
||||
if (IsTokenExpired(User->webtoken)) {
|
||||
Expired = true;
|
||||
Cache_.remove(SessionToken);
|
||||
return false;
|
||||
@@ -73,50 +73,53 @@ namespace OpenWifi {
|
||||
return RetrieveTokenInformation(SessionToken, UInfo, TID, Expired, Contacted, Sub);
|
||||
}
|
||||
|
||||
bool AuthClient::RetrieveApiKeyInformation(const std::string & SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy & UInfo,
|
||||
std::uint64_t TID,
|
||||
bool & Expired, bool & Contacted, [[maybe_unused]] bool & Suspended) {
|
||||
bool AuthClient::RetrieveApiKeyInformation(const std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy &UInfo,
|
||||
std::uint64_t TID, bool &Expired, bool &Contacted,
|
||||
[[maybe_unused]] bool &Suspended) {
|
||||
try {
|
||||
Types::StringPairVec QueryData;
|
||||
QueryData.push_back(std::make_pair("apikey",SessionToken));
|
||||
std::string AlternateURIForLogging = fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken));
|
||||
OpenAPIRequestGet Req( uSERVICE_SECURITY,
|
||||
"/api/v1/validateApiKey" ,
|
||||
QueryData,
|
||||
10000,
|
||||
QueryData.push_back(std::make_pair("apikey", SessionToken));
|
||||
std::string AlternateURIForLogging =
|
||||
fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken));
|
||||
OpenAPIRequestGet Req(uSERVICE_SECURITY, "/api/v1/validateApiKey", QueryData, 10000,
|
||||
AlternateURIForLogging);
|
||||
Poco::JSON::Object::Ptr Response;
|
||||
|
||||
auto StatusCode = Req.Do(Response);
|
||||
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
|
||||
if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
|
||||
Contacted = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
Contacted = true;
|
||||
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_OK) {
|
||||
if(Response->has("tokenInfo") && Response->has("userInfo") && Response->has("expiresOn")) {
|
||||
if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) {
|
||||
if (Response->has("tokenInfo") && Response->has("userInfo") &&
|
||||
Response->has("expiresOn")) {
|
||||
UInfo.from_json(Response);
|
||||
Expired = false;
|
||||
ApiKeyCache_.update(SessionToken, ApiKeyCacheEntry{ .UserInfo = UInfo, .ExpiresOn = Response->get("expiresOn")});
|
||||
ApiKeyCache_.update(SessionToken,
|
||||
ApiKeyCacheEntry{.UserInfo = UInfo,
|
||||
.ExpiresOn = Response->get("expiresOn")});
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (...) {
|
||||
poco_error(Logger(),fmt::format("Failed to retrieve api key={} for TID={}", Utils::SanitizeToken(SessionToken), TID));
|
||||
poco_error(Logger(), fmt::format("Failed to retrieve api key={} for TID={}",
|
||||
Utils::SanitizeToken(SessionToken), TID));
|
||||
}
|
||||
Expired = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool AuthClient::IsValidApiKey(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy &UInfo,
|
||||
std::uint64_t TID, bool &Expired, bool &Contacted, bool & Suspended) {
|
||||
bool AuthClient::IsValidApiKey(const std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
|
||||
bool &Expired, bool &Contacted, bool &Suspended) {
|
||||
auto User = ApiKeyCache_.get(SessionToken);
|
||||
if (!User.isNull()) {
|
||||
if(User->ExpiresOn < Utils::Now()) {
|
||||
if (User->ExpiresOn < Utils::Now()) {
|
||||
Expired = false;
|
||||
UInfo = User->UserInfo;
|
||||
return true;
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "RESTObjects/RESTAPI_SecurityObjects.h"
|
||||
#include "Poco/ExpireLRUCache.h"
|
||||
#include "RESTObjects/RESTAPI_SecurityObjects.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
@@ -14,10 +14,8 @@ namespace OpenWifi {
|
||||
class AuthClient : public SubSystemServer {
|
||||
|
||||
public:
|
||||
explicit AuthClient() noexcept:
|
||||
SubSystemServer("Authentication", "AUTH-CLNT", "authentication")
|
||||
{
|
||||
}
|
||||
explicit AuthClient() noexcept
|
||||
: SubSystemServer("Authentication", "AUTH-CLNT", "authentication") {}
|
||||
|
||||
static auto instance() {
|
||||
static auto instance_ = new AuthClient;
|
||||
@@ -29,15 +27,13 @@ namespace OpenWifi {
|
||||
std::uint64_t ExpiresOn;
|
||||
};
|
||||
|
||||
inline int Start() override {
|
||||
return 0;
|
||||
}
|
||||
inline int Start() override { return 0; }
|
||||
|
||||
inline void Stop() override {
|
||||
poco_information(Logger(),"Stopping...");
|
||||
poco_information(Logger(), "Stopping...");
|
||||
std::lock_guard G(Mutex_);
|
||||
Cache_.clear();
|
||||
poco_information(Logger(),"Stopped...");
|
||||
poco_information(Logger(), "Stopped...");
|
||||
}
|
||||
|
||||
inline void RemovedCachedToken(const std::string &Token) {
|
||||
@@ -46,34 +42,31 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
inline static bool IsTokenExpired(const SecurityObjects::WebToken &T) {
|
||||
return ((T.expires_in_+T.created_) < Utils::Now());
|
||||
return ((T.expires_in_ + T.created_) < Utils::Now());
|
||||
}
|
||||
|
||||
bool RetrieveTokenInformation(const std::string & SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy & UInfo,
|
||||
std::uint64_t TID,
|
||||
bool & Expired, bool & Contacted, bool Sub=false);
|
||||
bool RetrieveTokenInformation(const std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
|
||||
bool &Expired, bool &Contacted, bool Sub = false);
|
||||
|
||||
bool RetrieveApiKeyInformation(const std::string & SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy & UInfo,
|
||||
std::uint64_t TID,
|
||||
bool & Expired, bool & Contacted, bool & Suspended);
|
||||
bool RetrieveApiKeyInformation(const std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
|
||||
bool &Expired, bool &Contacted, bool &Suspended);
|
||||
|
||||
bool IsAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo,
|
||||
std::uint64_t TID,
|
||||
bool & Expired, bool & Contacted, bool Sub = false);
|
||||
bool IsAuthorized(const std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
|
||||
bool &Expired, bool &Contacted, bool Sub = false);
|
||||
|
||||
bool IsValidApiKey(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo,
|
||||
std::uint64_t TID,
|
||||
bool & Expired, bool & Contacted, bool & Suspended) ;
|
||||
bool IsValidApiKey(const std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
|
||||
bool &Expired, bool &Contacted, bool &Suspended);
|
||||
|
||||
private:
|
||||
|
||||
Poco::ExpireLRUCache<std::string,OpenWifi::SecurityObjects::UserInfoAndPolicy> Cache_{512,1200000 };
|
||||
Poco::ExpireLRUCache<std::string,ApiKeyCacheEntry> ApiKeyCache_{512,1200000 };
|
||||
Poco::ExpireLRUCache<std::string, OpenWifi::SecurityObjects::UserInfoAndPolicy> Cache_{
|
||||
512, 1200000};
|
||||
Poco::ExpireLRUCache<std::string, ApiKeyCacheEntry> ApiKeyCache_{512, 1200000};
|
||||
};
|
||||
|
||||
inline auto AuthClient() { return AuthClient::instance(); }
|
||||
|
||||
} // namespace OpenWifi
|
||||
|
||||
|
||||
@@ -21,13 +21,13 @@ namespace OpenWifi::CIDR {
|
||||
}
|
||||
|
||||
static bool cidr6_match(const in6_addr &address, const in6_addr &network, uint8_t bits) {
|
||||
#ifdef __linux__
|
||||
#ifdef __linux__
|
||||
const uint32_t *a = address.s6_addr32;
|
||||
const uint32_t *n = network.s6_addr32;
|
||||
#else
|
||||
#else
|
||||
const uint32_t *a = address.__u6_addr.__u6_addr32;
|
||||
const uint32_t *n = network.__u6_addr.__u6_addr32;
|
||||
#endif
|
||||
#endif
|
||||
int bits_whole, bits_incomplete;
|
||||
bits_whole = bits >> 5; // number of whole u32
|
||||
bits_incomplete = bits & 0x1F; // number of bits in incomplete u32
|
||||
@@ -152,4 +152,4 @@ namespace OpenWifi::CIDR {
|
||||
[[nodiscard]] inline bool ValidateIpRanges(const Types::StringVec &Ranges) {
|
||||
return std::all_of(cbegin(Ranges), cend(Ranges), ValidateRange);
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi::CIDR
|
||||
@@ -2,8 +2,8 @@
|
||||
// Created by stephane bourque on 2021-09-14.
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <regex>
|
||||
|
||||
#include "ConfigurationValidator.h"
|
||||
@@ -17,14 +17,15 @@
|
||||
#include "fmt/format.h"
|
||||
|
||||
#include <valijson/adapters/poco_json_adapter.hpp>
|
||||
#include <valijson/utils/poco_json_utils.hpp>
|
||||
#include <valijson/constraints/constraint.hpp>
|
||||
#include <valijson/schema.hpp>
|
||||
#include <valijson/schema_parser.hpp>
|
||||
#include <valijson/utils/poco_json_utils.hpp>
|
||||
#include <valijson/validator.hpp>
|
||||
#include <valijson/constraints/constraint.hpp>
|
||||
|
||||
static const std::string GitUCentralJSONSchemaFile{
|
||||
"https://raw.githubusercontent.com/Telecominfraproject/wlan-ucentral-schema/main/ucentral.schema.json"};
|
||||
"https://raw.githubusercontent.com/Telecominfraproject/wlan-ucentral-schema/main/"
|
||||
"ucentral.schema.json"};
|
||||
|
||||
static std::string DefaultUCentralSchema = R"foo(
|
||||
|
||||
@@ -3184,7 +3185,6 @@ static std::string DefaultUCentralSchema = R"foo(
|
||||
|
||||
)foo";
|
||||
|
||||
|
||||
static inline bool IsIPv4(const std::string &value) {
|
||||
Poco::Net::IPAddress A;
|
||||
return ((Poco::Net::IPAddress::tryParse(value, A) && A.family() == Poco::Net::IPAddress::IPv4));
|
||||
@@ -3242,57 +3242,68 @@ bool ExternalValijsonFormatChecker(const std::string &format, const std::string
|
||||
if (format == "uc-cidr4") {
|
||||
if (IsCIDRv4(value))
|
||||
return true;
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid CIDR IPv4 block",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid CIDR IPv4 block", value));
|
||||
} else if (format == "uc-cidr6") {
|
||||
if (IsCIDRv6(value))
|
||||
return true;
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid CIDR IPv6 block",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid CIDR IPv6 block", value));
|
||||
} else if (format == "uc-cidr") {
|
||||
if (IsCIDR(value))
|
||||
return true;
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid CIDR block",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid CIDR block", value));
|
||||
} else if (format == "uc-mac") {
|
||||
if (std::regex_match(value, mac_regex))
|
||||
return true;
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid MAC address",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid MAC address", value));
|
||||
} else if (format == "uc-timeout") {
|
||||
if (std::regex_match(value, uc_timeout_regex))
|
||||
return true;
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid timeout value",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid timeout value", value));
|
||||
} else if (format == "uc-host") {
|
||||
if (IsIP(value))
|
||||
return true;
|
||||
if (std::regex_match(value, host_regex))
|
||||
return true;
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid hostname",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid hostname", value));
|
||||
} else if (format == "fqdn" || format == "uc-fqdn") {
|
||||
if (std::regex_match(value, host_regex))
|
||||
return true;
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid FQDN",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid FQDN", value));
|
||||
} else if (format == "uc-base64") {
|
||||
std::string s{value};
|
||||
Poco::trimInPlace(s);
|
||||
if ((s.size() % 4 == 0) && std::regex_match(s, b64_regex))
|
||||
return true;
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid base 64 value",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid base 64 value", value));
|
||||
} else if (format == "uri") {
|
||||
try {
|
||||
Poco::URI uri(value);
|
||||
return true;
|
||||
} catch (...) {
|
||||
}
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid URL",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid URL", value));
|
||||
} else if (format == "uc-portrange") {
|
||||
try {
|
||||
if (IsPortRangeIsValid(value))
|
||||
return true;
|
||||
} catch (...) {
|
||||
}
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid post range",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid post range", value));
|
||||
} else if (format == "ip") {
|
||||
if (IsIP(value))
|
||||
return true;
|
||||
if(results) results->pushError(context,fmt::format("{} is not a valid IP address",value));
|
||||
if (results)
|
||||
results->pushError(context, fmt::format("{} is not a valid IP address", value));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -3304,9 +3315,7 @@ namespace OpenWifi {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ConfigurationValidator::Stop() {
|
||||
|
||||
}
|
||||
void ConfigurationValidator::Stop() {}
|
||||
|
||||
bool ConfigurationValidator::SetSchema(const std::string &SchemaStr) {
|
||||
try {
|
||||
@@ -3318,9 +3327,9 @@ namespace OpenWifi {
|
||||
SchemaParser_->populateSchema(*PocoJsonAdapter_, *RootSchema_);
|
||||
Initialized_ = Working_ = true;
|
||||
return true;
|
||||
} catch(const Poco::Exception &E) {
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger().log(E);
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
Logger().error("Validation schema is invalid, falling back.");
|
||||
}
|
||||
return false;
|
||||
@@ -3331,7 +3340,7 @@ namespace OpenWifi {
|
||||
return;
|
||||
|
||||
std::string GitSchema;
|
||||
if(MicroServiceConfigGetBool("ucentral.datamodel.internal",true)) {
|
||||
if (MicroServiceConfigGetBool("ucentral.datamodel.internal", true)) {
|
||||
SetSchema(DefaultUCentralSchema);
|
||||
poco_information(Logger(), "Using uCentral validation from built-in default.");
|
||||
return;
|
||||
@@ -3339,33 +3348,34 @@ namespace OpenWifi {
|
||||
|
||||
try {
|
||||
auto GitURI =
|
||||
MicroServiceConfigGetString("ucentral.datamodel.uri",GitUCentralJSONSchemaFile);
|
||||
if(Utils::wgets(GitURI, GitSchema) && SetSchema(GitSchema)) {
|
||||
poco_information(Logger(),"Using uCentral data model validation schema from GIT.");
|
||||
MicroServiceConfigGetString("ucentral.datamodel.uri", GitUCentralJSONSchemaFile);
|
||||
if (Utils::wgets(GitURI, GitSchema) && SetSchema(GitSchema)) {
|
||||
poco_information(Logger(), "Using uCentral data model validation schema from GIT.");
|
||||
return;
|
||||
} else {
|
||||
std::string FileName{ MicroServiceDataDirectory() + "/ucentral.schema.json" };
|
||||
std::string FileName{MicroServiceDataDirectory() + "/ucentral.schema.json"};
|
||||
std::ifstream input(FileName);
|
||||
std::stringstream schema_file;
|
||||
schema_file << input.rdbuf();
|
||||
input.close();
|
||||
if(SetSchema(schema_file.str())) {
|
||||
poco_information(Logger(),
|
||||
"Using uCentral data model validation schema from local file.");
|
||||
if (SetSchema(schema_file.str())) {
|
||||
poco_information(
|
||||
Logger(), "Using uCentral data model validation schema from local file.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (const Poco::Exception &E) {
|
||||
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
SetSchema(DefaultUCentralSchema);
|
||||
poco_information(Logger(),"Using uCentral data model validation schema from built-in default.");
|
||||
poco_information(Logger(),
|
||||
"Using uCentral data model validation schema from built-in default.");
|
||||
}
|
||||
|
||||
bool ConfigurationValidator::Validate(const std::string &C, std::vector<std::string> &Errors, bool Strict) {
|
||||
if(Working_) {
|
||||
bool ConfigurationValidator::Validate(const std::string &C, std::vector<std::string> &Errors,
|
||||
bool Strict) {
|
||||
if (Working_) {
|
||||
try {
|
||||
Poco::JSON::Parser P;
|
||||
auto Doc = P.parse(C).extract<Poco::JSON::Object::Ptr>();
|
||||
@@ -3375,27 +3385,28 @@ namespace OpenWifi {
|
||||
if (Validator.validate(*RootSchema_, Tester, &Results)) {
|
||||
return true;
|
||||
}
|
||||
for(const auto &error:Results) {
|
||||
for (const auto &error : Results) {
|
||||
Errors.push_back(error.description);
|
||||
}
|
||||
return false;
|
||||
} catch(const Poco::Exception &E) {
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger().log(E);
|
||||
} catch(const std::exception &E) {
|
||||
Logger().warning(fmt::format("Error wile validating a configuration (1): {}", E.what()));
|
||||
} catch(...) {
|
||||
} catch (const std::exception &E) {
|
||||
Logger().warning(
|
||||
fmt::format("Error wile validating a configuration (1): {}", E.what()));
|
||||
} catch (...) {
|
||||
Logger().warning("Error wile validating a configuration (2)");
|
||||
}
|
||||
}
|
||||
if(Strict)
|
||||
if (Strict)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ConfigurationValidator::reinitialize([[maybe_unused]] Poco::Util::Application &self) {
|
||||
poco_information(Logger(),"Reinitializing.");
|
||||
poco_information(Logger(), "Reinitializing.");
|
||||
Working_ = Initialized_ = false;
|
||||
Init();
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -7,17 +7,16 @@
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
#include <valijson/adapters/poco_json_adapter.hpp>
|
||||
#include <valijson/utils/poco_json_utils.hpp>
|
||||
#include <valijson/schema.hpp>
|
||||
#include <valijson/schema_parser.hpp>
|
||||
#include <valijson/validator.hpp>
|
||||
#include <valijson/constraints/constraint.hpp>
|
||||
#include <valijson/constraints/constraint_visitor.hpp>
|
||||
#include <valijson/schema.hpp>
|
||||
#include <valijson/schema_parser.hpp>
|
||||
#include <valijson/utils/poco_json_utils.hpp>
|
||||
#include <valijson/validator.hpp>
|
||||
|
||||
namespace OpenWifi {
|
||||
class ConfigurationValidator : public SubSystemServer {
|
||||
public:
|
||||
|
||||
static auto instance() {
|
||||
static auto instance_ = new ConfigurationValidator;
|
||||
return instance_;
|
||||
@@ -29,8 +28,8 @@ namespace OpenWifi {
|
||||
void reinitialize(Poco::Util::Application &self) override;
|
||||
|
||||
private:
|
||||
bool Initialized_=false;
|
||||
bool Working_=false;
|
||||
bool Initialized_ = false;
|
||||
bool Working_ = false;
|
||||
void Init();
|
||||
std::unique_ptr<valijson::Schema> RootSchema_;
|
||||
std::unique_ptr<valijson::SchemaParser> SchemaParser_;
|
||||
@@ -38,12 +37,13 @@ namespace OpenWifi {
|
||||
Poco::JSON::Object::Ptr SchemaDocPtr_;
|
||||
bool SetSchema(const std::string &SchemaStr);
|
||||
|
||||
ConfigurationValidator():
|
||||
SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") {
|
||||
}
|
||||
ConfigurationValidator()
|
||||
: SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") {}
|
||||
};
|
||||
|
||||
inline auto ConfigurationValidator() { return ConfigurationValidator::instance(); }
|
||||
inline bool ValidateUCentralConfiguration(const std::string &C, std::vector<std::string> &Error, bool strict) { return ConfigurationValidator::instance()->Validate(C, Error, strict); }
|
||||
}
|
||||
|
||||
inline bool ValidateUCentralConfiguration(const std::string &C, std::vector<std::string> &Error,
|
||||
bool strict) {
|
||||
return ConfigurationValidator::instance()->Validate(C, Error, strict);
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
@@ -15,257 +15,255 @@ namespace OpenWifi {
|
||||
std::string name;
|
||||
};
|
||||
|
||||
inline static const std::vector<CountryInfo> CountryCodes {
|
||||
{ .code= "US", .name= "United States" },
|
||||
{ .code= "GB", .name= "United Kingdom" },
|
||||
{ .code= "CA", .name= "Canada" },
|
||||
{ .code= "AF", .name= "Afghanistan" },
|
||||
{ .code= "AX", .name= "Aland Islands" },
|
||||
{ .code= "AL", .name= "Albania" },
|
||||
{ .code= "DZ", .name= "Algeria" },
|
||||
{ .code= "AS", .name= "American Samoa" },
|
||||
{ .code= "AD", .name= "Andorra" },
|
||||
{ .code= "AO", .name= "Angola" },
|
||||
{ .code= "AI", .name= "Anguilla" },
|
||||
{ .code= "AQ", .name= "Antarctica" },
|
||||
{ .code= "AG", .name= "Antigua And Barbuda" },
|
||||
{ .code= "AR", .name= "Argentina" },
|
||||
{ .code= "AM", .name= "Armenia" },
|
||||
{ .code= "AN", .name= "Netherlands Antilles" },
|
||||
{ .code= "AW", .name= "Aruba" },
|
||||
{ .code= "AU", .name= "Australia" },
|
||||
{ .code= "AT", .name= "Austria" },
|
||||
{ .code= "AZ", .name= "Azerbaijan" },
|
||||
{ .code= "BS", .name= "Bahamas" },
|
||||
{ .code= "BH", .name= "Bahrain" },
|
||||
{ .code= "BD", .name= "Bangladesh" },
|
||||
{ .code= "BB", .name= "Barbados" },
|
||||
{ .code= "BY", .name= "Belarus" },
|
||||
{ .code= "BE", .name= "Belgium" },
|
||||
{ .code= "BZ", .name= "Belize" },
|
||||
{ .code= "BJ", .name= "Benin" },
|
||||
{ .code= "BM", .name= "Bermuda" },
|
||||
{ .code= "BT", .name= "Bhutan" },
|
||||
{ .code= "BO", .name= "Bolivia" },
|
||||
{ .code= "BA", .name= "Bosnia And Herzegovina" },
|
||||
{ .code= "BW", .name= "Botswana" },
|
||||
{ .code= "BV", .name= "Bouvet Island" },
|
||||
{ .code= "BR", .name= "Brazil" },
|
||||
{ .code= "IO", .name= "British Indian Ocean Territory" },
|
||||
{ .code= "BN", .name= "Brunei Darussalam" },
|
||||
{ .code= "BG", .name= "Bulgaria" },
|
||||
{ .code= "BF", .name= "Burkina Faso" },
|
||||
{ .code= "BI", .name= "Burundi" },
|
||||
{ .code= "KH", .name= "Cambodia" },
|
||||
{ .code= "CM", .name= "Cameroon" },
|
||||
{ .code= "CA", .name= "Canada" },
|
||||
{ .code= "CV", .name= "Cape Verde" },
|
||||
{ .code= "KY", .name= "Cayman Islands" },
|
||||
{ .code= "CF", .name= "Central African Republic" },
|
||||
{ .code= "TD", .name= "Chad" },
|
||||
{ .code= "CL", .name= "Chile" },
|
||||
{ .code= "CN", .name= "China" },
|
||||
{ .code= "CX", .name= "Christmas Island" },
|
||||
{ .code= "CC", .name= "Cocos (Keeling) Islands" },
|
||||
{ .code= "CO", .name= "Colombia" },
|
||||
{ .code= "KM", .name= "Comoros" },
|
||||
{ .code= "CG", .name= "Congo" },
|
||||
{ .code= "CD", .name= "Congo, Democratic Republic" },
|
||||
{ .code= "CK", .name= "Cook Islands" },
|
||||
{ .code= "CR", .name= "Costa Rica" },
|
||||
{ .code= "CI", .name= "Cote D\"Ivoire" },
|
||||
{ .code= "HR", .name= "Croatia" },
|
||||
{ .code= "CU", .name= "Cuba" },
|
||||
{ .code= "CY", .name= "Cyprus" },
|
||||
{ .code= "CZ", .name= "Czech Republic" },
|
||||
{ .code= "DK", .name= "Denmark" },
|
||||
{ .code= "DJ", .name= "Djibouti" },
|
||||
{ .code= "DM", .name= "Dominica" },
|
||||
{ .code= "DO", .name= "Dominican Republic" },
|
||||
{ .code= "EC", .name= "Ecuador" },
|
||||
{ .code= "EG", .name= "Egypt" },
|
||||
{ .code= "SV", .name= "El Salvador" },
|
||||
{ .code= "GQ", .name= "Equatorial Guinea" },
|
||||
{ .code= "ER", .name= "Eritrea" },
|
||||
{ .code= "EE", .name= "Estonia" },
|
||||
{ .code= "ET", .name= "Ethiopia" },
|
||||
{ .code= "FK", .name= "Falkland Islands (Malvinas)" },
|
||||
{ .code= "FO", .name= "Faroe Islands" },
|
||||
{ .code= "FJ", .name= "Fiji" },
|
||||
{ .code= "FI", .name= "Finland" },
|
||||
{ .code= "FR", .name= "France" },
|
||||
{ .code= "GF", .name= "French Guiana" },
|
||||
{ .code= "PF", .name= "French Polynesia" },
|
||||
{ .code= "TF", .name= "French Southern Territories" },
|
||||
{ .code= "GA", .name= "Gabon" },
|
||||
{ .code= "GM", .name= "Gambia" },
|
||||
{ .code= "GE", .name= "Georgia" },
|
||||
{ .code= "DE", .name= "Germany" },
|
||||
{ .code= "GH", .name= "Ghana" },
|
||||
{ .code= "GI", .name= "Gibraltar" },
|
||||
{ .code= "GR", .name= "Greece" },
|
||||
{ .code= "GL", .name= "Greenland" },
|
||||
{ .code= "GD", .name= "Grenada" },
|
||||
{ .code= "GP", .name= "Guadeloupe" },
|
||||
{ .code= "GU", .name= "Guam" },
|
||||
{ .code= "GT", .name= "Guatemala" },
|
||||
{ .code= "GG", .name= "Guernsey" },
|
||||
{ .code= "GN", .name= "Guinea" },
|
||||
{ .code= "GW", .name= "Guinea-Bissau" },
|
||||
{ .code= "GY", .name= "Guyana" },
|
||||
{ .code= "HT", .name= "Haiti" },
|
||||
{ .code= "HM", .name= "Heard Island & Mcdonald Islands" },
|
||||
{ .code= "VA", .name= "Holy See (Vatican City State)" },
|
||||
{ .code= "HN", .name= "Honduras" },
|
||||
{ .code= "HK", .name= "Hong Kong" },
|
||||
{ .code= "HU", .name= "Hungary" },
|
||||
{ .code= "IS", .name= "Iceland" },
|
||||
{ .code= "IN", .name= "India" },
|
||||
{ .code= "ID", .name= "Indonesia" },
|
||||
{ .code= "IR", .name= "Iran, Islamic Republic Of" },
|
||||
{ .code= "IQ", .name= "Iraq" },
|
||||
{ .code= "IE", .name= "Ireland" },
|
||||
{ .code= "IM", .name= "Isle Of Man" },
|
||||
{ .code= "IL", .name= "Israel" },
|
||||
{ .code= "IT", .name= "Italy" },
|
||||
{ .code= "JM", .name= "Jamaica" },
|
||||
{ .code= "JP", .name= "Japan" },
|
||||
{ .code= "JE", .name= "Jersey" },
|
||||
{ .code= "JO", .name= "Jordan" },
|
||||
{ .code= "KZ", .name= "Kazakhstan" },
|
||||
{ .code= "KE", .name= "Kenya" },
|
||||
{ .code= "KI", .name= "Kiribati" },
|
||||
{ .code= "KR", .name= "Korea" },
|
||||
{ .code= "KW", .name= "Kuwait" },
|
||||
{ .code= "KG", .name= "Kyrgyzstan" },
|
||||
{ .code= "LA", .name= "Lao People\"s Democratic Republic" },
|
||||
{ .code= "LV", .name= "Latvia" },
|
||||
{ .code= "LB", .name= "Lebanon" },
|
||||
{ .code= "LS", .name= "Lesotho" },
|
||||
{ .code= "LR", .name= "Liberia" },
|
||||
{ .code= "LY", .name= "Libyan Arab Jamahiriya" },
|
||||
{ .code= "LI", .name= "Liechtenstein" },
|
||||
{ .code= "LT", .name= "Lithuania" },
|
||||
{ .code= "LU", .name= "Luxembourg" },
|
||||
{ .code= "MO", .name= "Macao" },
|
||||
{ .code= "MK", .name= "Macedonia" },
|
||||
{ .code= "MG", .name= "Madagascar" },
|
||||
{ .code= "MW", .name= "Malawi" },
|
||||
{ .code= "MY", .name= "Malaysia" },
|
||||
{ .code= "MV", .name= "Maldives" },
|
||||
{ .code= "ML", .name= "Mali" },
|
||||
{ .code= "MT", .name= "Malta" },
|
||||
{ .code= "MH", .name= "Marshall Islands" },
|
||||
{ .code= "MQ", .name= "Martinique" },
|
||||
{ .code= "MR", .name= "Mauritania" },
|
||||
{ .code= "MU", .name= "Mauritius" },
|
||||
{ .code= "YT", .name= "Mayotte" },
|
||||
{ .code= "MX", .name= "Mexico" },
|
||||
{ .code= "FM", .name= "Micronesia, Federated States Of" },
|
||||
{ .code= "MD", .name= "Moldova" },
|
||||
{ .code= "MC", .name= "Monaco" },
|
||||
{ .code= "MN", .name= "Mongolia" },
|
||||
{ .code= "ME", .name= "Montenegro" },
|
||||
{ .code= "MS", .name= "Montserrat" },
|
||||
{ .code= "MA", .name= "Morocco" },
|
||||
{ .code= "MZ", .name= "Mozambique" },
|
||||
{ .code= "MM", .name= "Myanmar" },
|
||||
{ .code= "NA", .name= "Namibia" },
|
||||
{ .code= "NR", .name= "Nauru" },
|
||||
{ .code= "NP", .name= "Nepal" },
|
||||
{ .code= "NL", .name= "Netherlands" },
|
||||
{ .code= "AN", .name= "Netherlands Antilles" },
|
||||
{ .code= "NC", .name= "New Caledonia" },
|
||||
{ .code= "NZ", .name= "New Zealand" },
|
||||
{ .code= "NI", .name= "Nicaragua" },
|
||||
{ .code= "NE", .name= "Niger" },
|
||||
{ .code= "NG", .name= "Nigeria" },
|
||||
{ .code= "NU", .name= "Niue" },
|
||||
{ .code= "NF", .name= "Norfolk Island" },
|
||||
{ .code= "MP", .name= "Northern Mariana Islands" },
|
||||
{ .code= "NO", .name= "Norway" },
|
||||
{ .code= "OM", .name= "Oman" },
|
||||
{ .code= "PK", .name= "Pakistan" },
|
||||
{ .code= "PW", .name= "Palau" },
|
||||
{ .code= "PS", .name= "Palestinian Territory, Occupied" },
|
||||
{ .code= "PA", .name= "Panama" },
|
||||
{ .code= "PG", .name= "Papua New Guinea" },
|
||||
{ .code= "PY", .name= "Paraguay" },
|
||||
{ .code= "PE", .name= "Peru" },
|
||||
{ .code= "PH", .name= "Philippines" },
|
||||
{ .code= "PN", .name= "Pitcairn" },
|
||||
{ .code= "PL", .name= "Poland" },
|
||||
{ .code= "PT", .name= "Portugal" },
|
||||
{ .code= "PR", .name= "Puerto Rico" },
|
||||
{ .code= "QA", .name= "Qatar" },
|
||||
{ .code= "RE", .name= "Reunion" },
|
||||
{ .code= "RO", .name= "Romania" },
|
||||
{ .code= "RU", .name= "Russian Federation" },
|
||||
{ .code= "RW", .name= "Rwanda" },
|
||||
{ .code= "BL", .name= "Saint Barthelemy" },
|
||||
{ .code= "SH", .name= "Saint Helena" },
|
||||
{ .code= "KN", .name= "Saint Kitts And Nevis" },
|
||||
{ .code= "LC", .name= "Saint Lucia" },
|
||||
{ .code= "MF", .name= "Saint Martin" },
|
||||
{ .code= "PM", .name= "Saint Pierre And Miquelon" },
|
||||
{ .code= "VC", .name= "Saint Vincent And Grenadines" },
|
||||
{ .code= "WS", .name= "Samoa" },
|
||||
{ .code= "SM", .name= "San Marino" },
|
||||
{ .code= "ST", .name= "Sao Tome And Principe" },
|
||||
{ .code= "SA", .name= "Saudi Arabia" },
|
||||
{ .code= "SN", .name= "Senegal" },
|
||||
{ .code= "RS", .name= "Serbia" },
|
||||
{ .code= "SC", .name= "Seychelles" },
|
||||
{ .code= "SL", .name= "Sierra Leone" },
|
||||
{ .code= "SG", .name= "Singapore" },
|
||||
{ .code= "SK", .name= "Slovakia" },
|
||||
{ .code= "SI", .name= "Slovenia" },
|
||||
{ .code= "SB", .name= "Solomon Islands" },
|
||||
{ .code= "SO", .name= "Somalia" },
|
||||
{ .code= "ZA", .name= "South Africa" },
|
||||
{ .code= "GS", .name= "South Georgia And Sandwich Isl." },
|
||||
{ .code= "ES", .name= "Spain" },
|
||||
{ .code= "LK", .name= "Sri Lanka" },
|
||||
{ .code= "SD", .name= "Sudan" },
|
||||
{ .code= "SR", .name= "Suriname" },
|
||||
{ .code= "SJ", .name= "Svalbard And Jan Mayen" },
|
||||
{ .code= "SZ", .name= "Swaziland" },
|
||||
{ .code= "SE", .name= "Sweden" },
|
||||
{ .code= "CH", .name= "Switzerland" },
|
||||
{ .code= "SY", .name= "Syrian Arab Republic" },
|
||||
{ .code= "TW", .name= "Taiwan" },
|
||||
{ .code= "TJ", .name= "Tajikistan" },
|
||||
{ .code= "TZ", .name= "Tanzania" },
|
||||
{ .code= "TH", .name= "Thailand" },
|
||||
{ .code= "TL", .name= "Timor-Leste" },
|
||||
{ .code= "TG", .name= "Togo" },
|
||||
{ .code= "TK", .name= "Tokelau" },
|
||||
{ .code= "TO", .name= "Tonga" },
|
||||
{ .code= "TT", .name= "Trinidad And Tobago" },
|
||||
{ .code= "TN", .name= "Tunisia" },
|
||||
{ .code= "TR", .name= "Turkey" },
|
||||
{ .code= "TM", .name= "Turkmenistan" },
|
||||
{ .code= "TC", .name= "Turks And Caicos Islands" },
|
||||
{ .code= "TV", .name= "Tuvalu" },
|
||||
{ .code= "UG", .name= "Uganda" },
|
||||
{ .code= "UA", .name= "Ukraine" },
|
||||
{ .code= "AE", .name= "United Arab Emirates" },
|
||||
{ .code= "GB", .name= "United Kingdom" },
|
||||
{ .code= "US", .name= "United States" },
|
||||
{ .code= "UM", .name= "United States Outlying Islands" },
|
||||
{ .code= "UY", .name= "Uruguay" },
|
||||
{ .code= "UZ", .name= "Uzbekistan" },
|
||||
{ .code= "VU", .name= "Vanuatu" },
|
||||
{ .code= "VE", .name= "Venezuela" },
|
||||
{ .code= "VN", .name= "Viet Nam" },
|
||||
{ .code= "VG", .name= "Virgin Islands, British" },
|
||||
{ .code= "VI", .name= "Virgin Islands, U.S." },
|
||||
{ .code= "WF", .name= "Wallis And Futuna" },
|
||||
{ .code= "EH", .name= "Western Sahara" },
|
||||
{ .code= "YE", .name= "Yemen" },
|
||||
{ .code= "ZM", .name= "Zambia" },
|
||||
{ .code= "ZW", .name= "Zimbabwe" }
|
||||
};
|
||||
|
||||
}
|
||||
inline static const std::vector<CountryInfo> CountryCodes{
|
||||
{.code = "US", .name = "United States"},
|
||||
{.code = "GB", .name = "United Kingdom"},
|
||||
{.code = "CA", .name = "Canada"},
|
||||
{.code = "AF", .name = "Afghanistan"},
|
||||
{.code = "AX", .name = "Aland Islands"},
|
||||
{.code = "AL", .name = "Albania"},
|
||||
{.code = "DZ", .name = "Algeria"},
|
||||
{.code = "AS", .name = "American Samoa"},
|
||||
{.code = "AD", .name = "Andorra"},
|
||||
{.code = "AO", .name = "Angola"},
|
||||
{.code = "AI", .name = "Anguilla"},
|
||||
{.code = "AQ", .name = "Antarctica"},
|
||||
{.code = "AG", .name = "Antigua And Barbuda"},
|
||||
{.code = "AR", .name = "Argentina"},
|
||||
{.code = "AM", .name = "Armenia"},
|
||||
{.code = "AN", .name = "Netherlands Antilles"},
|
||||
{.code = "AW", .name = "Aruba"},
|
||||
{.code = "AU", .name = "Australia"},
|
||||
{.code = "AT", .name = "Austria"},
|
||||
{.code = "AZ", .name = "Azerbaijan"},
|
||||
{.code = "BS", .name = "Bahamas"},
|
||||
{.code = "BH", .name = "Bahrain"},
|
||||
{.code = "BD", .name = "Bangladesh"},
|
||||
{.code = "BB", .name = "Barbados"},
|
||||
{.code = "BY", .name = "Belarus"},
|
||||
{.code = "BE", .name = "Belgium"},
|
||||
{.code = "BZ", .name = "Belize"},
|
||||
{.code = "BJ", .name = "Benin"},
|
||||
{.code = "BM", .name = "Bermuda"},
|
||||
{.code = "BT", .name = "Bhutan"},
|
||||
{.code = "BO", .name = "Bolivia"},
|
||||
{.code = "BA", .name = "Bosnia And Herzegovina"},
|
||||
{.code = "BW", .name = "Botswana"},
|
||||
{.code = "BV", .name = "Bouvet Island"},
|
||||
{.code = "BR", .name = "Brazil"},
|
||||
{.code = "IO", .name = "British Indian Ocean Territory"},
|
||||
{.code = "BN", .name = "Brunei Darussalam"},
|
||||
{.code = "BG", .name = "Bulgaria"},
|
||||
{.code = "BF", .name = "Burkina Faso"},
|
||||
{.code = "BI", .name = "Burundi"},
|
||||
{.code = "KH", .name = "Cambodia"},
|
||||
{.code = "CM", .name = "Cameroon"},
|
||||
{.code = "CA", .name = "Canada"},
|
||||
{.code = "CV", .name = "Cape Verde"},
|
||||
{.code = "KY", .name = "Cayman Islands"},
|
||||
{.code = "CF", .name = "Central African Republic"},
|
||||
{.code = "TD", .name = "Chad"},
|
||||
{.code = "CL", .name = "Chile"},
|
||||
{.code = "CN", .name = "China"},
|
||||
{.code = "CX", .name = "Christmas Island"},
|
||||
{.code = "CC", .name = "Cocos (Keeling) Islands"},
|
||||
{.code = "CO", .name = "Colombia"},
|
||||
{.code = "KM", .name = "Comoros"},
|
||||
{.code = "CG", .name = "Congo"},
|
||||
{.code = "CD", .name = "Congo, Democratic Republic"},
|
||||
{.code = "CK", .name = "Cook Islands"},
|
||||
{.code = "CR", .name = "Costa Rica"},
|
||||
{.code = "CI", .name = "Cote D\"Ivoire"},
|
||||
{.code = "HR", .name = "Croatia"},
|
||||
{.code = "CU", .name = "Cuba"},
|
||||
{.code = "CY", .name = "Cyprus"},
|
||||
{.code = "CZ", .name = "Czech Republic"},
|
||||
{.code = "DK", .name = "Denmark"},
|
||||
{.code = "DJ", .name = "Djibouti"},
|
||||
{.code = "DM", .name = "Dominica"},
|
||||
{.code = "DO", .name = "Dominican Republic"},
|
||||
{.code = "EC", .name = "Ecuador"},
|
||||
{.code = "EG", .name = "Egypt"},
|
||||
{.code = "SV", .name = "El Salvador"},
|
||||
{.code = "GQ", .name = "Equatorial Guinea"},
|
||||
{.code = "ER", .name = "Eritrea"},
|
||||
{.code = "EE", .name = "Estonia"},
|
||||
{.code = "ET", .name = "Ethiopia"},
|
||||
{.code = "FK", .name = "Falkland Islands (Malvinas)"},
|
||||
{.code = "FO", .name = "Faroe Islands"},
|
||||
{.code = "FJ", .name = "Fiji"},
|
||||
{.code = "FI", .name = "Finland"},
|
||||
{.code = "FR", .name = "France"},
|
||||
{.code = "GF", .name = "French Guiana"},
|
||||
{.code = "PF", .name = "French Polynesia"},
|
||||
{.code = "TF", .name = "French Southern Territories"},
|
||||
{.code = "GA", .name = "Gabon"},
|
||||
{.code = "GM", .name = "Gambia"},
|
||||
{.code = "GE", .name = "Georgia"},
|
||||
{.code = "DE", .name = "Germany"},
|
||||
{.code = "GH", .name = "Ghana"},
|
||||
{.code = "GI", .name = "Gibraltar"},
|
||||
{.code = "GR", .name = "Greece"},
|
||||
{.code = "GL", .name = "Greenland"},
|
||||
{.code = "GD", .name = "Grenada"},
|
||||
{.code = "GP", .name = "Guadeloupe"},
|
||||
{.code = "GU", .name = "Guam"},
|
||||
{.code = "GT", .name = "Guatemala"},
|
||||
{.code = "GG", .name = "Guernsey"},
|
||||
{.code = "GN", .name = "Guinea"},
|
||||
{.code = "GW", .name = "Guinea-Bissau"},
|
||||
{.code = "GY", .name = "Guyana"},
|
||||
{.code = "HT", .name = "Haiti"},
|
||||
{.code = "HM", .name = "Heard Island & Mcdonald Islands"},
|
||||
{.code = "VA", .name = "Holy See (Vatican City State)"},
|
||||
{.code = "HN", .name = "Honduras"},
|
||||
{.code = "HK", .name = "Hong Kong"},
|
||||
{.code = "HU", .name = "Hungary"},
|
||||
{.code = "IS", .name = "Iceland"},
|
||||
{.code = "IN", .name = "India"},
|
||||
{.code = "ID", .name = "Indonesia"},
|
||||
{.code = "IR", .name = "Iran, Islamic Republic Of"},
|
||||
{.code = "IQ", .name = "Iraq"},
|
||||
{.code = "IE", .name = "Ireland"},
|
||||
{.code = "IM", .name = "Isle Of Man"},
|
||||
{.code = "IL", .name = "Israel"},
|
||||
{.code = "IT", .name = "Italy"},
|
||||
{.code = "JM", .name = "Jamaica"},
|
||||
{.code = "JP", .name = "Japan"},
|
||||
{.code = "JE", .name = "Jersey"},
|
||||
{.code = "JO", .name = "Jordan"},
|
||||
{.code = "KZ", .name = "Kazakhstan"},
|
||||
{.code = "KE", .name = "Kenya"},
|
||||
{.code = "KI", .name = "Kiribati"},
|
||||
{.code = "KR", .name = "Korea"},
|
||||
{.code = "KW", .name = "Kuwait"},
|
||||
{.code = "KG", .name = "Kyrgyzstan"},
|
||||
{.code = "LA", .name = "Lao People\"s Democratic Republic"},
|
||||
{.code = "LV", .name = "Latvia"},
|
||||
{.code = "LB", .name = "Lebanon"},
|
||||
{.code = "LS", .name = "Lesotho"},
|
||||
{.code = "LR", .name = "Liberia"},
|
||||
{.code = "LY", .name = "Libyan Arab Jamahiriya"},
|
||||
{.code = "LI", .name = "Liechtenstein"},
|
||||
{.code = "LT", .name = "Lithuania"},
|
||||
{.code = "LU", .name = "Luxembourg"},
|
||||
{.code = "MO", .name = "Macao"},
|
||||
{.code = "MK", .name = "Macedonia"},
|
||||
{.code = "MG", .name = "Madagascar"},
|
||||
{.code = "MW", .name = "Malawi"},
|
||||
{.code = "MY", .name = "Malaysia"},
|
||||
{.code = "MV", .name = "Maldives"},
|
||||
{.code = "ML", .name = "Mali"},
|
||||
{.code = "MT", .name = "Malta"},
|
||||
{.code = "MH", .name = "Marshall Islands"},
|
||||
{.code = "MQ", .name = "Martinique"},
|
||||
{.code = "MR", .name = "Mauritania"},
|
||||
{.code = "MU", .name = "Mauritius"},
|
||||
{.code = "YT", .name = "Mayotte"},
|
||||
{.code = "MX", .name = "Mexico"},
|
||||
{.code = "FM", .name = "Micronesia, Federated States Of"},
|
||||
{.code = "MD", .name = "Moldova"},
|
||||
{.code = "MC", .name = "Monaco"},
|
||||
{.code = "MN", .name = "Mongolia"},
|
||||
{.code = "ME", .name = "Montenegro"},
|
||||
{.code = "MS", .name = "Montserrat"},
|
||||
{.code = "MA", .name = "Morocco"},
|
||||
{.code = "MZ", .name = "Mozambique"},
|
||||
{.code = "MM", .name = "Myanmar"},
|
||||
{.code = "NA", .name = "Namibia"},
|
||||
{.code = "NR", .name = "Nauru"},
|
||||
{.code = "NP", .name = "Nepal"},
|
||||
{.code = "NL", .name = "Netherlands"},
|
||||
{.code = "AN", .name = "Netherlands Antilles"},
|
||||
{.code = "NC", .name = "New Caledonia"},
|
||||
{.code = "NZ", .name = "New Zealand"},
|
||||
{.code = "NI", .name = "Nicaragua"},
|
||||
{.code = "NE", .name = "Niger"},
|
||||
{.code = "NG", .name = "Nigeria"},
|
||||
{.code = "NU", .name = "Niue"},
|
||||
{.code = "NF", .name = "Norfolk Island"},
|
||||
{.code = "MP", .name = "Northern Mariana Islands"},
|
||||
{.code = "NO", .name = "Norway"},
|
||||
{.code = "OM", .name = "Oman"},
|
||||
{.code = "PK", .name = "Pakistan"},
|
||||
{.code = "PW", .name = "Palau"},
|
||||
{.code = "PS", .name = "Palestinian Territory, Occupied"},
|
||||
{.code = "PA", .name = "Panama"},
|
||||
{.code = "PG", .name = "Papua New Guinea"},
|
||||
{.code = "PY", .name = "Paraguay"},
|
||||
{.code = "PE", .name = "Peru"},
|
||||
{.code = "PH", .name = "Philippines"},
|
||||
{.code = "PN", .name = "Pitcairn"},
|
||||
{.code = "PL", .name = "Poland"},
|
||||
{.code = "PT", .name = "Portugal"},
|
||||
{.code = "PR", .name = "Puerto Rico"},
|
||||
{.code = "QA", .name = "Qatar"},
|
||||
{.code = "RE", .name = "Reunion"},
|
||||
{.code = "RO", .name = "Romania"},
|
||||
{.code = "RU", .name = "Russian Federation"},
|
||||
{.code = "RW", .name = "Rwanda"},
|
||||
{.code = "BL", .name = "Saint Barthelemy"},
|
||||
{.code = "SH", .name = "Saint Helena"},
|
||||
{.code = "KN", .name = "Saint Kitts And Nevis"},
|
||||
{.code = "LC", .name = "Saint Lucia"},
|
||||
{.code = "MF", .name = "Saint Martin"},
|
||||
{.code = "PM", .name = "Saint Pierre And Miquelon"},
|
||||
{.code = "VC", .name = "Saint Vincent And Grenadines"},
|
||||
{.code = "WS", .name = "Samoa"},
|
||||
{.code = "SM", .name = "San Marino"},
|
||||
{.code = "ST", .name = "Sao Tome And Principe"},
|
||||
{.code = "SA", .name = "Saudi Arabia"},
|
||||
{.code = "SN", .name = "Senegal"},
|
||||
{.code = "RS", .name = "Serbia"},
|
||||
{.code = "SC", .name = "Seychelles"},
|
||||
{.code = "SL", .name = "Sierra Leone"},
|
||||
{.code = "SG", .name = "Singapore"},
|
||||
{.code = "SK", .name = "Slovakia"},
|
||||
{.code = "SI", .name = "Slovenia"},
|
||||
{.code = "SB", .name = "Solomon Islands"},
|
||||
{.code = "SO", .name = "Somalia"},
|
||||
{.code = "ZA", .name = "South Africa"},
|
||||
{.code = "GS", .name = "South Georgia And Sandwich Isl."},
|
||||
{.code = "ES", .name = "Spain"},
|
||||
{.code = "LK", .name = "Sri Lanka"},
|
||||
{.code = "SD", .name = "Sudan"},
|
||||
{.code = "SR", .name = "Suriname"},
|
||||
{.code = "SJ", .name = "Svalbard And Jan Mayen"},
|
||||
{.code = "SZ", .name = "Swaziland"},
|
||||
{.code = "SE", .name = "Sweden"},
|
||||
{.code = "CH", .name = "Switzerland"},
|
||||
{.code = "SY", .name = "Syrian Arab Republic"},
|
||||
{.code = "TW", .name = "Taiwan"},
|
||||
{.code = "TJ", .name = "Tajikistan"},
|
||||
{.code = "TZ", .name = "Tanzania"},
|
||||
{.code = "TH", .name = "Thailand"},
|
||||
{.code = "TL", .name = "Timor-Leste"},
|
||||
{.code = "TG", .name = "Togo"},
|
||||
{.code = "TK", .name = "Tokelau"},
|
||||
{.code = "TO", .name = "Tonga"},
|
||||
{.code = "TT", .name = "Trinidad And Tobago"},
|
||||
{.code = "TN", .name = "Tunisia"},
|
||||
{.code = "TR", .name = "Turkey"},
|
||||
{.code = "TM", .name = "Turkmenistan"},
|
||||
{.code = "TC", .name = "Turks And Caicos Islands"},
|
||||
{.code = "TV", .name = "Tuvalu"},
|
||||
{.code = "UG", .name = "Uganda"},
|
||||
{.code = "UA", .name = "Ukraine"},
|
||||
{.code = "AE", .name = "United Arab Emirates"},
|
||||
{.code = "GB", .name = "United Kingdom"},
|
||||
{.code = "US", .name = "United States"},
|
||||
{.code = "UM", .name = "United States Outlying Islands"},
|
||||
{.code = "UY", .name = "Uruguay"},
|
||||
{.code = "UZ", .name = "Uzbekistan"},
|
||||
{.code = "VU", .name = "Vanuatu"},
|
||||
{.code = "VE", .name = "Venezuela"},
|
||||
{.code = "VN", .name = "Viet Nam"},
|
||||
{.code = "VG", .name = "Virgin Islands, British"},
|
||||
{.code = "VI", .name = "Virgin Islands, U.S."},
|
||||
{.code = "WF", .name = "Wallis And Futuna"},
|
||||
{.code = "EH", .name = "Western Sahara"},
|
||||
{.code = "YE", .name = "Yemen"},
|
||||
{.code = "ZM", .name = "Zambia"},
|
||||
{.code = "ZW", .name = "Zimbabwe"}};
|
||||
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -4,45 +4,46 @@
|
||||
|
||||
#include "framework/EventBusManager.h"
|
||||
#include "framework/KafkaManager.h"
|
||||
#include "framework/utils.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
EventBusManager::EventBusManager(Poco::Logger &L) :
|
||||
Logger_(L) {
|
||||
}
|
||||
EventBusManager::EventBusManager(Poco::Logger &L) : Logger_(L) {}
|
||||
|
||||
void EventBusManager::run() {
|
||||
Running_ = true;
|
||||
Utils::SetThreadName("fmwk:EventMgr");
|
||||
auto Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_JOIN);
|
||||
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false);
|
||||
while(Running_) {
|
||||
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg,
|
||||
false);
|
||||
while (Running_) {
|
||||
Poco::Thread::trySleep((unsigned long)MicroServiceDaemonBusTimer());
|
||||
if(!Running_)
|
||||
if (!Running_)
|
||||
break;
|
||||
Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE);
|
||||
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false);
|
||||
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(),
|
||||
Msg, false);
|
||||
}
|
||||
Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE);
|
||||
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false);
|
||||
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg,
|
||||
false);
|
||||
};
|
||||
|
||||
void EventBusManager::Start() {
|
||||
poco_information(Logger(),"Starting...");
|
||||
if(KafkaManager()->Enabled()) {
|
||||
poco_information(Logger(), "Starting...");
|
||||
if (KafkaManager()->Enabled()) {
|
||||
Thread_.start(*this);
|
||||
}
|
||||
}
|
||||
|
||||
void EventBusManager::Stop() {
|
||||
if(KafkaManager()->Enabled()) {
|
||||
poco_information(Logger(),"Stopping...");
|
||||
if (KafkaManager()->Enabled()) {
|
||||
poco_information(Logger(), "Stopping...");
|
||||
Running_ = false;
|
||||
Thread_.wakeUp();
|
||||
Thread_.join();
|
||||
poco_information(Logger(),"Stopped...");
|
||||
poco_information(Logger(), "Stopped...");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Poco/Runnable.h"
|
||||
#include "Poco/Logger.h"
|
||||
#include "Poco/Runnable.h"
|
||||
#include "Poco/Thread.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
@@ -16,7 +16,7 @@ namespace OpenWifi {
|
||||
void run() final;
|
||||
void Start();
|
||||
void Stop();
|
||||
inline Poco::Logger & Logger() { return Logger_; }
|
||||
inline Poco::Logger &Logger() { return Logger_; }
|
||||
|
||||
private:
|
||||
mutable std::atomic_bool Running_ = false;
|
||||
@@ -25,4 +25,3 @@ namespace OpenWifi {
|
||||
};
|
||||
|
||||
} // namespace OpenWifi
|
||||
|
||||
|
||||
@@ -4,251 +4,260 @@
|
||||
|
||||
#include "KafkaManager.h"
|
||||
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "fmt/format.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int level, const std::string & facility, const std::string &message) {
|
||||
switch ((cppkafka::LogLevel) level) {
|
||||
void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int level,
|
||||
const std::string &facility, const std::string &message) {
|
||||
switch ((cppkafka::LogLevel)level) {
|
||||
case cppkafka::LogLevel::LogNotice: {
|
||||
poco_notice(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
|
||||
}
|
||||
break;
|
||||
poco_notice(KafkaManager()->Logger(),
|
||||
fmt::format("kafka-log: facility: {} message: {}", facility, message));
|
||||
} break;
|
||||
case cppkafka::LogLevel::LogDebug: {
|
||||
poco_debug(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
|
||||
}
|
||||
break;
|
||||
poco_debug(KafkaManager()->Logger(),
|
||||
fmt::format("kafka-log: facility: {} message: {}", facility, message));
|
||||
} break;
|
||||
case cppkafka::LogLevel::LogInfo: {
|
||||
poco_information(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
|
||||
}
|
||||
break;
|
||||
poco_information(KafkaManager()->Logger(),
|
||||
fmt::format("kafka-log: facility: {} message: {}", facility, message));
|
||||
} break;
|
||||
case cppkafka::LogLevel::LogWarning: {
|
||||
poco_warning(KafkaManager()->Logger(), fmt::format("kafka-log: facility: {} message: {}",facility, message));
|
||||
}
|
||||
break;
|
||||
poco_warning(KafkaManager()->Logger(),
|
||||
fmt::format("kafka-log: facility: {} message: {}", facility, message));
|
||||
} break;
|
||||
case cppkafka::LogLevel::LogAlert:
|
||||
case cppkafka::LogLevel::LogCrit: {
|
||||
poco_critical(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
|
||||
}
|
||||
break;
|
||||
poco_critical(KafkaManager()->Logger(),
|
||||
fmt::format("kafka-log: facility: {} message: {}", facility, message));
|
||||
} break;
|
||||
case cppkafka::LogLevel::LogErr:
|
||||
case cppkafka::LogLevel::LogEmerg:
|
||||
default: {
|
||||
poco_error(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
|
||||
}
|
||||
break;
|
||||
poco_error(KafkaManager()->Logger(),
|
||||
fmt::format("kafka-log: facility: {} message: {}", facility, message));
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int error, const std::string &reason) {
|
||||
poco_error(KafkaManager()->Logger(),fmt::format("kafka-error: {}, reason: {}", error, reason));
|
||||
inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int error,
|
||||
const std::string &reason) {
|
||||
poco_error(KafkaManager()->Logger(),
|
||||
fmt::format("kafka-error: {}, reason: {}", error, reason));
|
||||
}
|
||||
|
||||
inline void AddKafkaSecurity(cppkafka::Configuration & Config) {
|
||||
auto CA = MicroServiceConfigGetString("openwifi.kafka.ssl.ca.location","");
|
||||
auto Certificate = MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location","");
|
||||
auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location","");
|
||||
auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password","");
|
||||
inline void AddKafkaSecurity(cppkafka::Configuration &Config) {
|
||||
auto CA = MicroServiceConfigGetString("openwifi.kafka.ssl.ca.location", "");
|
||||
auto Certificate =
|
||||
MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location", "");
|
||||
auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location", "");
|
||||
auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password", "");
|
||||
|
||||
if(CA.empty() || Certificate.empty() || Key.empty())
|
||||
if (CA.empty() || Certificate.empty() || Key.empty())
|
||||
return;
|
||||
|
||||
Config.set("ssl.ca.location", CA);
|
||||
Config.set("ssl.certificate.location", Certificate);
|
||||
Config.set("ssl.key.location", Key);
|
||||
if(!Password.empty())
|
||||
if (!Password.empty())
|
||||
Config.set("ssl.key.password", Password);
|
||||
}
|
||||
|
||||
|
||||
void KafkaManager::initialize(Poco::Util::Application & self) {
|
||||
void KafkaManager::initialize(Poco::Util::Application &self) {
|
||||
SubSystemServer::initialize(self);
|
||||
KafkaEnabled_ = MicroServiceConfigGetBool("openwifi.kafka.enable",false);
|
||||
KafkaEnabled_ = MicroServiceConfigGetBool("openwifi.kafka.enable", false);
|
||||
}
|
||||
|
||||
inline void KafkaProducer::run() {
|
||||
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel());
|
||||
poco_information(Logger_,"Starting...");
|
||||
Poco::Logger &Logger_ =
|
||||
Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel());
|
||||
poco_information(Logger_, "Starting...");
|
||||
|
||||
Utils::SetThreadName("Kafka:Prod");
|
||||
cppkafka::Configuration Config({
|
||||
{ "client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "") },
|
||||
{ "metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist", "") }
|
||||
});
|
||||
cppkafka::Configuration Config(
|
||||
{{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")},
|
||||
{"metadata.broker.list",
|
||||
MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")}});
|
||||
|
||||
AddKafkaSecurity(Config);
|
||||
|
||||
Config.set_log_callback(KafkaLoggerFun);
|
||||
Config.set_error_callback(KafkaErrorFun);
|
||||
|
||||
KafkaManager()->SystemInfoWrapper_ = R"lit({ "system" : { "id" : )lit" +
|
||||
std::to_string(MicroServiceID()) +
|
||||
KafkaManager()->SystemInfoWrapper_ =
|
||||
R"lit({ "system" : { "id" : )lit" + std::to_string(MicroServiceID()) +
|
||||
R"lit( , "host" : ")lit" + MicroServicePrivateEndPoint() +
|
||||
R"lit(" } , "payload" : )lit" ;
|
||||
R"lit(" } , "payload" : )lit";
|
||||
|
||||
cppkafka::Producer Producer(Config);
|
||||
Running_ = true;
|
||||
|
||||
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
|
||||
while(Note && Running_) {
|
||||
while (Note && Running_) {
|
||||
try {
|
||||
auto Msg = dynamic_cast<KafkaMessage *>(Note.get());
|
||||
if (Msg != nullptr) {
|
||||
Producer.produce(
|
||||
cppkafka::MessageBuilder(Msg->Topic()).key(Msg->Key()).payload(Msg->Payload()));
|
||||
Producer.produce(cppkafka::MessageBuilder(Msg->Topic())
|
||||
.key(Msg->Key())
|
||||
.payload(Msg->Payload()));
|
||||
}
|
||||
} catch (const cppkafka::HandleException &E) {
|
||||
poco_warning(Logger_,fmt::format("Caught a Kafka exception (producer): {}", E.what()));
|
||||
} catch( const Poco::Exception &E) {
|
||||
poco_warning(Logger_,
|
||||
fmt::format("Caught a Kafka exception (producer): {}", E.what()));
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
} catch (...) {
|
||||
poco_error(Logger_,"std::exception");
|
||||
poco_error(Logger_, "std::exception");
|
||||
}
|
||||
Note = Queue_.waitDequeueNotification();
|
||||
}
|
||||
poco_information(Logger_,"Stopped...");
|
||||
poco_information(Logger_, "Stopped...");
|
||||
}
|
||||
|
||||
inline void KafkaConsumer::run() {
|
||||
Utils::SetThreadName("Kafka:Cons");
|
||||
|
||||
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-CONSUMER", KafkaManager()->Logger().getChannel());
|
||||
Poco::Logger &Logger_ =
|
||||
Poco::Logger::create("KAFKA-CONSUMER", KafkaManager()->Logger().getChannel());
|
||||
|
||||
poco_information(Logger_,"Starting...");
|
||||
poco_information(Logger_, "Starting...");
|
||||
|
||||
cppkafka::Configuration Config({
|
||||
{ "client.id", MicroServiceConfigGetString("openwifi.kafka.client.id","") },
|
||||
{ "metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist","") },
|
||||
{ "group.id", MicroServiceConfigGetString("openwifi.kafka.group.id","") },
|
||||
{ "enable.auto.commit", MicroServiceConfigGetBool("openwifi.kafka.auto.commit",false) },
|
||||
{ "auto.offset.reset", "latest" } ,
|
||||
{ "enable.partition.eof", false }
|
||||
});
|
||||
cppkafka::Configuration Config(
|
||||
{{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")},
|
||||
{"metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")},
|
||||
{"group.id", MicroServiceConfigGetString("openwifi.kafka.group.id", "")},
|
||||
{"enable.auto.commit", MicroServiceConfigGetBool("openwifi.kafka.auto.commit", false)},
|
||||
{"auto.offset.reset", "latest"},
|
||||
{"enable.partition.eof", false}});
|
||||
|
||||
AddKafkaSecurity(Config);
|
||||
|
||||
Config.set_log_callback(KafkaLoggerFun);
|
||||
Config.set_error_callback(KafkaErrorFun);
|
||||
|
||||
cppkafka::TopicConfiguration topic_config = {
|
||||
{ "auto.offset.reset", "smallest" }
|
||||
};
|
||||
cppkafka::TopicConfiguration topic_config = {{"auto.offset.reset", "smallest"}};
|
||||
|
||||
// Now configure it to be the default topic config
|
||||
Config.set_default_topic_configuration(topic_config);
|
||||
|
||||
cppkafka::Consumer Consumer(Config);
|
||||
Consumer.set_assignment_callback([&](cppkafka::TopicPartitionList& partitions) {
|
||||
if(!partitions.empty()) {
|
||||
poco_information(Logger_,fmt::format("Partition assigned: {}...",
|
||||
Consumer.set_assignment_callback([&](cppkafka::TopicPartitionList &partitions) {
|
||||
if (!partitions.empty()) {
|
||||
poco_information(Logger_, fmt::format("Partition assigned: {}...",
|
||||
partitions.front().get_partition()));
|
||||
}
|
||||
});
|
||||
Consumer.set_revocation_callback([&](const cppkafka::TopicPartitionList& partitions) {
|
||||
if(!partitions.empty()) {
|
||||
poco_information(Logger_,fmt::format("Partition revocation: {}...",
|
||||
Consumer.set_revocation_callback([&](const cppkafka::TopicPartitionList &partitions) {
|
||||
if (!partitions.empty()) {
|
||||
poco_information(Logger_, fmt::format("Partition revocation: {}...",
|
||||
partitions.front().get_partition()));
|
||||
}
|
||||
});
|
||||
|
||||
bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit",false);
|
||||
auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize",20);
|
||||
bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit", false);
|
||||
auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize", 20);
|
||||
|
||||
Types::StringVec Topics;
|
||||
KafkaManager()->Topics(Topics);
|
||||
Consumer.subscribe(Topics);
|
||||
|
||||
Running_ = true;
|
||||
while(Running_) {
|
||||
while (Running_) {
|
||||
try {
|
||||
std::vector<cppkafka::Message> MsgVec = Consumer.poll_batch(BatchSize, std::chrono::milliseconds(100));
|
||||
for(auto const &Msg:MsgVec) {
|
||||
std::vector<cppkafka::Message> MsgVec =
|
||||
Consumer.poll_batch(BatchSize, std::chrono::milliseconds(100));
|
||||
for (auto const &Msg : MsgVec) {
|
||||
if (!Msg)
|
||||
continue;
|
||||
if (Msg.get_error()) {
|
||||
if (!Msg.is_eof()) {
|
||||
poco_error(Logger_,fmt::format("Error: {}", Msg.get_error().to_string()));
|
||||
poco_error(Logger_,
|
||||
fmt::format("Error: {}", Msg.get_error().to_string()));
|
||||
}
|
||||
if(!AutoCommit)
|
||||
if (!AutoCommit)
|
||||
Consumer.async_commit(Msg);
|
||||
continue;
|
||||
}
|
||||
KafkaManager()->Dispatch(Msg.get_topic(), Msg.get_key(),Msg.get_payload() );
|
||||
KafkaManager()->Dispatch(Msg.get_topic(), Msg.get_key(), Msg.get_payload());
|
||||
if (!AutoCommit)
|
||||
Consumer.async_commit(Msg);
|
||||
}
|
||||
} catch (const cppkafka::HandleException &E) {
|
||||
poco_warning(Logger_,fmt::format("Caught a Kafka exception (consumer): {}", E.what()));
|
||||
poco_warning(Logger_,
|
||||
fmt::format("Caught a Kafka exception (consumer): {}", E.what()));
|
||||
} catch (const Poco::Exception &E) {
|
||||
Logger_.log(E);
|
||||
} catch (...) {
|
||||
poco_error(Logger_,"std::exception");
|
||||
poco_error(Logger_, "std::exception");
|
||||
}
|
||||
}
|
||||
Consumer.unsubscribe();
|
||||
poco_information(Logger_,"Stopped...");
|
||||
poco_information(Logger_, "Stopped...");
|
||||
}
|
||||
|
||||
void KafkaProducer::Start() {
|
||||
if(!Running_) {
|
||||
Running_=true;
|
||||
if (!Running_) {
|
||||
Running_ = true;
|
||||
Worker_.start(*this);
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaProducer::Stop() {
|
||||
if(Running_) {
|
||||
Running_=false;
|
||||
if (Running_) {
|
||||
Running_ = false;
|
||||
Queue_.wakeUpAll();
|
||||
Worker_.join();
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaProducer::Produce(const std::string &Topic, const std::string &Key, const std::string &Payload) {
|
||||
void KafkaProducer::Produce(const std::string &Topic, const std::string &Key,
|
||||
const std::string &Payload) {
|
||||
std::lock_guard G(Mutex_);
|
||||
Queue_.enqueueNotification( new KafkaMessage(Topic,Key,Payload));
|
||||
Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload));
|
||||
}
|
||||
|
||||
void KafkaConsumer::Start() {
|
||||
if(!Running_) {
|
||||
Running_=true;
|
||||
if (!Running_) {
|
||||
Running_ = true;
|
||||
Worker_.start(*this);
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaConsumer::Stop() {
|
||||
if(Running_) {
|
||||
Running_=false;
|
||||
if (Running_) {
|
||||
Running_ = false;
|
||||
Worker_.wakeUp();
|
||||
Worker_.join();
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaDispatcher::Start() {
|
||||
if(!Running_) {
|
||||
Running_=true;
|
||||
if (!Running_) {
|
||||
Running_ = true;
|
||||
Worker_.start(*this);
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaDispatcher::Stop() {
|
||||
if(Running_) {
|
||||
Running_=false;
|
||||
if (Running_) {
|
||||
Running_ = false;
|
||||
Queue_.wakeUpAll();
|
||||
Worker_.join();
|
||||
}
|
||||
}
|
||||
|
||||
auto KafkaDispatcher::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) {
|
||||
auto KafkaDispatcher::RegisterTopicWatcher(const std::string &Topic,
|
||||
Types::TopicNotifyFunction &F) {
|
||||
std::lock_guard G(Mutex_);
|
||||
auto It = Notifiers_.find(Topic);
|
||||
if(It == Notifiers_.end()) {
|
||||
if (It == Notifiers_.end()) {
|
||||
Types::TopicNotifyFunctionList L;
|
||||
L.emplace(L.end(),std::make_pair(F,FunctionId_));
|
||||
L.emplace(L.end(), std::make_pair(F, FunctionId_));
|
||||
Notifiers_[Topic] = std::move(L);
|
||||
} else {
|
||||
It->second.emplace(It->second.end(),std::make_pair(F,FunctionId_));
|
||||
It->second.emplace(It->second.end(), std::make_pair(F, FunctionId_));
|
||||
}
|
||||
return FunctionId_++;
|
||||
}
|
||||
@@ -256,54 +265,55 @@ namespace OpenWifi {
|
||||
void KafkaDispatcher::UnregisterTopicWatcher(const std::string &Topic, int Id) {
|
||||
std::lock_guard G(Mutex_);
|
||||
auto It = Notifiers_.find(Topic);
|
||||
if(It != Notifiers_.end()) {
|
||||
Types::TopicNotifyFunctionList & L = It->second;
|
||||
for(auto it=L.begin(); it!=L.end(); it++)
|
||||
if(it->second == Id) {
|
||||
if (It != Notifiers_.end()) {
|
||||
Types::TopicNotifyFunctionList &L = It->second;
|
||||
for (auto it = L.begin(); it != L.end(); it++)
|
||||
if (it->second == Id) {
|
||||
L.erase(it);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaDispatcher::Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload) {
|
||||
void KafkaDispatcher::Dispatch(const std::string &Topic, const std::string &Key,
|
||||
const std::string &Payload) {
|
||||
std::lock_guard G(Mutex_);
|
||||
auto It = Notifiers_.find(Topic);
|
||||
if(It!=Notifiers_.end()) {
|
||||
if (It != Notifiers_.end()) {
|
||||
Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload));
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaDispatcher::run() {
|
||||
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-DISPATCHER", KafkaManager()->Logger().getChannel());
|
||||
poco_information(Logger_,"Starting...");
|
||||
Poco::Logger &Logger_ =
|
||||
Poco::Logger::create("KAFKA-DISPATCHER", KafkaManager()->Logger().getChannel());
|
||||
poco_information(Logger_, "Starting...");
|
||||
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
|
||||
Utils::SetThreadName("kafka:dispatch");
|
||||
while(Note && Running_) {
|
||||
auto Msg = dynamic_cast<KafkaMessage*>(Note.get());
|
||||
if(Msg!= nullptr) {
|
||||
while (Note && Running_) {
|
||||
auto Msg = dynamic_cast<KafkaMessage *>(Note.get());
|
||||
if (Msg != nullptr) {
|
||||
auto It = Notifiers_.find(Msg->Topic());
|
||||
if (It != Notifiers_.end()) {
|
||||
const auto & FL = It->second;
|
||||
for(const auto &[CallbackFunc,_]:FL) {
|
||||
const auto &FL = It->second;
|
||||
for (const auto &[CallbackFunc, _] : FL) {
|
||||
CallbackFunc(Msg->Key(), Msg->Payload());
|
||||
}
|
||||
}
|
||||
}
|
||||
Note = Queue_.waitDequeueNotification();
|
||||
}
|
||||
poco_information(Logger_,"Stopped...");
|
||||
poco_information(Logger_, "Stopped...");
|
||||
}
|
||||
|
||||
void KafkaDispatcher::Topics(std::vector<std::string> &T) {
|
||||
T.clear();
|
||||
for(const auto &[TopicName,_]:Notifiers_)
|
||||
for (const auto &[TopicName, _] : Notifiers_)
|
||||
T.push_back(TopicName);
|
||||
}
|
||||
|
||||
|
||||
int KafkaManager::Start() {
|
||||
if(!KafkaEnabled_)
|
||||
if (!KafkaEnabled_)
|
||||
return 0;
|
||||
ConsumerThr_.Start();
|
||||
ProducerThr_.Start();
|
||||
@@ -312,54 +322,57 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void KafkaManager::Stop() {
|
||||
if(KafkaEnabled_) {
|
||||
poco_information(Logger(),"Stopping...");
|
||||
if (KafkaEnabled_) {
|
||||
poco_information(Logger(), "Stopping...");
|
||||
Dispatcher_.Stop();
|
||||
ProducerThr_.Stop();
|
||||
ConsumerThr_.Stop();
|
||||
poco_information(Logger(),"Stopped...");
|
||||
poco_information(Logger(), "Stopped...");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaManager::PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage ) {
|
||||
if(KafkaEnabled_) {
|
||||
ProducerThr_.Produce(topic,key,WrapMessage ? WrapSystemId(PayLoad) : PayLoad);
|
||||
void KafkaManager::PostMessage(const std::string &topic, const std::string &key,
|
||||
const std::string &PayLoad, bool WrapMessage) {
|
||||
if (KafkaEnabled_) {
|
||||
ProducerThr_.Produce(topic, key, WrapMessage ? WrapSystemId(PayLoad) : PayLoad);
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaManager::Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload) {
|
||||
void KafkaManager::Dispatch(const std::string &Topic, const std::string &Key,
|
||||
const std::string &Payload) {
|
||||
Dispatcher_.Dispatch(Topic, Key, Payload);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string KafkaManager::WrapSystemId(const std::string & PayLoad) {
|
||||
[[nodiscard]] std::string KafkaManager::WrapSystemId(const std::string &PayLoad) {
|
||||
return SystemInfoWrapper_ + PayLoad + "}";
|
||||
}
|
||||
|
||||
uint64_t KafkaManager::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) {
|
||||
if(KafkaEnabled_) {
|
||||
return Dispatcher_.RegisterTopicWatcher(Topic,F);
|
||||
uint64_t KafkaManager::RegisterTopicWatcher(const std::string &Topic,
|
||||
Types::TopicNotifyFunction &F) {
|
||||
if (KafkaEnabled_) {
|
||||
return Dispatcher_.RegisterTopicWatcher(Topic, F);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaManager::UnregisterTopicWatcher(const std::string &Topic, uint64_t Id) {
|
||||
if(KafkaEnabled_) {
|
||||
if (KafkaEnabled_) {
|
||||
Dispatcher_.UnregisterTopicWatcher(Topic, Id);
|
||||
}
|
||||
}
|
||||
|
||||
void KafkaManager::Topics(std::vector<std::string> &T) {
|
||||
Dispatcher_.Topics(T);
|
||||
void KafkaManager::Topics(std::vector<std::string> &T) { Dispatcher_.Topics(T); }
|
||||
|
||||
void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList &partitions) {
|
||||
poco_information(
|
||||
Logger(), fmt::format("Partition assigned: {}...", partitions.front().get_partition()));
|
||||
}
|
||||
|
||||
void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList& partitions) {
|
||||
poco_information(Logger(),fmt::format("Partition assigned: {}...", partitions.front().get_partition()));
|
||||
}
|
||||
|
||||
void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList& partitions) {
|
||||
poco_information(Logger(),fmt::format("Partition revocation: {}...",partitions.front().get_partition()));
|
||||
void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList &partitions) {
|
||||
poco_information(Logger(), fmt::format("Partition revocation: {}...",
|
||||
partitions.front().get_partition()));
|
||||
}
|
||||
|
||||
} // namespace OpenWifi
|
||||
@@ -7,24 +7,23 @@
|
||||
#include "Poco/Notification.h"
|
||||
#include "Poco/NotificationQueue.h"
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
#include "framework/utils.h"
|
||||
#include "framework/KafkaTopics.h"
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
#include "cppkafka/cppkafka.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class KafkaMessage: public Poco::Notification {
|
||||
class KafkaMessage : public Poco::Notification {
|
||||
public:
|
||||
KafkaMessage( const std::string &Topic, const std::string &Key, const std::string & Payload) :
|
||||
Topic_(Topic), Key_(Key), Payload_(Payload) {
|
||||
}
|
||||
KafkaMessage(const std::string &Topic, const std::string &Key, const std::string &Payload)
|
||||
: Topic_(Topic), Key_(Key), Payload_(Payload) {}
|
||||
|
||||
inline const std::string & Topic() { return Topic_; }
|
||||
inline const std::string & Key() { return Key_; }
|
||||
inline const std::string & Payload() { return Payload_; }
|
||||
inline const std::string &Topic() { return Topic_; }
|
||||
inline const std::string &Key() { return Key_; }
|
||||
inline const std::string &Payload() { return Payload_; }
|
||||
|
||||
private:
|
||||
std::string Topic_;
|
||||
@@ -34,7 +33,7 @@ namespace OpenWifi {
|
||||
|
||||
class KafkaProducer : public Poco::Runnable {
|
||||
public:
|
||||
void run () override;
|
||||
void run() override;
|
||||
void Start();
|
||||
void Stop();
|
||||
void Produce(const std::string &Topic, const std::string &Key, const std::string &Payload);
|
||||
@@ -42,7 +41,7 @@ namespace OpenWifi {
|
||||
private:
|
||||
std::recursive_mutex Mutex_;
|
||||
Poco::Thread Worker_;
|
||||
mutable std::atomic_bool Running_=false;
|
||||
mutable std::atomic_bool Running_ = false;
|
||||
Poco::NotificationQueue Queue_;
|
||||
};
|
||||
|
||||
@@ -55,7 +54,7 @@ namespace OpenWifi {
|
||||
private:
|
||||
std::recursive_mutex Mutex_;
|
||||
Poco::Thread Worker_;
|
||||
mutable std::atomic_bool Running_=false;
|
||||
mutable std::atomic_bool Running_ = false;
|
||||
};
|
||||
|
||||
class KafkaDispatcher : public Poco::Runnable {
|
||||
@@ -72,18 +71,17 @@ namespace OpenWifi {
|
||||
std::recursive_mutex Mutex_;
|
||||
Types::NotifyTable Notifiers_;
|
||||
Poco::Thread Worker_;
|
||||
mutable std::atomic_bool Running_=false;
|
||||
uint64_t FunctionId_=1;
|
||||
mutable std::atomic_bool Running_ = false;
|
||||
uint64_t FunctionId_ = 1;
|
||||
Poco::NotificationQueue Queue_;
|
||||
};
|
||||
|
||||
class KafkaManager : public SubSystemServer {
|
||||
public:
|
||||
|
||||
friend class KafkaConsumer;
|
||||
friend class KafkaProducer;
|
||||
|
||||
inline void initialize(Poco::Util::Application & self) override;
|
||||
inline void initialize(Poco::Util::Application &self) override;
|
||||
|
||||
static auto instance() {
|
||||
static auto instance_ = new KafkaManager;
|
||||
@@ -93,9 +91,10 @@ namespace OpenWifi {
|
||||
int Start() override;
|
||||
void Stop() override;
|
||||
|
||||
void PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage = true );
|
||||
void Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload);
|
||||
[[nodiscard]] std::string WrapSystemId(const std::string & PayLoad);
|
||||
void PostMessage(const std::string &topic, const std::string &key,
|
||||
const std::string &PayLoad, bool WrapMessage = true);
|
||||
void Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload);
|
||||
[[nodiscard]] std::string WrapSystemId(const std::string &PayLoad);
|
||||
[[nodiscard]] inline bool Enabled() const { return KafkaEnabled_; }
|
||||
uint64_t RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F);
|
||||
void UnregisterTopicWatcher(const std::string &Topic, uint64_t Id);
|
||||
@@ -108,15 +107,12 @@ namespace OpenWifi {
|
||||
KafkaConsumer ConsumerThr_;
|
||||
KafkaDispatcher Dispatcher_;
|
||||
|
||||
void PartitionAssignment(const cppkafka::TopicPartitionList& partitions);
|
||||
void PartitionRevocation(const cppkafka::TopicPartitionList& partitions);
|
||||
void PartitionAssignment(const cppkafka::TopicPartitionList &partitions);
|
||||
void PartitionRevocation(const cppkafka::TopicPartitionList &partitions);
|
||||
|
||||
KafkaManager() noexcept:
|
||||
SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") {
|
||||
}
|
||||
KafkaManager() noexcept : SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") {}
|
||||
};
|
||||
|
||||
inline auto KafkaManager() { return KafkaManager::instance(); }
|
||||
|
||||
} // namespace OpenWifi
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ namespace OpenWifi::KafkaTopics {
|
||||
static const std::string KEY{"key"};
|
||||
static const std::string VRSN{"version"};
|
||||
static const std::string TOKEN{"token"};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Fields
|
||||
} // namespace ServiceEvents
|
||||
} // namespace OpenWifi::KafkaTopics
|
||||
|
||||
@@ -2,40 +2,39 @@
|
||||
// Created by stephane bourque on 2022-10-26.
|
||||
//
|
||||
|
||||
#include "Poco/FileChannel.h"
|
||||
#include "Poco/ConsoleChannel.h"
|
||||
#include "Poco/PatternFormatter.h"
|
||||
#include "Poco/FormattingChannel.h"
|
||||
#include "Poco/AsyncChannel.h"
|
||||
#include "Poco/NullChannel.h"
|
||||
#include "Poco/SplitterChannel.h"
|
||||
#include "Poco/Net/HTTPStreamFactory.h"
|
||||
#include "Poco/Net/HTTPSStreamFactory.h"
|
||||
#include "Poco/ConsoleChannel.h"
|
||||
#include "Poco/FileChannel.h"
|
||||
#include "Poco/FormattingChannel.h"
|
||||
#include "Poco/JSON/JSONException.h"
|
||||
#include "Poco/Net/FTPSStreamFactory.h"
|
||||
#include "Poco/Net/FTPStreamFactory.h"
|
||||
#include "Poco/Net/HTTPSStreamFactory.h"
|
||||
#include "Poco/Net/HTTPStreamFactory.h"
|
||||
#include "Poco/Net/SSLManager.h"
|
||||
#include "Poco/JSON/JSONException.h"
|
||||
#include "Poco/NullChannel.h"
|
||||
#include "Poco/PatternFormatter.h"
|
||||
#include "Poco/SplitterChannel.h"
|
||||
|
||||
#include "framework/ALBserver.h"
|
||||
#include "framework/AuthClient.h"
|
||||
#include "framework/KafkaManager.h"
|
||||
#include "framework/MicroService.h"
|
||||
#include "framework/MicroServiceErrorHandler.h"
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
#include "framework/MicroServiceNames.h"
|
||||
#include "framework/AuthClient.h"
|
||||
#include "framework/ALBserver.h"
|
||||
#include "framework/KafkaManager.h"
|
||||
#include "framework/RESTAPI_GenericServerAccounting.h"
|
||||
#include "framework/RESTAPI_ExtServer.h"
|
||||
#include "framework/RESTAPI_GenericServerAccounting.h"
|
||||
#include "framework/RESTAPI_IntServer.h"
|
||||
#include "framework/utils.h"
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
#include "framework/WebSocketLogger.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
void MicroService::Exit(int Reason) {
|
||||
std::exit(Reason);
|
||||
}
|
||||
void MicroService::Exit(int Reason) { std::exit(Reason); }
|
||||
|
||||
void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key, const std::string & Payload) {
|
||||
void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key,
|
||||
const std::string &Payload) {
|
||||
std::lock_guard G(InfraMutex_);
|
||||
try {
|
||||
Poco::JSON::Parser P;
|
||||
@@ -46,63 +45,96 @@ namespace OpenWifi {
|
||||
uint64_t ID = Object->get(KafkaTopics::ServiceEvents::Fields::ID);
|
||||
auto Event = Object->get(KafkaTopics::ServiceEvents::Fields::EVENT).toString();
|
||||
if (ID != ID_) {
|
||||
if( Event==KafkaTopics::ServiceEvents::EVENT_JOIN ||
|
||||
Event==KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE ||
|
||||
Event==KafkaTopics::ServiceEvents::EVENT_LEAVE ) {
|
||||
if( Object->has(KafkaTopics::ServiceEvents::Fields::TYPE) &&
|
||||
if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN ||
|
||||
Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE ||
|
||||
Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) {
|
||||
if (Object->has(KafkaTopics::ServiceEvents::Fields::TYPE) &&
|
||||
Object->has(KafkaTopics::ServiceEvents::Fields::PUBLIC) &&
|
||||
Object->has(KafkaTopics::ServiceEvents::Fields::PRIVATE) &&
|
||||
Object->has(KafkaTopics::ServiceEvents::Fields::VRSN) &&
|
||||
Object->has(KafkaTopics::ServiceEvents::Fields::KEY)) {
|
||||
auto PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString();
|
||||
if (Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE && Services_.find(PrivateEndPoint) != Services_.end()) {
|
||||
auto PrivateEndPoint =
|
||||
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString();
|
||||
if (Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE &&
|
||||
Services_.find(PrivateEndPoint) != Services_.end()) {
|
||||
Services_[PrivateEndPoint].LastUpdate = Utils::Now();
|
||||
} else if (Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) {
|
||||
Services_.erase(PrivateEndPoint);
|
||||
poco_debug(logger(),fmt::format("Service {} ID={} leaving system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID));
|
||||
} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN || Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) {
|
||||
poco_debug(logger(),fmt::format("Service {} ID={} joining system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID));
|
||||
poco_debug(
|
||||
logger(),
|
||||
fmt::format(
|
||||
"Service {} ID={} leaving system.",
|
||||
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
|
||||
.toString(),
|
||||
ID));
|
||||
} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN ||
|
||||
Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) {
|
||||
poco_debug(
|
||||
logger(),
|
||||
fmt::format(
|
||||
"Service {} ID={} joining system.",
|
||||
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
|
||||
.toString(),
|
||||
ID));
|
||||
Services_[PrivateEndPoint] = Types::MicroServiceMeta{
|
||||
.Id = ID,
|
||||
.Type = Poco::toLower(Object->get(KafkaTopics::ServiceEvents::Fields::TYPE).toString()),
|
||||
.PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),
|
||||
.PublicEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PUBLIC).toString(),
|
||||
.AccessKey = Object->get(KafkaTopics::ServiceEvents::Fields::KEY).toString(),
|
||||
.Version = Object->get(KafkaTopics::ServiceEvents::Fields::VRSN).toString(),
|
||||
.LastUpdate = Utils::Now() };
|
||||
.Type = Poco::toLower(
|
||||
Object->get(KafkaTopics::ServiceEvents::Fields::TYPE)
|
||||
.toString()),
|
||||
.PrivateEndPoint =
|
||||
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
|
||||
.toString(),
|
||||
.PublicEndPoint =
|
||||
Object->get(KafkaTopics::ServiceEvents::Fields::PUBLIC)
|
||||
.toString(),
|
||||
.AccessKey =
|
||||
Object->get(KafkaTopics::ServiceEvents::Fields::KEY)
|
||||
.toString(),
|
||||
.Version = Object->get(KafkaTopics::ServiceEvents::Fields::VRSN)
|
||||
.toString(),
|
||||
.LastUpdate = Utils::Now()};
|
||||
|
||||
std::string SvcList;
|
||||
for (const auto &Svc: Services_) {
|
||||
if(SvcList.empty())
|
||||
for (const auto &Svc : Services_) {
|
||||
if (SvcList.empty())
|
||||
SvcList = Svc.second.Type;
|
||||
else
|
||||
SvcList += ", " + Svc.second.Type;
|
||||
}
|
||||
poco_information(logger(),fmt::format("Current list of microservices: {}", SvcList));
|
||||
poco_information(
|
||||
logger(),
|
||||
fmt::format("Current list of microservices: {}", SvcList));
|
||||
}
|
||||
} else {
|
||||
poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing a field.",Event));
|
||||
poco_error(
|
||||
logger(),
|
||||
fmt::format("KAFKA-MSG: invalid event '{}', missing a field.",
|
||||
Event));
|
||||
}
|
||||
} else if (Event==KafkaTopics::ServiceEvents::EVENT_REMOVE_TOKEN) {
|
||||
if(Object->has(KafkaTopics::ServiceEvents::Fields::TOKEN)) {
|
||||
#ifndef TIP_SECURITY_SERVICE
|
||||
AuthClient()->RemovedCachedToken(Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString());
|
||||
#endif
|
||||
} else if (Event == KafkaTopics::ServiceEvents::EVENT_REMOVE_TOKEN) {
|
||||
if (Object->has(KafkaTopics::ServiceEvents::Fields::TOKEN)) {
|
||||
#ifndef TIP_SECURITY_SERVICE
|
||||
AuthClient()->RemovedCachedToken(
|
||||
Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString());
|
||||
#endif
|
||||
} else {
|
||||
poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing token",Event));
|
||||
poco_error(
|
||||
logger(),
|
||||
fmt::format("KAFKA-MSG: invalid event '{}', missing token", Event));
|
||||
}
|
||||
} else {
|
||||
poco_error(logger(),fmt::format("Unknown Event: {} Source: {}", Event, ID));
|
||||
poco_error(logger(),
|
||||
fmt::format("Unknown Event: {} Source: {}", Event, ID));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
poco_error(logger(),"Bad bus message.");
|
||||
poco_error(logger(), "Bad bus message.");
|
||||
}
|
||||
|
||||
auto i=Services_.begin();
|
||||
auto i = Services_.begin();
|
||||
auto now = Utils::Now();
|
||||
for(;i!=Services_.end();) {
|
||||
if((now - i->second.LastUpdate)>60) {
|
||||
for (; i != Services_.end();) {
|
||||
if ((now - i->second.LastUpdate) > 60) {
|
||||
i = Services_.erase(i);
|
||||
} else
|
||||
++i;
|
||||
@@ -113,13 +145,13 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
Types::MicroServiceMetaVec MicroService::GetServices(const std::string & Type) {
|
||||
Types::MicroServiceMetaVec MicroService::GetServices(const std::string &Type) {
|
||||
std::lock_guard G(InfraMutex_);
|
||||
|
||||
auto T = Poco::toLower(Type);
|
||||
Types::MicroServiceMetaVec Res;
|
||||
for(const auto &[_,ServiceRec]:Services_) {
|
||||
if(ServiceRec.Type==T)
|
||||
for (const auto &[_, ServiceRec] : Services_) {
|
||||
if (ServiceRec.Type == T)
|
||||
Res.push_back(ServiceRec);
|
||||
}
|
||||
return Res;
|
||||
@@ -129,22 +161,24 @@ namespace OpenWifi {
|
||||
std::lock_guard G(InfraMutex_);
|
||||
|
||||
Types::MicroServiceMetaVec Res;
|
||||
for(const auto &[_,ServiceRec]:Services_) {
|
||||
for (const auto &[_, ServiceRec] : Services_) {
|
||||
Res.push_back(ServiceRec);
|
||||
}
|
||||
return Res;
|
||||
}
|
||||
|
||||
void MicroService::LoadConfigurationFile() {
|
||||
std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR,".");
|
||||
ConfigFileName_ = ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_;
|
||||
std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR, ".");
|
||||
ConfigFileName_ =
|
||||
ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_;
|
||||
Poco::Path ConfigFile(ConfigFileName_);
|
||||
|
||||
if(!ConfigFile.isFile())
|
||||
{
|
||||
std::cerr << DAEMON_APP_NAME << ": Configuration "
|
||||
<< ConfigFile.toString() << " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR
|
||||
+ " env variable the path of the " + DAEMON_PROPERTIES_FILENAME + " file." << std::endl;
|
||||
if (!ConfigFile.isFile()) {
|
||||
std::cerr << DAEMON_APP_NAME << ": Configuration " << ConfigFile.toString()
|
||||
<< " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR +
|
||||
" env variable the path of the " + DAEMON_PROPERTIES_FILENAME +
|
||||
" file."
|
||||
<< std::endl;
|
||||
std::exit(Poco::Util::Application::EXIT_CONFIG);
|
||||
}
|
||||
|
||||
@@ -159,11 +193,12 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void MicroService::LoadMyConfig() {
|
||||
NoAPISecurity_ = ConfigGetBool("openwifi.security.restapi.disable",false);
|
||||
std::string KeyFile = ConfigPath("openwifi.service.key","");
|
||||
if(!KeyFile.empty()) {
|
||||
NoAPISecurity_ = ConfigGetBool("openwifi.security.restapi.disable", false);
|
||||
std::string KeyFile = ConfigPath("openwifi.service.key", "");
|
||||
if (!KeyFile.empty()) {
|
||||
std::string KeyFilePassword = ConfigPath("openwifi.service.key.password", "");
|
||||
AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword));
|
||||
AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(
|
||||
new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword));
|
||||
Cipher_ = CipherFactory_.createCipher(*AppKey_);
|
||||
Signer_.setRSAKey(AppKey_);
|
||||
Signer_.addAllAlgorithms();
|
||||
@@ -173,8 +208,8 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
ID_ = Utils::GetSystemId();
|
||||
if(!DebugMode_)
|
||||
DebugMode_ = ConfigGetBool("openwifi.system.debug",false);
|
||||
if (!DebugMode_)
|
||||
DebugMode_ = ConfigGetBool("openwifi.system.debug", false);
|
||||
MyPrivateEndPoint_ = ConfigGetString("openwifi.system.uri.private");
|
||||
MyPublicEndPoint_ = ConfigGetString("openwifi.system.uri.public");
|
||||
UIURI_ = ConfigGetString("openwifi.system.uri.ui");
|
||||
@@ -184,15 +219,17 @@ namespace OpenWifi {
|
||||
void MicroService::InitializeLoggingSystem() {
|
||||
static auto initialized = false;
|
||||
|
||||
if(!initialized) {
|
||||
if (!initialized) {
|
||||
initialized = true;
|
||||
LoadConfigurationFile();
|
||||
|
||||
auto LoggingDestination = MicroService::instance().ConfigGetString("logging.type", "file");
|
||||
auto LoggingFormat = MicroService::instance().ConfigGetString("logging.format",
|
||||
"%Y-%m-%d %H:%M:%S.%i %s: [%p][thr:%I] %t");
|
||||
auto LoggingDestination =
|
||||
MicroService::instance().ConfigGetString("logging.type", "file");
|
||||
auto LoggingFormat = MicroService::instance().ConfigGetString(
|
||||
"logging.format", "%Y-%m-%d %H:%M:%S.%i %s: [%p][thr:%I] %t");
|
||||
auto UseAsyncLogs_ = MicroService::instance().ConfigGetBool("logging.asynch", true);
|
||||
auto DisableWebSocketLogging = MicroService::instance().ConfigGetBool("logging.websocket",false);
|
||||
auto DisableWebSocketLogging =
|
||||
MicroService::instance().ConfigGetBool("logging.websocket", false);
|
||||
|
||||
if (LoggingDestination == "null") {
|
||||
Poco::AutoPtr<Poco::NullChannel> DevNull(new Poco::NullChannel);
|
||||
@@ -206,12 +243,14 @@ namespace OpenWifi {
|
||||
} else if (LoggingDestination == "syslog") {
|
||||
SetSyslogLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
|
||||
} else {
|
||||
SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat, DAEMON_ROOT_ENV_VAR);
|
||||
SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat,
|
||||
DAEMON_ROOT_ENV_VAR);
|
||||
}
|
||||
|
||||
auto Level = Poco::Logger::parseLevel(MicroService::instance().ConfigGetString("logging.level", "debug"));
|
||||
auto Level = Poco::Logger::parseLevel(
|
||||
MicroService::instance().ConfigGetString("logging.level", "debug"));
|
||||
Poco::Logger::root().setLevel(Level);
|
||||
if(!DisableWebSocketLogging) {
|
||||
if (!DisableWebSocketLogging) {
|
||||
static const UI_WebSocketClientServer::NotificationTypeIdVec Notifications = {
|
||||
{1, "log"}};
|
||||
UI_WebSocketClientServer()->RegisterNotifications(Notifications);
|
||||
@@ -219,15 +258,17 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) {
|
||||
void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging,
|
||||
const std::string &FormatterPattern) {
|
||||
|
||||
Poco::AutoPtr<Poco::ConsoleChannel> Console(new Poco::ConsoleChannel);
|
||||
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
|
||||
Formatter->setProperty("pattern", FormatterPattern);
|
||||
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console));
|
||||
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(
|
||||
new Poco::FormattingChannel(Formatter, Console));
|
||||
|
||||
if(DisableWebSocketLogging) {
|
||||
if(UseAsync) {
|
||||
if (DisableWebSocketLogging) {
|
||||
if (UseAsync) {
|
||||
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
|
||||
Poco::Logger::root().setChannel(Async);
|
||||
} else {
|
||||
@@ -238,25 +279,28 @@ namespace OpenWifi {
|
||||
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
|
||||
Splitter->addChannel(WSLogger);
|
||||
Splitter->addChannel(FormattingChannel);
|
||||
if(UseAsync) {
|
||||
if (UseAsync) {
|
||||
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
|
||||
Poco::Logger::root().setChannel(Async);
|
||||
} else {
|
||||
Poco::Logger::root().setChannel(Splitter);
|
||||
}
|
||||
}
|
||||
Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
|
||||
Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}",
|
||||
UseAsync, DisableWebSocketLogging));
|
||||
}
|
||||
|
||||
void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) {
|
||||
void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging,
|
||||
const std::string &FormatterPattern) {
|
||||
|
||||
Poco::AutoPtr<Poco::ColorConsoleChannel> Console(new Poco::ColorConsoleChannel);
|
||||
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
|
||||
Formatter->setProperty("pattern", FormatterPattern);
|
||||
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console));
|
||||
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(
|
||||
new Poco::FormattingChannel(Formatter, Console));
|
||||
|
||||
if(DisableWebSocketLogging) {
|
||||
if(UseAsync) {
|
||||
if (DisableWebSocketLogging) {
|
||||
if (UseAsync) {
|
||||
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
|
||||
Poco::Logger::root().setChannel(Async);
|
||||
} else {
|
||||
@@ -267,33 +311,41 @@ namespace OpenWifi {
|
||||
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
|
||||
Splitter->addChannel(WSLogger);
|
||||
Splitter->addChannel(FormattingChannel);
|
||||
if(UseAsync) {
|
||||
if (UseAsync) {
|
||||
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
|
||||
Poco::Logger::root().setChannel(Async);
|
||||
} else {
|
||||
Poco::Logger::root().setChannel(Splitter);
|
||||
}
|
||||
}
|
||||
Poco::Logger::root().information(fmt::format("Enabled color console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
|
||||
Poco::Logger::root().information(
|
||||
fmt::format("Enabled color console logs: asynch={} websocket={}", UseAsync,
|
||||
DisableWebSocketLogging));
|
||||
}
|
||||
|
||||
void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]] bool DisableWebSocketLogging,[[maybe_unused]] const std::string & FormatterPattern) {
|
||||
//"CREATE TABLE T_POCO_LOG (Source VARCHAR, Name VARCHAR, ProcessId INTEGER, Thread VARCHAR, ThreadId INTEGER, Priority INTEGER, Text VARCHAR, DateTime DATE)"
|
||||
void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync,
|
||||
[[maybe_unused]] bool DisableWebSocketLogging,
|
||||
[[maybe_unused]] const std::string &FormatterPattern) {
|
||||
//"CREATE TABLE T_POCO_LOG (Source VARCHAR, Name VARCHAR, ProcessId INTEGER, Thread VARCHAR,
|
||||
//ThreadId INTEGER, Priority INTEGER, Text VARCHAR, DateTime DATE)"
|
||||
}
|
||||
|
||||
void MicroService::SetSyslogLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]] bool DisableWebSocketLogging,[[maybe_unused]] const std::string & FormatterPattern) {
|
||||
void MicroService::SetSyslogLogs([[maybe_unused]] bool UseAsync,
|
||||
[[maybe_unused]] bool DisableWebSocketLogging,
|
||||
[[maybe_unused]] const std::string &FormatterPattern) {}
|
||||
|
||||
}
|
||||
|
||||
void MicroService::SetFileLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern, const std::string & root_env_var) {
|
||||
std::string DefaultLogPath = fmt::format("${}/logs",root_env_var);
|
||||
auto LoggingLocationDir = MicroService::instance().ConfigPath("logging.path", DefaultLogPath);
|
||||
void MicroService::SetFileLogs(bool UseAsync, bool DisableWebSocketLogging,
|
||||
const std::string &FormatterPattern,
|
||||
const std::string &root_env_var) {
|
||||
std::string DefaultLogPath = fmt::format("${}/logs", root_env_var);
|
||||
auto LoggingLocationDir =
|
||||
MicroService::instance().ConfigPath("logging.path", DefaultLogPath);
|
||||
Poco::File LD(LoggingLocationDir);
|
||||
try {
|
||||
if(!LD.exists()) {
|
||||
if (!LD.exists()) {
|
||||
LD.createDirectory();
|
||||
}
|
||||
} catch(const Poco::Exception &E) {
|
||||
} catch (const Poco::Exception &E) {
|
||||
std::cout << "Cannot create " << LD.path() << " Error: " << E.message() << std::endl;
|
||||
}
|
||||
auto LoggingLocationDirFilePattern = LoggingLocationDir + "/log";
|
||||
@@ -306,10 +358,11 @@ namespace OpenWifi {
|
||||
|
||||
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
|
||||
Formatter->setProperty("pattern", FormatterPattern);
|
||||
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, FileChannel));
|
||||
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(
|
||||
new Poco::FormattingChannel(Formatter, FileChannel));
|
||||
|
||||
if(DisableWebSocketLogging) {
|
||||
if(UseAsync) {
|
||||
if (DisableWebSocketLogging) {
|
||||
if (UseAsync) {
|
||||
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
|
||||
Poco::Logger::root().setChannel(Async);
|
||||
} else {
|
||||
@@ -320,14 +373,15 @@ namespace OpenWifi {
|
||||
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
|
||||
Splitter->addChannel(WSLogger);
|
||||
Splitter->addChannel(FormattingChannel);
|
||||
if(UseAsync) {
|
||||
if (UseAsync) {
|
||||
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
|
||||
Poco::Logger::root().setChannel(Async);
|
||||
} else {
|
||||
Poco::Logger::root().setChannel(Splitter);
|
||||
}
|
||||
}
|
||||
Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
|
||||
Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}",
|
||||
UseAsync, DisableWebSocketLogging));
|
||||
}
|
||||
|
||||
void DaemonPostInitialization(Poco::Util::Application &self);
|
||||
@@ -341,9 +395,9 @@ namespace OpenWifi {
|
||||
SubSystems_.push_back(ALBHealthCheckServer());
|
||||
SubSystems_.push_back(RESTAPI_ExtServer());
|
||||
SubSystems_.push_back(RESTAPI_IntServer());
|
||||
#ifndef TIP_SECURITY_SERVICE
|
||||
#ifndef TIP_SECURITY_SERVICE
|
||||
SubSystems_.push_back(AuthClient());
|
||||
#endif
|
||||
#endif
|
||||
Poco::Net::initializeSSL();
|
||||
Poco::Net::HTTPStreamFactory::registerFactory();
|
||||
Poco::Net::HTTPSStreamFactory::registerFactory();
|
||||
@@ -352,26 +406,28 @@ namespace OpenWifi {
|
||||
|
||||
Poco::File DataDir(ConfigPath("openwifi.system.data"));
|
||||
DataDir_ = DataDir.path();
|
||||
if(!DataDir.exists()) {
|
||||
if (!DataDir.exists()) {
|
||||
try {
|
||||
DataDir.createDirectory();
|
||||
} catch (const Poco::Exception &E) {
|
||||
logger().log(E);
|
||||
}
|
||||
}
|
||||
WWWAssetsDir_ = ConfigPath("openwifi.restapi.wwwassets","");
|
||||
if(WWWAssetsDir_.empty())
|
||||
WWWAssetsDir_ = ConfigPath("openwifi.restapi.wwwassets", "");
|
||||
if (WWWAssetsDir_.empty())
|
||||
WWWAssetsDir_ = DataDir_;
|
||||
|
||||
LoadMyConfig();
|
||||
|
||||
AllowExternalMicroServices_ = ConfigGetBool("allowexternalmicroservices",true);
|
||||
AllowExternalMicroServices_ = ConfigGetBool("allowexternalmicroservices", true);
|
||||
|
||||
InitializeSubSystemServers();
|
||||
ServerApplication::initialize(self);
|
||||
DaemonPostInitialization(self);
|
||||
|
||||
Types::TopicNotifyFunction F = [this](const std::string &Key,const std::string &Payload) { this->BusMessageReceived(Key, Payload); };
|
||||
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) {
|
||||
this->BusMessageReceived(Key, Payload);
|
||||
};
|
||||
KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F);
|
||||
}
|
||||
|
||||
@@ -392,58 +448,64 @@ namespace OpenWifi {
|
||||
Poco::Util::Option("help", "", "display help information on command line arguments")
|
||||
.required(false)
|
||||
.repeatable(false)
|
||||
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp)));
|
||||
.callback(
|
||||
Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp)));
|
||||
|
||||
options.addOption(
|
||||
Poco::Util::Option("file", "", "specify the configuration file")
|
||||
options.addOption(Poco::Util::Option("file", "", "specify the configuration file")
|
||||
.required(false)
|
||||
.repeatable(false)
|
||||
.argument("file")
|
||||
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleConfig)));
|
||||
.callback(Poco::Util::OptionCallback<MicroService>(
|
||||
this, &MicroService::handleConfig)));
|
||||
|
||||
options.addOption(
|
||||
Poco::Util::Option("debug", "", "to run in debug, set to true")
|
||||
options.addOption(Poco::Util::Option("debug", "", "to run in debug, set to true")
|
||||
.required(false)
|
||||
.repeatable(false)
|
||||
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleDebug)));
|
||||
.callback(Poco::Util::OptionCallback<MicroService>(
|
||||
this, &MicroService::handleDebug)));
|
||||
|
||||
options.addOption(
|
||||
Poco::Util::Option("logs", "", "specify the log directory and file (i.e. dir/file.log)")
|
||||
.required(false)
|
||||
.repeatable(false)
|
||||
.argument("dir")
|
||||
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs)));
|
||||
.callback(
|
||||
Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs)));
|
||||
|
||||
options.addOption(
|
||||
Poco::Util::Option("version", "", "get the version and quit.")
|
||||
options.addOption(Poco::Util::Option("version", "", "get the version and quit.")
|
||||
.required(false)
|
||||
.repeatable(false)
|
||||
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleVersion)));
|
||||
|
||||
.callback(Poco::Util::OptionCallback<MicroService>(
|
||||
this, &MicroService::handleVersion)));
|
||||
}
|
||||
|
||||
void MicroService::handleHelp([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) {
|
||||
void MicroService::handleHelp([[maybe_unused]] const std::string &name,
|
||||
[[maybe_unused]] const std::string &value) {
|
||||
HelpRequested_ = true;
|
||||
displayHelp();
|
||||
stopOptionsProcessing();
|
||||
}
|
||||
|
||||
void MicroService::handleVersion([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) {
|
||||
void MicroService::handleVersion([[maybe_unused]] const std::string &name,
|
||||
[[maybe_unused]] const std::string &value) {
|
||||
HelpRequested_ = true;
|
||||
std::cout << Version() << std::endl;
|
||||
stopOptionsProcessing();
|
||||
}
|
||||
|
||||
void MicroService::handleDebug([[maybe_unused]] const std::string &name, const std::string &value) {
|
||||
if(value == "true")
|
||||
DebugMode_ = true ;
|
||||
void MicroService::handleDebug([[maybe_unused]] const std::string &name,
|
||||
const std::string &value) {
|
||||
if (value == "true")
|
||||
DebugMode_ = true;
|
||||
}
|
||||
|
||||
void MicroService::handleLogs([[maybe_unused]] const std::string &name, const std::string &value) {
|
||||
void MicroService::handleLogs([[maybe_unused]] const std::string &name,
|
||||
const std::string &value) {
|
||||
LogDir_ = value;
|
||||
}
|
||||
|
||||
void MicroService::handleConfig([[maybe_unused]] const std::string &name, const std::string &value) {
|
||||
void MicroService::handleConfig([[maybe_unused]] const std::string &name,
|
||||
const std::string &value) {
|
||||
ConfigFileName_ = value;
|
||||
}
|
||||
|
||||
@@ -456,24 +518,25 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
void MicroService::InitializeSubSystemServers() {
|
||||
for(auto i:SubSystems_) {
|
||||
for (auto i : SubSystems_) {
|
||||
addSubsystem(i);
|
||||
}
|
||||
}
|
||||
|
||||
void MicroService::StartSubSystemServers() {
|
||||
AddActivity("Starting");
|
||||
for(auto i:SubSystems_) {
|
||||
for (auto i : SubSystems_) {
|
||||
i->Start();
|
||||
}
|
||||
EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create("EventBusManager",Poco::Logger::root().getChannel(),Poco::Logger::root().getLevel()));
|
||||
EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create(
|
||||
"EventBusManager", Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel()));
|
||||
EventBusManager_->Start();
|
||||
}
|
||||
|
||||
void MicroService::StopSubSystemServers() {
|
||||
AddActivity("Stopping");
|
||||
EventBusManager_->Stop();
|
||||
for(auto i=SubSystems_.rbegin(); i!=SubSystems_.rend(); ++i) {
|
||||
for (auto i = SubSystems_.rbegin(); i != SubSystems_.rend(); ++i) {
|
||||
(*i)->Stop();
|
||||
}
|
||||
}
|
||||
@@ -510,7 +573,8 @@ namespace OpenWifi {
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) {
|
||||
bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem,
|
||||
const std::string &Level) {
|
||||
try {
|
||||
auto P = Poco::Logger::parseLevel(Level);
|
||||
auto Sub = Poco::toLower(SubSystem);
|
||||
@@ -528,7 +592,7 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (const Poco::Exception & E) {
|
||||
} catch (const Poco::Exception &E) {
|
||||
std::cerr << "Exception" << std::endl;
|
||||
}
|
||||
return false;
|
||||
@@ -545,7 +609,7 @@ namespace OpenWifi {
|
||||
|
||||
Types::StringVec MicroService::GetSubSystems() const {
|
||||
Types::StringVec Result;
|
||||
for(auto i:SubSystems_)
|
||||
for (auto i : SubSystems_)
|
||||
Result.push_back(Poco::toLower(i->Name()));
|
||||
return Result;
|
||||
}
|
||||
@@ -553,35 +617,32 @@ namespace OpenWifi {
|
||||
Types::StringPairVec MicroService::GetLogLevels() {
|
||||
Types::StringPairVec Result;
|
||||
|
||||
for(auto &i:SubSystems_) {
|
||||
auto P = std::make_pair( i->Name(), Utils::LogLevelToString(i->GetLoggingLevel()));
|
||||
for (auto &i : SubSystems_) {
|
||||
auto P = std::make_pair(i->Name(), Utils::LogLevelToString(i->GetLoggingLevel()));
|
||||
Result.push_back(P);
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
const Types::StringVec & MicroService::GetLogLevelNames() {
|
||||
static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning", "notice", "information", "debug", "trace" };
|
||||
const Types::StringVec &MicroService::GetLogLevelNames() {
|
||||
static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning",
|
||||
"notice", "information", "debug", "trace"};
|
||||
return LevelNames;
|
||||
}
|
||||
|
||||
uint64_t MicroService::ConfigGetInt(const std::string &Key,uint64_t Default) {
|
||||
return (uint64_t) config().getInt64(Key,Default);
|
||||
uint64_t MicroService::ConfigGetInt(const std::string &Key, uint64_t Default) {
|
||||
return (uint64_t)config().getInt64(Key, Default);
|
||||
}
|
||||
|
||||
uint64_t MicroService::ConfigGetInt(const std::string &Key) {
|
||||
return config().getInt(Key);
|
||||
uint64_t MicroService::ConfigGetInt(const std::string &Key) { return config().getInt(Key); }
|
||||
|
||||
uint64_t MicroService::ConfigGetBool(const std::string &Key, bool Default) {
|
||||
return config().getBool(Key, Default);
|
||||
}
|
||||
|
||||
uint64_t MicroService::ConfigGetBool(const std::string &Key,bool Default) {
|
||||
return config().getBool(Key,Default);
|
||||
}
|
||||
uint64_t MicroService::ConfigGetBool(const std::string &Key) { return config().getBool(Key); }
|
||||
|
||||
uint64_t MicroService::ConfigGetBool(const std::string &Key) {
|
||||
return config().getBool(Key);
|
||||
}
|
||||
|
||||
std::string MicroService::ConfigGetString(const std::string &Key,const std::string & Default) {
|
||||
std::string MicroService::ConfigGetString(const std::string &Key, const std::string &Default) {
|
||||
return config().getString(Key, Default);
|
||||
}
|
||||
|
||||
@@ -589,7 +650,7 @@ namespace OpenWifi {
|
||||
return config().getString(Key);
|
||||
}
|
||||
|
||||
std::string MicroService::ConfigPath(const std::string &Key,const std::string & Default) {
|
||||
std::string MicroService::ConfigPath(const std::string &Key, const std::string &Default) {
|
||||
std::string R = config().getString(Key, Default);
|
||||
return Poco::Path::expand(R);
|
||||
}
|
||||
@@ -600,28 +661,30 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
std::string MicroService::Encrypt(const std::string &S) {
|
||||
if(NoBuiltInCrypto_) {
|
||||
if (NoBuiltInCrypto_) {
|
||||
return S;
|
||||
}
|
||||
return Cipher_->encryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);;
|
||||
return Cipher_->encryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);
|
||||
;
|
||||
}
|
||||
|
||||
std::string MicroService::Decrypt(const std::string &S) {
|
||||
if(NoBuiltInCrypto_) {
|
||||
if (NoBuiltInCrypto_) {
|
||||
return S;
|
||||
}
|
||||
return Cipher_->decryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);;
|
||||
return Cipher_->decryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);
|
||||
;
|
||||
}
|
||||
|
||||
std::string MicroService::MakeSystemEventMessage( const std::string & Type ) const {
|
||||
std::string MicroService::MakeSystemEventMessage(const std::string &Type) const {
|
||||
Poco::JSON::Object Obj;
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::EVENT,Type);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::ID,ID_);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::TYPE,Poco::toLower(DAEMON_APP_NAME));
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::PUBLIC,MyPublicEndPoint_);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::PRIVATE,MyPrivateEndPoint_);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::KEY,MyHash_);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::VRSN,Version_);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::EVENT, Type);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::ID, ID_);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::TYPE, Poco::toLower(DAEMON_APP_NAME));
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::PUBLIC, MyPublicEndPoint_);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::PRIVATE, MyPrivateEndPoint_);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::KEY, MyHash_);
|
||||
Obj.set(KafkaTopics::ServiceEvents::Fields::VRSN, Version_);
|
||||
std::stringstream ResultText;
|
||||
Poco::JSON::Stringifier::stringify(Obj, ResultText);
|
||||
return ResultText.str();
|
||||
@@ -640,11 +703,11 @@ namespace OpenWifi {
|
||||
void MicroService::SavePID() {
|
||||
try {
|
||||
std::ofstream O;
|
||||
O.open(MicroService::instance().DataDir() + "/pidfile",std::ios::binary | std::ios::trunc);
|
||||
O.open(MicroService::instance().DataDir() + "/pidfile",
|
||||
std::ios::binary | std::ios::trunc);
|
||||
O << Poco::Process::id();
|
||||
O.close();
|
||||
} catch (...)
|
||||
{
|
||||
} catch (...) {
|
||||
std::cout << "Could not save system ID" << std::endl;
|
||||
}
|
||||
}
|
||||
@@ -657,46 +720,45 @@ namespace OpenWifi {
|
||||
SavePID();
|
||||
|
||||
Poco::Logger &logger = Poco::Logger::get(DAEMON_APP_NAME);
|
||||
logger.notice(fmt::format("Starting {} version {}.",DAEMON_APP_NAME, Version()));
|
||||
logger.notice(fmt::format("Starting {} version {}.", DAEMON_APP_NAME, Version()));
|
||||
|
||||
if(Poco::Net::Socket::supportsIPv6())
|
||||
poco_information(logger,"System supports IPv6.");
|
||||
if (Poco::Net::Socket::supportsIPv6())
|
||||
poco_information(logger, "System supports IPv6.");
|
||||
else
|
||||
poco_information(logger,"System does NOT support IPv6.");
|
||||
poco_information(logger, "System does NOT support IPv6.");
|
||||
|
||||
if (config().getBool("application.runAsDaemon", false)) {
|
||||
poco_information(logger,"Starting as a daemon.");
|
||||
poco_information(logger, "Starting as a daemon.");
|
||||
}
|
||||
|
||||
poco_information(logger,fmt::format("System ID set to {}",ID_));
|
||||
poco_information(logger, fmt::format("System ID set to {}", ID_));
|
||||
StartSubSystemServers();
|
||||
waitForTerminationRequest();
|
||||
StopSubSystemServers();
|
||||
logger.notice(fmt::format("Stopped {}...",DAEMON_APP_NAME));
|
||||
logger.notice(fmt::format("Stopped {}...", DAEMON_APP_NAME));
|
||||
}
|
||||
|
||||
return Application::EXIT_OK;
|
||||
}
|
||||
|
||||
void MicroService::AddActivity(const std::string &Activity) {
|
||||
if(!DataDir_.empty()) {
|
||||
std::string ActivityFile{ DataDir_ + "/activity.log"};
|
||||
if (!DataDir_.empty()) {
|
||||
std::string ActivityFile{DataDir_ + "/activity.log"};
|
||||
try {
|
||||
std::ofstream of(ActivityFile,std::ios_base::app | std::ios_base::out );
|
||||
std::ofstream of(ActivityFile, std::ios_base::app | std::ios_base::out);
|
||||
auto t = std::chrono::system_clock::now();
|
||||
std::time_t now = std::chrono::system_clock::to_time_t(t);
|
||||
of << Activity << " at " << std::ctime(&now) ;
|
||||
of << Activity << " at " << std::ctime(&now);
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string MicroService::Sign(Poco::JWT::Token &T, const std::string &Algo) {
|
||||
if(NoBuiltInCrypto_) {
|
||||
if (NoBuiltInCrypto_) {
|
||||
return T.toString();
|
||||
} else {
|
||||
return Signer_.sign(T,Algo);
|
||||
return Signer_.sign(T, Algo);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -704,11 +766,10 @@ namespace OpenWifi {
|
||||
Poco::File F(DataDir_ + ExtraConfigurationFilename);
|
||||
|
||||
try {
|
||||
if(F.exists())
|
||||
if (F.exists())
|
||||
F.remove();
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -9,12 +9,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <fstream>
|
||||
#include <random>
|
||||
#include <ctime>
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
// This must be defined for poco_debug and poco_trace macros to function.
|
||||
|
||||
@@ -24,96 +23,93 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
inline uint64_t Now() { return std::time(nullptr); };
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
#include "Poco/Util/Application.h"
|
||||
#include "Poco/Util/ServerApplication.h"
|
||||
#include "Poco/Util/Option.h"
|
||||
#include "Poco/Util/OptionSet.h"
|
||||
#include "Poco/Crypto/RSAKey.h"
|
||||
#include "Poco/Crypto/CipherFactory.h"
|
||||
#include "Poco/AutoPtr.h"
|
||||
#include "Poco/Crypto/Cipher.h"
|
||||
#include "Poco/Crypto/CipherFactory.h"
|
||||
#include "Poco/Crypto/RSAKey.h"
|
||||
#include "Poco/Environment.h"
|
||||
#include "Poco/JSON/Object.h"
|
||||
#include "Poco/JWT/Signer.h"
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
#include "Poco/Process.h"
|
||||
#include "Poco/Util/Application.h"
|
||||
#include "Poco/Util/HelpFormatter.h"
|
||||
#include "Poco/JSON/Object.h"
|
||||
#include "Poco/AutoPtr.h"
|
||||
#include "Poco/Util/Option.h"
|
||||
#include "Poco/Util/OptionSet.h"
|
||||
#include "Poco/Util/PropertyFileConfiguration.h"
|
||||
#include "Poco/JWT/Signer.h"
|
||||
#include "Poco/Environment.h"
|
||||
#include "Poco/Util/ServerApplication.h"
|
||||
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
|
||||
#include "framework/EventBusManager.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "framework/ow_constants.h"
|
||||
#include "framework/utils.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "framework/EventBusManager.h"
|
||||
|
||||
#include "RESTObjects/RESTAPI_SecurityObjects.h"
|
||||
#include "cppkafka/cppkafka.h"
|
||||
|
||||
#include "fmt/core.h"
|
||||
#include "nlohmann/json.hpp"
|
||||
#include "ow_version.h"
|
||||
#include "fmt/core.h"
|
||||
|
||||
#define _OWDEBUG_ std::cout<< __FILE__ <<":" << __LINE__ << std::endl;
|
||||
#define _OWDEBUG_ std::cout << __FILE__ << ":" << __LINE__ << std::endl;
|
||||
// #define _OWDEBUG_ Logger().debug(Poco::format("%s: %lu",__FILE__,__LINE__));
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class MicroService : public Poco::Util::ServerApplication {
|
||||
public:
|
||||
explicit MicroService( std::string PropFile,
|
||||
std::string RootEnv,
|
||||
std::string ConfigVar,
|
||||
std::string AppName,
|
||||
uint64_t BusTimer,
|
||||
SubSystemVec Subsystems) :
|
||||
DAEMON_PROPERTIES_FILENAME(std::move(PropFile)),
|
||||
DAEMON_ROOT_ENV_VAR(std::move(RootEnv)),
|
||||
DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)),
|
||||
DAEMON_APP_NAME(std::move(AppName)),
|
||||
DAEMON_BUS_TIMER(BusTimer),
|
||||
SubSystems_(std::move(Subsystems)),
|
||||
Logger_(Poco::Logger::get("FRAMEWORK")) {
|
||||
explicit MicroService(std::string PropFile, std::string RootEnv, std::string ConfigVar,
|
||||
std::string AppName, uint64_t BusTimer, SubSystemVec Subsystems)
|
||||
: DAEMON_PROPERTIES_FILENAME(std::move(PropFile)),
|
||||
DAEMON_ROOT_ENV_VAR(std::move(RootEnv)), DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)),
|
||||
DAEMON_APP_NAME(std::move(AppName)), DAEMON_BUS_TIMER(BusTimer),
|
||||
SubSystems_(std::move(Subsystems)), Logger_(Poco::Logger::get("FRAMEWORK")) {
|
||||
instance_ = this;
|
||||
RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count());
|
||||
// Logger_ = Poco::Logger::root().get("BASE-SVC");
|
||||
}
|
||||
|
||||
inline static const char * ExtraConfigurationFilename = "/configuration_override.json";
|
||||
inline static const char *ExtraConfigurationFilename = "/configuration_override.json";
|
||||
|
||||
inline void SaveConfig() { PropConfigurationFile_->save(ConfigFileName_); }
|
||||
inline auto UpdateConfig() { return PropConfigurationFile_; }
|
||||
inline bool NoAPISecurity() const { return NoAPISecurity_; }
|
||||
inline Poco::ThreadPool & TimerPool() { return TimerPool_; }
|
||||
inline Poco::ThreadPool &TimerPool() { return TimerPool_; }
|
||||
[[nodiscard]] std::string Version() { return Version_; }
|
||||
[[nodiscard]] inline const std::string & DataDir() { return DataDir_; }
|
||||
[[nodiscard]] inline const std::string & WWWAssetsDir() { return WWWAssetsDir_; }
|
||||
[[nodiscard]] inline const std::string &DataDir() { return DataDir_; }
|
||||
[[nodiscard]] inline const std::string &WWWAssetsDir() { return WWWAssetsDir_; }
|
||||
[[nodiscard]] bool Debug() const { return DebugMode_; }
|
||||
[[nodiscard]] uint64_t ID() const { return ID_; }
|
||||
[[nodiscard]] std::string Hash() const { return MyHash_; };
|
||||
[[nodiscard]] std::string ServiceType() const { return DAEMON_APP_NAME; };
|
||||
[[nodiscard]] std::string PrivateEndPoint() const { return MyPrivateEndPoint_; };
|
||||
[[nodiscard]] std::string PublicEndPoint() const { return MyPublicEndPoint_; };
|
||||
[[nodiscard]] const SubSystemVec & GetFullSubSystems() { return SubSystems_; }
|
||||
[[nodiscard]] const SubSystemVec &GetFullSubSystems() { return SubSystems_; }
|
||||
inline uint64_t DaemonBusTimer() const { return DAEMON_BUS_TIMER; };
|
||||
[[nodiscard]] const std::string & AppName() { return DAEMON_APP_NAME; }
|
||||
[[nodiscard]] const std::string &AppName() { return DAEMON_APP_NAME; }
|
||||
static inline uint64_t GetPID() { return Poco::Process::id(); };
|
||||
[[nodiscard]] inline const std::string GetPublicAPIEndPoint() { return MyPublicEndPoint_ + "/api/v1"; };
|
||||
[[nodiscard]] inline const std::string & GetUIURI() const { return UIURI_;};
|
||||
[[nodiscard]] inline uint64_t Random(uint64_t ceiling) { return (RandomEngine_() % ceiling); }
|
||||
[[nodiscard]] inline const std::string GetPublicAPIEndPoint() {
|
||||
return MyPublicEndPoint_ + "/api/v1";
|
||||
};
|
||||
[[nodiscard]] inline const std::string &GetUIURI() const { return UIURI_; };
|
||||
[[nodiscard]] inline uint64_t Random(uint64_t ceiling) {
|
||||
return (RandomEngine_() % ceiling);
|
||||
}
|
||||
[[nodiscard]] inline uint64_t Random(uint64_t min, uint64_t max) {
|
||||
return ((RandomEngine_() % (max-min)) + min);
|
||||
return ((RandomEngine_() % (max - min)) + min);
|
||||
}
|
||||
virtual void GetExtraConfiguration(Poco::JSON::Object & Cfg) {
|
||||
Cfg.set("additionalConfiguration",false);
|
||||
virtual void GetExtraConfiguration(Poco::JSON::Object &Cfg) {
|
||||
Cfg.set("additionalConfiguration", false);
|
||||
}
|
||||
static MicroService & instance() { return *instance_; }
|
||||
static MicroService &instance() { return *instance_; }
|
||||
|
||||
inline void Exit(int Reason);
|
||||
void BusMessageReceived(const std::string &Key, const std::string & Payload);
|
||||
Types::MicroServiceMetaVec GetServices(const std::string & Type);
|
||||
void BusMessageReceived(const std::string &Key, const std::string &Payload);
|
||||
Types::MicroServiceMetaVec GetServices(const std::string &Type);
|
||||
Types::MicroServiceMetaVec GetServices();
|
||||
void LoadConfigurationFile();
|
||||
void Reload();
|
||||
@@ -136,18 +132,18 @@ namespace OpenWifi {
|
||||
void Reload(const std::string &Sub);
|
||||
Types::StringVec GetSubSystems() const;
|
||||
Types::StringPairVec GetLogLevels();
|
||||
const Types::StringVec & GetLogLevelNames();
|
||||
uint64_t ConfigGetInt(const std::string &Key,uint64_t Default);
|
||||
const Types::StringVec &GetLogLevelNames();
|
||||
uint64_t ConfigGetInt(const std::string &Key, uint64_t Default);
|
||||
uint64_t ConfigGetInt(const std::string &Key);
|
||||
uint64_t ConfigGetBool(const std::string &Key,bool Default);
|
||||
uint64_t ConfigGetBool(const std::string &Key, bool Default);
|
||||
uint64_t ConfigGetBool(const std::string &Key);
|
||||
std::string ConfigGetString(const std::string &Key,const std::string & Default);
|
||||
std::string ConfigGetString(const std::string &Key, const std::string &Default);
|
||||
std::string ConfigGetString(const std::string &Key);
|
||||
std::string ConfigPath(const std::string &Key,const std::string & Default);
|
||||
std::string ConfigPath(const std::string &Key, const std::string &Default);
|
||||
std::string ConfigPath(const std::string &Key);
|
||||
std::string Encrypt(const std::string &S);
|
||||
std::string Decrypt(const std::string &S);
|
||||
std::string MakeSystemEventMessage( const std::string & Type ) const;
|
||||
std::string MakeSystemEventMessage(const std::string &Type) const;
|
||||
[[nodiscard]] bool IsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request);
|
||||
static void SavePID();
|
||||
int main(const ArgVec &args) override;
|
||||
@@ -158,15 +154,21 @@ namespace OpenWifi {
|
||||
[[nodiscard]] std::string Sign(Poco::JWT::Token &T, const std::string &Algo);
|
||||
void AddActivity(const std::string &Activity);
|
||||
|
||||
static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
|
||||
static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
|
||||
static void SetSQLLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
|
||||
static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
|
||||
static void SetFileLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern, const std::string & root_env_var);
|
||||
static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket,
|
||||
const std::string &FormatterPattern);
|
||||
static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket,
|
||||
const std::string &FormatterPattern);
|
||||
static void SetSQLLogs(bool UseAsync, bool AllowWebSocket,
|
||||
const std::string &FormatterPattern);
|
||||
static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket,
|
||||
const std::string &FormatterPattern);
|
||||
static void SetFileLogs(bool UseAsync, bool AllowWebSocket,
|
||||
const std::string &FormatterPattern,
|
||||
const std::string &root_env_var);
|
||||
inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; }
|
||||
|
||||
private:
|
||||
static MicroService * instance_;
|
||||
static MicroService *instance_;
|
||||
bool HelpRequested_ = false;
|
||||
std::string LogDir_;
|
||||
std::string ConfigFileName_;
|
||||
@@ -175,32 +177,33 @@ namespace OpenWifi {
|
||||
bool DebugMode_ = false;
|
||||
std::string DataDir_;
|
||||
std::string WWWAssetsDir_;
|
||||
Poco::Crypto::CipherFactory & CipherFactory_ = Poco::Crypto::CipherFactory::defaultFactory();
|
||||
Poco::Crypto::Cipher * Cipher_ = nullptr;
|
||||
Poco::Crypto::CipherFactory &CipherFactory_ = Poco::Crypto::CipherFactory::defaultFactory();
|
||||
Poco::Crypto::Cipher *Cipher_ = nullptr;
|
||||
Types::MicroServiceMetaMap Services_;
|
||||
std::string MyHash_;
|
||||
std::string MyPrivateEndPoint_;
|
||||
std::string MyPublicEndPoint_;
|
||||
std::string UIURI_;
|
||||
std::string Version_{ OW_VERSION::VERSION + "("+ OW_VERSION::BUILD + ")" + " - " + OW_VERSION::HASH };
|
||||
std::string Version_{OW_VERSION::VERSION + "(" + OW_VERSION::BUILD + ")" + " - " +
|
||||
OW_VERSION::HASH};
|
||||
std::recursive_mutex InfraMutex_;
|
||||
std::default_random_engine RandomEngine_;
|
||||
Poco::Util::PropertyFileConfiguration * PropConfigurationFile_ = nullptr;
|
||||
Poco::Util::PropertyFileConfiguration *PropConfigurationFile_ = nullptr;
|
||||
std::string DAEMON_PROPERTIES_FILENAME;
|
||||
std::string DAEMON_ROOT_ENV_VAR;
|
||||
std::string DAEMON_CONFIG_ENV_VAR;
|
||||
std::string DAEMON_APP_NAME;
|
||||
uint64_t DAEMON_BUS_TIMER;
|
||||
SubSystemVec SubSystems_;
|
||||
bool NoAPISecurity_=false;
|
||||
bool NoBuiltInCrypto_=false;
|
||||
bool AllowExternalMicroServices_=false;
|
||||
bool NoAPISecurity_ = false;
|
||||
bool NoBuiltInCrypto_ = false;
|
||||
bool AllowExternalMicroServices_ = false;
|
||||
Poco::JWT::Signer Signer_;
|
||||
Poco::Logger &Logger_;
|
||||
Poco::ThreadPool TimerPool_{"timer:pool",2,32};
|
||||
Poco::ThreadPool TimerPool_{"timer:pool", 2, 32};
|
||||
std::unique_ptr<EventBusManager> EventBusManager_;
|
||||
};
|
||||
|
||||
inline MicroService * MicroService::instance_ = nullptr;
|
||||
inline MicroService *MicroService::instance_ = nullptr;
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -4,25 +4,24 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "fmt/format.h"
|
||||
#include "Poco/Util/Application.h"
|
||||
#include "Poco/ErrorHandler.h"
|
||||
#include "Poco/JSON/JSONException.h"
|
||||
#include "Poco/JSON/Template.h"
|
||||
#include "Poco/Net/NetException.h"
|
||||
#include "Poco/Net/SSLException.h"
|
||||
#include "Poco/JSON/Template.h"
|
||||
#include "Poco/JSON/JSONException.h"
|
||||
#include "Poco/Thread.h"
|
||||
#include "Poco/Util/Application.h"
|
||||
#include "fmt/format.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class MicroServiceErrorHandler : public Poco::ErrorHandler {
|
||||
public:
|
||||
explicit MicroServiceErrorHandler(Poco::Util::Application &App) : App_(App) {
|
||||
}
|
||||
explicit MicroServiceErrorHandler(Poco::Util::Application &App) : App_(App) {}
|
||||
|
||||
inline void exception(const Poco::Exception & Base) override {
|
||||
inline void exception(const Poco::Exception &Base) override {
|
||||
try {
|
||||
if(Poco::Thread::current()!= nullptr) {
|
||||
if (Poco::Thread::current() != nullptr) {
|
||||
t_name = Poco::Thread::current()->getName();
|
||||
t_id = Poco::Thread::current()->id();
|
||||
} else {
|
||||
@@ -34,179 +33,167 @@ namespace OpenWifi {
|
||||
Base.rethrow();
|
||||
|
||||
} catch (const Poco::Net::InvalidCertificateException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::InvalidCertificateException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
poco_error(App_.logger(),
|
||||
fmt::format("Poco::Net::InvalidCertificateException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(),
|
||||
E.what()));
|
||||
} catch (const Poco::Net::InvalidSocketException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::InvalidSocketException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
poco_error(App_.logger(),
|
||||
fmt::format("Poco::Net::InvalidSocketException thr_name={} thr_id={} "
|
||||
"code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(),
|
||||
E.what()));
|
||||
} catch (const Poco::Net::WebSocketException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::Net::ConnectionResetException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::ConnectionResetException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
poco_error(App_.logger(),
|
||||
fmt::format("Poco::Net::ConnectionResetException thr_name={} thr_id={} "
|
||||
"code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(),
|
||||
E.what()));
|
||||
} catch (const Poco::Net::CertificateValidationException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::CertificateValidationException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
poco_error(App_.logger(),
|
||||
fmt::format("Poco::Net::CertificateValidationException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(),
|
||||
E.what()));
|
||||
} catch (const Poco::Net::SSLConnectionUnexpectedlyClosedException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
poco_error(App_.logger(),
|
||||
fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException "
|
||||
"thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(),
|
||||
E.what()));
|
||||
} catch (const Poco::Net::SSLContextException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::Net::SSLException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::SSLException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::SSLException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
|
||||
} catch (const Poco::Net::InvalidAddressException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::InvalidAddressException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
poco_error(App_.logger(),
|
||||
fmt::format("Poco::Net::InvalidAddressException thr_name={} thr_id={} "
|
||||
"code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(),
|
||||
E.what()));
|
||||
|
||||
} catch (const Poco::Net::NetException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
|
||||
} catch (const Poco::IOException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::IOException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(
|
||||
App_.logger(),
|
||||
fmt::format(
|
||||
"Poco::IOException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(), E.what()));
|
||||
} catch (const Poco::TimeoutException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::NoThreadAvailableException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::NoThreadAvailableException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
poco_error(App_.logger(),
|
||||
fmt::format("Poco::NoThreadAvailableException thr_name={} thr_id={} "
|
||||
"code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(),
|
||||
E.what()));
|
||||
} catch (const Poco::OutOfMemoryException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::BadCastException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::DataException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::DataException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(
|
||||
App_.logger(),
|
||||
fmt::format(
|
||||
"Poco::DataException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(), E.what()));
|
||||
} catch (const Poco::PoolOverflowException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::SystemException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} "
|
||||
"code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::RuntimeException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::JSON::JSONTemplateException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::JSON::JSONTemplateException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
poco_error(App_.logger(),
|
||||
fmt::format("Poco::JSON::JSONTemplateException thr_name={} thr_id={} "
|
||||
"code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(),
|
||||
E.what()));
|
||||
} catch (const Poco::JSON::JSONException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::ApplicationException &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} "
|
||||
"thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(),
|
||||
E.message(), E.what()));
|
||||
} catch (const Poco::Exception &E) {
|
||||
poco_error(App_.logger(), fmt::format("Poco::Exception thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(),
|
||||
E.displayText(),
|
||||
E.message(),
|
||||
E.what()));
|
||||
poco_error(
|
||||
App_.logger(),
|
||||
fmt::format(
|
||||
"Poco::Exception thr_name={} thr_id={} code={} text={} msg={} what={}",
|
||||
t_name, t_id, E.code(), E.displayText(), E.message(), E.what()));
|
||||
} catch (...) {
|
||||
poco_error(App_.logger(), fmt::format("Poco:Generic thr_name={}",t_name, t_id));
|
||||
poco_error(App_.logger(), fmt::format("Poco:Generic thr_name={}", t_name, t_id));
|
||||
}
|
||||
}
|
||||
|
||||
inline void exception(const std::exception & E) override {
|
||||
if(Poco::Thread::current()!= nullptr) {
|
||||
inline void exception(const std::exception &E) override {
|
||||
if (Poco::Thread::current() != nullptr) {
|
||||
t_name = Poco::Thread::current()->getName();
|
||||
t_id = Poco::Thread::current()->id();
|
||||
} else {
|
||||
t_name = "startup_code";
|
||||
t_id = 0;
|
||||
}
|
||||
poco_warning(App_.logger(), fmt::format("std::exception in {}: {} thr_id={}",
|
||||
t_name,E.what(),
|
||||
t_id));
|
||||
poco_warning(App_.logger(),
|
||||
fmt::format("std::exception in {}: {} thr_id={}", t_name, E.what(), t_id));
|
||||
}
|
||||
|
||||
inline void exception() override {
|
||||
if(Poco::Thread::current()!= nullptr) {
|
||||
if (Poco::Thread::current() != nullptr) {
|
||||
t_name = Poco::Thread::current()->getName();
|
||||
t_id = Poco::Thread::current()->id();
|
||||
} else {
|
||||
t_name = "startup_code";
|
||||
t_id = 0;
|
||||
}
|
||||
poco_warning(App_.logger(), fmt::format("generic exception in {} thr_id={}",
|
||||
t_name, t_id));
|
||||
poco_warning(App_.logger(),
|
||||
fmt::format("generic exception in {} thr_id={}", t_name, t_id));
|
||||
}
|
||||
|
||||
private:
|
||||
Poco::Util::Application &App_;
|
||||
std::string t_name;
|
||||
int t_id=0;
|
||||
int t_id = 0;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#include "Poco/BasicEvent.h"
|
||||
#include "Poco/ExpireLRUCache.h"
|
||||
@@ -13,46 +13,40 @@
|
||||
namespace OpenWifi {
|
||||
class ConfigurationEntry {
|
||||
public:
|
||||
template <typename T> explicit ConfigurationEntry(T def) :
|
||||
Default_(def),
|
||||
Current_(def){
|
||||
template <typename T> explicit ConfigurationEntry(T def) : Default_(def), Current_(def) {}
|
||||
|
||||
template <typename T>
|
||||
explicit ConfigurationEntry(T def, T cur, const std::string &Hint = "")
|
||||
: Default_(def), Current_(cur), Hint_(Hint) {}
|
||||
|
||||
inline ConfigurationEntry() = default;
|
||||
inline ~ConfigurationEntry() = default;
|
||||
|
||||
template <typename T> explicit operator T() const { return std::get<T>(Current_); }
|
||||
inline ConfigurationEntry &operator=(const char *v) {
|
||||
Current_ = std::string(v);
|
||||
return *this;
|
||||
}
|
||||
template <typename T> ConfigurationEntry &operator=(T v) {
|
||||
Current_ = (T)v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename T> explicit ConfigurationEntry(T def, T cur, const std::string &Hint="") :
|
||||
Default_(def),
|
||||
Current_(cur),
|
||||
Hint_(Hint){
|
||||
}
|
||||
|
||||
inline ConfigurationEntry()=default;
|
||||
inline ~ConfigurationEntry()=default;
|
||||
|
||||
template <typename T> explicit operator T () const { return std::get<T>(Current_); }
|
||||
inline ConfigurationEntry & operator=(const char *v) { Current_ = std::string(v); return *this;}
|
||||
template <typename T> ConfigurationEntry & operator=(T v) { Current_ = (T) v; return *this;}
|
||||
|
||||
void reset() {
|
||||
Current_ = Default_;
|
||||
}
|
||||
void reset() { Current_ = Default_; }
|
||||
|
||||
private:
|
||||
std::variant<bool,uint64_t,std::string> Default_, Current_;
|
||||
std::variant<bool, uint64_t, std::string> Default_, Current_;
|
||||
std::string Hint_;
|
||||
};
|
||||
inline std::string to_string(const ConfigurationEntry &v) { return (std::string) v; }
|
||||
inline std::string to_string(const ConfigurationEntry &v) { return (std::string)v; }
|
||||
|
||||
typedef std::map<std::string,ConfigurationEntry> ConfigurationMap_t;
|
||||
typedef std::map<std::string, ConfigurationEntry> ConfigurationMap_t;
|
||||
|
||||
template <typename T> class FIFO {
|
||||
public:
|
||||
explicit FIFO(uint32_t Size) :
|
||||
Size_(Size) {
|
||||
Buffer_ = new T [Size_];
|
||||
}
|
||||
explicit FIFO(uint32_t Size) : Size_(Size) { Buffer_ = new T[Size_]; }
|
||||
|
||||
~FIFO() {
|
||||
delete [] Buffer_;
|
||||
}
|
||||
~FIFO() { delete[] Buffer_; }
|
||||
|
||||
mutable Poco::BasicEvent<bool> Writable_;
|
||||
mutable Poco::BasicEvent<bool> Readable_;
|
||||
@@ -84,7 +78,7 @@ namespace OpenWifi {
|
||||
Write_ = 0;
|
||||
}
|
||||
Used_++;
|
||||
MaxEverUsed_ = std::max(Used_,MaxEverUsed_);
|
||||
MaxEverUsed_ = std::max(Used_, MaxEverUsed_);
|
||||
}
|
||||
bool flag = true;
|
||||
Readable_.notify(this, flag);
|
||||
@@ -93,40 +87,32 @@ namespace OpenWifi {
|
||||
|
||||
inline bool isFull() {
|
||||
std::lock_guard M(Mutex_);
|
||||
return Used_==Buffer_->capacity();
|
||||
return Used_ == Buffer_->capacity();
|
||||
}
|
||||
|
||||
inline auto MaxEverUser() const { return MaxEverUsed_; }
|
||||
|
||||
private:
|
||||
std::recursive_mutex Mutex_;
|
||||
uint32_t Size_=0;
|
||||
uint32_t Read_=0;
|
||||
uint32_t Write_=0;
|
||||
uint32_t Used_=0;
|
||||
uint32_t MaxEverUsed_=0;
|
||||
T * Buffer_ = nullptr;
|
||||
uint32_t Size_ = 0;
|
||||
uint32_t Read_ = 0;
|
||||
uint32_t Write_ = 0;
|
||||
uint32_t Used_ = 0;
|
||||
uint32_t MaxEverUsed_ = 0;
|
||||
T *Buffer_ = nullptr;
|
||||
};
|
||||
|
||||
template <class Record, typename KeyType = std::string, int Size=256, int Expiry=60000> class RecordCache {
|
||||
template <class Record, typename KeyType = std::string, int Size = 256, int Expiry = 60000>
|
||||
class RecordCache {
|
||||
public:
|
||||
explicit RecordCache( KeyType Record::* Q) :
|
||||
MemberOffset(Q){
|
||||
};
|
||||
inline auto update(const Record &R) {
|
||||
return Cache_.update(R.*MemberOffset, R);
|
||||
}
|
||||
inline auto get(const KeyType &K) {
|
||||
return Cache_.get(K);
|
||||
}
|
||||
inline auto remove(const KeyType &K) {
|
||||
return Cache_.remove(K);
|
||||
}
|
||||
inline auto remove(const Record &R) {
|
||||
return Cache_.remove(R.*MemberOffset);
|
||||
}
|
||||
explicit RecordCache(KeyType Record::*Q) : MemberOffset(Q){};
|
||||
inline auto update(const Record &R) { return Cache_.update(R.*MemberOffset, R); }
|
||||
inline auto get(const KeyType &K) { return Cache_.get(K); }
|
||||
inline auto remove(const KeyType &K) { return Cache_.remove(K); }
|
||||
inline auto remove(const Record &R) { return Cache_.remove(R.*MemberOffset); }
|
||||
|
||||
private:
|
||||
KeyType Record::* MemberOffset;
|
||||
Poco::ExpireLRUCache<KeyType,Record> Cache_{Size,Expiry};
|
||||
KeyType Record::*MemberOffset;
|
||||
Poco::ExpireLRUCache<KeyType, Record> Cache_{Size, Expiry};
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -2,8 +2,8 @@
|
||||
// Created by stephane bourque on 2022-10-25.
|
||||
//
|
||||
|
||||
#include "framework/MicroService.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "framework/MicroService.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
const std::string &MicroServiceDataDirectory() { return MicroService::instance().DataDir(); }
|
||||
@@ -18,7 +18,8 @@ namespace OpenWifi {
|
||||
|
||||
std::string MicroServicePublicEndPoint() { return MicroService::instance().PublicEndPoint(); }
|
||||
|
||||
std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue) {
|
||||
std::string MicroServiceConfigGetString(const std::string &Key,
|
||||
const std::string &DefaultValue) {
|
||||
return MicroService::instance().ConfigGetString(Key, DefaultValue);
|
||||
}
|
||||
|
||||
@@ -54,7 +55,9 @@ namespace OpenWifi {
|
||||
return MicroService::instance().GetSubSystems();
|
||||
}
|
||||
|
||||
Types::StringPairVec MicroServiceGetLogLevels() { return MicroService::instance().GetLogLevels(); }
|
||||
Types::StringPairVec MicroServiceGetLogLevels() {
|
||||
return MicroService::instance().GetLogLevels();
|
||||
}
|
||||
|
||||
bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) {
|
||||
return MicroService::instance().SetSubsystemLogLevel(SubSystem, Level);
|
||||
@@ -90,16 +93,13 @@ namespace OpenWifi {
|
||||
|
||||
Poco::ThreadPool &MicroServiceTimerPool() { return MicroService::instance().TimerPool(); }
|
||||
|
||||
std::string MicroServiceConfigPath(const std::string &Key,
|
||||
const std::string &DefaultValue) {
|
||||
std::string MicroServiceConfigPath(const std::string &Key, const std::string &DefaultValue) {
|
||||
return MicroService::instance().ConfigPath(Key, DefaultValue);
|
||||
}
|
||||
|
||||
std::string MicroServiceWWWAssetsDir() {
|
||||
return MicroService::instance().WWWAssetsDir();
|
||||
}
|
||||
std::string MicroServiceWWWAssetsDir() { return MicroService::instance().WWWAssetsDir(); }
|
||||
|
||||
std::uint64_t MicroServiceRandom(std::uint64_t Start,std::uint64_t End) {
|
||||
std::uint64_t MicroServiceRandom(std::uint64_t Start, std::uint64_t End) {
|
||||
return MicroService::instance().Random(Start, End);
|
||||
}
|
||||
|
||||
@@ -123,4 +123,4 @@ namespace OpenWifi {
|
||||
return MicroService::instance().AllowExternalMicroServices();
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -8,20 +8,20 @@
|
||||
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
#include "Poco/JSON/Object.h"
|
||||
#include "Poco/ThreadPool.h"
|
||||
#include "Poco/JWT/Token.h"
|
||||
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
#include "Poco/ThreadPool.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
class SubSystemServer;
|
||||
using SubSystemVec=std::vector<SubSystemServer *>;
|
||||
const std::string & MicroServiceDataDirectory();
|
||||
Types::MicroServiceMetaVec MicroServiceGetServices(const std::string & Type);
|
||||
using SubSystemVec = std::vector<SubSystemServer *>;
|
||||
const std::string &MicroServiceDataDirectory();
|
||||
Types::MicroServiceMetaVec MicroServiceGetServices(const std::string &Type);
|
||||
Types::MicroServiceMetaVec MicroServiceGetServices();
|
||||
std::string MicroServicePublicEndPoint();
|
||||
std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue);
|
||||
std::string MicroServiceConfigGetString(const std::string &Key,
|
||||
const std::string &DefaultValue);
|
||||
bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue);
|
||||
std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue);
|
||||
std::string MicroServicePrivateEndPoint();
|
||||
@@ -43,15 +43,14 @@ namespace OpenWifi {
|
||||
const SubSystemVec MicroServiceGetFullSubSystems();
|
||||
std::string MicroServiceCreateUUID();
|
||||
std::uint64_t MicroServiceDaemonBusTimer();
|
||||
std::string MicroServiceMakeSystemEventMessage( const std::string & Type );
|
||||
Poco::ThreadPool & MicroServiceTimerPool();
|
||||
std::string MicroServiceConfigPath(const std::string &Key,
|
||||
const std::string &DefaultValue);
|
||||
std::string MicroServiceMakeSystemEventMessage(const std::string &Type);
|
||||
Poco::ThreadPool &MicroServiceTimerPool();
|
||||
std::string MicroServiceConfigPath(const std::string &Key, const std::string &DefaultValue);
|
||||
std::string MicroServiceWWWAssetsDir();
|
||||
std::uint64_t MicroServiceRandom(std::uint64_t Start,std::uint64_t End);
|
||||
std::uint64_t MicroServiceRandom(std::uint64_t Start, std::uint64_t End);
|
||||
std::uint64_t MicroServiceRandom(std::uint64_t Range);
|
||||
std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo);
|
||||
std::string MicroServiceGetPublicAPIEndPoint();
|
||||
void MicroServiceDeleteOverrideConfiguration();
|
||||
bool AllowExternalMicroServices();
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -10,13 +10,13 @@ namespace OpenWifi {
|
||||
|
||||
static const std::string uSERVICE_SECURITY{"owsec"};
|
||||
static const std::string uSERVICE_GATEWAY{"owgw"};
|
||||
static const std::string uSERVICE_FIRMWARE{ "owfms"};
|
||||
static const std::string uSERVICE_TOPOLOGY{ "owtopo"};
|
||||
static const std::string uSERVICE_PROVISIONING{ "owprov"};
|
||||
static const std::string uSERVICE_OWLS{ "owls"};
|
||||
static const std::string uSERVICE_SUBCRIBER{ "owsub"};
|
||||
static const std::string uSERVICE_INSTALLER{ "owinst"};
|
||||
static const std::string uSERVICE_ANALYTICS{ "owanalytics"};
|
||||
static const std::string uSERVICE_OWRRM{ "owrrm"};
|
||||
static const std::string uSERVICE_FIRMWARE{"owfms"};
|
||||
static const std::string uSERVICE_TOPOLOGY{"owtopo"};
|
||||
static const std::string uSERVICE_PROVISIONING{"owprov"};
|
||||
static const std::string uSERVICE_OWLS{"owls"};
|
||||
static const std::string uSERVICE_SUBCRIBER{"owsub"};
|
||||
static const std::string uSERVICE_INSTALLER{"owinst"};
|
||||
static const std::string uSERVICE_ANALYTICS{"owanalytics"};
|
||||
static const std::string uSERVICE_OWRRM{"owrrm"};
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,22 +4,23 @@
|
||||
|
||||
#include "OpenAPIRequests.h"
|
||||
|
||||
#include "Poco/JSON/Parser.h"
|
||||
#include "Poco/Logger.h"
|
||||
#include "Poco/URI.h"
|
||||
#include "Poco/Net/HTTPRequest.h"
|
||||
#include "Poco/Net/HTTPSClientSession.h"
|
||||
#include "Poco/JSON/Parser.h"
|
||||
#include "Poco/URI.h"
|
||||
|
||||
#include "fmt/format.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus
|
||||
OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) {
|
||||
try {
|
||||
|
||||
auto Services = MicroServiceGetServices(Type_);
|
||||
for(auto const &Svc:Services) {
|
||||
for (auto const &Svc : Services) {
|
||||
Poco::URI URI(Svc.PrivateEndPoint);
|
||||
|
||||
auto Secure = (URI.getScheme() == "https");
|
||||
@@ -29,13 +30,13 @@ namespace OpenWifi {
|
||||
URI.addQueryParameter(qp.first, qp.second);
|
||||
|
||||
std::string Path(URI.getPathAndQuery());
|
||||
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Path,
|
||||
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, Path,
|
||||
Poco::Net::HTTPMessage::HTTP_1_1);
|
||||
|
||||
poco_debug(Poco::Logger::get("REST-CALLER-GET"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
|
||||
poco_debug(Poco::Logger::get("REST-CALLER-GET"),
|
||||
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
|
||||
|
||||
if(BearerToken.empty()) {
|
||||
if (BearerToken.empty()) {
|
||||
Request.add("X-API-KEY", Svc.AccessKey);
|
||||
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
|
||||
} else {
|
||||
@@ -43,7 +44,7 @@ namespace OpenWifi {
|
||||
Request.add("Authorization", "Bearer " + BearerToken);
|
||||
}
|
||||
|
||||
if(Secure) {
|
||||
if (Secure) {
|
||||
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
|
||||
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
|
||||
|
||||
@@ -71,18 +72,17 @@ namespace OpenWifi {
|
||||
return Response.getStatus();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const Poco::Exception &E)
|
||||
{
|
||||
} catch (const Poco::Exception &E) {
|
||||
Poco::Logger::get("REST-CALLER-GET").log(E);
|
||||
}
|
||||
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
|
||||
}
|
||||
}
|
||||
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus
|
||||
OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) {
|
||||
try {
|
||||
auto Services = MicroServiceGetServices(Type_);
|
||||
for(auto const &Svc:Services) {
|
||||
for (auto const &Svc : Services) {
|
||||
Poco::URI URI(Svc.PrivateEndPoint);
|
||||
|
||||
auto Secure = (URI.getScheme() == "https");
|
||||
@@ -91,20 +91,20 @@ namespace OpenWifi {
|
||||
for (const auto &qp : QueryData_)
|
||||
URI.addQueryParameter(qp.first, qp.second);
|
||||
|
||||
poco_debug(Poco::Logger::get("REST-CALLER-PUT"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
|
||||
poco_debug(Poco::Logger::get("REST-CALLER-PUT"),
|
||||
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
|
||||
|
||||
std::string Path(URI.getPathAndQuery());
|
||||
|
||||
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT,
|
||||
Path,
|
||||
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT, Path,
|
||||
Poco::Net::HTTPMessage::HTTP_1_1);
|
||||
std::ostringstream obody;
|
||||
Poco::JSON::Stringifier::stringify(Body_,obody);
|
||||
Poco::JSON::Stringifier::stringify(Body_, obody);
|
||||
|
||||
Request.setContentType("application/json");
|
||||
Request.setContentLength(obody.str().size());
|
||||
|
||||
if(BearerToken.empty()) {
|
||||
if (BearerToken.empty()) {
|
||||
Request.add("X-API-KEY", Svc.AccessKey);
|
||||
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
|
||||
} else {
|
||||
@@ -112,7 +112,7 @@ namespace OpenWifi {
|
||||
Request.add("Authorization", "Bearer " + BearerToken);
|
||||
}
|
||||
|
||||
if(Secure) {
|
||||
if (Secure) {
|
||||
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
|
||||
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
|
||||
|
||||
@@ -148,42 +148,41 @@ namespace OpenWifi {
|
||||
return Response.getStatus();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const Poco::Exception &E)
|
||||
{
|
||||
} catch (const Poco::Exception &E) {
|
||||
Poco::Logger::get("REST-CALLER-PUT").log(E);
|
||||
}
|
||||
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
|
||||
}
|
||||
}
|
||||
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus
|
||||
OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject,
|
||||
const std::string &BearerToken) {
|
||||
try {
|
||||
auto Services = MicroServiceGetServices(Type_);
|
||||
|
||||
for(auto const &Svc:Services) {
|
||||
for (auto const &Svc : Services) {
|
||||
Poco::URI URI(Svc.PrivateEndPoint);
|
||||
|
||||
|
||||
auto Secure = (URI.getScheme() == "https");
|
||||
|
||||
URI.setPath(EndPoint_);
|
||||
for (const auto &qp : QueryData_)
|
||||
URI.addQueryParameter(qp.first, qp.second);
|
||||
|
||||
poco_debug(Poco::Logger::get("REST-CALLER-POST"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
|
||||
poco_debug(Poco::Logger::get("REST-CALLER-POST"),
|
||||
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
|
||||
|
||||
std::string Path(URI.getPathAndQuery());
|
||||
|
||||
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST,
|
||||
Path,
|
||||
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST, Path,
|
||||
Poco::Net::HTTPMessage::HTTP_1_1);
|
||||
std::ostringstream obody;
|
||||
Poco::JSON::Stringifier::stringify(Body_,obody);
|
||||
Poco::JSON::Stringifier::stringify(Body_, obody);
|
||||
|
||||
Request.setContentType("application/json");
|
||||
Request.setContentLength(obody.str().size());
|
||||
|
||||
if(BearerToken.empty()) {
|
||||
if (BearerToken.empty()) {
|
||||
Request.add("X-API-KEY", Svc.AccessKey);
|
||||
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
|
||||
} else {
|
||||
@@ -191,7 +190,7 @@ namespace OpenWifi {
|
||||
Request.add("Authorization", "Bearer " + BearerToken);
|
||||
}
|
||||
|
||||
if(Secure) {
|
||||
if (Secure) {
|
||||
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
|
||||
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
|
||||
std::ostream &os = Session.sendRequest(Request);
|
||||
@@ -225,19 +224,18 @@ namespace OpenWifi {
|
||||
return Response.getStatus();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const Poco::Exception &E)
|
||||
{
|
||||
} catch (const Poco::Exception &E) {
|
||||
Poco::Logger::get("REST-CALLER-POST").log(E);
|
||||
}
|
||||
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
|
||||
}
|
||||
}
|
||||
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestDelete::Do(const std::string & BearerToken) {
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus
|
||||
OpenAPIRequestDelete::Do(const std::string &BearerToken) {
|
||||
try {
|
||||
auto Services = MicroServiceGetServices(Type_);
|
||||
|
||||
for(auto const &Svc:Services) {
|
||||
for (auto const &Svc : Services) {
|
||||
Poco::URI URI(Svc.PrivateEndPoint);
|
||||
|
||||
auto Secure = (URI.getScheme() == "https");
|
||||
@@ -246,14 +244,14 @@ namespace OpenWifi {
|
||||
for (const auto &qp : QueryData_)
|
||||
URI.addQueryParameter(qp.first, qp.second);
|
||||
|
||||
poco_debug(Poco::Logger::get("REST-CALLER-DELETE"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
|
||||
poco_debug(Poco::Logger::get("REST-CALLER-DELETE"),
|
||||
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
|
||||
|
||||
std::string Path(URI.getPathAndQuery());
|
||||
|
||||
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_DELETE,
|
||||
Path,
|
||||
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_DELETE, Path,
|
||||
Poco::Net::HTTPMessage::HTTP_1_1);
|
||||
if(BearerToken.empty()) {
|
||||
if (BearerToken.empty()) {
|
||||
Request.add("X-API-KEY", Svc.AccessKey);
|
||||
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
|
||||
} else {
|
||||
@@ -261,7 +259,7 @@ namespace OpenWifi {
|
||||
Request.add("Authorization", "Bearer " + BearerToken);
|
||||
}
|
||||
|
||||
if(Secure) {
|
||||
if (Secure) {
|
||||
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
|
||||
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
|
||||
Session.sendRequest(Request);
|
||||
@@ -277,13 +275,10 @@ namespace OpenWifi {
|
||||
return Response.getStatus();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const Poco::Exception &E)
|
||||
{
|
||||
} catch (const Poco::Exception &E) {
|
||||
Poco::Logger::get("REST-CALLER-DELETE").log(E);
|
||||
}
|
||||
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} // namespace OpenWifi
|
||||
@@ -15,17 +15,14 @@ namespace OpenWifi {
|
||||
|
||||
class OpenAPIRequestGet {
|
||||
public:
|
||||
explicit OpenAPIRequestGet( const std::string & Type,
|
||||
const std::string & EndPoint,
|
||||
const Types::StringPairVec & QueryData,
|
||||
uint64_t msTimeout,
|
||||
const std::string &LoggingStr=""):
|
||||
Type_(Type),
|
||||
EndPoint_(EndPoint),
|
||||
QueryData_(QueryData),
|
||||
msTimeout_(msTimeout),
|
||||
explicit OpenAPIRequestGet(const std::string &Type, const std::string &EndPoint,
|
||||
const Types::StringPairVec &QueryData, uint64_t msTimeout,
|
||||
const std::string &LoggingStr = "")
|
||||
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
|
||||
LoggingStr_(LoggingStr){};
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject,
|
||||
const std::string &BearerToken = "");
|
||||
|
||||
private:
|
||||
std::string Type_;
|
||||
std::string EndPoint_;
|
||||
@@ -36,20 +33,15 @@ namespace OpenWifi {
|
||||
|
||||
class OpenAPIRequestPut {
|
||||
public:
|
||||
explicit OpenAPIRequestPut( const std::string & Type,
|
||||
const std::string & EndPoint,
|
||||
const Types::StringPairVec & QueryData,
|
||||
const Poco::JSON::Object & Body,
|
||||
uint64_t msTimeout,
|
||||
const std::string &LoggingStr=""):
|
||||
Type_(Type),
|
||||
EndPoint_(EndPoint),
|
||||
QueryData_(QueryData),
|
||||
msTimeout_(msTimeout),
|
||||
Body_(Body),
|
||||
LoggingStr_(LoggingStr){};
|
||||
explicit OpenAPIRequestPut(const std::string &Type, const std::string &EndPoint,
|
||||
const Types::StringPairVec &QueryData,
|
||||
const Poco::JSON::Object &Body, uint64_t msTimeout,
|
||||
const std::string &LoggingStr = "")
|
||||
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
|
||||
Body_(Body), LoggingStr_(LoggingStr){};
|
||||
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject,
|
||||
const std::string &BearerToken = "");
|
||||
|
||||
private:
|
||||
std::string Type_;
|
||||
@@ -62,19 +54,15 @@ namespace OpenWifi {
|
||||
|
||||
class OpenAPIRequestPost {
|
||||
public:
|
||||
explicit OpenAPIRequestPost( const std::string & Type,
|
||||
const std::string & EndPoint,
|
||||
const Types::StringPairVec & QueryData,
|
||||
const Poco::JSON::Object & Body,
|
||||
uint64_t msTimeout,
|
||||
const std::string &LoggingStr=""):
|
||||
Type_(Type),
|
||||
EndPoint_(EndPoint),
|
||||
QueryData_(QueryData),
|
||||
msTimeout_(msTimeout),
|
||||
Body_(Body),
|
||||
LoggingStr_(LoggingStr){};
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
|
||||
explicit OpenAPIRequestPost(const std::string &Type, const std::string &EndPoint,
|
||||
const Types::StringPairVec &QueryData,
|
||||
const Poco::JSON::Object &Body, uint64_t msTimeout,
|
||||
const std::string &LoggingStr = "")
|
||||
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
|
||||
Body_(Body), LoggingStr_(LoggingStr){};
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject,
|
||||
const std::string &BearerToken = "");
|
||||
|
||||
private:
|
||||
std::string Type_;
|
||||
std::string EndPoint_;
|
||||
@@ -86,17 +74,12 @@ namespace OpenWifi {
|
||||
|
||||
class OpenAPIRequestDelete {
|
||||
public:
|
||||
explicit OpenAPIRequestDelete( const std::string & Type,
|
||||
const std::string & EndPoint,
|
||||
const Types::StringPairVec & QueryData,
|
||||
uint64_t msTimeout,
|
||||
const std::string &LoggingStr=""):
|
||||
Type_(Type),
|
||||
EndPoint_(EndPoint),
|
||||
QueryData_(QueryData),
|
||||
msTimeout_(msTimeout),
|
||||
explicit OpenAPIRequestDelete(const std::string &Type, const std::string &EndPoint,
|
||||
const Types::StringPairVec &QueryData, uint64_t msTimeout,
|
||||
const std::string &LoggingStr = "")
|
||||
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
|
||||
LoggingStr_(LoggingStr){};
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string & BearerToken = "");
|
||||
Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string &BearerToken = "");
|
||||
|
||||
private:
|
||||
std::string Type_;
|
||||
|
||||
@@ -4,70 +4,71 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <queue>
|
||||
#include <list>
|
||||
#include <set>
|
||||
|
||||
namespace OpenWifi::Types {
|
||||
typedef std::pair<std::string,std::string> StringPair;
|
||||
typedef std::pair<std::string, std::string> StringPair;
|
||||
typedef std::vector<StringPair> StringPairVec;
|
||||
typedef std::queue<StringPair> StringPairQueue;
|
||||
typedef std::vector<std::string> StringVec;
|
||||
typedef std::set<std::string> StringSet;
|
||||
typedef std::map<std::string,std::set<std::string>> StringMapStringSet;
|
||||
typedef std::map<std::string, std::set<std::string>> StringMapStringSet;
|
||||
typedef std::function<void(const std::string &, const std::string &)> TopicNotifyFunction;
|
||||
typedef std::list<std::pair<TopicNotifyFunction,int>> TopicNotifyFunctionList;
|
||||
typedef std::list<std::pair<TopicNotifyFunction, int>> TopicNotifyFunctionList;
|
||||
typedef std::map<std::string, TopicNotifyFunctionList> NotifyTable;
|
||||
typedef std::map<std::string,uint64_t> CountedMap;
|
||||
typedef std::map<std::string, uint64_t> CountedMap;
|
||||
typedef std::vector<uint64_t> TagList;
|
||||
typedef std::string UUID_t;
|
||||
typedef std::vector<UUID_t> UUIDvec_t;
|
||||
typedef std::map<std::string,std::map<uint32_t,uint64_t>> Counted3DMapSII;
|
||||
typedef std::map<std::string, std::map<uint32_t, uint64_t>> Counted3DMapSII;
|
||||
|
||||
struct MicroServiceMeta {
|
||||
uint64_t Id=0;
|
||||
uint64_t Id = 0;
|
||||
std::string Type;
|
||||
std::string PrivateEndPoint;
|
||||
std::string PublicEndPoint;
|
||||
std::string AccessKey;
|
||||
std::string Version;
|
||||
uint64_t LastUpdate=0;
|
||||
uint64_t LastUpdate = 0;
|
||||
};
|
||||
|
||||
typedef std::map<std::string, MicroServiceMeta> MicroServiceMetaMap;
|
||||
typedef std::vector<MicroServiceMeta> MicroServiceMetaVec;
|
||||
}
|
||||
} // namespace OpenWifi::Types
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
inline void UpdateCountedMap(OpenWifi::Types::CountedMap &M, const std::string &S, uint64_t Increment=1) {
|
||||
inline void UpdateCountedMap(OpenWifi::Types::CountedMap &M, const std::string &S,
|
||||
uint64_t Increment = 1) {
|
||||
auto it = M.find(S);
|
||||
if(it==M.end())
|
||||
if (it == M.end())
|
||||
M[S] = Increment;
|
||||
else
|
||||
it->second += Increment;
|
||||
}
|
||||
|
||||
inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S, uint32_t Index, uint64_t Increment=1) {
|
||||
inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S,
|
||||
uint32_t Index, uint64_t Increment = 1) {
|
||||
auto it = M.find(S);
|
||||
if(it==M.end()) {
|
||||
std::map<uint32_t,uint64_t> E;
|
||||
if (it == M.end()) {
|
||||
std::map<uint32_t, uint64_t> E;
|
||||
E[Index] = Increment;
|
||||
M[S] = E;
|
||||
}
|
||||
else {
|
||||
std::map<uint32_t,uint64_t> & IndexMap = it->second;
|
||||
} else {
|
||||
std::map<uint32_t, uint64_t> &IndexMap = it->second;
|
||||
auto it_index = IndexMap.find(Index);
|
||||
if(it_index == IndexMap.end()) {
|
||||
if (it_index == IndexMap.end()) {
|
||||
IndexMap[Index] = Increment;
|
||||
} else {
|
||||
it_index->second += Increment;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -6,22 +6,23 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
Poco::Net::HTTPRequestHandler *ExtRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &Request) {
|
||||
Poco::Net::HTTPRequestHandler *
|
||||
ExtRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &Request) {
|
||||
try {
|
||||
Poco::URI uri(Request.getURI());
|
||||
auto TID = NextTransactionId_++;
|
||||
Utils::SetThreadName(fmt::format("x-rest:{}",TID).c_str());
|
||||
Utils::SetThreadName(fmt::format("x-rest:{}", TID).c_str());
|
||||
return RESTAPI_ExtServer()->CallServer(uri.getPath(), TID);
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Poco::Net::HTTPRequestHandler *RESTAPI_ExtServer::CallServer(const std::string &Path, uint64_t Id) {
|
||||
Poco::Net::HTTPRequestHandler *RESTAPI_ExtServer::CallServer(const std::string &Path,
|
||||
uint64_t Id) {
|
||||
RESTAPIHandler::BindingMap Bindings;
|
||||
Utils::SetThreadName(fmt::format("x-rest:{}",Id).c_str());
|
||||
Utils::SetThreadName(fmt::format("x-rest:{}", Id).c_str());
|
||||
return RESTAPI_ExtRouter(Path, Bindings, Logger(), Server_, Id);
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -6,18 +6,21 @@
|
||||
|
||||
#include "Poco/Net/HTTPServer.h"
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
Poco::Net::HTTPRequestHandler * RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t Id);
|
||||
Poco::Net::HTTPRequestHandler *
|
||||
RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t Id);
|
||||
|
||||
class ExtRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
|
||||
public:
|
||||
ExtRequestHandlerFactory() = default;
|
||||
Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
|
||||
Poco::Net::HTTPRequestHandler *
|
||||
createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
|
||||
|
||||
private:
|
||||
static inline std::atomic_uint64_t NextTransactionId_ = 1;
|
||||
};
|
||||
@@ -30,16 +33,21 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
inline int Start() override {
|
||||
poco_information(Logger(),"Starting.");
|
||||
poco_information(Logger(), "Starting.");
|
||||
Server_.InitLogging();
|
||||
|
||||
for(const auto & Svr: ConfigServersList_) {
|
||||
for (const auto &Svr : ConfigServersList_) {
|
||||
|
||||
if(MicroServiceNoAPISecurity()) {
|
||||
poco_information(Logger(),fmt::format("Starting: {}:{}. Security has been disabled for APIs.", Svr.Address(), Svr.Port()));
|
||||
if (MicroServiceNoAPISecurity()) {
|
||||
poco_information(
|
||||
Logger(),
|
||||
fmt::format("Starting: {}:{}. Security has been disabled for APIs.",
|
||||
Svr.Address(), Svr.Port()));
|
||||
} else {
|
||||
poco_information(Logger(),fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}", Svr.Address(), Svr.Port(),
|
||||
Svr.KeyFile(),Svr.CertFile()));
|
||||
poco_information(Logger(),
|
||||
fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}",
|
||||
Svr.Address(), Svr.Port(), Svr.KeyFile(),
|
||||
Svr.CertFile()));
|
||||
Svr.LogCert(Logger());
|
||||
if (!Svr.RootCA().empty())
|
||||
Svr.LogCas(Logger());
|
||||
@@ -50,12 +58,14 @@ namespace OpenWifi {
|
||||
Params->setName("ws:xrest");
|
||||
|
||||
std::unique_ptr<Poco::Net::HTTPServer> NewServer;
|
||||
if(MicroServiceNoAPISecurity()) {
|
||||
if (MicroServiceNoAPISecurity()) {
|
||||
auto Sock{Svr.CreateSocket(Logger())};
|
||||
NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params);
|
||||
NewServer = std::make_unique<Poco::Net::HTTPServer>(
|
||||
new ExtRequestHandlerFactory, Pool_, Sock, Params);
|
||||
} else {
|
||||
auto Sock{Svr.CreateSecureSocket(Logger())};
|
||||
NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params);
|
||||
NewServer = std::make_unique<Poco::Net::HTTPServer>(
|
||||
new ExtRequestHandlerFactory, Pool_, Sock, Params);
|
||||
};
|
||||
NewServer->start();
|
||||
RESTServers_.push_back(std::move(NewServer));
|
||||
@@ -64,36 +74,34 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
inline void Stop() override {
|
||||
poco_information(Logger(),"Stopping...");
|
||||
for( const auto & svr : RESTServers_ )
|
||||
poco_information(Logger(), "Stopping...");
|
||||
for (const auto &svr : RESTServers_)
|
||||
svr->stopAll(true);
|
||||
Pool_.stopAll();
|
||||
Pool_.joinAll();
|
||||
RESTServers_.clear();
|
||||
poco_information(Logger(),"Stopped...");
|
||||
poco_information(Logger(), "Stopped...");
|
||||
}
|
||||
|
||||
inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override {
|
||||
MicroServiceLoadConfigurationFile();
|
||||
poco_information(Logger(),"Reinitializing.");
|
||||
poco_information(Logger(), "Reinitializing.");
|
||||
Stop();
|
||||
Start();
|
||||
}
|
||||
|
||||
Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id);
|
||||
const Poco::ThreadPool & Pool() { return Pool_; }
|
||||
const Poco::ThreadPool &Pool() { return Pool_; }
|
||||
|
||||
private:
|
||||
std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
|
||||
Poco::ThreadPool Pool_{"x-rest",8,128};
|
||||
Poco::ThreadPool Pool_{"x-rest", 8, 128};
|
||||
RESTAPI_GenericServerAccounting Server_;
|
||||
|
||||
RESTAPI_ExtServer() noexcept:
|
||||
SubSystemServer("RESTAPI_ExtServer", "REST-XSRV", "openwifi.restapi")
|
||||
{
|
||||
}
|
||||
RESTAPI_ExtServer() noexcept
|
||||
: SubSystemServer("RESTAPI_ExtServer", "REST-XSRV", "openwifi.restapi") {}
|
||||
};
|
||||
|
||||
inline auto RESTAPI_ExtServer() { return RESTAPI_ExtServer::instance(); };
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,72 +4,70 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <array>
|
||||
#include <string>
|
||||
|
||||
#include "Poco/StringTokenizer.h"
|
||||
#include "Poco/String.h"
|
||||
#include "Poco/Net/HTTPRequest.h"
|
||||
#include "Poco/String.h"
|
||||
#include "Poco/StringTokenizer.h"
|
||||
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_GenericServerAccounting {
|
||||
public:
|
||||
|
||||
enum {
|
||||
LOG_GET=0,
|
||||
LOG_DELETE,
|
||||
LOG_PUT,
|
||||
LOG_POST
|
||||
};
|
||||
enum { LOG_GET = 0, LOG_DELETE, LOG_PUT, LOG_POST };
|
||||
|
||||
void inline SetFlags(bool External, const std::string &Methods) {
|
||||
Poco::StringTokenizer Tokens(Methods,",");
|
||||
Poco::StringTokenizer Tokens(Methods, ",");
|
||||
auto Offset = (External ? 0 : 4);
|
||||
for(const auto &i:Tokens) {
|
||||
if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_DELETE)==0)
|
||||
LogFlags_[Offset+LOG_DELETE]=true;
|
||||
else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_PUT)==0)
|
||||
LogFlags_[Offset+LOG_PUT]=true;
|
||||
else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_POST)==0)
|
||||
LogFlags_[Offset+LOG_POST]=true;
|
||||
else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_GET)==0)
|
||||
LogFlags_[Offset+LOG_GET]=true;
|
||||
for (const auto &i : Tokens) {
|
||||
if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_DELETE) == 0)
|
||||
LogFlags_[Offset + LOG_DELETE] = true;
|
||||
else if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_PUT) == 0)
|
||||
LogFlags_[Offset + LOG_PUT] = true;
|
||||
else if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_POST) == 0)
|
||||
LogFlags_[Offset + LOG_POST] = true;
|
||||
else if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_GET) == 0)
|
||||
LogFlags_[Offset + LOG_GET] = true;
|
||||
}
|
||||
}
|
||||
|
||||
inline void InitLogging() {
|
||||
std::string Public = MicroServiceConfigGetString("apilogging.public.methods","PUT,POST,DELETE");
|
||||
std::string Public =
|
||||
MicroServiceConfigGetString("apilogging.public.methods", "PUT,POST,DELETE");
|
||||
SetFlags(true, Public);
|
||||
std::string Private = MicroServiceConfigGetString("apilogging.private.methods","PUT,POST,DELETE");
|
||||
std::string Private =
|
||||
MicroServiceConfigGetString("apilogging.private.methods", "PUT,POST,DELETE");
|
||||
SetFlags(false, Private);
|
||||
|
||||
std::string PublicBadTokens = MicroServiceConfigGetString("apilogging.public.badtokens.methods","");
|
||||
LogBadTokens_[0] = (Poco::icompare(PublicBadTokens,"true")==0);
|
||||
std::string PrivateBadTokens = MicroServiceConfigGetString("apilogging.private.badtokens.methods","");
|
||||
LogBadTokens_[1] = (Poco::icompare(PrivateBadTokens,"true")==0);
|
||||
std::string PublicBadTokens =
|
||||
MicroServiceConfigGetString("apilogging.public.badtokens.methods", "");
|
||||
LogBadTokens_[0] = (Poco::icompare(PublicBadTokens, "true") == 0);
|
||||
std::string PrivateBadTokens =
|
||||
MicroServiceConfigGetString("apilogging.private.badtokens.methods", "");
|
||||
LogBadTokens_[1] = (Poco::icompare(PrivateBadTokens, "true") == 0);
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool LogIt(const std::string &Method, bool External) const {
|
||||
auto Offset = (External ? 0 : 4);
|
||||
if(Method == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
return LogFlags_[Offset+LOG_GET];
|
||||
if(Method == Poco::Net::HTTPRequest::HTTP_POST)
|
||||
return LogFlags_[Offset+LOG_POST];
|
||||
if(Method == Poco::Net::HTTPRequest::HTTP_PUT)
|
||||
return LogFlags_[Offset+LOG_PUT];
|
||||
if(Method == Poco::Net::HTTPRequest::HTTP_DELETE)
|
||||
return LogFlags_[Offset+LOG_DELETE];
|
||||
if (Method == Poco::Net::HTTPRequest::HTTP_GET)
|
||||
return LogFlags_[Offset + LOG_GET];
|
||||
if (Method == Poco::Net::HTTPRequest::HTTP_POST)
|
||||
return LogFlags_[Offset + LOG_POST];
|
||||
if (Method == Poco::Net::HTTPRequest::HTTP_PUT)
|
||||
return LogFlags_[Offset + LOG_PUT];
|
||||
if (Method == Poco::Net::HTTPRequest::HTTP_DELETE)
|
||||
return LogFlags_[Offset + LOG_DELETE];
|
||||
return false;
|
||||
};
|
||||
|
||||
[[nodiscard]] inline bool LogBadTokens(bool External) const {
|
||||
return LogBadTokens_[ (External ? 0 : 1) ];
|
||||
return LogBadTokens_[(External ? 0 : 1)];
|
||||
};
|
||||
|
||||
private:
|
||||
std::array<bool,8> LogFlags_{false};
|
||||
std::array<bool,2> LogBadTokens_{false};
|
||||
std::array<bool, 8> LogFlags_{false};
|
||||
std::array<bool, 2> LogBadTokens_{false};
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,5 +4,4 @@
|
||||
|
||||
#include "RESTAPI_Handler.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
} // namespace OpenWifi
|
||||
namespace OpenWifi {} // namespace OpenWifi
|
||||
@@ -4,27 +4,27 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
|
||||
#include "Poco/Net/HTTPRequestHandler.h"
|
||||
#include "Poco/Logger.h"
|
||||
#include "Poco/DeflatingStream.h"
|
||||
#include "Poco/JSON/Object.h"
|
||||
#include "Poco/JSON/Parser.h"
|
||||
#include "Poco/Logger.h"
|
||||
#include "Poco/Net/HTTPRequestHandler.h"
|
||||
#include "Poco/Net/HTTPResponse.h"
|
||||
#include "Poco/Net/HTTPServerResponse.h"
|
||||
#include "Poco/DeflatingStream.h"
|
||||
#include "Poco/TemporaryFile.h"
|
||||
#include "Poco/Net/OAuth20Credentials.h"
|
||||
#include "Poco/TemporaryFile.h"
|
||||
|
||||
#include "framework/ow_constants.h"
|
||||
#include "RESTObjects/RESTAPI_SecurityObjects.h"
|
||||
#include "framework/AuthClient.h"
|
||||
#include "framework/RESTAPI_GenericServerAccounting.h"
|
||||
#include "framework/RESTAPI_RateLimiter.h"
|
||||
#include "framework/utils.h"
|
||||
#include "framework/RESTAPI_utils.h"
|
||||
#include "framework/AuthClient.h"
|
||||
#include "RESTObjects/RESTAPI_SecurityObjects.h"
|
||||
#include "framework/ow_constants.h"
|
||||
#include "framework/utils.h"
|
||||
|
||||
#if defined(TIP_SECURITY_SERVICE)
|
||||
#include "AuthService.h"
|
||||
@@ -37,42 +37,32 @@ namespace OpenWifi {
|
||||
class RESTAPIHandler : public Poco::Net::HTTPRequestHandler {
|
||||
public:
|
||||
struct QueryBlock {
|
||||
uint64_t StartDate = 0 , EndDate = 0 , Offset = 0 , Limit = 0, LogType = 0 ;
|
||||
uint64_t StartDate = 0, EndDate = 0, Offset = 0, Limit = 0, LogType = 0;
|
||||
std::string SerialNumber, Filter;
|
||||
std::vector<std::string> Select;
|
||||
bool Lifetime=false, LastOnly=false, Newest=false, CountOnly=false, AdditionalInfo=false;
|
||||
bool Lifetime = false, LastOnly = false, Newest = false, CountOnly = false,
|
||||
AdditionalInfo = false;
|
||||
};
|
||||
typedef std::map<std::string, std::string> BindingMap;
|
||||
|
||||
struct RateLimit {
|
||||
int64_t Interval=1000;
|
||||
int64_t MaxCalls=10;
|
||||
int64_t Interval = 1000;
|
||||
int64_t MaxCalls = 10;
|
||||
};
|
||||
|
||||
RESTAPIHandler( BindingMap map,
|
||||
Poco::Logger &l,
|
||||
std::vector<std::string> Methods,
|
||||
RESTAPI_GenericServerAccounting & Server,
|
||||
uint64_t TransactionId,
|
||||
bool Internal,
|
||||
bool AlwaysAuthorize=true,
|
||||
bool RateLimited=false,
|
||||
const RateLimit & Profile = RateLimit{.Interval=1000,.MaxCalls=100},
|
||||
bool SubscriberOnly=false)
|
||||
: Bindings_(std::move(map)),
|
||||
Logger_(l),
|
||||
Methods_(std::move(Methods)),
|
||||
Internal_(Internal),
|
||||
RateLimited_(RateLimited),
|
||||
SubOnlyService_(SubscriberOnly),
|
||||
AlwaysAuthorize_(AlwaysAuthorize),
|
||||
Server_(Server),
|
||||
MyRates_(Profile),
|
||||
TransactionId_(TransactionId)
|
||||
{
|
||||
}
|
||||
RESTAPIHandler(BindingMap map, Poco::Logger &l, std::vector<std::string> Methods,
|
||||
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
|
||||
bool Internal, bool AlwaysAuthorize = true, bool RateLimited = false,
|
||||
const RateLimit &Profile = RateLimit{.Interval = 1000, .MaxCalls = 100},
|
||||
bool SubscriberOnly = false)
|
||||
: Bindings_(std::move(map)), Logger_(l), Methods_(std::move(Methods)),
|
||||
Internal_(Internal), RateLimited_(RateLimited), SubOnlyService_(SubscriberOnly),
|
||||
AlwaysAuthorize_(AlwaysAuthorize), Server_(Server), MyRates_(Profile),
|
||||
TransactionId_(TransactionId) {}
|
||||
|
||||
inline bool RoleIsAuthorized([[maybe_unused]] const std::string & Path, [[maybe_unused]] const std::string & Method, [[maybe_unused]] std::string & Reason) {
|
||||
inline bool RoleIsAuthorized([[maybe_unused]] const std::string &Path,
|
||||
[[maybe_unused]] const std::string &Method,
|
||||
[[maybe_unused]] std::string &Reason) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -85,31 +75,33 @@ namespace OpenWifi {
|
||||
// std::string th_name = "restsvr_" + std::to_string(TransactionId_);
|
||||
// Utils::SetThreadName(th_name.c_str());
|
||||
|
||||
if(Request->getContentLength()>0) {
|
||||
if(Request->getContentType().find("application/json")!=std::string::npos) {
|
||||
ParsedBody_ = IncomingParser_.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>();
|
||||
if (Request->getContentLength() > 0) {
|
||||
if (Request->getContentType().find("application/json") != std::string::npos) {
|
||||
ParsedBody_ = IncomingParser_.parse(Request->stream())
|
||||
.extract<Poco::JSON::Object::Ptr>();
|
||||
}
|
||||
}
|
||||
|
||||
if(RateLimited_ && RESTAPI_RateLimiter()->IsRateLimited(RequestIn,MyRates_.Interval, MyRates_.MaxCalls)) {
|
||||
if (RateLimited_ && RESTAPI_RateLimiter()->IsRateLimited(
|
||||
RequestIn, MyRates_.Interval, MyRates_.MaxCalls)) {
|
||||
return UnAuthorized(RESTAPI::Errors::RATE_LIMIT_EXCEEDED);
|
||||
}
|
||||
|
||||
if (!ContinueProcessing())
|
||||
return;
|
||||
|
||||
bool Expired=false, Contacted=false;
|
||||
bool Expired = false, Contacted = false;
|
||||
if (AlwaysAuthorize_ && !IsAuthorized(Expired, Contacted, SubOnlyService_)) {
|
||||
if(Expired)
|
||||
if (Expired)
|
||||
return UnAuthorized(RESTAPI::Errors::EXPIRED_TOKEN);
|
||||
if(Contacted)
|
||||
if (Contacted)
|
||||
return UnAuthorized(RESTAPI::Errors::INVALID_TOKEN);
|
||||
else
|
||||
return UnAuthorized(RESTAPI::Errors::SECURITY_SERVICE_UNREACHABLE);
|
||||
}
|
||||
|
||||
std::string Reason;
|
||||
if(!RoleIsAuthorized(RequestIn.getURI(), Request->getMethod(), Reason)) {
|
||||
if (!RoleIsAuthorized(RequestIn.getURI(), Request->getMethod(), Reason)) {
|
||||
return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED);
|
||||
}
|
||||
|
||||
@@ -130,13 +122,17 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool NeedAdditionalInfo() const { return QB_.AdditionalInfo; }
|
||||
[[nodiscard]] inline const std::vector<std::string> & SelectedRecords() const { return QB_.Select; }
|
||||
[[nodiscard]] inline const std::vector<std::string> &SelectedRecords() const {
|
||||
return QB_.Select;
|
||||
}
|
||||
|
||||
inline static bool ParseBindings(const std::string & Request, const std::list<std::string> & EndPoints, BindingMap &bindings) {
|
||||
inline static bool ParseBindings(const std::string &Request,
|
||||
const std::list<std::string> &EndPoints,
|
||||
BindingMap &bindings) {
|
||||
bindings.clear();
|
||||
auto PathItems = Poco::StringTokenizer(Request, "/");
|
||||
|
||||
for(const auto &EndPoint:EndPoints) {
|
||||
for (const auto &EndPoint : EndPoints) {
|
||||
auto ParamItems = Poco::StringTokenizer(EndPoint, "/");
|
||||
if (PathItems.count() != ParamItems.count())
|
||||
continue;
|
||||
@@ -153,7 +149,7 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
}
|
||||
if(Matched)
|
||||
if (Matched)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -180,44 +176,57 @@ namespace OpenWifi {
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline uint64_t GetParameter(const std::string &Name, const uint64_t Default) {
|
||||
auto Hint = std::find_if(Parameters_.begin(),Parameters_.end(),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==Parameters_.end() || !is_number(Hint->second))
|
||||
[[nodiscard]] inline uint64_t GetParameter(const std::string &Name,
|
||||
const uint64_t Default) {
|
||||
auto Hint = std::find_if(
|
||||
Parameters_.begin(), Parameters_.end(),
|
||||
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
|
||||
if (Hint == Parameters_.end() || !is_number(Hint->second))
|
||||
return Default;
|
||||
return std::stoull(Hint->second);
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool GetBoolParameter(const std::string &Name, bool Default=false) {
|
||||
auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==end(Parameters_) || !is_bool(Hint->second))
|
||||
[[nodiscard]] inline bool GetBoolParameter(const std::string &Name, bool Default = false) {
|
||||
auto Hint = std::find_if(
|
||||
begin(Parameters_), end(Parameters_),
|
||||
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
|
||||
if (Hint == end(Parameters_) || !is_bool(Hint->second))
|
||||
return Default;
|
||||
return Hint->second=="true";
|
||||
return Hint->second == "true";
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::string GetParameter(const std::string &Name, const std::string &Default="") {
|
||||
auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==end(Parameters_))
|
||||
[[nodiscard]] inline std::string GetParameter(const std::string &Name,
|
||||
const std::string &Default = "") {
|
||||
auto Hint = std::find_if(
|
||||
begin(Parameters_), end(Parameters_),
|
||||
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
|
||||
if (Hint == end(Parameters_))
|
||||
return Default;
|
||||
return Hint->second;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool HasParameter(const std::string &Name, std::string &Value) {
|
||||
auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==end(Parameters_))
|
||||
auto Hint = std::find_if(
|
||||
begin(Parameters_), end(Parameters_),
|
||||
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
|
||||
if (Hint == end(Parameters_))
|
||||
return false;
|
||||
Value = Hint->second;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool HasParameter(const std::string &Name, uint64_t & Value) {
|
||||
auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
|
||||
if(Hint==end(Parameters_))
|
||||
[[nodiscard]] inline bool HasParameter(const std::string &Name, uint64_t &Value) {
|
||||
auto Hint = std::find_if(
|
||||
begin(Parameters_), end(Parameters_),
|
||||
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
|
||||
if (Hint == end(Parameters_))
|
||||
return false;
|
||||
Value = std::stoull(Hint->second);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline const std::string & GetBinding(const std::string &Name, const std::string &Default="") {
|
||||
[[nodiscard]] inline const std::string &GetBinding(const std::string &Name,
|
||||
const std::string &Default = "") {
|
||||
auto E = Bindings_.find(Poco::toLower(Name));
|
||||
if (E == Bindings_.end())
|
||||
return Default;
|
||||
@@ -236,68 +245,75 @@ namespace OpenWifi {
|
||||
return Return;
|
||||
}
|
||||
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, Types::UUIDvec_t & Value) {
|
||||
if(O->has(Field) && O->isArray(Field)) {
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O,
|
||||
const std::string &Field, Types::UUIDvec_t &Value) {
|
||||
if (O->has(Field) && O->isArray(Field)) {
|
||||
auto Arr = O->getArray(Field);
|
||||
for(const auto &i:*Arr)
|
||||
for (const auto &i : *Arr)
|
||||
Value.emplace_back(i.toString());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, std::string &Value) {
|
||||
if(O->has(Field)) {
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O,
|
||||
const std::string &Field, std::string &Value) {
|
||||
if (O->has(Field)) {
|
||||
Value = O->get(Field).toString();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, uint64_t &Value) {
|
||||
if(O->has(Field)) {
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O,
|
||||
const std::string &Field, uint64_t &Value) {
|
||||
if (O->has(Field)) {
|
||||
Value = O->get(Field);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, bool &Value) {
|
||||
if(O->has(Field)) {
|
||||
Value = O->get(Field).toString()=="true";
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O,
|
||||
const std::string &Field, bool &Value) {
|
||||
if (O->has(Field)) {
|
||||
Value = O->get(Field).toString() == "true";
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, double &Value) {
|
||||
if(O->has(Field)) {
|
||||
Value = (double) O->get(Field);
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O,
|
||||
const std::string &Field, double &Value) {
|
||||
if (O->has(Field)) {
|
||||
Value = (double)O->get(Field);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, Poco::Data::BLOB &Value) {
|
||||
if(O->has(Field)) {
|
||||
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O,
|
||||
const std::string &Field, Poco::Data::BLOB &Value) {
|
||||
if (O->has(Field)) {
|
||||
std::string Content = O->get(Field).toString();
|
||||
auto DecodedBlob = Utils::base64decode(Content);
|
||||
Value.assignRaw((const unsigned char *)&DecodedBlob[0],DecodedBlob.size());
|
||||
Value.assignRaw((const unsigned char *)&DecodedBlob[0], DecodedBlob.size());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
template <typename T> bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, const T &value, T & assignee) {
|
||||
if(O->has(Field)) {
|
||||
template <typename T>
|
||||
bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field,
|
||||
const T &value, T &assignee) {
|
||||
if (O->has(Field)) {
|
||||
assignee = value;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
inline void SetCommonHeaders(bool CloseConnection=false) {
|
||||
inline void SetCommonHeaders(bool CloseConnection = false) {
|
||||
Response->setVersion(Poco::Net::HTTPMessage::HTTP_1_1);
|
||||
Response->setChunkedTransferEncoding(true);
|
||||
Response->setContentType("application/json");
|
||||
@@ -308,7 +324,7 @@ namespace OpenWifi {
|
||||
Response->set("Access-Control-Allow-Origin", "*");
|
||||
}
|
||||
Response->set("Vary", "Origin, Accept-Encoding");
|
||||
if(CloseConnection) {
|
||||
if (CloseConnection) {
|
||||
Response->set("Connection", "close");
|
||||
Response->setKeepAlive(false);
|
||||
} else {
|
||||
@@ -329,7 +345,7 @@ namespace OpenWifi {
|
||||
}
|
||||
Response->set("Access-Control-Allow-Methods", MakeList(Methods_));
|
||||
auto RequestHeaders = Request->find("Access-Control-Request-Headers");
|
||||
if(RequestHeaders!=Request->end())
|
||||
if (RequestHeaders != Request->end())
|
||||
Response->set("Access-Control-Allow-Headers", RequestHeaders->second);
|
||||
Response->set("Vary", "Origin, Accept-Encoding");
|
||||
Response->set("Access-Control-Allow-Credentials", "true");
|
||||
@@ -342,21 +358,24 @@ namespace OpenWifi {
|
||||
Response->send();
|
||||
}
|
||||
|
||||
inline void PrepareResponse(Poco::Net::HTTPResponse::HTTPStatus Status = Poco::Net::HTTPResponse::HTTP_OK,
|
||||
inline void PrepareResponse(
|
||||
Poco::Net::HTTPResponse::HTTPStatus Status = Poco::Net::HTTPResponse::HTTP_OK,
|
||||
bool CloseConnection = false) {
|
||||
Response->setStatus(Status);
|
||||
SetCommonHeaders(CloseConnection);
|
||||
}
|
||||
|
||||
inline void BadRequest(const OpenWifi::RESTAPI::Errors::msg &E, const std::string & Extra="") {
|
||||
inline void BadRequest(const OpenWifi::RESTAPI::Errors::msg &E,
|
||||
const std::string &Extra = "") {
|
||||
PrepareResponse(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
|
||||
Poco::JSON::Object ErrorObject;
|
||||
ErrorObject.set("ErrorCode",400);
|
||||
ErrorObject.set("ErrorDetails",Request->getMethod());
|
||||
if(Extra.empty())
|
||||
ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ;
|
||||
ErrorObject.set("ErrorCode", 400);
|
||||
ErrorObject.set("ErrorDetails", Request->getMethod());
|
||||
if (Extra.empty())
|
||||
ErrorObject.set("ErrorDescription", fmt::format("{}: {}", E.err_num, E.err_txt));
|
||||
else
|
||||
ErrorObject.set("ErrorDescription",fmt::format("{}: {} ({})",E.err_num,E.err_txt, Extra)) ;
|
||||
ErrorObject.set("ErrorDescription",
|
||||
fmt::format("{}: {} ({})", E.err_num, E.err_txt, Extra));
|
||||
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
|
||||
@@ -365,9 +384,9 @@ namespace OpenWifi {
|
||||
inline void InternalError(const OpenWifi::RESTAPI::Errors::msg &E) {
|
||||
PrepareResponse(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
|
||||
Poco::JSON::Object ErrorObject;
|
||||
ErrorObject.set("ErrorCode",500);
|
||||
ErrorObject.set("ErrorDetails",Request->getMethod());
|
||||
ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ;
|
||||
ErrorObject.set("ErrorCode", 500);
|
||||
ErrorObject.set("ErrorDetails", Request->getMethod());
|
||||
ErrorObject.set("ErrorDescription", fmt::format("{}: {}", E.err_num, E.err_txt));
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
|
||||
}
|
||||
@@ -375,9 +394,9 @@ namespace OpenWifi {
|
||||
inline void UnAuthorized(const OpenWifi::RESTAPI::Errors::msg &E) {
|
||||
PrepareResponse(Poco::Net::HTTPResponse::HTTP_FORBIDDEN);
|
||||
Poco::JSON::Object ErrorObject;
|
||||
ErrorObject.set("ErrorCode",E.err_num);
|
||||
ErrorObject.set("ErrorDetails",Request->getMethod());
|
||||
ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ;
|
||||
ErrorObject.set("ErrorCode", E.err_num);
|
||||
ErrorObject.set("ErrorDetails", Request->getMethod());
|
||||
ErrorObject.set("ErrorDescription", fmt::format("{}: {}", E.err_num, E.err_txt));
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
|
||||
}
|
||||
@@ -385,23 +404,22 @@ namespace OpenWifi {
|
||||
inline void NotFound() {
|
||||
PrepareResponse(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
|
||||
Poco::JSON::Object ErrorObject;
|
||||
ErrorObject.set("ErrorCode",404);
|
||||
ErrorObject.set("ErrorDetails",Request->getMethod());
|
||||
const auto & E = OpenWifi::RESTAPI::Errors::Error404;
|
||||
ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ;
|
||||
ErrorObject.set("ErrorCode", 404);
|
||||
ErrorObject.set("ErrorDetails", Request->getMethod());
|
||||
const auto &E = OpenWifi::RESTAPI::Errors::Error404;
|
||||
ErrorObject.set("ErrorDescription", fmt::format("{}: {}", E.err_num, E.err_txt));
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
|
||||
poco_debug(Logger_,fmt::format("RES-NOTFOUND: User='{}@{}' Method='{}' Path='{}",
|
||||
Requester(),
|
||||
poco_debug(Logger_,
|
||||
fmt::format("RES-NOTFOUND: User='{}@{}' Method='{}' Path='{}", Requester(),
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
Request->getMethod(),
|
||||
Request->getURI()));
|
||||
Request->getMethod(), Request->getURI()));
|
||||
}
|
||||
|
||||
inline void OK() {
|
||||
PrepareResponse();
|
||||
if( Request->getMethod()==Poco::Net::HTTPRequest::HTTP_DELETE ||
|
||||
Request->getMethod()==Poco::Net::HTTPRequest::HTTP_OPTIONS) {
|
||||
if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE ||
|
||||
Request->getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS) {
|
||||
Response->send();
|
||||
} else {
|
||||
Poco::JSON::Object ErrorObject;
|
||||
@@ -413,85 +431,86 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
inline void SendCompressedTarFile(const std::string & FileName, const std::string & Content) {
|
||||
inline void SendCompressedTarFile(const std::string &FileName, const std::string &Content) {
|
||||
Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
|
||||
SetCommonHeaders();
|
||||
Response->set("Content-Type","application/gzip");
|
||||
Response->set("Content-Disposition", "attachment; filename=" + FileName );
|
||||
Response->set("Content-Transfer-Encoding","binary");
|
||||
Response->set("Content-Type", "application/gzip");
|
||||
Response->set("Content-Disposition", "attachment; filename=" + FileName);
|
||||
Response->set("Content-Transfer-Encoding", "binary");
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
Response->set("Cache-Control", "no-store");
|
||||
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
Response->setStatus(Poco::Net::HTTPResponse::HTTP_OK);
|
||||
Response->setContentLength(Content.size());
|
||||
Response->setChunkedTransferEncoding(true);
|
||||
std::ostream& OutputStream = Response->send();
|
||||
std::ostream &OutputStream = Response->send();
|
||||
OutputStream << Content;
|
||||
}
|
||||
|
||||
inline void SendFile(Poco::File & File, const std::string & UUID) {
|
||||
inline void SendFile(Poco::File &File, const std::string &UUID) {
|
||||
Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
|
||||
SetCommonHeaders();
|
||||
Response->set("Content-Type","application/octet-stream");
|
||||
Response->set("Content-Disposition", "attachment; filename=" + UUID );
|
||||
Response->set("Content-Transfer-Encoding","binary");
|
||||
Response->set("Content-Type", "application/octet-stream");
|
||||
Response->set("Content-Disposition", "attachment; filename=" + UUID);
|
||||
Response->set("Content-Transfer-Encoding", "binary");
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
Response->set("Cache-Control", "no-store");
|
||||
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
Response->setContentLength(File.getSize());
|
||||
Response->sendFile(File.path(),"application/octet-stream");
|
||||
Response->sendFile(File.path(), "application/octet-stream");
|
||||
}
|
||||
|
||||
inline void SendFile(Poco::File & File) {
|
||||
inline void SendFile(Poco::File &File) {
|
||||
Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
|
||||
SetCommonHeaders();
|
||||
Poco::Path P(File.path());
|
||||
auto MT = Utils::FindMediaType(File);
|
||||
if(MT.Encoding==Utils::BINARY) {
|
||||
Response->set("Content-Transfer-Encoding","binary");
|
||||
if (MT.Encoding == Utils::BINARY) {
|
||||
Response->set("Content-Transfer-Encoding", "binary");
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
}
|
||||
Response->set("Cache-Control", "no-store");
|
||||
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
Response->sendFile(File.path(),MT.ContentType);
|
||||
Response->sendFile(File.path(), MT.ContentType);
|
||||
}
|
||||
|
||||
inline void SendFile(Poco::TemporaryFile &TempAvatar, [[maybe_unused]] const std::string &Type, const std::string & Name) {
|
||||
inline void SendFile(Poco::TemporaryFile &TempAvatar,
|
||||
[[maybe_unused]] const std::string &Type, const std::string &Name) {
|
||||
Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
|
||||
SetCommonHeaders();
|
||||
auto MT = Utils::FindMediaType(Name);
|
||||
if(MT.Encoding==Utils::BINARY) {
|
||||
Response->set("Content-Transfer-Encoding","binary");
|
||||
if (MT.Encoding == Utils::BINARY) {
|
||||
Response->set("Content-Transfer-Encoding", "binary");
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
}
|
||||
Response->set("Content-Disposition", "attachment; filename=" + Name );
|
||||
Response->set("Content-Disposition", "attachment; filename=" + Name);
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
Response->set("Cache-Control", "no-store");
|
||||
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
Response->setContentLength(TempAvatar.getSize());
|
||||
Response->sendFile(TempAvatar.path(),MT.ContentType);
|
||||
Response->sendFile(TempAvatar.path(), MT.ContentType);
|
||||
}
|
||||
|
||||
inline void SendFileContent(const std::string &Content, const std::string &Type, const std::string & Name) {
|
||||
inline void SendFileContent(const std::string &Content, const std::string &Type,
|
||||
const std::string &Name) {
|
||||
Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
|
||||
SetCommonHeaders();
|
||||
auto MT = Utils::FindMediaType(Name);
|
||||
if(MT.Encoding==Utils::BINARY) {
|
||||
Response->set("Content-Transfer-Encoding","binary");
|
||||
if (MT.Encoding == Utils::BINARY) {
|
||||
Response->set("Content-Transfer-Encoding", "binary");
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
}
|
||||
Response->set("Content-Disposition", "attachment; filename=" + Name );
|
||||
Response->set("Content-Disposition", "attachment; filename=" + Name);
|
||||
Response->set("Accept-Ranges", "bytes");
|
||||
Response->set("Cache-Control", "no-store");
|
||||
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
|
||||
Response->setContentLength(Content.size());
|
||||
Response->setContentType(Type );
|
||||
auto & OutputStream = Response->send();
|
||||
OutputStream << Content ;
|
||||
Response->setContentType(Type);
|
||||
auto &OutputStream = Response->send();
|
||||
OutputStream << Content;
|
||||
}
|
||||
|
||||
inline void SendHTMLFileBack(Poco::File & File,
|
||||
const Types::StringPairVec & FormVars) {
|
||||
inline void SendHTMLFileBack(Poco::File &File, const Types::StringPairVec &FormVars) {
|
||||
Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
|
||||
SetCommonHeaders();
|
||||
Response->set("Pragma", "private");
|
||||
@@ -501,13 +520,14 @@ namespace OpenWifi {
|
||||
Response->setContentLength(FormContent.size());
|
||||
Response->setChunkedTransferEncoding(true);
|
||||
Response->setContentType("text/html");
|
||||
std::ostream& ostr = Response->send();
|
||||
std::ostream &ostr = Response->send();
|
||||
ostr << FormContent;
|
||||
}
|
||||
|
||||
inline void ReturnStatus(Poco::Net::HTTPResponse::HTTPStatus Status, bool CloseConnection=false) {
|
||||
inline void ReturnStatus(Poco::Net::HTTPResponse::HTTPStatus Status,
|
||||
bool CloseConnection = false) {
|
||||
PrepareResponse(Status, CloseConnection);
|
||||
if(Status == Poco::Net::HTTPResponse::HTTP_NO_CONTENT) {
|
||||
if (Status == Poco::Net::HTTPResponse::HTTP_NO_CONTENT) {
|
||||
Response->setContentLength(0);
|
||||
Response->erase("Content-Type");
|
||||
Response->setChunkedTransferEncoding(false);
|
||||
@@ -519,7 +539,8 @@ namespace OpenWifi {
|
||||
if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS) {
|
||||
ProcessOptions();
|
||||
return false;
|
||||
} else if (std::find(Methods_.begin(), Methods_.end(), Request->getMethod()) == Methods_.end()) {
|
||||
} else if (std::find(Methods_.begin(), Methods_.end(), Request->getMethod()) ==
|
||||
Methods_.end()) {
|
||||
BadRequest(RESTAPI::Errors::UnsupportedHTTPMethod);
|
||||
return false;
|
||||
}
|
||||
@@ -527,19 +548,20 @@ namespace OpenWifi {
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool IsAuthorized(bool & Expired, bool & Contacted, bool SubOnly = false );
|
||||
inline bool IsAuthorized(bool &Expired, bool &Contacted, bool SubOnly = false);
|
||||
|
||||
inline void ReturnObject(Poco::JSON::Object &Object) {
|
||||
PrepareResponse();
|
||||
if(Request!= nullptr) {
|
||||
if (Request != nullptr) {
|
||||
// can we compress ???
|
||||
auto AcceptedEncoding = Request->find("Accept-Encoding");
|
||||
if(AcceptedEncoding!=Request->end()) {
|
||||
if( AcceptedEncoding->second.find("gzip")!=std::string::npos ||
|
||||
AcceptedEncoding->second.find("compress")!=std::string::npos) {
|
||||
if (AcceptedEncoding != Request->end()) {
|
||||
if (AcceptedEncoding->second.find("gzip") != std::string::npos ||
|
||||
AcceptedEncoding->second.find("compress") != std::string::npos) {
|
||||
Response->set("Content-Encoding", "gzip");
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::DeflatingOutputStream deflater(Answer, Poco::DeflatingStreamBuf::STREAM_GZIP);
|
||||
Poco::DeflatingOutputStream deflater(Answer,
|
||||
Poco::DeflatingStreamBuf::STREAM_GZIP);
|
||||
Poco::JSON::Stringifier::stringify(Object, deflater);
|
||||
deflater.close();
|
||||
return;
|
||||
@@ -552,15 +574,16 @@ namespace OpenWifi {
|
||||
|
||||
inline void ReturnRawJSON(const std::string &json_doc) {
|
||||
PrepareResponse();
|
||||
if(Request!= nullptr) {
|
||||
if (Request != nullptr) {
|
||||
// can we compress ???
|
||||
auto AcceptedEncoding = Request->find("Accept-Encoding");
|
||||
if(AcceptedEncoding!=Request->end()) {
|
||||
if( AcceptedEncoding->second.find("gzip")!=std::string::npos ||
|
||||
AcceptedEncoding->second.find("compress")!=std::string::npos) {
|
||||
if (AcceptedEncoding != Request->end()) {
|
||||
if (AcceptedEncoding->second.find("gzip") != std::string::npos ||
|
||||
AcceptedEncoding->second.find("compress") != std::string::npos) {
|
||||
Response->set("Content-Encoding", "gzip");
|
||||
std::ostream &Answer = Response->send();
|
||||
Poco::DeflatingOutputStream deflater(Answer, Poco::DeflatingStreamBuf::STREAM_GZIP);
|
||||
Poco::DeflatingOutputStream deflater(Answer,
|
||||
Poco::DeflatingStreamBuf::STREAM_GZIP);
|
||||
deflater << json_doc;
|
||||
deflater.close();
|
||||
return;
|
||||
@@ -578,48 +601,52 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
inline bool InitQueryBlock() {
|
||||
if(QueryBlockInitialized_)
|
||||
if (QueryBlockInitialized_)
|
||||
return true;
|
||||
QueryBlockInitialized_=true;
|
||||
QueryBlockInitialized_ = true;
|
||||
QB_.SerialNumber = GetParameter(RESTAPI::Protocol::SERIALNUMBER, "");
|
||||
QB_.StartDate = GetParameter(RESTAPI::Protocol::STARTDATE, 0);
|
||||
QB_.EndDate = GetParameter(RESTAPI::Protocol::ENDDATE, 0);
|
||||
QB_.Offset = GetParameter(RESTAPI::Protocol::OFFSET, 0);
|
||||
QB_.Limit = GetParameter(RESTAPI::Protocol::LIMIT, 100);
|
||||
QB_.Filter = GetParameter(RESTAPI::Protocol::FILTER, "");
|
||||
QB_.Lifetime = GetBoolParameter(RESTAPI::Protocol::LIFETIME,false);
|
||||
QB_.LogType = GetParameter(RESTAPI::Protocol::LOGTYPE,0);
|
||||
QB_.LastOnly = GetBoolParameter(RESTAPI::Protocol::LASTONLY,false);
|
||||
QB_.Newest = GetBoolParameter(RESTAPI::Protocol::NEWEST,false);
|
||||
QB_.CountOnly = GetBoolParameter(RESTAPI::Protocol::COUNTONLY,false);
|
||||
QB_.AdditionalInfo = GetBoolParameter(RESTAPI::Protocol::WITHEXTENDEDINFO,false);
|
||||
QB_.Lifetime = GetBoolParameter(RESTAPI::Protocol::LIFETIME, false);
|
||||
QB_.LogType = GetParameter(RESTAPI::Protocol::LOGTYPE, 0);
|
||||
QB_.LastOnly = GetBoolParameter(RESTAPI::Protocol::LASTONLY, false);
|
||||
QB_.Newest = GetBoolParameter(RESTAPI::Protocol::NEWEST, false);
|
||||
QB_.CountOnly = GetBoolParameter(RESTAPI::Protocol::COUNTONLY, false);
|
||||
QB_.AdditionalInfo = GetBoolParameter(RESTAPI::Protocol::WITHEXTENDEDINFO, false);
|
||||
|
||||
auto RawSelect = GetParameter(RESTAPI::Protocol::SELECT, "");
|
||||
|
||||
auto Entries = Poco::StringTokenizer(RawSelect,",");
|
||||
for(const auto &i:Entries) {
|
||||
auto Entries = Poco::StringTokenizer(RawSelect, ",");
|
||||
for (const auto &i : Entries) {
|
||||
QB_.Select.emplace_back(i);
|
||||
}
|
||||
if(QB_.Offset<1)
|
||||
QB_.Offset=0;
|
||||
if (QB_.Offset < 1)
|
||||
QB_.Offset = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline uint64_t Get(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, uint64_t Default=0){
|
||||
if(Obj->has(Parameter))
|
||||
[[nodiscard]] inline uint64_t Get(const char *Parameter, const Poco::JSON::Object::Ptr &Obj,
|
||||
uint64_t Default = 0) {
|
||||
if (Obj->has(Parameter))
|
||||
return Obj->get(Parameter);
|
||||
return Default;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::string GetS(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, const std::string & Default=""){
|
||||
if(Obj->has(Parameter))
|
||||
[[nodiscard]] inline std::string GetS(const char *Parameter,
|
||||
const Poco::JSON::Object::Ptr &Obj,
|
||||
const std::string &Default = "") {
|
||||
if (Obj->has(Parameter))
|
||||
return Obj->get(Parameter).toString();
|
||||
return Default;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline bool GetB(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, bool Default=false){
|
||||
if(Obj->has(Parameter))
|
||||
return Obj->get(Parameter).toString()=="true";
|
||||
[[nodiscard]] inline bool GetB(const char *Parameter, const Poco::JSON::Object::Ptr &Obj,
|
||||
bool Default = false) {
|
||||
if (Obj->has(Parameter))
|
||||
return Obj->get(Parameter).toString() == "true";
|
||||
return Default;
|
||||
}
|
||||
|
||||
@@ -627,15 +654,15 @@ namespace OpenWifi {
|
||||
return RESTAPIHandler::Get(RESTAPI::Protocol::WHEN, Obj);
|
||||
}
|
||||
|
||||
template<typename T> void ReturnObject(const char *Name, const std::vector<T> & Objects) {
|
||||
template <typename T> void ReturnObject(const char *Name, const std::vector<T> &Objects) {
|
||||
Poco::JSON::Object Answer;
|
||||
RESTAPI_utils::field_to_json(Answer,Name,Objects);
|
||||
RESTAPI_utils::field_to_json(Answer, Name, Objects);
|
||||
ReturnObject(Answer);
|
||||
}
|
||||
|
||||
template<typename T> void Object(const char *Name, const std::vector<T> & Objects) {
|
||||
template <typename T> void Object(const char *Name, const std::vector<T> &Objects) {
|
||||
Poco::JSON::Object Answer;
|
||||
RESTAPI_utils::field_to_json(Answer,Name,Objects);
|
||||
RESTAPI_utils::field_to_json(Answer, Name, Objects);
|
||||
ReturnObject(Answer);
|
||||
}
|
||||
|
||||
@@ -645,31 +672,32 @@ namespace OpenWifi {
|
||||
ReturnObject(Answer);
|
||||
}
|
||||
|
||||
Poco::Logger & Logger() { return Logger_; }
|
||||
Poco::Logger &Logger() { return Logger_; }
|
||||
|
||||
virtual void DoGet() = 0 ;
|
||||
virtual void DoDelete() = 0 ;
|
||||
virtual void DoPost() = 0 ;
|
||||
virtual void DoPut() = 0 ;
|
||||
virtual void DoGet() = 0;
|
||||
virtual void DoDelete() = 0;
|
||||
virtual void DoPost() = 0;
|
||||
virtual void DoPut() = 0;
|
||||
|
||||
Poco::Net::HTTPServerRequest *Request= nullptr;
|
||||
Poco::Net::HTTPServerResponse *Response= nullptr;
|
||||
Poco::Net::HTTPServerRequest *Request = nullptr;
|
||||
Poco::Net::HTTPServerResponse *Response = nullptr;
|
||||
SecurityObjects::UserInfoAndPolicy UserInfo_;
|
||||
QueryBlock QB_;
|
||||
const std::string & Requester() const { return REST_Requester_; }
|
||||
const std::string &Requester() const { return REST_Requester_; }
|
||||
|
||||
protected:
|
||||
BindingMap Bindings_;
|
||||
Poco::URI::QueryParameters Parameters_;
|
||||
Poco::Logger &Logger_;
|
||||
std::string SessionToken_;
|
||||
std::vector<std::string> Methods_;
|
||||
bool Internal_=false;
|
||||
bool RateLimited_=false;
|
||||
bool QueryBlockInitialized_=false;
|
||||
bool SubOnlyService_=false;
|
||||
bool AlwaysAuthorize_=true;
|
||||
bool Internal_ = false;
|
||||
bool RateLimited_ = false;
|
||||
bool QueryBlockInitialized_ = false;
|
||||
bool SubOnlyService_ = false;
|
||||
bool AlwaysAuthorize_ = true;
|
||||
Poco::JSON::Parser IncomingParser_;
|
||||
RESTAPI_GenericServerAccounting & Server_;
|
||||
RESTAPI_GenericServerAccounting &Server_;
|
||||
RateLimit MyRates_;
|
||||
uint64_t TransactionId_;
|
||||
Poco::JSON::Object::Ptr ParsedBody_;
|
||||
@@ -677,58 +705,64 @@ namespace OpenWifi {
|
||||
};
|
||||
|
||||
#ifdef TIP_SECURITY_SERVICE
|
||||
[[nodiscard]] bool AuthServiceIsAuthorized(Poco::Net::HTTPServerRequest & Request,std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy & UInfo, std::uint64_t TID, bool & Expired , bool Sub );
|
||||
[[nodiscard]] bool AuthServiceIsAuthorized(Poco::Net::HTTPServerRequest &Request,
|
||||
std::string &SessionToken,
|
||||
SecurityObjects::UserInfoAndPolicy &UInfo,
|
||||
std::uint64_t TID, bool &Expired, bool Sub);
|
||||
#endif
|
||||
inline bool RESTAPIHandler::IsAuthorized( bool & Expired , [[maybe_unused]] bool & Contacted , bool Sub ) {
|
||||
if(Internal_ && Request->has("X-INTERNAL-NAME")) {
|
||||
inline bool RESTAPIHandler::IsAuthorized(bool &Expired, [[maybe_unused]] bool &Contacted,
|
||||
bool Sub) {
|
||||
if (Internal_ && Request->has("X-INTERNAL-NAME")) {
|
||||
auto Allowed = MicroServiceIsValidAPIKEY(*Request);
|
||||
Contacted = true;
|
||||
if(!Allowed) {
|
||||
if(Server_.LogBadTokens(false)) {
|
||||
poco_debug(Logger_,fmt::format("I-REQ-DENIED({}): TID={} Method={} Path={}",
|
||||
if (!Allowed) {
|
||||
if (Server_.LogBadTokens(false)) {
|
||||
poco_debug(Logger_,
|
||||
fmt::format("I-REQ-DENIED({}): TID={} Method={} Path={}",
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
TransactionId_,
|
||||
Request->getMethod(), Request->getURI()));
|
||||
TransactionId_, Request->getMethod(),
|
||||
Request->getURI()));
|
||||
}
|
||||
} else {
|
||||
auto Id = Request->get("X-INTERNAL-NAME", "unknown");
|
||||
REST_Requester_ = Id;
|
||||
if(Server_.LogIt(Request->getMethod(),true)) {
|
||||
poco_debug(Logger_,fmt::format("I-REQ-ALLOWED({}): TID={} User='{}' Method={} Path={}",
|
||||
if (Server_.LogIt(Request->getMethod(), true)) {
|
||||
poco_debug(Logger_,
|
||||
fmt::format("I-REQ-ALLOWED({}): TID={} User='{}' Method={} Path={}",
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
TransactionId_,
|
||||
Id,
|
||||
Request->getMethod(), Request->getURI()));
|
||||
TransactionId_, Id, Request->getMethod(),
|
||||
Request->getURI()));
|
||||
}
|
||||
}
|
||||
return Allowed;
|
||||
} else if(!Internal_ && Request->has("X-API-KEY")) {
|
||||
} else if (!Internal_ && Request->has("X-API-KEY")) {
|
||||
SessionToken_ = Request->get("X-API-KEY", "");
|
||||
bool suspended=false;
|
||||
bool suspended = false;
|
||||
#ifdef TIP_SECURITY_SERVICE
|
||||
std::uint64_t expiresOn;
|
||||
if (AuthService()->IsValidApiKey(SessionToken_, UserInfo_.webtoken, UserInfo_.userinfo, Expired, expiresOn, suspended)) {
|
||||
if (AuthService()->IsValidApiKey(SessionToken_, UserInfo_.webtoken, UserInfo_.userinfo,
|
||||
Expired, expiresOn, suspended)) {
|
||||
#else
|
||||
if (AuthClient()->IsValidApiKey( SessionToken_, UserInfo_, TransactionId_, Expired, Contacted, suspended)) {
|
||||
if (AuthClient()->IsValidApiKey(SessionToken_, UserInfo_, TransactionId_, Expired,
|
||||
Contacted, suspended)) {
|
||||
#endif
|
||||
REST_Requester_ = UserInfo_.userinfo.email;
|
||||
if(Server_.LogIt(Request->getMethod(),true)) {
|
||||
poco_debug(Logger_,fmt::format("X-REQ-ALLOWED({}): APIKEY-ACCESS TID={} User='{}@{}' Method={} Path={}",
|
||||
UserInfo_.userinfo.email,
|
||||
TransactionId_,
|
||||
if (Server_.LogIt(Request->getMethod(), true)) {
|
||||
poco_debug(Logger_,
|
||||
fmt::format("X-REQ-ALLOWED({}): APIKEY-ACCESS TID={} User='{}@{}' "
|
||||
"Method={} Path={}",
|
||||
UserInfo_.userinfo.email, TransactionId_,
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
Request->clientAddress().toString(),
|
||||
Request->getMethod(),
|
||||
Request->getURI()));
|
||||
Request->getMethod(), Request->getURI()));
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
if(Server_.LogBadTokens(true)) {
|
||||
poco_debug(Logger_,fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}",
|
||||
if (Server_.LogBadTokens(true)) {
|
||||
poco_debug(Logger_,
|
||||
fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}",
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
TransactionId_,
|
||||
Request->getMethod(),
|
||||
TransactionId_, Request->getMethod(),
|
||||
Request->getURI()));
|
||||
}
|
||||
}
|
||||
@@ -745,27 +779,29 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
#ifdef TIP_SECURITY_SERVICE
|
||||
if (AuthServiceIsAuthorized(*Request, SessionToken_, UserInfo_, TransactionId_, Expired, Sub)) {
|
||||
if (AuthServiceIsAuthorized(*Request, SessionToken_, UserInfo_, TransactionId_, Expired,
|
||||
Sub)) {
|
||||
#else
|
||||
if (AuthClient()->IsAuthorized( SessionToken_, UserInfo_, TransactionId_, Expired, Contacted, Sub)) {
|
||||
if (AuthClient()->IsAuthorized(SessionToken_, UserInfo_, TransactionId_, Expired,
|
||||
Contacted, Sub)) {
|
||||
#endif
|
||||
REST_Requester_ = UserInfo_.userinfo.email;
|
||||
if(Server_.LogIt(Request->getMethod(),true)) {
|
||||
poco_debug(Logger_,fmt::format("X-REQ-ALLOWED({}): TID={} User='{}@{}' Method={} Path={}",
|
||||
UserInfo_.userinfo.email,
|
||||
TransactionId_,
|
||||
if (Server_.LogIt(Request->getMethod(), true)) {
|
||||
poco_debug(
|
||||
Logger_,
|
||||
fmt::format("X-REQ-ALLOWED({}): TID={} User='{}@{}' Method={} Path={}",
|
||||
UserInfo_.userinfo.email, TransactionId_,
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
Request->clientAddress().toString(),
|
||||
Request->getMethod(),
|
||||
Request->clientAddress().toString(), Request->getMethod(),
|
||||
Request->getURI()));
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
if(Server_.LogBadTokens(true)) {
|
||||
poco_debug(Logger_,fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}",
|
||||
if (Server_.LogBadTokens(true)) {
|
||||
poco_debug(Logger_,
|
||||
fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}",
|
||||
Utils::FormatIPv6(Request->clientAddress().toString()),
|
||||
TransactionId_,
|
||||
Request->getMethod(),
|
||||
TransactionId_, Request->getMethod(),
|
||||
Request->getURI()));
|
||||
}
|
||||
}
|
||||
@@ -775,52 +811,58 @@ namespace OpenWifi {
|
||||
|
||||
class RESTAPI_UnknownRequestHandler : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_UnknownRequestHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
|
||||
: RESTAPIHandler(bindings, L, std::vector<std::string>{}, Server, TransactionId, Internal) {}
|
||||
inline void DoGet() override {};
|
||||
inline void DoPost() override {};
|
||||
inline void DoPut() override {};
|
||||
inline void DoDelete() override {};
|
||||
RESTAPI_UnknownRequestHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
|
||||
RESTAPI_GenericServerAccounting &Server,
|
||||
uint64_t TransactionId, bool Internal)
|
||||
: RESTAPIHandler(bindings, L, std::vector<std::string>{}, Server, TransactionId,
|
||||
Internal) {}
|
||||
inline void DoGet() override{};
|
||||
inline void DoPost() override{};
|
||||
inline void DoPut() override{};
|
||||
inline void DoDelete() override{};
|
||||
};
|
||||
|
||||
template<class T>
|
||||
constexpr auto test_has_PathName_method(T*)
|
||||
-> decltype( T::PathName() , std::true_type{} )
|
||||
{
|
||||
template <class T>
|
||||
constexpr auto test_has_PathName_method(T *) -> decltype(T::PathName(), std::true_type{}) {
|
||||
return std::true_type{};
|
||||
}
|
||||
constexpr auto test_has_PathName_method(...) -> std::false_type
|
||||
{
|
||||
return std::false_type{};
|
||||
}
|
||||
constexpr auto test_has_PathName_method(...) -> std::false_type { return std::false_type{}; }
|
||||
|
||||
template<typename T, typename... Args>
|
||||
RESTAPIHandler * RESTAPI_Router(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger & Logger, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId) {
|
||||
static_assert(test_has_PathName_method((T*)nullptr), "Class must have a static PathName() method.");
|
||||
if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) {
|
||||
template <typename T, typename... Args>
|
||||
RESTAPIHandler *RESTAPI_Router(const std::string &RequestedPath,
|
||||
RESTAPIHandler::BindingMap &Bindings, Poco::Logger &Logger,
|
||||
RESTAPI_GenericServerAccounting &Server,
|
||||
uint64_t TransactionId) {
|
||||
static_assert(test_has_PathName_method((T *)nullptr),
|
||||
"Class must have a static PathName() method.");
|
||||
if (RESTAPIHandler::ParseBindings(RequestedPath, T::PathName(), Bindings)) {
|
||||
return new T(Bindings, Logger, Server, TransactionId, false);
|
||||
}
|
||||
|
||||
if constexpr (sizeof...(Args) == 0) {
|
||||
return new RESTAPI_UnknownRequestHandler(Bindings,Logger, Server, TransactionId, false);
|
||||
return new RESTAPI_UnknownRequestHandler(Bindings, Logger, Server, TransactionId,
|
||||
false);
|
||||
} else {
|
||||
return RESTAPI_Router<Args...>(RequestedPath, Bindings, Logger, Server, TransactionId);
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T, typename... Args>
|
||||
RESTAPIHandler * RESTAPI_Router_I(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger & Logger, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId) {
|
||||
static_assert(test_has_PathName_method((T*)nullptr), "Class must have a static PathName() method.");
|
||||
if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) {
|
||||
return new T(Bindings, Logger, Server, TransactionId, true );
|
||||
template <typename T, typename... Args>
|
||||
RESTAPIHandler *RESTAPI_Router_I(const std::string &RequestedPath,
|
||||
RESTAPIHandler::BindingMap &Bindings, Poco::Logger &Logger,
|
||||
RESTAPI_GenericServerAccounting &Server,
|
||||
uint64_t TransactionId) {
|
||||
static_assert(test_has_PathName_method((T *)nullptr),
|
||||
"Class must have a static PathName() method.");
|
||||
if (RESTAPIHandler::ParseBindings(RequestedPath, T::PathName(), Bindings)) {
|
||||
return new T(Bindings, Logger, Server, TransactionId, true);
|
||||
}
|
||||
|
||||
if constexpr (sizeof...(Args) == 0) {
|
||||
return new RESTAPI_UnknownRequestHandler(Bindings,Logger, Server, TransactionId, true);
|
||||
return new RESTAPI_UnknownRequestHandler(Bindings, Logger, Server, TransactionId, true);
|
||||
} else {
|
||||
return RESTAPI_Router_I<Args...>(RequestedPath, Bindings, Logger, Server, TransactionId);
|
||||
return RESTAPI_Router_I<Args...>(RequestedPath, Bindings, Logger, Server,
|
||||
TransactionId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,18 +6,21 @@
|
||||
|
||||
#include "Poco/Net/HTTPServer.h"
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
Poco::Net::HTTPRequestHandler * RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t Id);
|
||||
Poco::Net::HTTPRequestHandler *
|
||||
RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
|
||||
Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t Id);
|
||||
|
||||
class IntRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
|
||||
public:
|
||||
inline IntRequestHandlerFactory() = default;
|
||||
Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
|
||||
Poco::Net::HTTPRequestHandler *
|
||||
createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
|
||||
|
||||
private:
|
||||
static inline std::atomic_uint64_t NextTransactionId_ = 1;
|
||||
};
|
||||
@@ -30,16 +33,21 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
inline int Start() override {
|
||||
poco_information(Logger(),"Starting.");
|
||||
poco_information(Logger(), "Starting.");
|
||||
Server_.InitLogging();
|
||||
|
||||
for(const auto & Svr: ConfigServersList_) {
|
||||
for (const auto &Svr : ConfigServersList_) {
|
||||
|
||||
if(MicroServiceNoAPISecurity()) {
|
||||
poco_information(Logger(),fmt::format("Starting: {}:{}. Security has been disabled for APIs.", Svr.Address(), Svr.Port()));
|
||||
if (MicroServiceNoAPISecurity()) {
|
||||
poco_information(
|
||||
Logger(),
|
||||
fmt::format("Starting: {}:{}. Security has been disabled for APIs.",
|
||||
Svr.Address(), Svr.Port()));
|
||||
} else {
|
||||
poco_information(Logger(),fmt::format("Starting: {}:{}. Keyfile:{} CertFile: {}", Svr.Address(), Svr.Port(),
|
||||
Svr.KeyFile(),Svr.CertFile()));
|
||||
poco_information(Logger(),
|
||||
fmt::format("Starting: {}:{}. Keyfile:{} CertFile: {}",
|
||||
Svr.Address(), Svr.Port(), Svr.KeyFile(),
|
||||
Svr.CertFile()));
|
||||
Svr.LogCert(Logger());
|
||||
if (!Svr.RootCA().empty())
|
||||
Svr.LogCas(Logger());
|
||||
@@ -50,12 +58,14 @@ namespace OpenWifi {
|
||||
Params->setName("ws:irest");
|
||||
|
||||
std::unique_ptr<Poco::Net::HTTPServer> NewServer;
|
||||
if(MicroServiceNoAPISecurity()) {
|
||||
if (MicroServiceNoAPISecurity()) {
|
||||
auto Sock{Svr.CreateSocket(Logger())};
|
||||
NewServer = std::make_unique<Poco::Net::HTTPServer>(new IntRequestHandlerFactory, Pool_, Sock, Params);
|
||||
NewServer = std::make_unique<Poco::Net::HTTPServer>(
|
||||
new IntRequestHandlerFactory, Pool_, Sock, Params);
|
||||
} else {
|
||||
auto Sock{Svr.CreateSecureSocket(Logger())};
|
||||
NewServer = std::make_unique<Poco::Net::HTTPServer>(new IntRequestHandlerFactory, Pool_, Sock, Params);
|
||||
NewServer = std::make_unique<Poco::Net::HTTPServer>(
|
||||
new IntRequestHandlerFactory, Pool_, Sock, Params);
|
||||
};
|
||||
NewServer->start();
|
||||
RESTServers_.push_back(std::move(NewServer));
|
||||
@@ -65,40 +75,37 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
inline void Stop() override {
|
||||
poco_information(Logger(),"Stopping...");
|
||||
for( const auto & svr : RESTServers_ )
|
||||
poco_information(Logger(), "Stopping...");
|
||||
for (const auto &svr : RESTServers_)
|
||||
svr->stopAll(true);
|
||||
Pool_.stopAll();
|
||||
Pool_.joinAll();
|
||||
poco_information(Logger(),"Stopped...");
|
||||
poco_information(Logger(), "Stopped...");
|
||||
}
|
||||
|
||||
inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override {
|
||||
MicroServiceLoadConfigurationFile();
|
||||
poco_information(Logger(),"Reinitializing.");
|
||||
poco_information(Logger(), "Reinitializing.");
|
||||
Stop();
|
||||
Start();
|
||||
}
|
||||
|
||||
inline Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id) {
|
||||
RESTAPIHandler::BindingMap Bindings;
|
||||
Utils::SetThreadName(fmt::format("i-rest:{}",Id).c_str());
|
||||
Utils::SetThreadName(fmt::format("i-rest:{}", Id).c_str());
|
||||
return RESTAPI_IntRouter(Path, Bindings, Logger(), Server_, Id);
|
||||
}
|
||||
const Poco::ThreadPool & Pool() { return Pool_; }
|
||||
const Poco::ThreadPool &Pool() { return Pool_; }
|
||||
|
||||
private:
|
||||
std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
|
||||
Poco::ThreadPool Pool_{"i-rest",4,64};
|
||||
Poco::ThreadPool Pool_{"i-rest", 4, 64};
|
||||
RESTAPI_GenericServerAccounting Server_;
|
||||
|
||||
RESTAPI_IntServer() noexcept:
|
||||
SubSystemServer("RESTAPI_IntServer", "REST-ISRV", "openwifi.internal.restapi")
|
||||
{
|
||||
}
|
||||
RESTAPI_IntServer() noexcept
|
||||
: SubSystemServer("RESTAPI_IntServer", "REST-ISRV", "openwifi.internal.restapi") {}
|
||||
};
|
||||
|
||||
inline auto RESTAPI_IntServer() { return RESTAPI_IntServer::instance(); };
|
||||
|
||||
|
||||
} // namespace OpenWifi
|
||||
|
||||
|
||||
@@ -4,29 +4,26 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include "Poco/Net/PartHandler.h"
|
||||
#include "Poco/Net/MessageHeader.h"
|
||||
#include "Poco/CountingStream.h"
|
||||
#include "Poco/Net/MessageHeader.h"
|
||||
#include "Poco/Net/PartHandler.h"
|
||||
#include "Poco/NullStream.h"
|
||||
#include "Poco/StreamCopier.h"
|
||||
#include <string>
|
||||
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_PartHandler: public Poco::Net::PartHandler {
|
||||
class RESTAPI_PartHandler : public Poco::Net::PartHandler {
|
||||
public:
|
||||
RESTAPI_PartHandler():
|
||||
_length(0)
|
||||
{
|
||||
}
|
||||
RESTAPI_PartHandler() : _length(0) {}
|
||||
|
||||
inline void handlePart(const Poco::Net::MessageHeader& header, std::istream& stream) override
|
||||
{
|
||||
inline void handlePart(const Poco::Net::MessageHeader &header,
|
||||
std::istream &stream) override {
|
||||
_type = header.get("Content-Type", "(unspecified)");
|
||||
if (header.has("Content-Disposition"))
|
||||
{
|
||||
if (header.has("Content-Disposition")) {
|
||||
std::string disp;
|
||||
Poco::Net::NameValueCollection params;
|
||||
Poco::Net::MessageHeader::splitParameters(header["Content-Disposition"], disp, params);
|
||||
Poco::Net::MessageHeader::splitParameters(header["Content-Disposition"], disp,
|
||||
params);
|
||||
_name = params.get("name", "(unnamed)");
|
||||
_fileName = params.get("filename", "(unnamed)");
|
||||
}
|
||||
@@ -37,25 +34,13 @@ namespace OpenWifi {
|
||||
_length = (int)istr.chars();
|
||||
}
|
||||
|
||||
[[nodiscard]] inline int length() const
|
||||
{
|
||||
return _length;
|
||||
}
|
||||
[[nodiscard]] inline int length() const { return _length; }
|
||||
|
||||
[[nodiscard]] inline const std::string& name() const
|
||||
{
|
||||
return _name;
|
||||
}
|
||||
[[nodiscard]] inline const std::string &name() const { return _name; }
|
||||
|
||||
[[nodiscard]] inline const std::string& fileName() const
|
||||
{
|
||||
return _fileName;
|
||||
}
|
||||
[[nodiscard]] inline const std::string &fileName() const { return _fileName; }
|
||||
|
||||
[[nodiscard]] inline const std::string& contentType() const
|
||||
{
|
||||
return _type;
|
||||
}
|
||||
[[nodiscard]] inline const std::string &contentType() const { return _type; }
|
||||
|
||||
private:
|
||||
int _length;
|
||||
@@ -63,4 +48,4 @@ namespace OpenWifi {
|
||||
std::string _name;
|
||||
std::string _fileName;
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
#include "Poco/URI.h"
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
#include "Poco/ExpireLRUCache.h"
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
#include "Poco/URI.h"
|
||||
|
||||
#include "fmt/format.h"
|
||||
|
||||
@@ -16,10 +16,9 @@ namespace OpenWifi {
|
||||
|
||||
class RESTAPI_RateLimiter : public SubSystemServer {
|
||||
public:
|
||||
|
||||
struct ClientCacheEntry {
|
||||
int64_t Start=0;
|
||||
int Count=0;
|
||||
int64_t Start = 0;
|
||||
int Count = 0;
|
||||
};
|
||||
|
||||
static auto instance() {
|
||||
@@ -27,49 +26,47 @@ namespace OpenWifi {
|
||||
return instance_;
|
||||
}
|
||||
|
||||
inline int Start() final { return 0;};
|
||||
inline void Stop() final { };
|
||||
inline int Start() final { return 0; };
|
||||
inline void Stop() final{};
|
||||
|
||||
inline bool IsRateLimited(const Poco::Net::HTTPServerRequest &R, int64_t Period, int64_t MaxCalls) {
|
||||
inline bool IsRateLimited(const Poco::Net::HTTPServerRequest &R, int64_t Period,
|
||||
int64_t MaxCalls) {
|
||||
Poco::URI uri(R.getURI());
|
||||
auto H = str_hash(uri.getPath() + R.clientAddress().host().toString());
|
||||
auto E = Cache_.get(H);
|
||||
auto Now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
|
||||
if(E.isNull()) {
|
||||
Cache_.add(H,ClientCacheEntry{.Start=Now, .Count=1});
|
||||
auto Now = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
if (E.isNull()) {
|
||||
Cache_.add(H, ClientCacheEntry{.Start = Now, .Count = 1});
|
||||
return false;
|
||||
}
|
||||
if((Now-E->Start)<Period) {
|
||||
if ((Now - E->Start) < Period) {
|
||||
E->Count++;
|
||||
Cache_.update(H,E);
|
||||
if(E->Count > MaxCalls) {
|
||||
poco_warning(Logger(),fmt::format("RATE-LIMIT-EXCEEDED: from '{}'", R.clientAddress().toString()));
|
||||
Cache_.update(H, E);
|
||||
if (E->Count > MaxCalls) {
|
||||
poco_warning(Logger(), fmt::format("RATE-LIMIT-EXCEEDED: from '{}'",
|
||||
R.clientAddress().toString()));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
E->Start = Now;
|
||||
E->Count = 1;
|
||||
Cache_.update(H,E);
|
||||
Cache_.update(H, E);
|
||||
return false;
|
||||
}
|
||||
|
||||
inline void Clear() {
|
||||
Cache_.clear();
|
||||
}
|
||||
inline void Clear() { Cache_.clear(); }
|
||||
|
||||
private:
|
||||
Poco::ExpireLRUCache<uint64_t,ClientCacheEntry> Cache_{2048};
|
||||
Poco::ExpireLRUCache<uint64_t, ClientCacheEntry> Cache_{2048};
|
||||
std::hash<std::string> str_hash;
|
||||
|
||||
RESTAPI_RateLimiter() noexcept:
|
||||
SubSystemServer("RateLimiter", "RATE-LIMITER", "rate.limiter")
|
||||
{
|
||||
}
|
||||
|
||||
RESTAPI_RateLimiter() noexcept
|
||||
: SubSystemServer("RateLimiter", "RATE-LIMITER", "rate.limiter") {}
|
||||
};
|
||||
|
||||
inline auto RESTAPI_RateLimiter() { return RESTAPI_RateLimiter::instance(); }
|
||||
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -14,19 +14,19 @@ namespace OpenWifi {
|
||||
|
||||
class RESTAPI_system_command : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_system_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
|
||||
RESTAPI_system_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
|
||||
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
|
||||
bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST,
|
||||
Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server,
|
||||
TransactionId,
|
||||
Internal) {}
|
||||
static auto PathName() { return std::list<std::string>{"/api/v1/system"};}
|
||||
Server, TransactionId, Internal) {}
|
||||
static auto PathName() { return std::list<std::string>{"/api/v1/system"}; }
|
||||
|
||||
inline void DoGet() {
|
||||
std::string Arg;
|
||||
if(HasParameter("command",Arg) && Arg=="info") {
|
||||
if (HasParameter("command", Arg) && Arg == "info") {
|
||||
Poco::JSON::Object Answer;
|
||||
Answer.set(RESTAPI::Protocol::VERSION, MicroServiceVersion());
|
||||
Answer.set(RESTAPI::Protocol::UPTIME, MicroServiceUptimeTotalSeconds());
|
||||
@@ -40,15 +40,15 @@ namespace OpenWifi {
|
||||
auto SubSystems = MicroServiceGetFullSubSystems();
|
||||
std::set<std::string> CertNames;
|
||||
|
||||
for(const auto &i:SubSystems) {
|
||||
auto Hosts=i->HostSize();
|
||||
for(uint64_t j=0;j<Hosts;++j) {
|
||||
for (const auto &i : SubSystems) {
|
||||
auto Hosts = i->HostSize();
|
||||
for (uint64_t j = 0; j < Hosts; ++j) {
|
||||
auto CertFileName = i->Host(j).CertFile();
|
||||
if(!CertFileName.empty()) {
|
||||
if (!CertFileName.empty()) {
|
||||
Poco::File F1(CertFileName);
|
||||
if(F1.exists()) {
|
||||
if (F1.exists()) {
|
||||
auto InsertResult = CertNames.insert(CertFileName);
|
||||
if(InsertResult.second) {
|
||||
if (InsertResult.second) {
|
||||
Poco::JSON::Object Inner;
|
||||
Poco::Path F(CertFileName);
|
||||
Inner.set("filename", F.getFileName());
|
||||
@@ -64,7 +64,7 @@ namespace OpenWifi {
|
||||
Answer.set("certificates", Certificates);
|
||||
return ReturnObject(Answer);
|
||||
}
|
||||
if(GetBoolParameter("extraConfiguration")) {
|
||||
if (GetBoolParameter("extraConfiguration")) {
|
||||
Poco::JSON::Object Answer;
|
||||
MicroServiceGetExtraConfiguration(Answer);
|
||||
return ReturnObject(Answer);
|
||||
@@ -73,7 +73,7 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
inline void DoPost() final {
|
||||
const auto & Obj = ParsedBody_;
|
||||
const auto &Obj = ParsedBody_;
|
||||
if (Obj->has(RESTAPI::Protocol::COMMAND)) {
|
||||
auto Command = Poco::toLower(Obj->get(RESTAPI::Protocol::COMMAND).toString());
|
||||
if (Command == RESTAPI::Protocol::SETLOGLEVEL) {
|
||||
@@ -88,7 +88,8 @@ namespace OpenWifi {
|
||||
auto Name = GetS(RESTAPI::Protocol::TAG, InnerObj);
|
||||
auto Value = GetS(RESTAPI::Protocol::VALUE, InnerObj);
|
||||
MicroServiceSetSubsystemLogLevel(Name, Value);
|
||||
poco_information(Logger_,
|
||||
poco_information(
|
||||
Logger_,
|
||||
fmt::format("Setting log level for {} at {}", Name, Value));
|
||||
}
|
||||
}
|
||||
@@ -131,10 +132,10 @@ namespace OpenWifi {
|
||||
std::vector<std::string> Names;
|
||||
for (const auto &i : *SubSystems)
|
||||
Names.push_back(i.toString());
|
||||
std::thread ReloadThread([Names](){
|
||||
std::thread ReloadThread([Names]() {
|
||||
std::this_thread::sleep_for(10000ms);
|
||||
for(const auto &i:Names) {
|
||||
if(i=="daemon")
|
||||
for (const auto &i : Names) {
|
||||
if (i == "daemon")
|
||||
MicroServiceReload();
|
||||
else
|
||||
MicroServiceReload(i);
|
||||
@@ -150,8 +151,8 @@ namespace OpenWifi {
|
||||
BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
|
||||
}
|
||||
|
||||
void DoPut() final {};
|
||||
void DoDelete() final {};
|
||||
void DoPut() final{};
|
||||
void DoDelete() final{};
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
@@ -14,8 +14,8 @@ namespace OpenWifi {
|
||||
class RESTAPI_system_configuration : public RESTAPIHandler {
|
||||
public:
|
||||
RESTAPI_system_configuration(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
|
||||
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
|
||||
bool Internal)
|
||||
RESTAPI_GenericServerAccounting &Server,
|
||||
uint64_t TransactionId, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_PUT,
|
||||
Poco::Net::HTTPRequest::HTTP_GET,
|
||||
@@ -27,21 +27,18 @@ namespace OpenWifi {
|
||||
|
||||
inline void DoPost() final {}
|
||||
|
||||
inline void DoGet() final {
|
||||
inline void DoGet() final { return OK(); }
|
||||
|
||||
return OK();
|
||||
}
|
||||
|
||||
inline void DoPut() final{
|
||||
if(UserInfo_.userinfo.userRole!=SecurityObjects::ROOT) {
|
||||
inline void DoPut() final {
|
||||
if (UserInfo_.userinfo.userRole != SecurityObjects::ROOT) {
|
||||
return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED);
|
||||
}
|
||||
|
||||
return OK();
|
||||
};
|
||||
|
||||
inline void DoDelete() final{
|
||||
if(UserInfo_.userinfo.userRole!=SecurityObjects::ROOT) {
|
||||
inline void DoDelete() final {
|
||||
if (UserInfo_.userinfo.userRole != SecurityObjects::ROOT) {
|
||||
return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED);
|
||||
}
|
||||
MicroServiceDeleteOverrideConfiguration();
|
||||
@@ -49,4 +46,4 @@ namespace OpenWifi {
|
||||
};
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -4,42 +4,44 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
#include "Poco/Net/WebSocket.h"
|
||||
#include "framework/RESTAPI_Handler.h"
|
||||
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
class RESTAPI_webSocketServer : public RESTAPIHandler {
|
||||
public:
|
||||
inline RESTAPI_webSocketServer(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, bool Internal)
|
||||
inline RESTAPI_webSocketServer(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
|
||||
RESTAPI_GenericServerAccounting &Server,
|
||||
uint64_t TransactionId, bool Internal)
|
||||
: RESTAPIHandler(bindings, L,
|
||||
std::vector<std::string>{ Poco::Net::HTTPRequest::HTTP_GET,
|
||||
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
|
||||
Poco::Net::HTTPRequest::HTTP_OPTIONS},
|
||||
Server, TransactionId, Internal,false) {}
|
||||
static auto PathName() { return std::list<std::string>{"/api/v1/ws"};}
|
||||
Server, TransactionId, Internal, false) {}
|
||||
static auto PathName() { return std::list<std::string>{"/api/v1/ws"}; }
|
||||
void DoGet() final {
|
||||
try
|
||||
{
|
||||
if(Request->find("Upgrade") != Request->end() && Poco::icompare((*Request)["Upgrade"], "websocket") == 0) {
|
||||
try
|
||||
{
|
||||
try {
|
||||
if (Request->find("Upgrade") != Request->end() &&
|
||||
Poco::icompare((*Request)["Upgrade"], "websocket") == 0) {
|
||||
try {
|
||||
Poco::Net::WebSocket WS(*Request, *Response);
|
||||
auto Id = MicroServiceCreateUUID();
|
||||
UI_WebSocketClientServer()->NewClient(WS,Id,UserInfo_.userinfo.email, TransactionId_);
|
||||
}
|
||||
catch (...) {
|
||||
UI_WebSocketClientServer()->NewClient(WS, Id, UserInfo_.userinfo.email,
|
||||
TransactionId_);
|
||||
} catch (...) {
|
||||
std::cout << "Cannot create websocket client..." << std::endl;
|
||||
}
|
||||
}
|
||||
} catch(...) {
|
||||
} catch (...) {
|
||||
std::cout << "Cannot upgrade connection..." << std::endl;
|
||||
}
|
||||
};
|
||||
void DoDelete() final {};
|
||||
void DoPost() final {};
|
||||
void DoPut() final {};
|
||||
void DoDelete() final{};
|
||||
void DoPost() final{};
|
||||
void DoPut() final{};
|
||||
|
||||
private:
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "Poco/Data/LOB.h"
|
||||
#include "Poco/JSON/Object.h"
|
||||
#include "Poco/JSON/Parser.h"
|
||||
#include "Poco/Data/LOB.h"
|
||||
#include "Poco/Net/HTTPServerRequest.h"
|
||||
|
||||
#include "framework/OpenWifiTypes.h"
|
||||
@@ -16,7 +16,8 @@
|
||||
|
||||
namespace OpenWifi::RESTAPI_utils {
|
||||
|
||||
inline void EmbedDocument(const std::string & ObjName, Poco::JSON::Object & Obj, const std::string &ObjStr) {
|
||||
inline void EmbedDocument(const std::string &ObjName, Poco::JSON::Object &Obj,
|
||||
const std::string &ObjStr) {
|
||||
std::string D = ObjStr.empty() ? "{}" : ObjStr;
|
||||
Poco::JSON::Parser P;
|
||||
Poco::Dynamic::Var result = P.parse(D);
|
||||
@@ -25,23 +26,23 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, bool V) {
|
||||
Obj.set(Field,V);
|
||||
Obj.set(Field, V);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, double V) {
|
||||
Obj.set(Field,V);
|
||||
Obj.set(Field, V);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, float V) {
|
||||
Obj.set(Field,V);
|
||||
Obj.set(Field, V);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::string & S) {
|
||||
Obj.set(Field,S);
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::string &S) {
|
||||
Obj.set(Field, S);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const char * S) {
|
||||
Obj.set(Field,S);
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const char *S) {
|
||||
Obj.set(Field, S);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, int16_t Value) {
|
||||
@@ -65,78 +66,83 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, uint64_t Value) {
|
||||
Obj.set(Field,Value);
|
||||
Obj.set(Field, Value);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Poco::Data::BLOB &Value) {
|
||||
auto Result = Utils::base64encode((const unsigned char *)Value.rawContent(),Value.size());
|
||||
Obj.set(Field,Result);
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
|
||||
const Poco::Data::BLOB &Value) {
|
||||
auto Result = Utils::base64encode((const unsigned char *)Value.rawContent(), Value.size());
|
||||
Obj.set(Field, Result);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::StringPairVec & S) {
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
|
||||
const Types::StringPairVec &S) {
|
||||
Poco::JSON::Array Array;
|
||||
for(const auto &i:S) {
|
||||
for (const auto &i : S) {
|
||||
Poco::JSON::Object O;
|
||||
O.set("tag",i.first);
|
||||
O.set("tag", i.first);
|
||||
O.set("value", i.second);
|
||||
Array.add(O);
|
||||
}
|
||||
Obj.set(Field,Array);
|
||||
Obj.set(Field, Array);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::StringVec &V) {
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
|
||||
const Types::StringVec &V) {
|
||||
Poco::JSON::Array A;
|
||||
for(const auto &i:V)
|
||||
for (const auto &i : V)
|
||||
A.add(i);
|
||||
Obj.set(Field,A);
|
||||
Obj.set(Field, A);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::TagList &V) {
|
||||
Poco::JSON::Array A;
|
||||
for(const auto &i:V)
|
||||
for (const auto &i : V)
|
||||
A.add(i);
|
||||
Obj.set(Field,A);
|
||||
Obj.set(Field, A);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::CountedMap &M) {
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
|
||||
const Types::CountedMap &M) {
|
||||
Poco::JSON::Array A;
|
||||
for(const auto &[Key,Value]:M) {
|
||||
for (const auto &[Key, Value] : M) {
|
||||
Poco::JSON::Object O;
|
||||
O.set("tag",Key);
|
||||
O.set("tag", Key);
|
||||
O.set("value", Value);
|
||||
A.add(O);
|
||||
}
|
||||
Obj.set(Field,A);
|
||||
Obj.set(Field, A);
|
||||
}
|
||||
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::Counted3DMapSII &M) {
|
||||
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
|
||||
const Types::Counted3DMapSII &M) {
|
||||
Poco::JSON::Array A;
|
||||
for(const auto &[OrgName,MonthlyNumberMap]:M) {
|
||||
for (const auto &[OrgName, MonthlyNumberMap] : M) {
|
||||
Poco::JSON::Object OrgObject;
|
||||
OrgObject.set("tag",OrgName);
|
||||
OrgObject.set("tag", OrgName);
|
||||
Poco::JSON::Array MonthlyArray;
|
||||
for(const auto &[Month,Counter]:MonthlyNumberMap) {
|
||||
for (const auto &[Month, Counter] : MonthlyNumberMap) {
|
||||
Poco::JSON::Object Inner;
|
||||
Inner.set("value", Month);
|
||||
Inner.set("counter", Counter);
|
||||
MonthlyArray.add(Inner);
|
||||
}
|
||||
OrgObject.set("index",MonthlyArray);
|
||||
OrgObject.set("index", MonthlyArray);
|
||||
A.add(OrgObject);
|
||||
}
|
||||
Obj.set(Field, A);
|
||||
}
|
||||
|
||||
template<typename T> void field_to_json(Poco::JSON::Object &Obj,
|
||||
const char *Field,
|
||||
const T &V,
|
||||
template <typename T>
|
||||
void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &V,
|
||||
std::function<std::string(const T &)> F) {
|
||||
Obj.set(Field, F(V));
|
||||
}
|
||||
|
||||
template<class T> void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::vector<T> &Value) {
|
||||
template <class T>
|
||||
void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::vector<T> &Value) {
|
||||
Poco::JSON::Array Arr;
|
||||
for(const auto &i:Value) {
|
||||
for (const auto &i : Value) {
|
||||
Poco::JSON::Object AO;
|
||||
i.to_json(AO);
|
||||
Arr.add(AO);
|
||||
@@ -144,7 +150,8 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
Obj.set(Field, Arr);
|
||||
}
|
||||
|
||||
template<class T> void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &Value) {
|
||||
template <class T>
|
||||
void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &Value) {
|
||||
Poco::JSON::Object Answer;
|
||||
Value.to_json(Answer);
|
||||
Obj.set(Field, Answer);
|
||||
@@ -155,110 +162,127 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
///////////////////////////
|
||||
///////////////////////////
|
||||
|
||||
template<typename T> bool field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T & V,
|
||||
template <typename T>
|
||||
bool field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &V,
|
||||
std::function<T(const std::string &)> F) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
V = F(Obj->get(Field).toString());
|
||||
return true;
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, std::string &S) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
std::string &S) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
S = Obj->get(Field).toString();
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, double & Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
double &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (double)Obj->get(Field);
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, float & Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
float &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (float)Obj->get(Field);
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, bool &Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
bool &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (Obj->get(Field).toString() == "true");
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int16_t &Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
int16_t &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (int16_t)Obj->get(Field);
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int32_t &Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (int32_t) Obj->get(Field);
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
int32_t &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (int32_t)Obj->get(Field);
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int64_t &Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
int64_t &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (int64_t)Obj->get(Field);
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint16_t &Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
uint16_t &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (uint16_t)Obj->get(Field);
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint32_t &Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
uint32_t &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (uint32_t)Obj->get(Field);
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint64_t &Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field))
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
uint64_t &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field))
|
||||
Value = (uint64_t)Obj->get(Field);
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Poco::Data::BLOB &Value) {
|
||||
if(Obj->has(Field) && !Obj->isNull(Field)) {
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
Poco::Data::BLOB &Value) {
|
||||
if (Obj->has(Field) && !Obj->isNull(Field)) {
|
||||
auto Result = Utils::base64decode(Obj->get(Field).toString());
|
||||
Value.assignRaw((const unsigned char *)&Result[0],Result.size());
|
||||
Value.assignRaw((const unsigned char *)&Result[0], Result.size());
|
||||
}
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::StringPairVec &Vec) {
|
||||
if(Obj->isArray(Field) && !Obj->isNull(Field)) {
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
Types::StringPairVec &Vec) {
|
||||
if (Obj->isArray(Field) && !Obj->isNull(Field)) {
|
||||
auto O = Obj->getArray(Field);
|
||||
for(const auto &i:*O) {
|
||||
std::string S1,S2;
|
||||
for (const auto &i : *O) {
|
||||
std::string S1, S2;
|
||||
auto Inner = i.extract<Poco::JSON::Object::Ptr>();
|
||||
if(Inner->has("tag"))
|
||||
if (Inner->has("tag"))
|
||||
S1 = Inner->get("tag").toString();
|
||||
if(Inner->has("value"))
|
||||
if (Inner->has("value"))
|
||||
S2 = Inner->get("value").toString();
|
||||
auto P = std::make_pair(S1,S2);
|
||||
auto P = std::make_pair(S1, S2);
|
||||
Vec.push_back(P);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::StringVec &Value) {
|
||||
if(Obj->isArray(Field) && !Obj->isNull(Field)) {
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
Types::StringVec &Value) {
|
||||
if (Obj->isArray(Field) && !Obj->isNull(Field)) {
|
||||
Value.clear();
|
||||
Poco::JSON::Array::Ptr A = Obj->getArray(Field);
|
||||
for(const auto &i:*A) {
|
||||
for (const auto &i : *A) {
|
||||
Value.push_back(i.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::TagList &Value) {
|
||||
if(Obj->isArray(Field) && !Obj->isNull(Field)) {
|
||||
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
Types::TagList &Value) {
|
||||
if (Obj->isArray(Field) && !Obj->isNull(Field)) {
|
||||
Value.clear();
|
||||
Poco::JSON::Array::Ptr A = Obj->getArray(Field);
|
||||
for(const auto &i:*A) {
|
||||
for (const auto &i : *A) {
|
||||
Value.push_back(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template<class T> void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, std::vector<T> &Value) {
|
||||
if(Obj->isArray(Field) && !Obj->isNull(Field)) {
|
||||
template <class T>
|
||||
void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
|
||||
std::vector<T> &Value) {
|
||||
if (Obj->isArray(Field) && !Obj->isNull(Field)) {
|
||||
Poco::JSON::Array::Ptr Arr = Obj->getArray(Field);
|
||||
for(auto &i:*Arr) {
|
||||
for (auto &i : *Arr) {
|
||||
auto InnerObj = i.extract<Poco::JSON::Object::Ptr>();
|
||||
T NewItem;
|
||||
NewItem.from_json(InnerObj);
|
||||
@@ -267,76 +291,78 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
}
|
||||
}
|
||||
|
||||
template<class T> void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &Value) {
|
||||
if(Obj->isObject(Field) && !Obj->isNull(Field)) {
|
||||
template <class T>
|
||||
void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &Value) {
|
||||
if (Obj->isObject(Field) && !Obj->isNull(Field)) {
|
||||
Poco::JSON::Object::Ptr A = Obj->getObject(Field);
|
||||
Value.from_json(A);
|
||||
}
|
||||
}
|
||||
|
||||
inline std::string to_string(const Types::TagList & ObjectArray) {
|
||||
inline std::string to_string(const Types::TagList &ObjectArray) {
|
||||
Poco::JSON::Array OutputArr;
|
||||
if(ObjectArray.empty())
|
||||
if (ObjectArray.empty())
|
||||
return "[]";
|
||||
for(auto const &i:ObjectArray) {
|
||||
for (auto const &i : ObjectArray) {
|
||||
OutputArr.add(i);
|
||||
}
|
||||
std::ostringstream OS;
|
||||
Poco::JSON::Stringifier::stringify(OutputArr,OS, 0,0, Poco::JSON_PRESERVE_KEY_ORDER );
|
||||
Poco::JSON::Stringifier::stringify(OutputArr, OS, 0, 0, Poco::JSON_PRESERVE_KEY_ORDER);
|
||||
return OS.str();
|
||||
}
|
||||
|
||||
inline std::string to_string(const Types::StringVec & ObjectArray) {
|
||||
inline std::string to_string(const Types::StringVec &ObjectArray) {
|
||||
Poco::JSON::Array OutputArr;
|
||||
if(ObjectArray.empty())
|
||||
if (ObjectArray.empty())
|
||||
return "[]";
|
||||
for(auto const &i:ObjectArray) {
|
||||
for (auto const &i : ObjectArray) {
|
||||
OutputArr.add(i);
|
||||
}
|
||||
std::ostringstream OS;
|
||||
Poco::JSON::Stringifier::condense(OutputArr,OS);
|
||||
Poco::JSON::Stringifier::condense(OutputArr, OS);
|
||||
return OS.str();
|
||||
}
|
||||
|
||||
inline std::string to_string(const Types::StringPairVec & ObjectArray) {
|
||||
inline std::string to_string(const Types::StringPairVec &ObjectArray) {
|
||||
Poco::JSON::Array OutputArr;
|
||||
if(ObjectArray.empty())
|
||||
if (ObjectArray.empty())
|
||||
return "[]";
|
||||
for(auto const &i:ObjectArray) {
|
||||
for (auto const &i : ObjectArray) {
|
||||
Poco::JSON::Array InnerArray;
|
||||
InnerArray.add(i.first);
|
||||
InnerArray.add(i.second);
|
||||
OutputArr.add(InnerArray);
|
||||
}
|
||||
std::ostringstream OS;
|
||||
Poco::JSON::Stringifier::condense(OutputArr,OS);
|
||||
Poco::JSON::Stringifier::condense(OutputArr, OS);
|
||||
return OS.str();
|
||||
}
|
||||
|
||||
template<class T> std::string to_string(const std::vector<T> & ObjectArray) {
|
||||
template <class T> std::string to_string(const std::vector<T> &ObjectArray) {
|
||||
Poco::JSON::Array OutputArr;
|
||||
if(ObjectArray.empty())
|
||||
if (ObjectArray.empty())
|
||||
return "[]";
|
||||
for(auto const &i:ObjectArray) {
|
||||
for (auto const &i : ObjectArray) {
|
||||
Poco::JSON::Object O;
|
||||
i.to_json(O);
|
||||
OutputArr.add(O);
|
||||
}
|
||||
std::ostringstream OS;
|
||||
Poco::JSON::Stringifier::condense(OutputArr,OS);
|
||||
Poco::JSON::Stringifier::condense(OutputArr, OS);
|
||||
return OS.str();
|
||||
}
|
||||
|
||||
template<class T> std::string to_string(const std::vector<std::vector<T>> & ObjectArray) {
|
||||
template <class T> std::string to_string(const std::vector<std::vector<T>> &ObjectArray) {
|
||||
Poco::JSON::Array OutputArr;
|
||||
if(ObjectArray.empty())
|
||||
if (ObjectArray.empty())
|
||||
return "[]";
|
||||
for(auto const &i:ObjectArray) {
|
||||
for (auto const &i : ObjectArray) {
|
||||
Poco::JSON::Array InnerArr;
|
||||
for(auto const &j:i) {
|
||||
if constexpr(std::is_integral<T>::value) {
|
||||
for (auto const &j : i) {
|
||||
if constexpr (std::is_integral<T>::value) {
|
||||
InnerArr.add(j);
|
||||
} if constexpr(std::is_same_v<T,std::string>) {
|
||||
}
|
||||
if constexpr (std::is_same_v<T, std::string>) {
|
||||
InnerArr.add(j);
|
||||
} else {
|
||||
InnerArr.add(j);
|
||||
@@ -348,22 +374,22 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
OutputArr.add(InnerArr);
|
||||
}
|
||||
std::ostringstream OS;
|
||||
Poco::JSON::Stringifier::condense(OutputArr,OS);
|
||||
Poco::JSON::Stringifier::condense(OutputArr, OS);
|
||||
return OS.str();
|
||||
}
|
||||
|
||||
template<class T> std::string to_string(const T & Object) {
|
||||
template <class T> std::string to_string(const T &Object) {
|
||||
Poco::JSON::Object OutputObj;
|
||||
Object.to_json(OutputObj);
|
||||
std::ostringstream OS;
|
||||
Poco::JSON::Stringifier::condense(OutputObj,OS);
|
||||
Poco::JSON::Stringifier::condense(OutputObj, OS);
|
||||
return OS.str();
|
||||
}
|
||||
|
||||
inline Types::StringVec to_object_array(const std::string & ObjectString) {
|
||||
inline Types::StringVec to_object_array(const std::string &ObjectString) {
|
||||
|
||||
Types::StringVec Result;
|
||||
if(ObjectString.empty())
|
||||
if (ObjectString.empty())
|
||||
return Result;
|
||||
|
||||
try {
|
||||
@@ -373,14 +399,13 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
Result.push_back(i.toString());
|
||||
}
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
inline OpenWifi::Types::TagList to_taglist(const std::string & ObjectString) {
|
||||
inline OpenWifi::Types::TagList to_taglist(const std::string &ObjectString) {
|
||||
Types::TagList Result;
|
||||
if(ObjectString.empty())
|
||||
if (ObjectString.empty())
|
||||
return Result;
|
||||
|
||||
try {
|
||||
@@ -390,36 +415,34 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
Result.push_back(i);
|
||||
}
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
inline Types::StringPairVec to_stringpair_array(const std::string &S) {
|
||||
Types::StringPairVec R;
|
||||
if(S.empty())
|
||||
if (S.empty())
|
||||
return R;
|
||||
try {
|
||||
Poco::JSON::Parser P;
|
||||
auto Object = P.parse(S).template extract<Poco::JSON::Array::Ptr>();
|
||||
for (const auto &i : *Object) {
|
||||
auto InnerObject = i.template extract<Poco::JSON::Array::Ptr>();
|
||||
if(InnerObject->size()==2) {
|
||||
if (InnerObject->size() == 2) {
|
||||
auto S1 = InnerObject->getElement<std::string>(0);
|
||||
auto S2 = InnerObject->getElement<std::string>(1);
|
||||
R.push_back(std::make_pair(S1,S2));
|
||||
R.push_back(std::make_pair(S1, S2));
|
||||
}
|
||||
}
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
|
||||
return R;
|
||||
}
|
||||
|
||||
template<class T> std::vector<T> to_object_array(const std::string & ObjectString) {
|
||||
template <class T> std::vector<T> to_object_array(const std::string &ObjectString) {
|
||||
std::vector<T> Result;
|
||||
if(ObjectString.empty())
|
||||
if (ObjectString.empty())
|
||||
return Result;
|
||||
|
||||
try {
|
||||
@@ -432,14 +455,14 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
Result.push_back(Obj);
|
||||
}
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
template<class T> std::vector<std::vector<T>> to_array_of_array_of_object(const std::string & ObjectString) {
|
||||
template <class T>
|
||||
std::vector<std::vector<T>> to_array_of_array_of_object(const std::string &ObjectString) {
|
||||
std::vector<std::vector<T>> Result;
|
||||
if(ObjectString.empty())
|
||||
if (ObjectString.empty())
|
||||
return Result;
|
||||
try {
|
||||
Poco::JSON::Parser P1;
|
||||
@@ -448,7 +471,7 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
Poco::JSON::Parser P2;
|
||||
auto InnerArray = P2.parse(i).template extract<Poco::JSON::Array::Ptr>();
|
||||
std::vector<T> InnerVector;
|
||||
for(auto const &j: *InnerArray) {
|
||||
for (auto const &j : *InnerArray) {
|
||||
auto Object = j.template extract<Poco::JSON::Object::Ptr>();
|
||||
T Obj;
|
||||
Obj.from_json(Object);
|
||||
@@ -457,15 +480,14 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
Result.push_back(InnerVector);
|
||||
}
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
template<class T> T to_object(const std::string & ObjectString) {
|
||||
template <class T> T to_object(const std::string &ObjectString) {
|
||||
T Result;
|
||||
|
||||
if(ObjectString.empty())
|
||||
if (ObjectString.empty())
|
||||
return Result;
|
||||
|
||||
Poco::JSON::Parser P;
|
||||
@@ -475,10 +497,10 @@ namespace OpenWifi::RESTAPI_utils {
|
||||
return Result;
|
||||
}
|
||||
|
||||
template<class T> bool from_request(T & Obj, Poco::Net::HTTPServerRequest &Request) {
|
||||
template <class T> bool from_request(T &Obj, Poco::Net::HTTPServerRequest &Request) {
|
||||
Poco::JSON::Parser IncomingParser;
|
||||
auto RawObject = IncomingParser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>();
|
||||
Obj.from_json(RawObject);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} // namespace OpenWifi::RESTAPI_utils
|
||||
|
||||
@@ -4,38 +4,31 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Poco/Data/SQLite/Connector.h"
|
||||
#include "Poco/Data/Session.h"
|
||||
#include "Poco/Data/SessionPool.h"
|
||||
#include "Poco/Data/SQLite/Connector.h"
|
||||
#include "Poco/JSON/Object.h"
|
||||
|
||||
#ifndef SMALL_BUILD
|
||||
#include "Poco/Data/PostgreSQL/Connector.h"
|
||||
#include "Poco/Data/MySQL/Connector.h"
|
||||
#include "Poco/Data/PostgreSQL/Connector.h"
|
||||
#endif
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
enum DBType {
|
||||
sqlite,
|
||||
pgsql,
|
||||
mysql
|
||||
};
|
||||
enum DBType { sqlite, pgsql, mysql };
|
||||
|
||||
class StorageClass : public SubSystemServer {
|
||||
public:
|
||||
StorageClass() noexcept:
|
||||
SubSystemServer("StorageClass", "STORAGE-SVR", "storage")
|
||||
{
|
||||
}
|
||||
StorageClass() noexcept : SubSystemServer("StorageClass", "STORAGE-SVR", "storage") {}
|
||||
|
||||
int Start() override {
|
||||
std::lock_guard Guard(Mutex_);
|
||||
|
||||
Logger().notice("Starting.");
|
||||
std::string DBType = MicroServiceConfigGetString("storage.type","");
|
||||
std::string DBType = MicroServiceConfigGetString("storage.type", "");
|
||||
|
||||
if (DBType == "sqlite") {
|
||||
Setup_SQLite();
|
||||
@@ -47,11 +40,10 @@ namespace OpenWifi {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void Stop() override {
|
||||
Pool_->shutdown();
|
||||
}
|
||||
void Stop() override { Pool_->shutdown(); }
|
||||
|
||||
DBType Type() const { return dbType_; };
|
||||
|
||||
private:
|
||||
inline int Setup_SQLite();
|
||||
inline int Setup_MySQL();
|
||||
@@ -66,20 +58,29 @@ namespace OpenWifi {
|
||||
};
|
||||
|
||||
#ifdef SMALL_BUILD
|
||||
int Service::Setup_MySQL() { Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); return 0; }
|
||||
int Service::Setup_PostgreSQL() { Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); return 0; }
|
||||
int Service::Setup_MySQL() {
|
||||
Daemon()->exit(Poco::Util::Application::EXIT_CONFIG);
|
||||
return 0;
|
||||
}
|
||||
int Service::Setup_PostgreSQL() {
|
||||
Daemon()->exit(Poco::Util::Application::EXIT_CONFIG);
|
||||
return 0;
|
||||
}
|
||||
#else
|
||||
|
||||
inline int StorageClass::Setup_SQLite() {
|
||||
Logger().notice("SQLite StorageClass enabled.");
|
||||
dbType_ = sqlite;
|
||||
auto DBName = MicroServiceDataDirectory() + "/" + MicroServiceConfigGetString("storage.type.sqlite.db","");
|
||||
int NumSessions = (int) MicroServiceConfigGetInt("storage.type.sqlite.maxsessions", 64);
|
||||
int IdleTime = (int) MicroServiceConfigGetInt("storage.type.sqlite.idletime", 60);
|
||||
auto DBName = MicroServiceDataDirectory() + "/" +
|
||||
MicroServiceConfigGetString("storage.type.sqlite.db", "");
|
||||
int NumSessions = (int)MicroServiceConfigGetInt("storage.type.sqlite.maxsessions", 64);
|
||||
int IdleTime = (int)MicroServiceConfigGetInt("storage.type.sqlite.idletime", 60);
|
||||
|
||||
Poco::Data::SQLite::Connector::registerConnector();
|
||||
// Pool_ = std::make_unique<Poco::Data::SessionPool>(new Poco::Data::SessionPool(SQLiteConn_.name(), DBName, 8,
|
||||
// (int)NumSessions, (int)IdleTime));
|
||||
// Pool_ = std::make_unique<Poco::Data::SessionPool>(new
|
||||
// Poco::Data::SessionPool(SQLiteConn_.name(), DBName, 8,
|
||||
// (int)NumSessions,
|
||||
// (int)IdleTime));
|
||||
Pool_ = std::make_unique<Poco::Data::SessionPool>(SQLiteConn_.name(), DBName, 8,
|
||||
(int)NumSessions, (int)IdleTime);
|
||||
return 0;
|
||||
@@ -88,24 +89,21 @@ namespace OpenWifi {
|
||||
inline int StorageClass::Setup_MySQL() {
|
||||
Logger().notice("MySQL StorageClass enabled.");
|
||||
dbType_ = mysql;
|
||||
int NumSessions = (int) MicroServiceConfigGetInt("storage.type.mysql.maxsessions", 64);
|
||||
int IdleTime = (int) MicroServiceConfigGetInt("storage.type.mysql.idletime", 60);
|
||||
auto Host = MicroServiceConfigGetString("storage.type.mysql.host","");
|
||||
auto Username = MicroServiceConfigGetString("storage.type.mysql.username","");
|
||||
auto Password = MicroServiceConfigGetString("storage.type.mysql.password","");
|
||||
auto Database = MicroServiceConfigGetString("storage.type.mysql.database","");
|
||||
auto Port = MicroServiceConfigGetString("storage.type.mysql.port","");
|
||||
int NumSessions = (int)MicroServiceConfigGetInt("storage.type.mysql.maxsessions", 64);
|
||||
int IdleTime = (int)MicroServiceConfigGetInt("storage.type.mysql.idletime", 60);
|
||||
auto Host = MicroServiceConfigGetString("storage.type.mysql.host", "");
|
||||
auto Username = MicroServiceConfigGetString("storage.type.mysql.username", "");
|
||||
auto Password = MicroServiceConfigGetString("storage.type.mysql.password", "");
|
||||
auto Database = MicroServiceConfigGetString("storage.type.mysql.database", "");
|
||||
auto Port = MicroServiceConfigGetString("storage.type.mysql.port", "");
|
||||
|
||||
std::string ConnectionStr =
|
||||
"host=" + Host +
|
||||
";user=" + Username +
|
||||
";password=" + Password +
|
||||
";db=" + Database +
|
||||
";port=" + Port +
|
||||
std::string ConnectionStr = "host=" + Host + ";user=" + Username + ";password=" + Password +
|
||||
";db=" + Database + ";port=" + Port +
|
||||
";compress=true;auto-reconnect=true";
|
||||
|
||||
Poco::Data::MySQL::Connector::registerConnector();
|
||||
Pool_ = std::make_unique<Poco::Data::SessionPool>(MySQLConn_.name(), ConnectionStr, 8, NumSessions, IdleTime);
|
||||
Pool_ = std::make_unique<Poco::Data::SessionPool>(MySQLConn_.name(), ConnectionStr, 8,
|
||||
NumSessions, IdleTime);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -113,28 +111,26 @@ namespace OpenWifi {
|
||||
inline int StorageClass::Setup_PostgreSQL() {
|
||||
Logger().notice("PostgreSQL StorageClass enabled.");
|
||||
dbType_ = pgsql;
|
||||
int NumSessions = (int) MicroServiceConfigGetInt("storage.type.postgresql.maxsessions", 64);
|
||||
int IdleTime = (int) MicroServiceConfigGetInt("storage.type.postgresql.idletime", 60);
|
||||
int NumSessions = (int)MicroServiceConfigGetInt("storage.type.postgresql.maxsessions", 64);
|
||||
int IdleTime = (int)MicroServiceConfigGetInt("storage.type.postgresql.idletime", 60);
|
||||
auto Host = MicroServiceConfigGetString("storage.type.postgresql.host", "");
|
||||
auto Username = MicroServiceConfigGetString("storage.type.postgresql.username", "");
|
||||
auto Password = MicroServiceConfigGetString("storage.type.postgresql.password", "");
|
||||
auto Database = MicroServiceConfigGetString("storage.type.postgresql.database", "");
|
||||
auto Port = MicroServiceConfigGetString("storage.type.postgresql.port", "");
|
||||
auto ConnectionTimeout = MicroServiceConfigGetString("storage.type.postgresql.connectiontimeout", "");
|
||||
auto ConnectionTimeout =
|
||||
MicroServiceConfigGetString("storage.type.postgresql.connectiontimeout", "");
|
||||
|
||||
std::string ConnectionStr =
|
||||
"host=" + Host +
|
||||
" user=" + Username +
|
||||
" password=" + Password +
|
||||
" dbname=" + Database +
|
||||
" port=" + Port +
|
||||
std::string ConnectionStr = "host=" + Host + " user=" + Username + " password=" + Password +
|
||||
" dbname=" + Database + " port=" + Port +
|
||||
" connect_timeout=" + ConnectionTimeout;
|
||||
|
||||
Poco::Data::PostgreSQL::Connector::registerConnector();
|
||||
Pool_ = std::make_unique<Poco::Data::SessionPool>(PostgresConn_.name(), ConnectionStr, 8, NumSessions, IdleTime);
|
||||
Pool_ = std::make_unique<Poco::Data::SessionPool>(PostgresConn_.name(), ConnectionStr, 8,
|
||||
NumSessions, IdleTime);
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -6,36 +6,29 @@
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
|
||||
#include "Poco/Net/SSLManager.h"
|
||||
#include "Poco/DateTimeFormatter.h"
|
||||
#include "Poco/DateTimeFormat.h"
|
||||
#include "Poco/DateTimeFormatter.h"
|
||||
#include "Poco/Net/SSLManager.h"
|
||||
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
PropertiesFileServerEntry::PropertiesFileServerEntry(std::string Address, uint32_t port, std::string Key_file,
|
||||
std::string Cert_file, std::string RootCa, std::string Issuer,
|
||||
std::string ClientCas, std::string Cas,
|
||||
std::string Key_file_password, std::string Name,
|
||||
Poco::Net::Context::VerificationMode M,
|
||||
PropertiesFileServerEntry::PropertiesFileServerEntry(
|
||||
std::string Address, uint32_t port, std::string Key_file, std::string Cert_file,
|
||||
std::string RootCa, std::string Issuer, std::string ClientCas, std::string Cas,
|
||||
std::string Key_file_password, std::string Name, Poco::Net::Context::VerificationMode M,
|
||||
int backlog)
|
||||
: address_(std::move(Address)),
|
||||
port_(port),
|
||||
cert_file_(std::move(Cert_file)),
|
||||
key_file_(std::move(Key_file)),
|
||||
root_ca_(std::move(RootCa)),
|
||||
key_file_password_(std::move(Key_file_password)),
|
||||
issuer_cert_file_(std::move(Issuer)),
|
||||
client_cas_(std::move(ClientCas)),
|
||||
cas_(std::move(Cas)),
|
||||
name_(std::move(Name)),
|
||||
backlog_(backlog),
|
||||
level_(M) {
|
||||
: address_(std::move(Address)), port_(port), cert_file_(std::move(Cert_file)),
|
||||
key_file_(std::move(Key_file)), root_ca_(std::move(RootCa)),
|
||||
key_file_password_(std::move(Key_file_password)), issuer_cert_file_(std::move(Issuer)),
|
||||
client_cas_(std::move(ClientCas)), cas_(std::move(Cas)), name_(std::move(Name)),
|
||||
backlog_(backlog), level_(M){
|
||||
|
||||
};
|
||||
|
||||
[[nodiscard]] Poco::Net::SecureServerSocket PropertiesFileServerEntry::CreateSecureSocket(Poco::Logger &L) const {
|
||||
[[nodiscard]] Poco::Net::SecureServerSocket
|
||||
PropertiesFileServerEntry::CreateSecureSocket(Poco::Logger &L) const {
|
||||
Poco::Net::Context::Params P;
|
||||
|
||||
P.verificationMode = level_;
|
||||
@@ -45,11 +38,13 @@ namespace OpenWifi {
|
||||
P.dhUse2048Bits = true;
|
||||
P.caLocation = cas_;
|
||||
|
||||
auto Context = Poco::AutoPtr<Poco::Net::Context>(new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P));
|
||||
auto Context = Poco::AutoPtr<Poco::Net::Context>(
|
||||
new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P));
|
||||
|
||||
if(!key_file_password_.empty()) {
|
||||
auto PassphraseHandler = Poco::SharedPtr<MyPrivateKeyPassphraseHandler>( new MyPrivateKeyPassphraseHandler(key_file_password_,L));
|
||||
Poco::Net::SSLManager::instance().initializeServer(PassphraseHandler, nullptr,Context);
|
||||
if (!key_file_password_.empty()) {
|
||||
auto PassphraseHandler = Poco::SharedPtr<MyPrivateKeyPassphraseHandler>(
|
||||
new MyPrivateKeyPassphraseHandler(key_file_password_, L));
|
||||
Poco::Net::SSLManager::instance().initializeServer(PassphraseHandler, nullptr, Context);
|
||||
}
|
||||
|
||||
if (!cert_file_.empty() && !key_file_.empty()) {
|
||||
@@ -111,7 +106,8 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Poco::Net::ServerSocket PropertiesFileServerEntry::CreateSocket([[maybe_unused]] Poco::Logger &L) const {
|
||||
[[nodiscard]] Poco::Net::ServerSocket
|
||||
PropertiesFileServerEntry::CreateSocket([[maybe_unused]] Poco::Logger &L) const {
|
||||
Poco::Net::Context::Params P;
|
||||
|
||||
if (address_ == "*") {
|
||||
@@ -127,19 +123,24 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
void PropertiesFileServerEntry::LogCertInfo(Poco::Logger &L, const Poco::Crypto::X509Certificate &C) const {
|
||||
L.information("=============================================================================================");
|
||||
void PropertiesFileServerEntry::LogCertInfo(Poco::Logger &L,
|
||||
const Poco::Crypto::X509Certificate &C) const {
|
||||
L.information("============================================================================"
|
||||
"=================");
|
||||
L.information(fmt::format("> Issuer: {}", C.issuerName()));
|
||||
L.information("---------------------------------------------------------------------------------------------");
|
||||
L.information("----------------------------------------------------------------------------"
|
||||
"-----------------");
|
||||
L.information(fmt::format("> Common Name: {}",
|
||||
C.issuerName(Poco::Crypto::X509Certificate::NID_COMMON_NAME)));
|
||||
L.information(fmt::format("> Country: {}",
|
||||
C.issuerName(Poco::Crypto::X509Certificate::NID_COUNTRY)));
|
||||
L.information(fmt::format("> Locality: {}",
|
||||
C.issuerName(Poco::Crypto::X509Certificate::NID_LOCALITY_NAME)));
|
||||
L.information(fmt::format("> State/Prov: {}",
|
||||
L.information(
|
||||
fmt::format("> State/Prov: {}",
|
||||
C.issuerName(Poco::Crypto::X509Certificate::NID_STATE_OR_PROVINCE)));
|
||||
L.information(fmt::format("> Org name: {}",
|
||||
L.information(
|
||||
fmt::format("> Org name: {}",
|
||||
C.issuerName(Poco::Crypto::X509Certificate::NID_ORGANIZATION_NAME)));
|
||||
L.information(
|
||||
fmt::format("> Org unit: {}",
|
||||
@@ -149,9 +150,11 @@ namespace OpenWifi {
|
||||
C.issuerName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS)));
|
||||
L.information(fmt::format("> Serial#: {}",
|
||||
C.issuerName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER)));
|
||||
L.information("---------------------------------------------------------------------------------------------");
|
||||
L.information("----------------------------------------------------------------------------"
|
||||
"-----------------");
|
||||
L.information(fmt::format("> Subject: {}", C.subjectName()));
|
||||
L.information("---------------------------------------------------------------------------------------------");
|
||||
L.information("----------------------------------------------------------------------------"
|
||||
"-----------------");
|
||||
L.information(fmt::format("> Common Name: {}",
|
||||
C.subjectName(Poco::Crypto::X509Certificate::NID_COMMON_NAME)));
|
||||
L.information(fmt::format("> Country: {}",
|
||||
@@ -172,52 +175,66 @@ namespace OpenWifi {
|
||||
C.subjectName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS)));
|
||||
L.information(fmt::format("> Serial#: {}",
|
||||
C.subjectName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER)));
|
||||
L.information("---------------------------------------------------------------------------------------------");
|
||||
L.information("----------------------------------------------------------------------------"
|
||||
"-----------------");
|
||||
L.information(fmt::format("> Signature Algo: {}", C.signatureAlgorithm()));
|
||||
auto From = Poco::DateTimeFormatter::format(C.validFrom(), Poco::DateTimeFormat::HTTP_FORMAT);
|
||||
auto From =
|
||||
Poco::DateTimeFormatter::format(C.validFrom(), Poco::DateTimeFormat::HTTP_FORMAT);
|
||||
L.information(fmt::format("> Valid from: {}", From));
|
||||
auto Expires =
|
||||
Poco::DateTimeFormatter::format(C.expiresOn(), Poco::DateTimeFormat::HTTP_FORMAT);
|
||||
L.information(fmt::format("> Expires on: {}", Expires));
|
||||
L.information(fmt::format("> Version: {}", (int)C.version()));
|
||||
L.information(fmt::format("> Serial #: {}", C.serialNumber()));
|
||||
L.information("=============================================================================================");
|
||||
L.information("============================================================================"
|
||||
"=================");
|
||||
}
|
||||
|
||||
void PropertiesFileServerEntry::LogCert(Poco::Logger &L) const {
|
||||
try {
|
||||
Poco::Crypto::X509Certificate C(cert_file_);
|
||||
L.information("=============================================================================================");
|
||||
L.information("=============================================================================================");
|
||||
L.information("========================================================================"
|
||||
"=====================");
|
||||
L.information("========================================================================"
|
||||
"=====================");
|
||||
L.information(fmt::format("Certificate Filename: {}", cert_file_));
|
||||
LogCertInfo(L, C);
|
||||
L.information("=============================================================================================");
|
||||
L.information("========================================================================"
|
||||
"=====================");
|
||||
|
||||
if (!issuer_cert_file_.empty()) {
|
||||
Poco::Crypto::X509Certificate C1(issuer_cert_file_);
|
||||
L.information("=============================================================================================");
|
||||
L.information("=============================================================================================");
|
||||
L.information("===================================================================="
|
||||
"=========================");
|
||||
L.information("===================================================================="
|
||||
"=========================");
|
||||
L.information(fmt::format("Issues Certificate Filename: {}", issuer_cert_file_));
|
||||
LogCertInfo(L, C1);
|
||||
L.information("=============================================================================================");
|
||||
L.information("===================================================================="
|
||||
"=========================");
|
||||
}
|
||||
|
||||
if (!client_cas_.empty()) {
|
||||
std::vector<Poco::Crypto::X509Certificate> Certs =
|
||||
Poco::Net::X509Certificate::readPEM(client_cas_);
|
||||
|
||||
L.information("=============================================================================================");
|
||||
L.information("=============================================================================================");
|
||||
L.information("===================================================================="
|
||||
"=========================");
|
||||
L.information("===================================================================="
|
||||
"=========================");
|
||||
L.information(fmt::format("Client CAs Filename: {}", client_cas_));
|
||||
L.information("=============================================================================================");
|
||||
L.information("===================================================================="
|
||||
"=========================");
|
||||
auto i = 1;
|
||||
for (const auto &C3 : Certs) {
|
||||
L.information(fmt::format(" Index: {}", i));
|
||||
L.information("=============================================================================================");
|
||||
L.information("================================================================"
|
||||
"=============================");
|
||||
LogCertInfo(L, C3);
|
||||
i++;
|
||||
}
|
||||
L.information("=============================================================================================");
|
||||
L.information("===================================================================="
|
||||
"=========================");
|
||||
}
|
||||
|
||||
} catch (const Poco::Exception &E) {
|
||||
@@ -230,28 +247,31 @@ namespace OpenWifi {
|
||||
std::vector<Poco::Crypto::X509Certificate> Certs =
|
||||
Poco::Net::X509Certificate::readPEM(root_ca_);
|
||||
|
||||
L.information("=============================================================================================");
|
||||
L.information("=============================================================================================");
|
||||
L.information("========================================================================"
|
||||
"=====================");
|
||||
L.information("========================================================================"
|
||||
"=====================");
|
||||
L.information(fmt::format("CA Filename: {}", root_ca_));
|
||||
L.information("=============================================================================================");
|
||||
L.information("========================================================================"
|
||||
"=====================");
|
||||
auto i = 1;
|
||||
for (const auto &C : Certs) {
|
||||
L.information(fmt::format(" Index: {}", i));
|
||||
L.information("=============================================================================================");
|
||||
L.information("===================================================================="
|
||||
"=========================");
|
||||
LogCertInfo(L, C);
|
||||
i++;
|
||||
}
|
||||
L.information("=============================================================================================");
|
||||
L.information("========================================================================"
|
||||
"=====================");
|
||||
} catch (const Poco::Exception &E) {
|
||||
L.log(E);
|
||||
}
|
||||
}
|
||||
|
||||
SubSystemServer::SubSystemServer(const std::string &Name, const std::string &LoggingPrefix,
|
||||
const std::string &SubSystemConfigPrefix):
|
||||
Name_(Name),
|
||||
LoggerPrefix_(LoggingPrefix),
|
||||
SubSystemConfigPrefix_(SubSystemConfigPrefix) {
|
||||
const std::string &SubSystemConfigPrefix)
|
||||
: Name_(Name), LoggerPrefix_(LoggingPrefix), SubSystemConfigPrefix_(SubSystemConfigPrefix) {
|
||||
}
|
||||
|
||||
void SubSystemServer::initialize([[maybe_unused]] Poco::Util::Application &self) {
|
||||
@@ -259,10 +279,13 @@ namespace OpenWifi {
|
||||
bool good = true;
|
||||
|
||||
auto NewLevel = MicroServiceConfigGetString("logging.level." + Name_, "");
|
||||
if(NewLevel.empty())
|
||||
Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel()));
|
||||
if (NewLevel.empty())
|
||||
Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(
|
||||
LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel()));
|
||||
else
|
||||
Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::parseLevel(NewLevel)));
|
||||
Logger_ = std::make_unique<LoggerWrapper>(
|
||||
Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(),
|
||||
Poco::Logger::parseLevel(NewLevel)));
|
||||
|
||||
ConfigServersList_.clear();
|
||||
while (good) {
|
||||
@@ -297,14 +320,11 @@ namespace OpenWifi {
|
||||
} else if (L == "once")
|
||||
M = Poco::Net::Context::VERIFY_ONCE;
|
||||
|
||||
PropertiesFileServerEntry entry(MicroServiceConfigGetString(address, ""),
|
||||
MicroServiceConfigGetInt(port, 0),
|
||||
MicroServiceConfigPath(key, ""),
|
||||
MicroServiceConfigPath(cert, ""),
|
||||
MicroServiceConfigPath(rootca, ""),
|
||||
MicroServiceConfigPath(issuer, ""),
|
||||
MicroServiceConfigPath(clientcas, ""),
|
||||
MicroServiceConfigPath(cas, ""),
|
||||
PropertiesFileServerEntry entry(
|
||||
MicroServiceConfigGetString(address, ""), MicroServiceConfigGetInt(port, 0),
|
||||
MicroServiceConfigPath(key, ""), MicroServiceConfigPath(cert, ""),
|
||||
MicroServiceConfigPath(rootca, ""), MicroServiceConfigPath(issuer, ""),
|
||||
MicroServiceConfigPath(clientcas, ""), MicroServiceConfigPath(cas, ""),
|
||||
MicroServiceConfigGetString(key_password, ""),
|
||||
MicroServiceConfigGetString(name, ""), M,
|
||||
(int)MicroServiceConfigGetInt(backlog, 64));
|
||||
@@ -314,7 +334,4 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
} // namespace OpenWifi
|
||||
@@ -4,32 +4,30 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include "Poco/Util/Application.h"
|
||||
#include "Poco/Net/Context.h"
|
||||
#include "Poco/Net/SecureServerSocket.h"
|
||||
#include "Poco/Net/PrivateKeyPassphraseHandler.h"
|
||||
#include "Poco/Net/SecureServerSocket.h"
|
||||
#include "Poco/Util/Application.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class MyPrivateKeyPassphraseHandler : public Poco::Net::PrivateKeyPassphraseHandler {
|
||||
public:
|
||||
explicit MyPrivateKeyPassphraseHandler(const std::string &Password, Poco::Logger & Logger):
|
||||
PrivateKeyPassphraseHandler(true),
|
||||
Password_(Password),
|
||||
Logger_(Logger) {
|
||||
}
|
||||
explicit MyPrivateKeyPassphraseHandler(const std::string &Password, Poco::Logger &Logger)
|
||||
: PrivateKeyPassphraseHandler(true), Password_(Password), Logger_(Logger) {}
|
||||
|
||||
void onPrivateKeyRequested([[maybe_unused]] const void * pSender,std::string & privateKey) {
|
||||
poco_information(Logger_,"Returning key passphrase.");
|
||||
void onPrivateKeyRequested([[maybe_unused]] const void *pSender, std::string &privateKey) {
|
||||
poco_information(Logger_, "Returning key passphrase.");
|
||||
privateKey = Password_;
|
||||
};
|
||||
inline Poco::Logger & Logger() { return Logger_; }
|
||||
inline Poco::Logger &Logger() { return Logger_; }
|
||||
|
||||
private:
|
||||
std::string Password_;
|
||||
Poco::Logger & Logger_;
|
||||
Poco::Logger &Logger_;
|
||||
};
|
||||
|
||||
class PropertiesFileServerEntry {
|
||||
@@ -76,24 +74,24 @@ namespace OpenWifi {
|
||||
|
||||
class SubSystemServer : public Poco::Util::Application::Subsystem {
|
||||
public:
|
||||
SubSystemServer(const std::string & Name, const std::string &LoggingPrefix,
|
||||
const std::string & SubSystemConfigPrefix);
|
||||
SubSystemServer(const std::string &Name, const std::string &LoggingPrefix,
|
||||
const std::string &SubSystemConfigPrefix);
|
||||
|
||||
void initialize(Poco::Util::Application &self) override;
|
||||
inline void uninitialize() override {
|
||||
}
|
||||
inline void uninitialize() override {}
|
||||
inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override {
|
||||
poco_information(Logger_->L_,"Reloading of this subsystem is not supported.");
|
||||
poco_information(Logger_->L_, "Reloading of this subsystem is not supported.");
|
||||
}
|
||||
inline void defineOptions([[maybe_unused]] Poco::Util::OptionSet &options) override {
|
||||
}
|
||||
inline const std::string & Name() const { return Name_; };
|
||||
inline const char * name() const override { return Name_.c_str(); }
|
||||
inline void defineOptions([[maybe_unused]] Poco::Util::OptionSet &options) override {}
|
||||
inline const std::string &Name() const { return Name_; };
|
||||
inline const char *name() const override { return Name_.c_str(); }
|
||||
|
||||
inline const PropertiesFileServerEntry & Host(uint64_t index) { return ConfigServersList_[index]; };
|
||||
inline const PropertiesFileServerEntry &Host(uint64_t index) {
|
||||
return ConfigServersList_[index];
|
||||
};
|
||||
inline uint64_t HostSize() const { return ConfigServersList_.size(); }
|
||||
inline Poco::Logger & Logger() const { return Logger_->L_; }
|
||||
inline void SetLoggingLevel(const std::string & levelName) {
|
||||
inline Poco::Logger &Logger() const { return Logger_->L_; }
|
||||
inline void SetLoggingLevel(const std::string &levelName) {
|
||||
Logger_->L_.setLevel(Poco::Logger::parseLevel(levelName));
|
||||
}
|
||||
inline int GetLoggingLevel() { return Logger_->L_.getLevel(); }
|
||||
@@ -102,10 +100,8 @@ namespace OpenWifi {
|
||||
virtual void Stop() = 0;
|
||||
|
||||
struct LoggerWrapper {
|
||||
Poco::Logger & L_;
|
||||
LoggerWrapper(Poco::Logger &L) :
|
||||
L_(L) {
|
||||
}
|
||||
Poco::Logger &L_;
|
||||
LoggerWrapper(Poco::Logger &L) : L_(L) {}
|
||||
};
|
||||
|
||||
protected:
|
||||
|
||||
@@ -5,7 +5,4 @@
|
||||
#include "framework/UI_WebSocketClientNotifications.h"
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
}
|
||||
|
||||
namespace OpenWifi {}
|
||||
|
||||
@@ -9,12 +9,12 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
template<typename ContentStruct>
|
||||
template <typename ContentStruct>
|
||||
|
||||
struct WebSocketNotification {
|
||||
inline static uint64_t xid = 1;
|
||||
uint64_t notification_id = ++xid;
|
||||
std::uint64_t type_id=0;
|
||||
std::uint64_t type_id = 0;
|
||||
ContentStruct content;
|
||||
|
||||
void to_json(Poco::JSON::Object &Obj) const;
|
||||
@@ -22,14 +22,14 @@ namespace OpenWifi {
|
||||
bool from_json(const Poco::JSON::Object::Ptr &Obj);
|
||||
};
|
||||
|
||||
template<typename ContentStruct>
|
||||
template <typename ContentStruct>
|
||||
void WebSocketNotification<ContentStruct>::to_json(Poco::JSON::Object &Obj) const {
|
||||
RESTAPI_utils::field_to_json(Obj, "notification_id", notification_id);
|
||||
RESTAPI_utils::field_to_json(Obj, "type_id", type_id);
|
||||
RESTAPI_utils::field_to_json(Obj, "content", content);
|
||||
}
|
||||
|
||||
template<typename ContentStruct>
|
||||
template <typename ContentStruct>
|
||||
bool WebSocketNotification<ContentStruct>::from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
try {
|
||||
RESTAPI_utils::field_from_json(Obj, "notification_id", notification_id);
|
||||
@@ -37,9 +37,7 @@ namespace OpenWifi {
|
||||
RESTAPI_utils::field_from_json(Obj, "content", content);
|
||||
return true;
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace OpenWifi
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
|
||||
#include <mutex>
|
||||
|
||||
#include "Poco/NObserver.h"
|
||||
#include "Poco/JSON/JSONException.h"
|
||||
#include "Poco/JSON/Parser.h"
|
||||
#include "Poco/Logger.h"
|
||||
#include "Poco/NObserver.h"
|
||||
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
#include "framework/AuthClient.h"
|
||||
#include "framework/MicroServiceFuncs.h"
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
|
||||
#include "fmt/format.h"
|
||||
|
||||
@@ -19,80 +19,82 @@
|
||||
#include "AuthService.h"
|
||||
#endif
|
||||
|
||||
#define DBG { std::cout << __LINE__ << std::endl; }
|
||||
#define DBG \
|
||||
{ std::cout << __LINE__ << std::endl; }
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
void UI_WebSocketClientServer::NewClient(Poco::Net::WebSocket & WS, const std::string &Id, const std::string &UserName, std::uint64_t TID ) {
|
||||
void UI_WebSocketClientServer::NewClient(Poco::Net::WebSocket &WS, const std::string &Id,
|
||||
const std::string &UserName, std::uint64_t TID) {
|
||||
|
||||
std::lock_guard G(LocalMutex_);
|
||||
auto Client = std::make_unique<UI_WebSocketClientInfo>(WS,Id, UserName);
|
||||
auto Client = std::make_unique<UI_WebSocketClientInfo>(WS, Id, UserName);
|
||||
auto ClientSocket = Client->WS_->impl()->sockfd();
|
||||
TID_ = TID;
|
||||
Client->WS_->setNoDelay(true);
|
||||
Client->WS_->setKeepAlive(true);
|
||||
Client->WS_->setBlocking(false);
|
||||
Reactor_.addEventHandler(*Client->WS_,
|
||||
Reactor_.addEventHandler(
|
||||
*Client->WS_,
|
||||
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ReadableNotification>(
|
||||
*this, &UI_WebSocketClientServer::OnSocketReadable));
|
||||
Reactor_.addEventHandler(*Client->WS_,
|
||||
Reactor_.addEventHandler(
|
||||
*Client->WS_,
|
||||
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ShutdownNotification>(
|
||||
*this, &UI_WebSocketClientServer::OnSocketShutdown));
|
||||
Reactor_.addEventHandler(*Client->WS_,
|
||||
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ErrorNotification>(
|
||||
Reactor_.addEventHandler(
|
||||
*Client->WS_, Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ErrorNotification>(
|
||||
*this, &UI_WebSocketClientServer::OnSocketError));
|
||||
Client->SocketRegistered_ = true;
|
||||
Clients_[ClientSocket] = std::move(Client);
|
||||
UsersConnected_ = Clients_.size();
|
||||
}
|
||||
|
||||
void UI_WebSocketClientServer::SetProcessor( UI_WebSocketClientProcessor * F) {
|
||||
Processor_ = F;
|
||||
}
|
||||
void UI_WebSocketClientServer::SetProcessor(UI_WebSocketClientProcessor *F) { Processor_ = F; }
|
||||
|
||||
UI_WebSocketClientServer::UI_WebSocketClientServer() noexcept:
|
||||
SubSystemServer("WebSocketClientServer", "UI-WSCLNT-SVR", "websocketclients")
|
||||
{
|
||||
}
|
||||
UI_WebSocketClientServer::UI_WebSocketClientServer() noexcept
|
||||
: SubSystemServer("WebSocketClientServer", "UI-WSCLNT-SVR", "websocketclients") {}
|
||||
|
||||
void UI_WebSocketClientServer::run() {
|
||||
Running_ = true;
|
||||
while(Running_) {
|
||||
while (Running_) {
|
||||
Poco::Thread::trySleep(2000);
|
||||
|
||||
if(!Running_)
|
||||
if (!Running_)
|
||||
break;
|
||||
|
||||
std::lock_guard G(LocalMutex_);
|
||||
for(const auto i:ToBeRemoved_) {
|
||||
for (const auto i : ToBeRemoved_) {
|
||||
// std::cout << "Erasing old WS UI connection..." << std::endl;
|
||||
Clients_.erase(i);
|
||||
}
|
||||
ToBeRemoved_.clear();
|
||||
UsersConnected_ = Clients_.size();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void UI_WebSocketClientServer::EndConnection(ClientList::iterator Client) {
|
||||
if(Client->second->SocketRegistered_) {
|
||||
if (Client->second->SocketRegistered_) {
|
||||
Client->second->SocketRegistered_ = false;
|
||||
Reactor_.removeEventHandler(*Client->second->WS_,
|
||||
Poco::NObserver<UI_WebSocketClientServer,
|
||||
Poco::Net::ReadableNotification>(*this,&UI_WebSocketClientServer::OnSocketReadable));
|
||||
Reactor_.removeEventHandler(*Client->second->WS_,
|
||||
Poco::NObserver<UI_WebSocketClientServer,
|
||||
Poco::Net::ShutdownNotification>(*this,&UI_WebSocketClientServer::OnSocketShutdown));
|
||||
Reactor_.removeEventHandler(*Client->second->WS_,
|
||||
Poco::NObserver<UI_WebSocketClientServer,
|
||||
Poco::Net::ErrorNotification>(*this,&UI_WebSocketClientServer::OnSocketError));
|
||||
Reactor_.removeEventHandler(
|
||||
*Client->second->WS_,
|
||||
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ReadableNotification>(
|
||||
*this, &UI_WebSocketClientServer::OnSocketReadable));
|
||||
Reactor_.removeEventHandler(
|
||||
*Client->second->WS_,
|
||||
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ShutdownNotification>(
|
||||
*this, &UI_WebSocketClientServer::OnSocketShutdown));
|
||||
Reactor_.removeEventHandler(
|
||||
*Client->second->WS_,
|
||||
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ErrorNotification>(
|
||||
*this, &UI_WebSocketClientServer::OnSocketError));
|
||||
}
|
||||
ToBeRemoved_.push_back(Client);
|
||||
}
|
||||
|
||||
int UI_WebSocketClientServer::Start() {
|
||||
poco_information(Logger(),"Starting...");
|
||||
GoogleApiKey_ = MicroServiceConfigGetString("google.apikey","");
|
||||
poco_information(Logger(), "Starting...");
|
||||
GoogleApiKey_ = MicroServiceConfigGetString("google.apikey", "");
|
||||
GeoCodeEnabled_ = !GoogleApiKey_.empty();
|
||||
ReactorThread_.start(Reactor_);
|
||||
ReactorThread_.setName("ws:ui-reactor");
|
||||
@@ -102,29 +104,31 @@ namespace OpenWifi {
|
||||
};
|
||||
|
||||
void UI_WebSocketClientServer::Stop() {
|
||||
if(Running_) {
|
||||
poco_information(Logger(),"Stopping...");
|
||||
if (Running_) {
|
||||
poco_information(Logger(), "Stopping...");
|
||||
Clients_.clear();
|
||||
Reactor_.stop();
|
||||
ReactorThread_.join();
|
||||
Running_ = false;
|
||||
CleanerThread_.wakeUp();
|
||||
CleanerThread_.join();
|
||||
poco_information(Logger(),"Stopped...");
|
||||
poco_information(Logger(), "Stopped...");
|
||||
}
|
||||
};
|
||||
|
||||
bool UI_WebSocketClientServer::IsFiltered(std::uint64_t id, const OpenWifi::UI_WebSocketClientInfo &Client) {
|
||||
return std::find(Client.Filter_.begin(), Client.Filter_.end(),id)!=end(Client.Filter_);
|
||||
bool UI_WebSocketClientServer::IsFiltered(std::uint64_t id,
|
||||
const OpenWifi::UI_WebSocketClientInfo &Client) {
|
||||
return std::find(Client.Filter_.begin(), Client.Filter_.end(), id) != end(Client.Filter_);
|
||||
}
|
||||
|
||||
bool UI_WebSocketClientServer::SendToUser(const std::string &UserName, std::uint64_t id, const std::string &Payload) {
|
||||
bool UI_WebSocketClientServer::SendToUser(const std::string &UserName, std::uint64_t id,
|
||||
const std::string &Payload) {
|
||||
std::lock_guard G(LocalMutex_);
|
||||
|
||||
for(const auto &Client:Clients_) {
|
||||
if(Client.second->UserName_ == UserName) {
|
||||
for (const auto &Client : Clients_) {
|
||||
if (Client.second->UserName_ == UserName) {
|
||||
try {
|
||||
if(!IsFiltered(id,*Client.second) && Client.second->Authenticated_) {
|
||||
if (!IsFiltered(id, *Client.second) && Client.second->Authenticated_) {
|
||||
return Client.second->WS_->sendFrame(
|
||||
Payload.c_str(), (int)Payload.size()) == (int)Payload.size();
|
||||
} else {
|
||||
@@ -141,30 +145,31 @@ namespace OpenWifi {
|
||||
void UI_WebSocketClientServer::SendToAll(std::uint64_t id, const std::string &Payload) {
|
||||
std::lock_guard G(LocalMutex_);
|
||||
|
||||
for(const auto &Client:Clients_) {
|
||||
for (const auto &Client : Clients_) {
|
||||
try {
|
||||
if(!IsFiltered(id,*Client.second) && Client.second->Authenticated_)
|
||||
Client.second->WS_->sendFrame(Payload.c_str(),(int)Payload.size());
|
||||
if (!IsFiltered(id, *Client.second) && Client.second->Authenticated_)
|
||||
Client.second->WS_->sendFrame(Payload.c_str(), (int)Payload.size());
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
UI_WebSocketClientServer::ClientList::iterator UI_WebSocketClientServer::FindWSClient( [[maybe_unused]] std::lock_guard<std::recursive_mutex> &G, int ClientSocket) {
|
||||
UI_WebSocketClientServer::ClientList::iterator UI_WebSocketClientServer::FindWSClient(
|
||||
[[maybe_unused]] std::lock_guard<std::recursive_mutex> &G, int ClientSocket) {
|
||||
return Clients_.find(ClientSocket);
|
||||
}
|
||||
|
||||
void UI_WebSocketClientServer::SortNotifications() {
|
||||
struct {
|
||||
bool operator()(const NotificationEntry &A, const NotificationEntry & B) const {
|
||||
return A.id < B.id; };
|
||||
bool operator()(const NotificationEntry &A, const NotificationEntry &B) const {
|
||||
return A.id < B.id;
|
||||
};
|
||||
} CompareNotifications;
|
||||
std::sort(NotificationTypes_.begin(), NotificationTypes_.end(), CompareNotifications);
|
||||
|
||||
NotificationTypesJSON_.clear();
|
||||
Poco::JSON::Array AllNotifications;
|
||||
for(const auto ¬ification:NotificationTypes_) {
|
||||
for (const auto ¬ification : NotificationTypes_) {
|
||||
Poco::JSON::Object Notification;
|
||||
Notification.set("id", notification.id);
|
||||
Notification.set("helper", notification.helper);
|
||||
@@ -173,20 +178,24 @@ namespace OpenWifi {
|
||||
NotificationTypesJSON_.set("notificationTypes", AllNotifications);
|
||||
}
|
||||
|
||||
void UI_WebSocketClientServer::RegisterNotifications(const OpenWifi::UI_WebSocketClientServer::NotificationTypeIdVec &Notifications) {
|
||||
std::copy(Notifications.begin(), Notifications.end(), std::back_inserter(NotificationTypes_));
|
||||
void UI_WebSocketClientServer::RegisterNotifications(
|
||||
const OpenWifi::UI_WebSocketClientServer::NotificationTypeIdVec &Notifications) {
|
||||
std::copy(Notifications.begin(), Notifications.end(),
|
||||
std::back_inserter(NotificationTypes_));
|
||||
SortNotifications();
|
||||
}
|
||||
|
||||
void UI_WebSocketClientServer::OnSocketError([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf) {
|
||||
void UI_WebSocketClientServer::OnSocketError(
|
||||
[[maybe_unused]] const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf) {
|
||||
std::lock_guard G(LocalMutex_);
|
||||
auto Client = Clients_.find(pNf->socket().impl()->sockfd());
|
||||
if(Client==end(Clients_))
|
||||
if (Client == end(Clients_))
|
||||
return;
|
||||
EndConnection(Client);
|
||||
}
|
||||
|
||||
void UI_WebSocketClientServer::OnSocketReadable([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf) {
|
||||
void UI_WebSocketClientServer::OnSocketReadable(
|
||||
[[maybe_unused]] const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf) {
|
||||
|
||||
UI_WebSocketClientServer::ClientList::iterator Client;
|
||||
std::lock_guard G(LocalMutex_);
|
||||
@@ -194,7 +203,7 @@ namespace OpenWifi {
|
||||
try {
|
||||
|
||||
Client = Clients_.find(pNf->socket().impl()->sockfd());
|
||||
if( Client == end(Clients_))
|
||||
if (Client == end(Clients_))
|
||||
return;
|
||||
|
||||
Poco::Buffer<char> IncomingFrame(0);
|
||||
@@ -204,7 +213,9 @@ namespace OpenWifi {
|
||||
auto Op = flags & Poco::Net::WebSocket::FRAME_OP_BITMASK;
|
||||
|
||||
if (n == 0) {
|
||||
poco_debug(Logger(),fmt::format("CLOSE({}): {} UI Client is closing WS connection.", Client->second->Id_, Client->second->UserName_));
|
||||
poco_debug(Logger(),
|
||||
fmt::format("CLOSE({}): {} UI Client is closing WS connection.",
|
||||
Client->second->Id_, Client->second->UserName_));
|
||||
return EndConnection(Client);
|
||||
}
|
||||
|
||||
@@ -217,7 +228,9 @@ namespace OpenWifi {
|
||||
case Poco::Net::WebSocket::FRAME_OP_PONG: {
|
||||
} break;
|
||||
case Poco::Net::WebSocket::FRAME_OP_CLOSE: {
|
||||
poco_debug(Logger(),fmt::format("CLOSE({}): {} UI Client is closing WS connection.", Client->second->Id_, Client->second->UserName_));
|
||||
poco_debug(Logger(),
|
||||
fmt::format("CLOSE({}): {} UI Client is closing WS connection.",
|
||||
Client->second->Id_, Client->second->UserName_));
|
||||
return EndConnection(Client);
|
||||
} break;
|
||||
case Poco::Net::WebSocket::FRAME_OP_TEXT: {
|
||||
@@ -232,46 +245,50 @@ namespace OpenWifi {
|
||||
#endif
|
||||
if (Tokens.size() == 2 &&
|
||||
#if defined(TIP_SECURITY_SERVICE)
|
||||
AuthService()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_, Expired)) {
|
||||
AuthService()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_,
|
||||
Expired)) {
|
||||
#else
|
||||
AuthClient()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_, Expired, Contacted)) {
|
||||
AuthClient()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_,
|
||||
Expired, Contacted)) {
|
||||
#endif
|
||||
Client->second->Authenticated_ = true;
|
||||
Client->second->UserName_ = Client->second->UserInfo_.userinfo.email;
|
||||
poco_debug(Logger(),fmt::format("START({}): {} UI Client is starting WS connection.", Client->second->Id_, Client->second->UserName_));
|
||||
poco_debug(Logger(),
|
||||
fmt::format("START({}): {} UI Client is starting WS connection.",
|
||||
Client->second->Id_, Client->second->UserName_));
|
||||
auto WelcomeMessage = NotificationTypesJSON_;
|
||||
WelcomeMessage.set("success", "Welcome! Bienvenue! Bienvenidos!");
|
||||
std::ostringstream OS;
|
||||
WelcomeMessage.stringify(OS);
|
||||
Client->second->WS_->sendFrame(OS.str().c_str(), (int) OS.str().size());
|
||||
Client->second->WS_->sendFrame(OS.str().c_str(), (int)OS.str().size());
|
||||
Client->second->UserName_ = Client->second->UserInfo_.userinfo.email;
|
||||
} else {
|
||||
Poco::JSON::Object WelcomeMessage;
|
||||
WelcomeMessage.set("error", "Invalid token. Closing connection.");
|
||||
std::ostringstream OS;
|
||||
WelcomeMessage.stringify(OS);
|
||||
Client->second->WS_->sendFrame(OS.str().c_str(), (int) OS.str().size());
|
||||
Client->second->WS_->sendFrame(OS.str().c_str(), (int)OS.str().size());
|
||||
return EndConnection(Client);
|
||||
}
|
||||
} else {
|
||||
Poco::JSON::Parser P;
|
||||
auto Obj =
|
||||
P.parse(IncomingFrame.begin()).extract<Poco::JSON::Object::Ptr>();
|
||||
auto Obj = P.parse(IncomingFrame.begin()).extract<Poco::JSON::Object::Ptr>();
|
||||
|
||||
if(Obj->has(DropMessagesCommand) && Obj->isArray(DropMessagesCommand)) {
|
||||
if (Obj->has(DropMessagesCommand) && Obj->isArray(DropMessagesCommand)) {
|
||||
auto Filters = Obj->getArray(DropMessagesCommand);
|
||||
Client->second->Filter_.clear();
|
||||
for(const auto &Filter:*Filters) {
|
||||
Client->second->Filter_.emplace_back( (std::uint64_t) Filter);
|
||||
for (const auto &Filter : *Filters) {
|
||||
Client->second->Filter_.emplace_back((std::uint64_t)Filter);
|
||||
}
|
||||
std::sort(begin(Client->second->Filter_),end(Client->second->Filter_));
|
||||
std::sort(begin(Client->second->Filter_), end(Client->second->Filter_));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string Answer;
|
||||
bool CloseConnection=false;
|
||||
bool CloseConnection = false;
|
||||
if (Processor_ != nullptr) {
|
||||
Processor_->Processor(Obj, Answer, CloseConnection,Client->second->UserInfo_.userinfo);
|
||||
Processor_->Processor(Obj, Answer, CloseConnection,
|
||||
Client->second->UserInfo_.userinfo);
|
||||
}
|
||||
if (!Answer.empty())
|
||||
Client->second->WS_->sendFrame(Answer.c_str(), (int)Answer.size());
|
||||
@@ -279,7 +296,7 @@ namespace OpenWifi {
|
||||
Client->second->WS_->sendFrame("{}", 2);
|
||||
}
|
||||
|
||||
if(CloseConnection) {
|
||||
if (CloseConnection) {
|
||||
return EndConnection(Client);
|
||||
}
|
||||
}
|
||||
@@ -292,7 +309,8 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
void UI_WebSocketClientServer::OnSocketShutdown([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf) {
|
||||
void UI_WebSocketClientServer::OnSocketShutdown(
|
||||
[[maybe_unused]] const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf) {
|
||||
try {
|
||||
std::lock_guard G(LocalMutex_);
|
||||
auto Client = Clients_.find(pNf->socket().impl()->sockfd());
|
||||
@@ -300,7 +318,6 @@ namespace OpenWifi {
|
||||
return;
|
||||
EndConnection(Client);
|
||||
} catch (...) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#include "Poco/Runnable.h"
|
||||
#include "Poco/Net/SocketReactor.h"
|
||||
#include "Poco/Net/WebSocket.h"
|
||||
#include "Poco/JSON/Object.h"
|
||||
#include "Poco/Net/SocketNotification.h"
|
||||
#include "Poco/Net/SocketReactor.h"
|
||||
#include "Poco/Net/WebSocket.h"
|
||||
#include "Poco/Runnable.h"
|
||||
|
||||
#include "RESTObjects/RESTAPI_SecurityObjects.h"
|
||||
#include "framework/SubSystemServer.h"
|
||||
@@ -21,7 +21,9 @@ namespace OpenWifi {
|
||||
|
||||
class UI_WebSocketClientProcessor {
|
||||
public:
|
||||
virtual void Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done , const SecurityObjects::UserInfo & UserInfo) = 0;
|
||||
virtual void Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done,
|
||||
const SecurityObjects::UserInfo &UserInfo) = 0;
|
||||
|
||||
private:
|
||||
};
|
||||
|
||||
@@ -30,11 +32,12 @@ namespace OpenWifi {
|
||||
std::string Id_;
|
||||
std::string UserName_;
|
||||
bool Authenticated_ = false;
|
||||
bool SocketRegistered_=false;
|
||||
bool SocketRegistered_ = false;
|
||||
std::vector<std::uint64_t> Filter_;
|
||||
SecurityObjects::UserInfoAndPolicy UserInfo_;
|
||||
|
||||
UI_WebSocketClientInfo(Poco::Net::WebSocket &WS, const std::string &Id, const std::string &username) {
|
||||
UI_WebSocketClientInfo(Poco::Net::WebSocket &WS, const std::string &Id,
|
||||
const std::string &username) {
|
||||
WS_ = std::make_unique<Poco::Net::WebSocket>(WS);
|
||||
Id_ = Id;
|
||||
UserName_ = username;
|
||||
@@ -49,26 +52,26 @@ namespace OpenWifi {
|
||||
return instance_;
|
||||
}
|
||||
|
||||
bool IsAnyoneConnected() {
|
||||
return UsersConnected_;
|
||||
}
|
||||
bool IsAnyoneConnected() { return UsersConnected_; }
|
||||
|
||||
int Start() override;
|
||||
void Stop() override;
|
||||
void run() override;
|
||||
Poco::Net::SocketReactor & Reactor() { return Reactor_; }
|
||||
void NewClient(Poco::Net::WebSocket &WS, const std::string &Id, const std::string &UserName, std::uint64_t TID);
|
||||
Poco::Net::SocketReactor &Reactor() { return Reactor_; }
|
||||
void NewClient(Poco::Net::WebSocket &WS, const std::string &Id, const std::string &UserName,
|
||||
std::uint64_t TID);
|
||||
void SetProcessor(UI_WebSocketClientProcessor *F);
|
||||
[[nodiscard]] inline bool GeoCodeEnabled() const { return GeoCodeEnabled_; }
|
||||
[[nodiscard]] inline std::string GoogleApiKey() const { return GoogleApiKey_; }
|
||||
|
||||
template <typename T> bool
|
||||
SendUserNotification(const std::string &userName, const WebSocketNotification<T> &Notification) {
|
||||
template <typename T>
|
||||
bool SendUserNotification(const std::string &userName,
|
||||
const WebSocketNotification<T> &Notification) {
|
||||
|
||||
Poco::JSON::Object Payload;
|
||||
Notification.to_json(Payload);
|
||||
Poco::JSON::Object Msg;
|
||||
Msg.set("notification",Payload);
|
||||
Msg.set("notification", Payload);
|
||||
std::ostringstream OO;
|
||||
Msg.stringify(OO);
|
||||
|
||||
@@ -79,29 +82,30 @@ namespace OpenWifi {
|
||||
Poco::JSON::Object Payload;
|
||||
Notification.to_json(Payload);
|
||||
Poco::JSON::Object Msg;
|
||||
Msg.set("notification",Payload);
|
||||
Msg.set("notification", Payload);
|
||||
std::ostringstream OO;
|
||||
Msg.stringify(OO);
|
||||
SendToAll(Notification.type_id, OO.str());
|
||||
}
|
||||
|
||||
[[nodiscard]] bool SendToUser(const std::string &userName, std::uint64_t id, const std::string &Payload);
|
||||
[[nodiscard]] bool SendToUser(const std::string &userName, std::uint64_t id,
|
||||
const std::string &Payload);
|
||||
void SendToAll(std::uint64_t id, const std::string &Payload);
|
||||
|
||||
struct NotificationEntry {
|
||||
std::uint64_t id=0;
|
||||
std::uint64_t id = 0;
|
||||
std::string helper;
|
||||
};
|
||||
|
||||
using ClientList = std::map<int,std::unique_ptr<UI_WebSocketClientInfo>>;
|
||||
using ClientList = std::map<int, std::unique_ptr<UI_WebSocketClientInfo>>;
|
||||
using NotificationTypeIdVec = std::vector<NotificationEntry>;
|
||||
|
||||
void RegisterNotifications(const NotificationTypeIdVec & Notifications);
|
||||
void RegisterNotifications(const NotificationTypeIdVec &Notifications);
|
||||
bool IsFiltered(std::uint64_t id, const UI_WebSocketClientInfo &Client);
|
||||
|
||||
private:
|
||||
volatile bool Running_ = false;
|
||||
std::atomic_uint64_t UsersConnected_=0;
|
||||
std::atomic_uint64_t UsersConnected_ = 0;
|
||||
Poco::Net::SocketReactor Reactor_;
|
||||
Poco::Thread ReactorThread_;
|
||||
Poco::Thread CleanerThread_;
|
||||
@@ -113,7 +117,7 @@ namespace OpenWifi {
|
||||
NotificationTypeIdVec NotificationTypes_;
|
||||
Poco::JSON::Object NotificationTypesJSON_;
|
||||
std::vector<ClientList::iterator> ToBeRemoved_;
|
||||
std::uint64_t TID_=0;
|
||||
std::uint64_t TID_ = 0;
|
||||
|
||||
UI_WebSocketClientServer() noexcept;
|
||||
void EndConnection(ClientList::iterator Client);
|
||||
@@ -122,12 +126,12 @@ namespace OpenWifi {
|
||||
void OnSocketShutdown(const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf);
|
||||
void OnSocketError(const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf);
|
||||
|
||||
ClientList::iterator FindWSClient( std::lock_guard<std::recursive_mutex> &G, int ClientSocket);
|
||||
ClientList::iterator FindWSClient(std::lock_guard<std::recursive_mutex> &G,
|
||||
int ClientSocket);
|
||||
|
||||
void SortNotifications();
|
||||
};
|
||||
|
||||
inline auto UI_WebSocketClientServer() { return UI_WebSocketClientServer::instance(); }
|
||||
|
||||
};
|
||||
|
||||
}; // namespace OpenWifi
|
||||
|
||||
@@ -5,43 +5,46 @@
|
||||
#pragma once
|
||||
|
||||
#include "framework/SubSystemServer.h"
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
#include "framework/UI_WebSocketClientNotifications.h"
|
||||
|
||||
#include "framework/UI_WebSocketClientServer.h"
|
||||
|
||||
namespace OpenWifi {
|
||||
|
||||
class WebSocketLogger : public Poco::Channel {
|
||||
public:
|
||||
WebSocketLogger() {}
|
||||
|
||||
WebSocketLogger() {
|
||||
}
|
||||
~WebSocketLogger() {}
|
||||
|
||||
~WebSocketLogger() {
|
||||
}
|
||||
|
||||
std::string getProperty( [[maybe_unused]] const std::string &p ) const {
|
||||
std::string getProperty([[maybe_unused]] const std::string &p) const {
|
||||
std::cout << "WS getProperty" << std::endl;
|
||||
return "";
|
||||
}
|
||||
|
||||
void close() final {
|
||||
}
|
||||
void close() final {}
|
||||
|
||||
void open() final {
|
||||
}
|
||||
void open() final {}
|
||||
|
||||
static std::string to_string(Poco::Message::Priority p) {
|
||||
switch(p) {
|
||||
case Poco::Message::PRIO_INFORMATION: return "information";
|
||||
case Poco::Message::PRIO_CRITICAL: return "critical";
|
||||
case Poco::Message::PRIO_DEBUG: return "debug";
|
||||
case Poco::Message::PRIO_ERROR: return "error";
|
||||
case Poco::Message::PRIO_FATAL: return "fatal";
|
||||
case Poco::Message::PRIO_NOTICE: return "notice";
|
||||
case Poco::Message::PRIO_TRACE: return "trace";
|
||||
case Poco::Message::PRIO_WARNING: return "warning";
|
||||
default: return "none";
|
||||
switch (p) {
|
||||
case Poco::Message::PRIO_INFORMATION:
|
||||
return "information";
|
||||
case Poco::Message::PRIO_CRITICAL:
|
||||
return "critical";
|
||||
case Poco::Message::PRIO_DEBUG:
|
||||
return "debug";
|
||||
case Poco::Message::PRIO_ERROR:
|
||||
return "error";
|
||||
case Poco::Message::PRIO_FATAL:
|
||||
return "fatal";
|
||||
case Poco::Message::PRIO_NOTICE:
|
||||
return "notice";
|
||||
case Poco::Message::PRIO_TRACE:
|
||||
return "trace";
|
||||
case Poco::Message::PRIO_WARNING:
|
||||
return "warning";
|
||||
default:
|
||||
return "none";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,15 +54,15 @@ namespace OpenWifi {
|
||||
std::uint64_t timestamp;
|
||||
std::string source;
|
||||
std::string thread_name;
|
||||
std::uint64_t thread_id=0;
|
||||
std::uint64_t thread_id = 0;
|
||||
|
||||
inline void to_json(Poco::JSON::Object &Obj) const {
|
||||
RESTAPI_utils::field_to_json(Obj,"msg", msg);
|
||||
RESTAPI_utils::field_to_json(Obj,"level", level);
|
||||
RESTAPI_utils::field_to_json(Obj,"timestamp", timestamp);
|
||||
RESTAPI_utils::field_to_json(Obj,"source", source);
|
||||
RESTAPI_utils::field_to_json(Obj,"thread_name", thread_name);
|
||||
RESTAPI_utils::field_to_json(Obj,"thread_id", thread_id);
|
||||
RESTAPI_utils::field_to_json(Obj, "msg", msg);
|
||||
RESTAPI_utils::field_to_json(Obj, "level", level);
|
||||
RESTAPI_utils::field_to_json(Obj, "timestamp", timestamp);
|
||||
RESTAPI_utils::field_to_json(Obj, "source", source);
|
||||
RESTAPI_utils::field_to_json(Obj, "thread_name", thread_name);
|
||||
RESTAPI_utils::field_to_json(Obj, "thread_id", thread_id);
|
||||
}
|
||||
|
||||
inline bool from_json(const Poco::JSON::Object::Ptr &Obj) {
|
||||
@@ -71,17 +74,17 @@ namespace OpenWifi {
|
||||
RESTAPI_utils::field_from_json(Obj, "thread_name", thread_name);
|
||||
RESTAPI_utils::field_from_json(Obj, "thread_id", thread_id);
|
||||
return true;
|
||||
} catch(...) {
|
||||
|
||||
} catch (...) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
typedef WebSocketNotification<NotificationLogMessage> WebSocketClientNotificationLogMessage_t;
|
||||
typedef WebSocketNotification<NotificationLogMessage>
|
||||
WebSocketClientNotificationLogMessage_t;
|
||||
|
||||
void log(const Poco::Message &m) final {
|
||||
if(UI_WebSocketClientServer()->IsAnyoneConnected()) {
|
||||
if (UI_WebSocketClientServer()->IsAnyoneConnected()) {
|
||||
WebSocketClientNotificationLogMessage_t Msg;
|
||||
Msg.content.msg = m.getText();
|
||||
Msg.content.level = WebSocketLogger::to_string(m.getPriority());
|
||||
@@ -94,7 +97,8 @@ namespace OpenWifi {
|
||||
}
|
||||
}
|
||||
|
||||
void setProperty([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) {
|
||||
void setProperty([[maybe_unused]] const std::string &name,
|
||||
[[maybe_unused]] const std::string &value) {
|
||||
std::cout << "WS setProperty" << std::endl;
|
||||
}
|
||||
|
||||
@@ -102,6 +106,6 @@ namespace OpenWifi {
|
||||
std::recursive_mutex Mutex_;
|
||||
};
|
||||
|
||||
// inline auto WebSocketLogger() { return WebSocketLogger::instance(); }
|
||||
// inline auto WebSocketLogger() { return WebSocketLogger::instance(); }
|
||||
|
||||
}
|
||||
} // namespace OpenWifi
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,8 +4,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include "Poco/String.h"
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
namespace OpenWifi {
|
||||
enum UNAUTHORIZED_REASON {
|
||||
SUCCESS=0,
|
||||
SUCCESS = 0,
|
||||
PASSWORD_CHANGE_REQUIRED,
|
||||
INVALID_CREDENTIALS,
|
||||
PASSWORD_ALREADY_USED,
|
||||
@@ -41,354 +41,497 @@ namespace OpenWifi {
|
||||
}
|
||||
|
||||
namespace OpenWifi::RESTAPI::Errors {
|
||||
struct msg { uint64_t err_num; std::string err_txt; };
|
||||
static const struct msg Error404{404,"Resource does not exist."};
|
||||
struct msg {
|
||||
uint64_t err_num;
|
||||
std::string err_txt;
|
||||
};
|
||||
static const struct msg Error404 { 404, "Resource does not exist." };
|
||||
|
||||
static const struct msg SUCCESS{0,"No error."};
|
||||
static const struct msg PASSWORD_CHANGE_REQUIRED{1,"Password change required"};
|
||||
static const struct msg INVALID_CREDENTIALS{2,"Invalid credentials."};
|
||||
static const struct msg PASSWORD_ALREADY_USED{3,"Password already used."};
|
||||
static const struct msg USERNAME_PENDING_VERIFICATION{4,"Username pending verification."};
|
||||
static const struct msg PASSWORD_INVALID{5,"Password is invalid"};
|
||||
static const struct msg INTERNAL_ERROR{6,"Internal error."};
|
||||
static const struct msg ACCESS_DENIED{7,"Access denied."};
|
||||
static const struct msg INVALID_TOKEN{8,"Invalid token."};
|
||||
static const struct msg EXPIRED_TOKEN{9,"Expired token."};
|
||||
static const struct msg RATE_LIMIT_EXCEEDED{10,"Rate limit exceeded."};
|
||||
static const struct msg BAD_MFA_TRANSACTION{11,"Bad MFA transaction."};
|
||||
static const struct msg MFA_FAILURE{12,"MFA failure."};
|
||||
static const struct msg SECURITY_SERVICE_UNREACHABLE{13,"Security service is unreachable, try again later."};
|
||||
static const struct msg CANNOT_REFRESH_TOKEN{14,"Cannot refresh token."};
|
||||
static const struct msg ACCOUNT_SUSPENDED{15,"Account has been suspended."};
|
||||
static const struct msg SUCCESS { 0, "No error." };
|
||||
static const struct msg PASSWORD_CHANGE_REQUIRED { 1, "Password change required" };
|
||||
static const struct msg INVALID_CREDENTIALS { 2, "Invalid credentials." };
|
||||
static const struct msg PASSWORD_ALREADY_USED { 3, "Password already used." };
|
||||
static const struct msg USERNAME_PENDING_VERIFICATION { 4, "Username pending verification." };
|
||||
static const struct msg PASSWORD_INVALID { 5, "Password is invalid" };
|
||||
static const struct msg INTERNAL_ERROR { 6, "Internal error." };
|
||||
static const struct msg ACCESS_DENIED { 7, "Access denied." };
|
||||
static const struct msg INVALID_TOKEN { 8, "Invalid token." };
|
||||
static const struct msg EXPIRED_TOKEN { 9, "Expired token." };
|
||||
static const struct msg RATE_LIMIT_EXCEEDED { 10, "Rate limit exceeded." };
|
||||
static const struct msg BAD_MFA_TRANSACTION { 11, "Bad MFA transaction." };
|
||||
static const struct msg MFA_FAILURE { 12, "MFA failure." };
|
||||
static const struct msg SECURITY_SERVICE_UNREACHABLE {
|
||||
13, "Security service is unreachable, try again later."
|
||||
};
|
||||
static const struct msg CANNOT_REFRESH_TOKEN { 14, "Cannot refresh token." };
|
||||
static const struct msg ACCOUNT_SUSPENDED { 15, "Account has been suspended." };
|
||||
|
||||
static const struct msg MissingUUID{1000,"Missing UUID."};
|
||||
static const struct msg MissingSerialNumber{1001,"Missing Serial Number."};
|
||||
static const struct msg InternalError{1002,"Internal error. Please try later."};
|
||||
static const struct msg InvalidJSONDocument{1003,"Invalid JSON document."};
|
||||
static const struct msg UnsupportedHTTPMethod{1004,"Unsupported HTTP Method"};
|
||||
static const struct msg StillInUse{1005,"Element still in use."};
|
||||
static const struct msg CouldNotBeDeleted{1006,"Element could not be deleted."};
|
||||
static const struct msg NameMustBeSet{1007,"The name property must be set."};
|
||||
static const struct msg ConfigBlockInvalid{1008,"Configuration block type invalid."};
|
||||
static const struct msg UnknownId{1009,"Unknown UUID."};
|
||||
static const struct msg InvalidDeviceTypes{1010,"Unknown or invalid device type(s)."};
|
||||
static const struct msg RecordNotCreated{1011,"Record could not be created."};
|
||||
static const struct msg RecordNotUpdated{1012,"Record could not be updated."};
|
||||
static const struct msg UnknownManagementPolicyUUID{1013,"Unknown management policy UUID."};
|
||||
static const struct msg CannotDeleteRoot{1014,"Root Entity cannot be removed, only modified."};
|
||||
static const struct msg MustCreateRootFirst{1015,"Root entity must be created first."};
|
||||
static const struct msg ParentUUIDMustExist{1016,"Parent UUID must exist."};
|
||||
static const struct msg ConfigurationMustExist{1017,"Configuration must exist."};
|
||||
static const struct msg MissingOrInvalidParameters{1018,"Invalid or missing parameters."};
|
||||
static const struct msg UnknownSerialNumber{1019,"Unknown Serial Number."};
|
||||
static const struct msg InvalidSerialNumber{1020,"Invalid Serial Number."};
|
||||
static const struct msg SerialNumberExists{1021,"Serial Number already exists."};
|
||||
static const struct msg ValidNonRootUUID{1022,"Must be a non-root, and valid UUID."};
|
||||
static const struct msg VenueMustExist{1023,"Venue does not exist."};
|
||||
static const struct msg NotBoth{1024,"You cannot specify both Entity and Venue"};
|
||||
static const struct msg EntityMustExist{1025,"Entity must exist."};
|
||||
static const struct msg ParentOrEntityMustBeSet{1026,"Parent or Entity must be set."};
|
||||
static const struct msg ContactMustExist{1027,"Contact must exist."};
|
||||
static const struct msg LocationMustExist{1028,"Location must exist."};
|
||||
static const struct msg OnlyWSSupported{1029,"This endpoint only supports WebSocket."};
|
||||
static const struct msg SerialNumberMismatch{1030,"Serial Number mismatch."};
|
||||
static const struct msg InvalidCommand{1031,"Invalid command."};
|
||||
static const struct msg NoRecordsDeleted{1032,"No records deleted."};
|
||||
static const struct msg DeviceNotConnected{1033,"Device is not currently connected."};
|
||||
static const struct msg CannotCreateWS{1034,"Telemetry system could not create WS endpoint. Please try again."};
|
||||
static const struct msg BothDeviceTypeRevision{1035,"Both deviceType and revision must be set."};
|
||||
static const struct msg IdOrSerialEmpty{1036,"SerialNumber and Id must not be empty."};
|
||||
static const struct msg MissingUserID{1037,"Missing user ID."};
|
||||
static const struct msg IdMustBe0{1038,"To create a user, you must set the ID to 0"};
|
||||
static const struct msg InvalidUserRole{1039,"Invalid userRole."};
|
||||
static const struct msg InvalidEmailAddress{1040,"Invalid email address."};
|
||||
static const struct msg PasswordRejected{1041,"Password was rejected. This maybe an old password."};
|
||||
static const struct msg InvalidIPRanges{1042,"Invalid IP range specifications."};
|
||||
static const struct msg InvalidLOrderBy{1043,"Invalid orderBy specification."};
|
||||
static const struct msg NeedMobileNumber{1044,"You must provide at least one validated phone number."};
|
||||
static const struct msg BadMFAMethod{1045,"MFA only supports sms or email."};
|
||||
static const struct msg InvalidCredentials{1046,"Invalid credentials (username/password)."};
|
||||
static const struct msg InvalidPassword{1047,"Password does not conform to basic password rules."};
|
||||
static const struct msg UserPendingVerification{1048,"User access denied pending email verification."};
|
||||
static const struct msg PasswordMustBeChanged{1049,"Password must be changed."};
|
||||
static const struct msg UnrecognizedRequest{1050,"Ill-formed request. Please consult documentation."};
|
||||
static const struct msg MissingAuthenticationInformation{1051,"Missing authentication information."};
|
||||
static const struct msg InsufficientAccessRights{1052,"Insufficient access rights to complete the operation."};
|
||||
static const struct msg ExpiredToken{1053,"Token has expired, user must login."};
|
||||
static const struct msg SubscriberMustExist{1054,"Subscriber must exist."};
|
||||
static const struct msg AuthenticatorVerificationIncomplete{1055,"Authenticator validation is not complete."};
|
||||
static const struct msg SMSCouldNotBeSentRetry{1056,"SMS could not be sent to validate device, try later or change the phone number."};
|
||||
static const struct msg SMSCouldNotValidate{1057,"Code and number could not be validated"};
|
||||
static const struct msg InvalidDeviceClass{1058,"Invalid device class. Must be: any, venue, entity, or subscriber"};
|
||||
static const struct msg SerialNumberAlreadyProvisioned{1059,"This device has already been provisioned to a subscriber."};
|
||||
static const struct msg SerialNumberNotTheProperClass{1060,"Device is not available to subscribers. It ahs been assigned to another class of devices."};
|
||||
static const struct msg UserAlreadyExists{1061,"Username already exists."};
|
||||
static const struct msg NotImplemented{1062,"Function not implemented."};
|
||||
static const struct msg VariableMustExist{1063,"Specified variable does not exist."};
|
||||
static const struct msg InvalidEntityType{1064,"Invalid entity type."};
|
||||
static const struct msg CannotDeleteSubEntity{1065,"Cannot delete the default subscriber entity."};
|
||||
static const struct msg OperatorIdMustExist{1066,"Missing or bad Operator ID"};
|
||||
static const struct msg CannotDeleteDefaultOperator{1067,"Cannot delete the default operator."};
|
||||
static const struct msg CannotCreateDefaultOperator{1068,"Cannot create the default operator."};
|
||||
static const struct msg InvalidRRM{1069,"Invalid RRM value."};
|
||||
static const struct msg InvalidIPAddresses{1070,"Invalid IP addresses."};
|
||||
static const struct msg InvalidBillingCode{1071,"Empty of invalid billing code."};
|
||||
static const struct msg InvalidBillingPeriod{1072,"Invalid billing period."};
|
||||
static const struct msg InvalidSubscriberId{1073,"Invalid subscriber ID."};
|
||||
static const struct msg InvalidContactId{1074,"Invalid contact ID."};
|
||||
static const struct msg InvalidLocationId{1075,"Invalid location ID."};
|
||||
static const struct msg InvalidContactType{1076,"Invalid contact type."};
|
||||
static const struct msg InvalidLocationType{1077,"Invalid location type."};
|
||||
static const struct msg InvalidOperatorId{1078,"Invalid operator ID."};
|
||||
static const struct msg InvalidServiceClassId{1079,"Invalid service class ID."};
|
||||
static const struct msg InvalidSubscriberDeviceId{1080,"Invalid subscriber device ID."};
|
||||
static const struct msg InvalidRegistrationOperatorId{1081,"Invalid registration operator ID."};
|
||||
static const struct msg InvalidRegistrationOperatorName{1082,"Invalid registration operator name."};
|
||||
static const struct msg RegistrationNameDuplicate{1083,"Registration name must be unique."};
|
||||
static const struct msg SMSMFANotEnabled{1084,"SMS is not enabled in the security service."};
|
||||
static const struct msg EMailMFANotEnabled{1085,"email is not enabled in the security service."};
|
||||
static const struct msg MissingUUID { 1000, "Missing UUID." };
|
||||
static const struct msg MissingSerialNumber { 1001, "Missing Serial Number." };
|
||||
static const struct msg InternalError { 1002, "Internal error. Please try later." };
|
||||
static const struct msg InvalidJSONDocument { 1003, "Invalid JSON document." };
|
||||
static const struct msg UnsupportedHTTPMethod { 1004, "Unsupported HTTP Method" };
|
||||
static const struct msg StillInUse { 1005, "Element still in use." };
|
||||
static const struct msg CouldNotBeDeleted { 1006, "Element could not be deleted." };
|
||||
static const struct msg NameMustBeSet { 1007, "The name property must be set." };
|
||||
static const struct msg ConfigBlockInvalid { 1008, "Configuration block type invalid." };
|
||||
static const struct msg UnknownId { 1009, "Unknown UUID." };
|
||||
static const struct msg InvalidDeviceTypes { 1010, "Unknown or invalid device type(s)." };
|
||||
static const struct msg RecordNotCreated { 1011, "Record could not be created." };
|
||||
static const struct msg RecordNotUpdated { 1012, "Record could not be updated." };
|
||||
static const struct msg UnknownManagementPolicyUUID { 1013, "Unknown management policy UUID." };
|
||||
static const struct msg CannotDeleteRoot {
|
||||
1014, "Root Entity cannot be removed, only modified."
|
||||
};
|
||||
static const struct msg MustCreateRootFirst { 1015, "Root entity must be created first." };
|
||||
static const struct msg ParentUUIDMustExist { 1016, "Parent UUID must exist." };
|
||||
static const struct msg ConfigurationMustExist { 1017, "Configuration must exist." };
|
||||
static const struct msg MissingOrInvalidParameters { 1018, "Invalid or missing parameters." };
|
||||
static const struct msg UnknownSerialNumber { 1019, "Unknown Serial Number." };
|
||||
static const struct msg InvalidSerialNumber { 1020, "Invalid Serial Number." };
|
||||
static const struct msg SerialNumberExists { 1021, "Serial Number already exists." };
|
||||
static const struct msg ValidNonRootUUID { 1022, "Must be a non-root, and valid UUID." };
|
||||
static const struct msg VenueMustExist { 1023, "Venue does not exist." };
|
||||
static const struct msg NotBoth { 1024, "You cannot specify both Entity and Venue" };
|
||||
static const struct msg EntityMustExist { 1025, "Entity must exist." };
|
||||
static const struct msg ParentOrEntityMustBeSet { 1026, "Parent or Entity must be set." };
|
||||
static const struct msg ContactMustExist { 1027, "Contact must exist." };
|
||||
static const struct msg LocationMustExist { 1028, "Location must exist." };
|
||||
static const struct msg OnlyWSSupported { 1029, "This endpoint only supports WebSocket." };
|
||||
static const struct msg SerialNumberMismatch { 1030, "Serial Number mismatch." };
|
||||
static const struct msg InvalidCommand { 1031, "Invalid command." };
|
||||
static const struct msg NoRecordsDeleted { 1032, "No records deleted." };
|
||||
static const struct msg DeviceNotConnected { 1033, "Device is not currently connected." };
|
||||
static const struct msg CannotCreateWS {
|
||||
1034, "Telemetry system could not create WS endpoint. Please try again."
|
||||
};
|
||||
static const struct msg BothDeviceTypeRevision {
|
||||
1035, "Both deviceType and revision must be set."
|
||||
};
|
||||
static const struct msg IdOrSerialEmpty { 1036, "SerialNumber and Id must not be empty." };
|
||||
static const struct msg MissingUserID { 1037, "Missing user ID." };
|
||||
static const struct msg IdMustBe0 { 1038, "To create a user, you must set the ID to 0" };
|
||||
static const struct msg InvalidUserRole { 1039, "Invalid userRole." };
|
||||
static const struct msg InvalidEmailAddress { 1040, "Invalid email address." };
|
||||
static const struct msg PasswordRejected {
|
||||
1041, "Password was rejected. This maybe an old password."
|
||||
};
|
||||
static const struct msg InvalidIPRanges { 1042, "Invalid IP range specifications." };
|
||||
static const struct msg InvalidLOrderBy { 1043, "Invalid orderBy specification." };
|
||||
static const struct msg NeedMobileNumber {
|
||||
1044, "You must provide at least one validated phone number."
|
||||
};
|
||||
static const struct msg BadMFAMethod { 1045, "MFA only supports sms or email." };
|
||||
static const struct msg InvalidCredentials { 1046, "Invalid credentials (username/password)." };
|
||||
static const struct msg InvalidPassword {
|
||||
1047, "Password does not conform to basic password rules."
|
||||
};
|
||||
static const struct msg UserPendingVerification {
|
||||
1048, "User access denied pending email verification."
|
||||
};
|
||||
static const struct msg PasswordMustBeChanged { 1049, "Password must be changed." };
|
||||
static const struct msg UnrecognizedRequest {
|
||||
1050, "Ill-formed request. Please consult documentation."
|
||||
};
|
||||
static const struct msg MissingAuthenticationInformation {
|
||||
1051, "Missing authentication information."
|
||||
};
|
||||
static const struct msg InsufficientAccessRights {
|
||||
1052, "Insufficient access rights to complete the operation."
|
||||
};
|
||||
static const struct msg ExpiredToken { 1053, "Token has expired, user must login." };
|
||||
static const struct msg SubscriberMustExist { 1054, "Subscriber must exist." };
|
||||
static const struct msg AuthenticatorVerificationIncomplete {
|
||||
1055, "Authenticator validation is not complete."
|
||||
};
|
||||
static const struct msg SMSCouldNotBeSentRetry {
|
||||
1056, "SMS could not be sent to validate device, try later or change the phone number."
|
||||
};
|
||||
static const struct msg SMSCouldNotValidate { 1057, "Code and number could not be validated" };
|
||||
static const struct msg InvalidDeviceClass {
|
||||
1058, "Invalid device class. Must be: any, venue, entity, or subscriber"
|
||||
};
|
||||
static const struct msg SerialNumberAlreadyProvisioned {
|
||||
1059, "This device has already been provisioned to a subscriber."
|
||||
};
|
||||
static const struct msg SerialNumberNotTheProperClass {
|
||||
1060, "Device is not available to subscribers. It ahs been assigned to another class of "
|
||||
"devices."
|
||||
};
|
||||
static const struct msg UserAlreadyExists { 1061, "Username already exists." };
|
||||
static const struct msg NotImplemented { 1062, "Function not implemented." };
|
||||
static const struct msg VariableMustExist { 1063, "Specified variable does not exist." };
|
||||
static const struct msg InvalidEntityType { 1064, "Invalid entity type." };
|
||||
static const struct msg CannotDeleteSubEntity {
|
||||
1065, "Cannot delete the default subscriber entity."
|
||||
};
|
||||
static const struct msg OperatorIdMustExist { 1066, "Missing or bad Operator ID" };
|
||||
static const struct msg CannotDeleteDefaultOperator {
|
||||
1067, "Cannot delete the default operator."
|
||||
};
|
||||
static const struct msg CannotCreateDefaultOperator {
|
||||
1068, "Cannot create the default operator."
|
||||
};
|
||||
static const struct msg InvalidRRM { 1069, "Invalid RRM value." };
|
||||
static const struct msg InvalidIPAddresses { 1070, "Invalid IP addresses." };
|
||||
static const struct msg InvalidBillingCode { 1071, "Empty of invalid billing code." };
|
||||
static const struct msg InvalidBillingPeriod { 1072, "Invalid billing period." };
|
||||
static const struct msg InvalidSubscriberId { 1073, "Invalid subscriber ID." };
|
||||
static const struct msg InvalidContactId { 1074, "Invalid contact ID." };
|
||||
static const struct msg InvalidLocationId { 1075, "Invalid location ID." };
|
||||
static const struct msg InvalidContactType { 1076, "Invalid contact type." };
|
||||
static const struct msg InvalidLocationType { 1077, "Invalid location type." };
|
||||
static const struct msg InvalidOperatorId { 1078, "Invalid operator ID." };
|
||||
static const struct msg InvalidServiceClassId { 1079, "Invalid service class ID." };
|
||||
static const struct msg InvalidSubscriberDeviceId { 1080, "Invalid subscriber device ID." };
|
||||
static const struct msg InvalidRegistrationOperatorId {
|
||||
1081, "Invalid registration operator ID."
|
||||
};
|
||||
static const struct msg InvalidRegistrationOperatorName {
|
||||
1082, "Invalid registration operator name."
|
||||
};
|
||||
static const struct msg RegistrationNameDuplicate { 1083, "Registration name must be unique." };
|
||||
static const struct msg SMSMFANotEnabled {
|
||||
1084, "SMS is not enabled in the security service."
|
||||
};
|
||||
static const struct msg EMailMFANotEnabled {
|
||||
1085, "email is not enabled in the security service."
|
||||
};
|
||||
|
||||
static const struct msg TOTInvalidCode{1086,"Invalid code."};
|
||||
static const struct msg TOTInvalidIndex{1087,"Invalid index."};
|
||||
static const struct msg TOTRepeatedCode{1088,"Code is repeated. Must be new code."};
|
||||
static const struct msg TOTInvalidProtocol{1089,"Invalid protocol sequence."};
|
||||
static const struct msg TOTNoSession{1090,"No validation session present."};
|
||||
static const struct msg TOTInvalidCode { 1086, "Invalid code." };
|
||||
static const struct msg TOTInvalidIndex { 1087, "Invalid index." };
|
||||
static const struct msg TOTRepeatedCode { 1088, "Code is repeated. Must be new code." };
|
||||
static const struct msg TOTInvalidProtocol { 1089, "Invalid protocol sequence." };
|
||||
static const struct msg TOTNoSession { 1090, "No validation session present." };
|
||||
|
||||
static const struct msg SignupAlreadySigned{1091,"Code is repeated. Must be new code."};
|
||||
static const struct msg SignupEmailCheck{1092,"Waiting for email check completion."};
|
||||
static const struct msg SignupWaitingForDevice{1093,"Waiting for device."};
|
||||
static const struct msg SignupAlreadySigned { 1091, "Code is repeated. Must be new code." };
|
||||
static const struct msg SignupEmailCheck { 1092, "Waiting for email check completion." };
|
||||
static const struct msg SignupWaitingForDevice { 1093, "Waiting for device." };
|
||||
|
||||
static const struct msg SMSMissingPhoneNumber{1094,"Missing phone number"};
|
||||
static const struct msg SMSTryLater{1095,"SMS could not be sent. Verify the number or try again later."};
|
||||
static const struct msg SMSMissingChallenge{1096,"Missing 'challengeCode'"};
|
||||
static const struct msg MustHaveConfigElement{1097,"Must have 'configuration' element."};
|
||||
static const struct msg SMSMissingPhoneNumber { 1094, "Missing phone number" };
|
||||
static const struct msg SMSTryLater {
|
||||
1095, "SMS could not be sent. Verify the number or try again later."
|
||||
};
|
||||
static const struct msg SMSMissingChallenge { 1096, "Missing 'challengeCode'" };
|
||||
static const struct msg MustHaveConfigElement { 1097, "Must have 'configuration' element." };
|
||||
|
||||
static const struct msg ModelIDListCannotBeEmpty{1098,"Model ID list cannot be empty."};
|
||||
static const struct msg DefConfigNameExists{1099,"Configuration name already exists."};
|
||||
static const struct msg ModelIDListCannotBeEmpty { 1098, "Model ID list cannot be empty." };
|
||||
static const struct msg DefConfigNameExists { 1099, "Configuration name already exists." };
|
||||
|
||||
static const struct msg SubNoDeviceActivated{1100,"No devices activated yet."};
|
||||
static const struct msg SubConfigNotRefreshed{1101,"Configuration could not be refreshed."};
|
||||
static const struct msg SubNoDeviceActivated { 1100, "No devices activated yet." };
|
||||
static const struct msg SubConfigNotRefreshed { 1101, "Configuration could not be refreshed." };
|
||||
|
||||
static const struct msg ProvServiceNotAvailable{1102,"Provisioning service not available yet."};
|
||||
static const struct msg SSIDInvalidPassword{1103,"Invalid password length. Must be 8 characters or greater, and a maximum of 32 characters."};
|
||||
static const struct msg InvalidStartingIPAddress{1104,"Invalid starting/ending IP address."};
|
||||
static const struct msg SubnetFormatError{1105,"Subnet must be in format like 192.168.1.1/24."};
|
||||
static const struct msg DeviceModeError{1106,"Device mode subnet must be of the form 192.168.1.1/24."};
|
||||
static const struct msg ProvServiceNotAvailable {
|
||||
1102, "Provisioning service not available yet."
|
||||
};
|
||||
static const struct msg SSIDInvalidPassword {
|
||||
1103, "Invalid password length. Must be 8 characters or greater, and a maximum of 32 "
|
||||
"characters."
|
||||
};
|
||||
static const struct msg InvalidStartingIPAddress {
|
||||
1104, "Invalid starting/ending IP address."
|
||||
};
|
||||
static const struct msg SubnetFormatError {
|
||||
1105, "Subnet must be in format like 192.168.1.1/24."
|
||||
};
|
||||
static const struct msg DeviceModeError {
|
||||
1106, "Device mode subnet must be of the form 192.168.1.1/24."
|
||||
};
|
||||
|
||||
static const struct msg BadDeviceMode{1107,"Mode must be bridge, nat, or manual."};
|
||||
static const struct msg DefaultGatewayFormat{1108,"Default gateway must be in format like 192.168.1.1."};
|
||||
static const struct msg PrimaryDNSFormat{1109,"Primary DNS must be an IP address i.e. 192.168.1.1."};
|
||||
static const struct msg BadDeviceMode { 1107, "Mode must be bridge, nat, or manual." };
|
||||
static const struct msg DefaultGatewayFormat {
|
||||
1108, "Default gateway must be in format like 192.168.1.1."
|
||||
};
|
||||
static const struct msg PrimaryDNSFormat {
|
||||
1109, "Primary DNS must be an IP address i.e. 192.168.1.1."
|
||||
};
|
||||
|
||||
static const struct msg SecondaryDNSFormat{1110,"Secondary DNS must be an IP address i.e. 192.168.1.1."};
|
||||
static const struct msg BadConnectionType{1111,"Internet Connection must be automatic, bridge, pppoe, or manual."};
|
||||
static const struct msg InvalidDeviceID{1112,"Invalid deviceID."};
|
||||
static const struct msg InvalidVisibilityAttribute{1113,"Invalid visibility attribute."};
|
||||
static const struct msg UnknownConfigurationSection{1114,"Unknown section."};
|
||||
static const struct msg SecondaryDNSFormat {
|
||||
1110, "Secondary DNS must be an IP address i.e. 192.168.1.1."
|
||||
};
|
||||
static const struct msg BadConnectionType {
|
||||
1111, "Internet Connection must be automatic, bridge, pppoe, or manual."
|
||||
};
|
||||
static const struct msg InvalidDeviceID { 1112, "Invalid deviceID." };
|
||||
static const struct msg InvalidVisibilityAttribute { 1113, "Invalid visibility attribute." };
|
||||
static const struct msg UnknownConfigurationSection { 1114, "Unknown section." };
|
||||
|
||||
static const struct msg CannotValidatePhoneNumber{1115,"Phone number could not be validated."};
|
||||
static const struct msg RootUsersNoOwners{1116,"ROOT users may not have owners."};
|
||||
static const struct msg PartnerMustHaveEntity{1118,"Partner user must belong to an entity."};
|
||||
static const struct msg RootCannotModifyUsers{1119,"ROOT may not modify user roles."};
|
||||
static const struct msg CannotValidatePhoneNumber {
|
||||
1115, "Phone number could not be validated."
|
||||
};
|
||||
static const struct msg RootUsersNoOwners { 1116, "ROOT users may not have owners." };
|
||||
static const struct msg PartnerMustHaveEntity {
|
||||
1118, "Partner user must belong to an entity."
|
||||
};
|
||||
static const struct msg RootCannotModifyUsers { 1119, "ROOT may not modify user roles." };
|
||||
|
||||
static const struct msg CertificateNotIssued{1120,"Certificate was not issued."};
|
||||
static const struct msg IncompleteCertificate{1121,"Incomplete certificate information. Cannot be downloaded. You must delete and recreate."};
|
||||
static const struct msg InvalidCertificateType{1122,"Invalid certificate type."};
|
||||
static const struct msg InvalidDeviceName{1123,"Invalid device name."};
|
||||
static const struct msg CertificateNotIssued { 1120, "Certificate was not issued." };
|
||||
static const struct msg IncompleteCertificate {
|
||||
1121, "Incomplete certificate information. Cannot be downloaded. You must delete and "
|
||||
"recreate."
|
||||
};
|
||||
static const struct msg InvalidCertificateType { 1122, "Invalid certificate type." };
|
||||
static const struct msg InvalidDeviceName { 1123, "Invalid device name." };
|
||||
|
||||
static const struct msg InvalidRedirectorName{1124,"Invalid redirector name"};
|
||||
static const struct msg CommonNameAlreadyExists{1125,"A device/server of this name already exists"};
|
||||
static const struct msg CertificateAlreadyExists{1126,"A certificate for this device already exists."};
|
||||
static const struct msg CannotCreateCertTryAgain{1127,"Device certificate could not be created. Please try later."};
|
||||
static const struct msg CouldNotRevoke{1128,"Certificate could not be revoked."};
|
||||
static const struct msg InvalidRedirectorName { 1124, "Invalid redirector name" };
|
||||
static const struct msg CommonNameAlreadyExists {
|
||||
1125, "A device/server of this name already exists"
|
||||
};
|
||||
static const struct msg CertificateAlreadyExists {
|
||||
1126, "A certificate for this device already exists."
|
||||
};
|
||||
static const struct msg CannotCreateCertTryAgain {
|
||||
1127, "Device certificate could not be created. Please try later."
|
||||
};
|
||||
static const struct msg CouldNotRevoke { 1128, "Certificate could not be revoked." };
|
||||
|
||||
static const struct msg CouldNotModifyCert{1129,"Certificate could not me modified. Please verify the information you supplied."};
|
||||
static const struct msg BatchCertNoCreated{1130,"Certificates have not been created for this batch."};
|
||||
static const struct msg BatchTooBig{1131,"Illegal number of MAC Addresses: must be between 1 and 1000."};
|
||||
static const struct msg CouldNotModifyCert {
|
||||
1129, "Certificate could not me modified. Please verify the information you supplied."
|
||||
};
|
||||
static const struct msg BatchCertNoCreated {
|
||||
1130, "Certificates have not been created for this batch."
|
||||
};
|
||||
static const struct msg BatchTooBig {
|
||||
1131, "Illegal number of MAC Addresses: must be between 1 and 1000."
|
||||
};
|
||||
|
||||
static const struct msg OutstandingJobs{1132,"Batch has running outstanding jobs. Please wait until job is finished."};
|
||||
static const struct msg InvalidSMSNotificationList{1133,"Invalid SMS Notification list."};
|
||||
static const struct msg InvalidEMailNotificationList{1134,"Invalid email Notification list."};
|
||||
static const struct msg CannotChangeCommanNames{1135,"You cannot provide new/modified common names after jobs have been run for a batch."};
|
||||
static const struct msg FailedToVerifyDigicert{1136,"Failed to verify the DigiCert information provided."};
|
||||
static const struct msg CouldNotPerformCommand{1137,"Could not perform command."};
|
||||
static const struct msg OutstandingJobs {
|
||||
1132, "Batch has running outstanding jobs. Please wait until job is finished."
|
||||
};
|
||||
static const struct msg InvalidSMSNotificationList { 1133, "Invalid SMS Notification list." };
|
||||
static const struct msg InvalidEMailNotificationList {
|
||||
1134, "Invalid email Notification list."
|
||||
};
|
||||
static const struct msg CannotChangeCommanNames {
|
||||
1135, "You cannot provide new/modified common names after jobs have been run for a batch."
|
||||
};
|
||||
static const struct msg FailedToVerifyDigicert {
|
||||
1136, "Failed to verify the DigiCert information provided."
|
||||
};
|
||||
static const struct msg CouldNotPerformCommand { 1137, "Could not perform command." };
|
||||
|
||||
static const struct msg PoolNameInvalid{1138,"Pool name is invalid."};
|
||||
static const struct msg InvalidRadiusProxyStrategy{1139,"Strategy name must be: random, round_robin, weighted."};
|
||||
static const struct msg InvalidRadiusProxyMonitorMethod{1140,"monitorMethod must be: none, https, radius."};
|
||||
static const struct msg MustHaveAtLeastOneRadiusServer{1141,"Must have at least one RADIUS server."};
|
||||
static const struct msg InvalidRadiusServerEntry{1142,"RADIUS Server IP address invalid or port missing."};
|
||||
static const struct msg InvalidRadiusServerWeigth{1143,"RADIUS Server IP weight cannot be 0."};
|
||||
static const struct msg PoolNameInvalid { 1138, "Pool name is invalid." };
|
||||
static const struct msg InvalidRadiusProxyStrategy {
|
||||
1139, "Strategy name must be: random, round_robin, weighted."
|
||||
};
|
||||
static const struct msg InvalidRadiusProxyMonitorMethod {
|
||||
1140, "monitorMethod must be: none, https, radius."
|
||||
};
|
||||
static const struct msg MustHaveAtLeastOneRadiusServer {
|
||||
1141, "Must have at least one RADIUS server."
|
||||
};
|
||||
static const struct msg InvalidRadiusServerEntry {
|
||||
1142, "RADIUS Server IP address invalid or port missing."
|
||||
};
|
||||
static const struct msg InvalidRadiusServerWeigth {
|
||||
1143, "RADIUS Server IP weight cannot be 0."
|
||||
};
|
||||
|
||||
static const struct msg MaximumRTTYSessionsReached{1144,"Too many RTTY sessions currently active"};
|
||||
static const struct msg DeviceIsAlreadyBusy{1145,"Device is already executing a command. Please try later."};
|
||||
static const struct msg MaximumRTTYSessionsReached {
|
||||
1144, "Too many RTTY sessions currently active"
|
||||
};
|
||||
static const struct msg DeviceIsAlreadyBusy {
|
||||
1145, "Device is already executing a command. Please try later."
|
||||
};
|
||||
|
||||
static const struct msg DeviceRequiresSignature{1146,"Device requires device signature to be provided."};
|
||||
static const struct msg DeviceRequiresSignature {
|
||||
1146, "Device requires device signature to be provided."
|
||||
};
|
||||
|
||||
static const struct msg ApiKeyNameAlreadyExists{1147,"API Key name must be unique."};
|
||||
static const struct msg TooManyApiKeys{1148,"Too many API Keys have already been created."};
|
||||
static const struct msg UserMustExist{1149,"User must exist."};
|
||||
static const struct msg ApiKeyNameDoesNotExist{1150,"API Key name does not exist."};
|
||||
static const struct msg ApiKeyDoesNotExist{1150,"API Key does not exist."};
|
||||
static const struct msg ApiKeyNameAlreadyExists { 1147, "API Key name must be unique." };
|
||||
static const struct msg TooManyApiKeys { 1148, "Too many API Keys have already been created." };
|
||||
static const struct msg UserMustExist { 1149, "User must exist." };
|
||||
static const struct msg ApiKeyNameDoesNotExist { 1150, "API Key name does not exist." };
|
||||
static const struct msg ApiKeyDoesNotExist { 1150, "API Key does not exist." };
|
||||
|
||||
static const struct msg DeviceIsRestricted{1151,"Device is protected by regulation. This function is not allowed."};
|
||||
static const struct msg InvalidURI{1152,"Invalid URI."};
|
||||
static const struct msg InvalidScriptSelection{1153,"Only script or scriptId must be specified. Not both."};
|
||||
static const struct msg DeviceIsRestricted {
|
||||
1151, "Device is protected by regulation. This function is not allowed."
|
||||
};
|
||||
static const struct msg InvalidURI { 1152, "Invalid URI." };
|
||||
static const struct msg InvalidScriptSelection {
|
||||
1153, "Only script or scriptId must be specified. Not both."
|
||||
};
|
||||
|
||||
static const struct msg NoDeviceStatisticsYet{1154,"Device statistics not available yet."};
|
||||
static const struct msg AccountSuspended{1155,"You account was suspended. You can only use this site in read-only mode for now."};
|
||||
static const struct msg BatchNameAlreadyExists{1156,"Batch name must be unique."};
|
||||
static const struct msg RedirectorNameIsInvalid{1157,"Redirector name is invalid."};
|
||||
static const struct msg CertificateAlreadyBelongsToYou{1158,"The serial number already belongs to you. Please use the certificate modification API to change the redirector."};
|
||||
static const struct msg RelocationDisabledForThisDevice{1159,"Relocation disabled for this device."};
|
||||
static const struct msg CannotModifyServerCertificates{1160,"Server certificates cannot be modified."};
|
||||
|
||||
static const struct msg TransferNotInDispute{1161,"The specified transfer is not being disputed."};
|
||||
static const struct msg MissingComment{1162,"Missing comment."};
|
||||
static const struct msg EntityNotAllowedToTransfer{1163,"Entity is not allowed to transfer devices."};
|
||||
static const struct msg DailyTransferQuotaExceeded{1164,"Entity has exceeded its daily quota."};
|
||||
static const struct msg CertificateWasNotRevoked{1165,"Certificate was not revoked, so it may not be re-created."};
|
||||
static const struct msg CertificateTransferNoLongerExists{1166,"The device certificate associated with this transfer no longer seem to exist."};
|
||||
static const struct msg CertificateTransferEntityNoLongerExists{1167,"The entity tied to this transfer no longer seems to exist."};
|
||||
static const struct msg CannotRollBackDueToDigiCert{1168,"The change could not be rolled back at this time. Please try later."};
|
||||
static const struct msg CertificateTransferAlreadyRolledBack{1169,"The certificate has already been rolled back."};
|
||||
static const struct msg FirmwareBDInProgress{1170,"Firmware DB update already in progress."};
|
||||
|
||||
}
|
||||
static const struct msg NoDeviceStatisticsYet { 1154, "Device statistics not available yet." };
|
||||
static const struct msg AccountSuspended {
|
||||
1155, "You account was suspended. You can only use this site in read-only mode for now."
|
||||
};
|
||||
static const struct msg BatchNameAlreadyExists { 1156, "Batch name must be unique." };
|
||||
static const struct msg RedirectorNameIsInvalid { 1157, "Redirector name is invalid." };
|
||||
static const struct msg CertificateAlreadyBelongsToYou {
|
||||
1158, "The serial number already belongs to you. Please use the certificate modification "
|
||||
"API to change the redirector."
|
||||
};
|
||||
static const struct msg RelocationDisabledForThisDevice {
|
||||
1159, "Relocation disabled for this device."
|
||||
};
|
||||
static const struct msg CannotModifyServerCertificates {
|
||||
1160, "Server certificates cannot be modified."
|
||||
};
|
||||
|
||||
static const struct msg TransferNotInDispute {
|
||||
1161, "The specified transfer is not being disputed."
|
||||
};
|
||||
static const struct msg MissingComment { 1162, "Missing comment." };
|
||||
static const struct msg EntityNotAllowedToTransfer {
|
||||
1163, "Entity is not allowed to transfer devices."
|
||||
};
|
||||
static const struct msg DailyTransferQuotaExceeded {
|
||||
1164, "Entity has exceeded its daily quota."
|
||||
};
|
||||
static const struct msg CertificateWasNotRevoked {
|
||||
1165, "Certificate was not revoked, so it may not be re-created."
|
||||
};
|
||||
static const struct msg CertificateTransferNoLongerExists {
|
||||
1166, "The device certificate associated with this transfer no longer seem to exist."
|
||||
};
|
||||
static const struct msg CertificateTransferEntityNoLongerExists {
|
||||
1167, "The entity tied to this transfer no longer seems to exist."
|
||||
};
|
||||
static const struct msg CannotRollBackDueToDigiCert {
|
||||
1168, "The change could not be rolled back at this time. Please try later."
|
||||
};
|
||||
static const struct msg CertificateTransferAlreadyRolledBack {
|
||||
1169, "The certificate has already been rolled back."
|
||||
};
|
||||
static const struct msg FirmwareBDInProgress {
|
||||
1170, "Firmware DB update already in progress."
|
||||
};
|
||||
|
||||
} // namespace OpenWifi::RESTAPI::Errors
|
||||
|
||||
namespace OpenWifi::RESTAPI::Protocol {
|
||||
static const char * CAPABILITIES = "capabilities";
|
||||
static const char * LOGS = "logs";
|
||||
static const char * HEALTHCHECKS = "healthchecks";
|
||||
static const char * STATISTICS = "statistics";
|
||||
static const char * STATUS = "status";
|
||||
static const char * SERIALNUMBER = "serialNumber";
|
||||
static const char * PERFORM = "perform";
|
||||
static const char * CONFIGURE = "configure";
|
||||
static const char * UPGRADE = "upgrade";
|
||||
static const char * REBOOT = "reboot";
|
||||
static const char * FACTORY = "factory";
|
||||
static const char * LEDS = "leds";
|
||||
static const char * TRACE = "trace";
|
||||
static const char * REQUEST = "request";
|
||||
static const char * WIFISCAN = "wifiscan";
|
||||
static const char * EVENTQUEUE = "eventqueue";
|
||||
static const char * RTTY = "rtty";
|
||||
static const char * COMMAND = "command";
|
||||
static const char * STARTDATE = "startDate";
|
||||
static const char * ENDDATE = "endDate";
|
||||
static const char * OFFSET = "offset";
|
||||
static const char * LIMIT = "limit";
|
||||
static const char * LIFETIME = "lifetime";
|
||||
static const char * UUID = "UUID";
|
||||
static const char * DATA = "data";
|
||||
static const char * CONFIGURATION = "configuration";
|
||||
static const char * WHEN = "when";
|
||||
static const char * URI = "uri";
|
||||
static const char * LOGTYPE = "logType";
|
||||
static const char * VALUES = "values";
|
||||
static const char * TYPES = "types";
|
||||
static const char * PAYLOAD = "payload";
|
||||
static const char * KEEPREDIRECTOR = "keepRedirector";
|
||||
static const char * NETWORK = "network";
|
||||
static const char * INTERFACE = "interface";
|
||||
static const char * BANDS = "bands";
|
||||
static const char * CHANNELS = "channels";
|
||||
static const char * VERBOSE = "verbose";
|
||||
static const char * MESSAGE = "message";
|
||||
static const char * STATE = "state";
|
||||
static const char * HEALTHCHECK = "healthcheck";
|
||||
static const char * PCAP_FILE_TYPE = "pcap";
|
||||
static const char * DURATION = "duration";
|
||||
static const char * NUMBEROFPACKETS = "numberOfPackets";
|
||||
static const char * FILTER = "filter";
|
||||
static const char * SELECT = "select";
|
||||
static const char * SERIALONLY = "serialOnly";
|
||||
static const char * COUNTONLY = "countOnly";
|
||||
static const char * DEVICEWITHSTATUS = "deviceWithStatus";
|
||||
static const char * DEVICESWITHSTATUS = "devicesWithStatus";
|
||||
static const char * DEVICES = "devices";
|
||||
static const char * COUNT = "count";
|
||||
static const char * SERIALNUMBERS = "serialNumbers";
|
||||
static const char * CONFIGURATIONS = "configurations";
|
||||
static const char * NAME = "name";
|
||||
static const char * COMMANDS = "commands";
|
||||
static const char * COMMANDUUID = "commandUUID";
|
||||
static const char * FIRMWARES = "firmwares";
|
||||
static const char * TOPIC = "topic";
|
||||
static const char * HOST = "host";
|
||||
static const char * OS = "os";
|
||||
static const char * HOSTNAME = "hostname";
|
||||
static const char * PROCESSORS = "processors";
|
||||
static const char * REASON = "reason";
|
||||
static const char * RELOAD = "reload";
|
||||
static const char * SUBSYSTEMS = "subsystems";
|
||||
static const char * FILEUUID = "uuid";
|
||||
static const char * USERID = "userId";
|
||||
static const char * PASSWORD = "password";
|
||||
static const char * TOKEN = "token";
|
||||
static const char * SETLOGLEVEL = "setloglevel";
|
||||
static const char * GETLOGLEVELS = "getloglevels";
|
||||
static const char * GETSUBSYSTEMNAMES = "getsubsystemnames";
|
||||
static const char * GETLOGLEVELNAMES = "getloglevelnames";
|
||||
static const char * STATS = "stats";
|
||||
static const char * PING = "ping";
|
||||
static const char * PARAMETERS = "parameters";
|
||||
static const char * VALUE = "value";
|
||||
static const char * LASTONLY = "lastOnly";
|
||||
static const char * NEWEST = "newest";
|
||||
static const char * ACTIVESCAN = "activeScan";
|
||||
static const char * OVERRIDEDFS = "override_dfs";
|
||||
static const char * LIST = "list";
|
||||
static const char * TAG = "tag";
|
||||
static const char * TAGLIST = "tagList";
|
||||
static const char * DESCRIPTION = "description";
|
||||
static const char * NOTES = "notes";
|
||||
static const char * DEVICETYPE = "deviceType";
|
||||
static const char * REVISION = "revision";
|
||||
static const char * AGES = "ages";
|
||||
static const char * REVISIONS = "revisions";
|
||||
static const char * DEVICETYPES = "deviceTypes";
|
||||
static const char * LATESTONLY = "latestOnly";
|
||||
static const char * IDONLY = "idOnly";
|
||||
static const char * REVISIONSET = "revisionSet";
|
||||
static const char * DEVICESET = "deviceSet";
|
||||
static const char * HISTORY = "history";
|
||||
static const char * ID = "id";
|
||||
static const char * VERSION = "version";
|
||||
static const char * TIMES = "times";
|
||||
static const char * UPTIME = "uptime";
|
||||
static const char * START = "start";
|
||||
static const char * DEBUG = "debug";
|
||||
static const char * SCRIPT = "script";
|
||||
static const char * TIMEOUT = "timeout";
|
||||
static const char *CAPABILITIES = "capabilities";
|
||||
static const char *LOGS = "logs";
|
||||
static const char *HEALTHCHECKS = "healthchecks";
|
||||
static const char *STATISTICS = "statistics";
|
||||
static const char *STATUS = "status";
|
||||
static const char *SERIALNUMBER = "serialNumber";
|
||||
static const char *PERFORM = "perform";
|
||||
static const char *CONFIGURE = "configure";
|
||||
static const char *UPGRADE = "upgrade";
|
||||
static const char *REBOOT = "reboot";
|
||||
static const char *FACTORY = "factory";
|
||||
static const char *LEDS = "leds";
|
||||
static const char *TRACE = "trace";
|
||||
static const char *REQUEST = "request";
|
||||
static const char *WIFISCAN = "wifiscan";
|
||||
static const char *EVENTQUEUE = "eventqueue";
|
||||
static const char *RTTY = "rtty";
|
||||
static const char *COMMAND = "command";
|
||||
static const char *STARTDATE = "startDate";
|
||||
static const char *ENDDATE = "endDate";
|
||||
static const char *OFFSET = "offset";
|
||||
static const char *LIMIT = "limit";
|
||||
static const char *LIFETIME = "lifetime";
|
||||
static const char *UUID = "UUID";
|
||||
static const char *DATA = "data";
|
||||
static const char *CONFIGURATION = "configuration";
|
||||
static const char *WHEN = "when";
|
||||
static const char *URI = "uri";
|
||||
static const char *LOGTYPE = "logType";
|
||||
static const char *VALUES = "values";
|
||||
static const char *TYPES = "types";
|
||||
static const char *PAYLOAD = "payload";
|
||||
static const char *KEEPREDIRECTOR = "keepRedirector";
|
||||
static const char *NETWORK = "network";
|
||||
static const char *INTERFACE = "interface";
|
||||
static const char *BANDS = "bands";
|
||||
static const char *CHANNELS = "channels";
|
||||
static const char *VERBOSE = "verbose";
|
||||
static const char *MESSAGE = "message";
|
||||
static const char *STATE = "state";
|
||||
static const char *HEALTHCHECK = "healthcheck";
|
||||
static const char *PCAP_FILE_TYPE = "pcap";
|
||||
static const char *DURATION = "duration";
|
||||
static const char *NUMBEROFPACKETS = "numberOfPackets";
|
||||
static const char *FILTER = "filter";
|
||||
static const char *SELECT = "select";
|
||||
static const char *SERIALONLY = "serialOnly";
|
||||
static const char *COUNTONLY = "countOnly";
|
||||
static const char *DEVICEWITHSTATUS = "deviceWithStatus";
|
||||
static const char *DEVICESWITHSTATUS = "devicesWithStatus";
|
||||
static const char *DEVICES = "devices";
|
||||
static const char *COUNT = "count";
|
||||
static const char *SERIALNUMBERS = "serialNumbers";
|
||||
static const char *CONFIGURATIONS = "configurations";
|
||||
static const char *NAME = "name";
|
||||
static const char *COMMANDS = "commands";
|
||||
static const char *COMMANDUUID = "commandUUID";
|
||||
static const char *FIRMWARES = "firmwares";
|
||||
static const char *TOPIC = "topic";
|
||||
static const char *HOST = "host";
|
||||
static const char *OS = "os";
|
||||
static const char *HOSTNAME = "hostname";
|
||||
static const char *PROCESSORS = "processors";
|
||||
static const char *REASON = "reason";
|
||||
static const char *RELOAD = "reload";
|
||||
static const char *SUBSYSTEMS = "subsystems";
|
||||
static const char *FILEUUID = "uuid";
|
||||
static const char *USERID = "userId";
|
||||
static const char *PASSWORD = "password";
|
||||
static const char *TOKEN = "token";
|
||||
static const char *SETLOGLEVEL = "setloglevel";
|
||||
static const char *GETLOGLEVELS = "getloglevels";
|
||||
static const char *GETSUBSYSTEMNAMES = "getsubsystemnames";
|
||||
static const char *GETLOGLEVELNAMES = "getloglevelnames";
|
||||
static const char *STATS = "stats";
|
||||
static const char *PING = "ping";
|
||||
static const char *PARAMETERS = "parameters";
|
||||
static const char *VALUE = "value";
|
||||
static const char *LASTONLY = "lastOnly";
|
||||
static const char *NEWEST = "newest";
|
||||
static const char *ACTIVESCAN = "activeScan";
|
||||
static const char *OVERRIDEDFS = "override_dfs";
|
||||
static const char *LIST = "list";
|
||||
static const char *TAG = "tag";
|
||||
static const char *TAGLIST = "tagList";
|
||||
static const char *DESCRIPTION = "description";
|
||||
static const char *NOTES = "notes";
|
||||
static const char *DEVICETYPE = "deviceType";
|
||||
static const char *REVISION = "revision";
|
||||
static const char *AGES = "ages";
|
||||
static const char *REVISIONS = "revisions";
|
||||
static const char *DEVICETYPES = "deviceTypes";
|
||||
static const char *LATESTONLY = "latestOnly";
|
||||
static const char *IDONLY = "idOnly";
|
||||
static const char *REVISIONSET = "revisionSet";
|
||||
static const char *DEVICESET = "deviceSet";
|
||||
static const char *HISTORY = "history";
|
||||
static const char *ID = "id";
|
||||
static const char *VERSION = "version";
|
||||
static const char *TIMES = "times";
|
||||
static const char *UPTIME = "uptime";
|
||||
static const char *START = "start";
|
||||
static const char *DEBUG = "debug";
|
||||
static const char *SCRIPT = "script";
|
||||
static const char *TIMEOUT = "timeout";
|
||||
|
||||
static const char * NEWPASSWORD = "newPassword";
|
||||
static const char * USERS = "users";
|
||||
static const char * WITHEXTENDEDINFO = "withExtendedInfo";
|
||||
static const char *NEWPASSWORD = "newPassword";
|
||||
static const char *USERS = "users";
|
||||
static const char *WITHEXTENDEDINFO = "withExtendedInfo";
|
||||
|
||||
static const char * ERRORTEXT = "errorText";
|
||||
static const char * ERRORCODE = "errorCode";
|
||||
static const char * AVATARID = "avatarId";
|
||||
static const char * UNNAMED = "(unnamed)";
|
||||
static const char * UNSPECIFIED = "(unspecified)";
|
||||
static const char * CONTENTDISPOSITION = "Content-Disposition";
|
||||
static const char * CONTENTTYPE = "Content-Type";
|
||||
static const char *ERRORTEXT = "errorText";
|
||||
static const char *ERRORCODE = "errorCode";
|
||||
static const char *AVATARID = "avatarId";
|
||||
static const char *UNNAMED = "(unnamed)";
|
||||
static const char *UNSPECIFIED = "(unspecified)";
|
||||
static const char *CONTENTDISPOSITION = "Content-Disposition";
|
||||
static const char *CONTENTTYPE = "Content-Type";
|
||||
|
||||
static const char * REQUIREMENTS = "requirements";
|
||||
static const char * PASSWORDPATTERN = "passwordPattern";
|
||||
static const char * ACCESSPOLICY = "accessPolicy";
|
||||
static const char * PASSWORDPOLICY = "passwordPolicy";
|
||||
static const char * FORGOTPASSWORD = "forgotPassword";
|
||||
static const char * RESENDMFACODE = "resendMFACode";
|
||||
static const char * COMPLETEMFACHALLENGE = "completeMFAChallenge";
|
||||
static const char * ME = "me";
|
||||
static const char * TELEMETRY = "telemetry";
|
||||
static const char * INTERVAL = "interval";
|
||||
static const char * UI = "UI";
|
||||
static const char * BANDWIDTH = "bandwidth";
|
||||
}
|
||||
static const char *REQUIREMENTS = "requirements";
|
||||
static const char *PASSWORDPATTERN = "passwordPattern";
|
||||
static const char *ACCESSPOLICY = "accessPolicy";
|
||||
static const char *PASSWORDPOLICY = "passwordPolicy";
|
||||
static const char *FORGOTPASSWORD = "forgotPassword";
|
||||
static const char *RESENDMFACODE = "resendMFACode";
|
||||
static const char *COMPLETEMFACHALLENGE = "completeMFAChallenge";
|
||||
static const char *ME = "me";
|
||||
static const char *TELEMETRY = "telemetry";
|
||||
static const char *INTERVAL = "interval";
|
||||
static const char *UI = "UI";
|
||||
static const char *BANDWIDTH = "bandwidth";
|
||||
} // namespace OpenWifi::RESTAPI::Protocol
|
||||
|
||||
namespace OpenWifi::uCentralProtocol {
|
||||
|
||||
@@ -490,7 +633,7 @@ namespace OpenWifi::uCentralProtocol {
|
||||
static const char *RADIUSCOA = "coa";
|
||||
static const char *RADIUSDST = "dst";
|
||||
static const char *IES = "ies";
|
||||
}
|
||||
} // namespace OpenWifi::uCentralProtocol
|
||||
|
||||
namespace OpenWifi::uCentralProtocol::Events {
|
||||
|
||||
@@ -525,41 +668,41 @@ namespace OpenWifi::uCentralProtocol::Events {
|
||||
ET_ALARM
|
||||
};
|
||||
|
||||
inline EVENT_MSG EventFromString(const std::string & Method) {
|
||||
if(strcmp(STATE,Method.c_str())==0)
|
||||
inline EVENT_MSG EventFromString(const std::string &Method) {
|
||||
if (strcmp(STATE, Method.c_str()) == 0)
|
||||
return ET_STATE;
|
||||
else if(strcmp(HEALTHCHECK,Method.c_str())==0)
|
||||
else if (strcmp(HEALTHCHECK, Method.c_str()) == 0)
|
||||
return ET_HEALTHCHECK;
|
||||
else if(strcmp(CONNECT,Method.c_str())==0)
|
||||
else if (strcmp(CONNECT, Method.c_str()) == 0)
|
||||
return ET_CONNECT;
|
||||
else if(strcmp(CFGPENDING,Method.c_str())==0)
|
||||
else if (strcmp(CFGPENDING, Method.c_str()) == 0)
|
||||
return ET_CFGPENDING;
|
||||
else if(strcmp(CRASHLOG,Method.c_str())==0)
|
||||
else if (strcmp(CRASHLOG, Method.c_str()) == 0)
|
||||
return ET_CRASHLOG;
|
||||
else if(strcmp(DEVICEUPDATE,Method.c_str())==0)
|
||||
else if (strcmp(DEVICEUPDATE, Method.c_str()) == 0)
|
||||
return ET_DEVICEUPDATE;
|
||||
else if(strcmp(LOG,Method.c_str())==0)
|
||||
else if (strcmp(LOG, Method.c_str()) == 0)
|
||||
return ET_LOG;
|
||||
else if(strcmp(PING,Method.c_str())==0)
|
||||
else if (strcmp(PING, Method.c_str()) == 0)
|
||||
return ET_PING;
|
||||
else if(strcmp(RECOVERY,Method.c_str())==0)
|
||||
else if (strcmp(RECOVERY, Method.c_str()) == 0)
|
||||
return ET_RECOVERY;
|
||||
else if(strcmp(TELEMETRY,Method.c_str())==0)
|
||||
else if (strcmp(TELEMETRY, Method.c_str()) == 0)
|
||||
return ET_TELEMETRY;
|
||||
else if(strcmp(VENUE_BROADCAST,Method.c_str())==0)
|
||||
else if (strcmp(VENUE_BROADCAST, Method.c_str()) == 0)
|
||||
return ET_VENUEBROADCAST;
|
||||
else if(strcmp(EVENT,Method.c_str())==0)
|
||||
else if (strcmp(EVENT, Method.c_str()) == 0)
|
||||
return ET_EVENT;
|
||||
else if(strcmp(WIFISCAN,Method.c_str())==0)
|
||||
else if (strcmp(WIFISCAN, Method.c_str()) == 0)
|
||||
return ET_WIFISCAN;
|
||||
else if(strcmp(ALARM,Method.c_str())==0)
|
||||
else if (strcmp(ALARM, Method.c_str()) == 0)
|
||||
return ET_WIFISCAN;
|
||||
return ET_ALARM;
|
||||
};
|
||||
}
|
||||
} // namespace OpenWifi::uCentralProtocol::Events
|
||||
|
||||
namespace OpenWifi::APCommands {
|
||||
enum class Commands:uint8_t {
|
||||
enum class Commands : uint8_t {
|
||||
capabilities,
|
||||
logs,
|
||||
healthchecks,
|
||||
@@ -581,60 +724,47 @@ namespace OpenWifi::APCommands {
|
||||
unknown
|
||||
};
|
||||
|
||||
inline static const std::vector<const char *> uCentralAPCommands {
|
||||
RESTAPI::Protocol::CAPABILITIES,
|
||||
RESTAPI::Protocol::LOGS,
|
||||
RESTAPI::Protocol::HEALTHCHECKS,
|
||||
RESTAPI::Protocol::STATISTICS,
|
||||
RESTAPI::Protocol::STATUS,
|
||||
RESTAPI::Protocol::RTTY,
|
||||
RESTAPI::Protocol::CONFIGURE,
|
||||
RESTAPI::Protocol::UPGRADE,
|
||||
RESTAPI::Protocol::REBOOT,
|
||||
RESTAPI::Protocol::FACTORY,
|
||||
RESTAPI::Protocol::LEDS,
|
||||
RESTAPI::Protocol::TRACE,
|
||||
RESTAPI::Protocol::REQUEST,
|
||||
RESTAPI::Protocol::WIFISCAN,
|
||||
RESTAPI::Protocol::EVENTQUEUE,
|
||||
RESTAPI::Protocol::TELEMETRY,
|
||||
RESTAPI::Protocol::PING,
|
||||
RESTAPI::Protocol::SCRIPT};
|
||||
inline static const std::vector<const char *> uCentralAPCommands{
|
||||
RESTAPI::Protocol::CAPABILITIES, RESTAPI::Protocol::LOGS,
|
||||
RESTAPI::Protocol::HEALTHCHECKS, RESTAPI::Protocol::STATISTICS,
|
||||
RESTAPI::Protocol::STATUS, RESTAPI::Protocol::RTTY,
|
||||
RESTAPI::Protocol::CONFIGURE, RESTAPI::Protocol::UPGRADE,
|
||||
RESTAPI::Protocol::REBOOT, RESTAPI::Protocol::FACTORY,
|
||||
RESTAPI::Protocol::LEDS, RESTAPI::Protocol::TRACE,
|
||||
RESTAPI::Protocol::REQUEST, RESTAPI::Protocol::WIFISCAN,
|
||||
RESTAPI::Protocol::EVENTQUEUE, RESTAPI::Protocol::TELEMETRY,
|
||||
RESTAPI::Protocol::PING, RESTAPI::Protocol::SCRIPT};
|
||||
|
||||
inline const char * to_string(Commands Cmd) {
|
||||
return uCentralAPCommands[(uint8_t)Cmd];
|
||||
}
|
||||
inline const char *to_string(Commands Cmd) { return uCentralAPCommands[(uint8_t)Cmd]; }
|
||||
|
||||
inline Commands to_apcommand(const char *cmd) {
|
||||
for(auto i=(uint8_t)Commands::capabilities;i!=(uint8_t)Commands::unknown;++i) {
|
||||
if(strcmp(uCentralAPCommands[i],cmd)==0)
|
||||
for (auto i = (uint8_t)Commands::capabilities; i != (uint8_t)Commands::unknown; ++i) {
|
||||
if (strcmp(uCentralAPCommands[i], cmd) == 0)
|
||||
return (Commands)i;
|
||||
}
|
||||
return Commands::unknown;
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi::APCommands
|
||||
|
||||
namespace OpenWifi::Provisioning::DeviceClass {
|
||||
|
||||
static const char * ANY = "any";
|
||||
static const char * SUBSCRIBER = "subscriber";
|
||||
static const char * VENUE = "venue";
|
||||
static const char * ENTITY = "entity";
|
||||
static const char *ANY = "any";
|
||||
static const char *SUBSCRIBER = "subscriber";
|
||||
static const char *VENUE = "venue";
|
||||
static const char *ENTITY = "entity";
|
||||
|
||||
inline bool Validate(const char *s) {
|
||||
static std::vector<std::string> Values{ ANY, ENTITY, SUBSCRIBER, VENUE };
|
||||
static std::vector<std::string> Values{ANY, ENTITY, SUBSCRIBER, VENUE};
|
||||
return std::find(cbegin(Values), cend(Values), s) != cend(Values);
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace OpenWifi::Provisioning::DeviceClass
|
||||
|
||||
#if defined(__GNUC__ )
|
||||
#if defined(__GNUC__)
|
||||
#pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
#if defined(__clang__)
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user