Compare commits

..

1 Commits

Author SHA1 Message Date
TIP Automation User
1063080859 Chg: update image tag in helm values to v3.0.0-RC1 2023-11-27 17:38:12 +00:00
20 changed files with 160 additions and 358 deletions

View File

@@ -21,7 +21,7 @@ defaults:
jobs: jobs:
docker: docker:
runs-on: ubuntu-latest runs-on: ubuntu-20.04
env: env:
DOCKER_REGISTRY_URL: tip-tip-wlan-cloud-ucentral.jfrog.io DOCKER_REGISTRY_URL: tip-tip-wlan-cloud-ucentral.jfrog.io
DOCKER_REGISTRY_USERNAME: ucentral DOCKER_REGISTRY_USERNAME: ucentral

View File

@@ -1,6 +1,6 @@
# Building from source # Building from source
In order to build OWSEC, you will need to install its dependencies, which includes the following: In order to build the OWSEC, you will need to install its dependencies, which includes the following:
- cmake - cmake
- boost - boost
- POCO 1.10.1 or later - POCO 1.10.1 or later
@@ -13,43 +13,43 @@ In order to build OWSEC, you will need to install its dependencies, which includ
The build is done in 2 parts. The first part is to build a local copy of the framework tailored to your environment. This The build is done in 2 parts. The first part is to build a local copy of the framework tailored to your environment. This
framework is called [Poco](https://github.com/pocoproject/poco). The version used in this project has a couple of fixes framework is called [Poco](https://github.com/pocoproject/poco). The version used in this project has a couple of fixes
from the master copy needed for cmake. Please use the version of this [Poco fix](https://github.com/Telecominfraproject/wlan-cloud-lib-poco). Building from the master copy needed for cmake. Please use the version of this [Poco fix](https://github.com/AriliaWireless/poco). Building
Poco may take several minutes depending on the platform you are building on. Poco may take several minutes depending on the platform you are building on.
## Ubuntu ## Ubuntu
These instructions have proven to work on Ubuntu 20.4. These instructions have proven to work on Ubuntu 20.4.
```bash ```bash
sudo apt install git cmake g++ libssl-dev libmariadb-dev \ sudo apt install git cmake g++ libssl-dev libmariadb-dev
libpq-dev libaprutil1-dev apache2-dev libboost-all-dev \ sudo apt install libpq-dev libaprutil1-dev apache2-dev libboost-all-dev
librdkafka-dev default-libmysqlclient-dev \ sudo apt install librdkafka-dev default-libmysqlclient-dev
nlohmann-json-dev sudo apt install nlohmann-json-dev
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-poco --branch poco-tip-v1 poco cd ~
git clone https://github.com/AriliaWireless/poco --branch poco-tip-v1
cd poco cd poco
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake .. cmake ..
cmake --build . --config Release cmake --build . --config Release
sudo cmake --build . --target install sudo cmake --build . --target install
cd ../..
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-cppkafka --branch tip-v1 cppkafka cd ~
git clone https://github.com/AriliaWireless/cppkafka --branch tip-v1
cd cppkafka cd cppkafka
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake .. cmake ..
cmake --build . --config Release cmake --build . --config Release
sudo cmake --build . --target install sudo cmake --build . --target install
cd ../..
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-valijson --branch tip-v1 valijson cd ~
git clone https://github.com/AriliaWireless/valijson --branch tip-v1
cd valijson cd valijson
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake .. cmake ..
cmake --build . --config Release cmake --build . --config Release
sudo cmake --build . --target install sudo cmake --build . --target install
cd ../..
git clone https://github.com/fmtlib/fmt --branch 9.0.0 /fmtlib git clone https://github.com/fmtlib/fmt --branch 9.0.0 /fmtlib
cd fmtlib cd fmtlib
@@ -58,59 +58,56 @@ cd cmake-build
cmake .. cmake ..
make make
make install make install
cd ../..
cd ~
git clone https://github.com/Telecominfraproject/wlan-cloud-ucentralsec git clone https://github.com/Telecominfraproject/wlan-cloud-ucentralsec
cd wlan-cloud-ucentralsec cd wlan-cloud-ucentralsec
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake .. cmake ..
make -j 8 make -j 8
cd ../..
``` ```
## Fedora ## Fedora
The following instructions have proven to work on Fedora 33 The following instructions have proven to work on Fedora 33
```bash ```bash
sudo yum install cmake g++ openssl-devel mysql-devel mysql apr-util-devel boost boost-devel \ sudo yum install cmake g++ openssl-devel mysql-devel mysql apr-util-devel boost boost-devel
yaml-cpp-devel lua-devel sudo yum install yaml-cpp-devel lua-devel
sudo dnf install postgresql.x86_64 librdkafka-devel sudo dnf install postgresql.x86_64 librdkafka-devel
sudo dnf install postgresql-devel json-devel sudo dnf install postgresql-devel json-devel
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-poco --branch poco-tip-v1 poco git clone https://github.com/AriliaWireless/poco --branch poco-tip-v1
cd poco cd poco
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake .. cmake ..
cmake --build . --config Release cmake --build . --config Release
sudo cmake --build . --target install sudo cmake --build . --target install
cd ../..
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-cppkafka --branch tip-v1 cppkafka git clone https://github.com/AriliaWireless/cppkafka --branch tip-v1
cd cppkafka cd cppkafka
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake .. cmake ..
cmake --build . --config Release cmake --build . --config Release
sudo cmake --build . --target install sudo cmake --build . --target install
cd ../..
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-valijson --branch tip-v1 valijson cd ~
git clone https://github.com/AriliaWireless/valijson --branch tip-v1
cd valijson cd valijson
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake .. cmake ..
cmake --build . --config Release cmake --build . --config Release
sudo cmake --build . --target install sudo cmake --build . --target install
cd ../..
cd ~
git clone https://github.com/Telecominfraproject/wlan-cloud-ucentralsec git clone https://github.com/Telecominfraproject/wlan-cloud-ucentralsec
cd wlan-cloud-ucentralsec cd wlan-cloud-ucentralsec
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake .. cmake ..
make make
cd ../..
``` ```
## macOS Build ## macOS Build
@@ -129,7 +126,7 @@ brew install openssl \
nlohmann-json \ nlohmann-json \
fmt fmt
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-poco --branch poco-tip-v1 poco git clone https://github.com/AriliaWireless/poco --branch poco-tip-v1
pushd poco pushd poco
mkdir cmake-build mkdir cmake-build
push cmake-build push cmake-build
@@ -139,7 +136,7 @@ sudo cmake --build . --target install
popd popd
popd popd
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-cppkafka --branch tip-v1 cppkafka git clone https://github.com/AriliaWireless/cppkafka --branch tip-v1
pushd cppkafka pushd cppkafka
mkdir cmake-build mkdir cmake-build
pushd cmake-build pushd cmake-build
@@ -149,10 +146,10 @@ sudo cmake --build . --target install
popd popd
popd popd
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-valijson --branch tip-v1 valijson git clone https://github.com/AriliaWireless/valijson --branch tip-v1
pushd valijson cd valijson
mkdir cmake-build mkdir cmake-build
pushd cmake-build cd cmake-build
cmake .. cmake ..
cmake --build . --config Release cmake --build . --config Release
sudo cmake --build . --target install sudo cmake --build . --target install
@@ -175,23 +172,20 @@ support. You can build with only SQLite support by not installing the packages f
adding -DSMALL_BUILD=1 on the cmake build line. adding -DSMALL_BUILD=1 on the cmake build line.
```bash ```bash
sudo apt install git cmake g++ libssl-dev libaprutil1-dev apache2-dev \ sudo apt install git cmake g++ libssl-dev libaprutil1-dev apache2-dev libboost-all-dev libyaml-cpp-dev
libboost-all-dev libyaml-cpp-dev git clone https://github.com/stephb9959/poco
git clone https://github.com/Telecominfraproject/wlan-cloud-lib-poco --branch poco-tip-v1 poco
cd poco cd poco
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake .. cmake ..
cmake --build . --config Release cmake --build . --config Release
sudo cmake --build . --target install sudo cmake --build . --target install
cd ../..
cd ~
git clone https://github.com/Telecominfraproject/wlan-cloud-ucentralsec git clone https://github.com/Telecominfraproject/wlan-cloud-ucentralsec
cd wlan-cloud-ucentralsec cd wlan-cloud-ucentralsec
mkdir cmake-build mkdir cmake-build
cd cmake-build cd cmake-build
cmake -DSMALL_BUILD=1 .. cmake -DSMALL_BUILD=1 ..
make make
cd ../..
``` ```

View File

@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.13) cmake_minimum_required(VERSION 3.13)
project(owsec VERSION 3.2.0) project(owsec VERSION 3.0.0)
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)

View File

@@ -15,8 +15,8 @@ FROM build-base AS poco-build
ARG POCO_VERSION ARG POCO_VERSION
ADD https://api.github.com/repos/Telecominfraproject/wlan-cloud-lib-poco/git/refs/tags/${POCO_VERSION} version.json ADD https://api.github.com/repos/AriliaWireless/poco/git/refs/tags/${POCO_VERSION} version.json
RUN git clone https://github.com/Telecominfraproject/wlan-cloud-lib-poco --branch ${POCO_VERSION} /poco RUN git clone https://github.com/AriliaWireless/poco --branch ${POCO_VERSION} /poco
WORKDIR /poco WORKDIR /poco
RUN mkdir cmake-build RUN mkdir cmake-build
@@ -29,8 +29,8 @@ FROM build-base AS cppkafka-build
ARG CPPKAFKA_VERSION ARG CPPKAFKA_VERSION
ADD https://api.github.com/repos/Telecominfraproject/wlan-cloud-lib-cppkafka/git/refs/tags/${CPPKAFKA_VERSION} version.json ADD https://api.github.com/repos/AriliaWireless/cppkafka/git/refs/tags/${CPPKAFKA_VERSION} version.json
RUN git clone https://github.com/Telecominfraproject/wlan-cloud-lib-cppkafka --branch ${CPPKAFKA_VERSION} /cppkafka RUN git clone https://github.com/AriliaWireless/cppkafka --branch ${CPPKAFKA_VERSION} /cppkafka
WORKDIR /cppkafka WORKDIR /cppkafka
RUN mkdir cmake-build RUN mkdir cmake-build
@@ -43,8 +43,8 @@ FROM build-base AS valijson-build
ARG VALIJASON_VERSION ARG VALIJASON_VERSION
ADD https://api.github.com/repos/Telecominfraproject/wlan-cloud-lib-valijson/git/refs/tags/${VALIJASON_VERSION} version.json ADD https://api.github.com/repos/AriliaWireless/valijson/git/refs/tags/${VALIJASON_VERSION} version.json
RUN git clone https://github.com/Telecominfraproject/wlan-cloud-lib-valijson --branch ${VALIJASON_VERSION} /valijson RUN git clone https://github.com/AriliaWireless/valijson --branch ${VALIJASON_VERSION} /valijson
WORKDIR /valijson WORKDIR /valijson
RUN mkdir cmake-build RUN mkdir cmake-build

2
build
View File

@@ -1 +1 @@
1 2

View File

@@ -9,7 +9,7 @@ fullnameOverride: ""
images: images:
owsec: owsec:
repository: tip-tip-wlan-cloud-ucentral.jfrog.io/owsec repository: tip-tip-wlan-cloud-ucentral.jfrog.io/owsec
tag: main tag: v3.0.0-RC1
pullPolicy: Always pullPolicy: Always
# regcred: # regcred:
# registry: tip-tip-wlan-cloud-ucentral.jfrog.io # registry: tip-tip-wlan-cloud-ucentral.jfrog.io

View File

@@ -218,7 +218,7 @@ namespace OpenWifi {
Expired = (WT.created_ + WT.expires_in_) < now; Expired = (WT.created_ + WT.expires_in_) < now;
if (StorageService()->UserDB().GetUserById(UserId, UInfo.userinfo)) { if (StorageService()->UserDB().GetUserById(UserId, UInfo.userinfo)) {
UInfo.webtoken = WT; UInfo.webtoken = WT;
poco_trace(Logger(), fmt::format("TokenValidation success for TID={} Token={}", poco_debug(Logger(), fmt::format("TokenValidation success for TID={} Token={}",
TID, Utils::SanitizeToken(CallToken))); TID, Utils::SanitizeToken(CallToken)));
return true; return true;
} }

View File

@@ -587,9 +587,6 @@ namespace OpenWifi::ProvObjects {
field_to_json(Obj, "locale", locale); field_to_json(Obj, "locale", locale);
field_to_json(Obj, "realMacAddress", realMacAddress); field_to_json(Obj, "realMacAddress", realMacAddress);
field_to_json(Obj, "doNotAllowOverrides", doNotAllowOverrides); field_to_json(Obj, "doNotAllowOverrides", doNotAllowOverrides);
field_to_json(Obj, "imported", imported);
field_to_json(Obj, "connected", connected);
field_to_json(Obj, "platform", platform);
} }
bool InventoryTag::from_json(const Poco::JSON::Object::Ptr &Obj) { bool InventoryTag::from_json(const Poco::JSON::Object::Ptr &Obj) {
@@ -612,9 +609,6 @@ namespace OpenWifi::ProvObjects {
field_from_json(Obj, "locale", locale); field_from_json(Obj, "locale", locale);
field_from_json(Obj, "realMacAddress", realMacAddress); field_from_json(Obj, "realMacAddress", realMacAddress);
field_from_json(Obj, "doNotAllowOverrides", doNotAllowOverrides); field_from_json(Obj, "doNotAllowOverrides", doNotAllowOverrides);
field_from_json(Obj, "imported", imported);
field_from_json(Obj, "connected", connected);
field_from_json(Obj, "platform", platform);
return true; return true;
} catch (...) { } catch (...) {
} }

View File

@@ -490,11 +490,9 @@ namespace OpenWifi::ProvObjects {
std::string locale; std::string locale;
std::string realMacAddress; std::string realMacAddress;
bool doNotAllowOverrides = false; bool doNotAllowOverrides = false;
std::uint64_t imported=0;
std::uint64_t connected=0;
std::string platform{"AP"};
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };

View File

@@ -9,6 +9,8 @@
namespace OpenWifi { namespace OpenWifi {
EventBusManager::EventBusManager(Poco::Logger &L) : Logger_(L) {}
void EventBusManager::run() { void EventBusManager::run() {
Running_ = true; Running_ = true;
Utils::SetThreadName("fmwk:EventMgr"); Utils::SetThreadName("fmwk:EventMgr");
@@ -16,9 +18,9 @@ namespace OpenWifi {
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg, KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg,
false); false);
while (Running_) { while (Running_) {
if(!Poco::Thread::trySleep((unsigned long)MicroServiceDaemonBusTimer())) { Poco::Thread::trySleep((unsigned long)MicroServiceDaemonBusTimer());
break; if (!Running_)
} break;
Msg = (MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE)); Msg = (MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE));
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(),
Msg, false); Msg, false);
@@ -29,7 +31,7 @@ namespace OpenWifi {
}; };
void EventBusManager::Start() { void EventBusManager::Start() {
poco_information(Logger_, "Starting..."); poco_information(Logger(), "Starting...");
if (KafkaManager()->Enabled()) { if (KafkaManager()->Enabled()) {
Thread_.start(*this); Thread_.start(*this);
} }
@@ -37,11 +39,11 @@ namespace OpenWifi {
void EventBusManager::Stop() { void EventBusManager::Stop() {
if (KafkaManager()->Enabled()) { if (KafkaManager()->Enabled()) {
poco_information(Logger_, "Stopping..."); poco_information(Logger(), "Stopping...");
Running_ = false; Running_ = false;
Thread_.wakeUp(); Thread_.wakeUp();
Thread_.join(); Thread_.join();
poco_information(Logger_, "Stopped..."); poco_information(Logger(), "Stopped...");
} }
} }

View File

@@ -12,16 +12,7 @@ namespace OpenWifi {
class EventBusManager : public Poco::Runnable { class EventBusManager : public Poco::Runnable {
public: public:
EventBusManager() : explicit EventBusManager(Poco::Logger &L);
Logger_(Poco::Logger::create(
"EventBusManager", Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel())) {
}
static auto instance() {
static auto instance_ = new EventBusManager;
return instance_;
}
void run() final; void run() final;
void Start(); void Start();
void Stop(); void Stop();
@@ -33,6 +24,4 @@ namespace OpenWifi {
Poco::Logger &Logger_; Poco::Logger &Logger_;
}; };
inline auto EventBusManager() { return EventBusManager::instance(); }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -79,10 +79,8 @@ namespace OpenWifi {
Utils::SetThreadName("Kafka:Prod"); Utils::SetThreadName("Kafka:Prod");
cppkafka::Configuration Config( cppkafka::Configuration Config(
{{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")}, {{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")},
{"metadata.broker.list",MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")} // , {"metadata.broker.list",
// {"send.buffer.bytes", KafkaManager()->KafkaManagerMaximumPayloadSize() } MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")}});
}
);
AddKafkaSecurity(Config); AddKafkaSecurity(Config);
@@ -107,19 +105,6 @@ namespace OpenWifi {
NewMessage.partition(0); NewMessage.partition(0);
NewMessage.payload(Msg->Payload()); NewMessage.payload(Msg->Payload());
Producer.produce(NewMessage); Producer.produce(NewMessage);
if (Queue_.size() < 100) {
// use flush when internal queue is lightly loaded, i.e. flush after each
// message
Producer.flush();
}
else {
// use poll when internal queue is loaded to allow messages to be sent in
// batches
Producer.poll((std::chrono::milliseconds) 0);
}
}
if (Queue_.size() == 0) {
// message queue is empty, flush all previously sent messages
Producer.flush(); Producer.flush();
} }
} catch (const cppkafka::HandleException &E) { } catch (const cppkafka::HandleException &E) {
@@ -132,7 +117,6 @@ namespace OpenWifi {
} }
Note = Queue_.waitDequeueNotification(); Note = Queue_.waitDequeueNotification();
} }
Producer.flush();
poco_information(Logger_, "Stopped..."); poco_information(Logger_, "Stopped...");
} }
@@ -291,7 +275,6 @@ namespace OpenWifi {
int KafkaManager::Start() { int KafkaManager::Start() {
if (!KafkaEnabled_) if (!KafkaEnabled_)
return 0; return 0;
MaxPayloadSize_ = MicroServiceConfigGetInt("openwifi.kafka.max.payload", 250000);
ConsumerThr_.Start(); ConsumerThr_.Start();
ProducerThr_.Start(); ProducerThr_.Start();
return 0; return 0;
@@ -338,4 +321,4 @@ namespace OpenWifi {
partitions.front().get_partition())); partitions.front().get_partition()));
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -94,14 +94,11 @@ namespace OpenWifi {
return ConsumerThr_.UnregisterTopicWatcher(Topic,Id); return ConsumerThr_.UnregisterTopicWatcher(Topic,Id);
} }
std::uint64_t KafkaManagerMaximumPayloadSize() const { return MaxPayloadSize_; }
private: private:
bool KafkaEnabled_ = false; bool KafkaEnabled_ = false;
std::string SystemInfoWrapper_; std::string SystemInfoWrapper_;
KafkaProducer ProducerThr_; KafkaProducer ProducerThr_;
KafkaConsumer ConsumerThr_; KafkaConsumer ConsumerThr_;
std::uint64_t MaxPayloadSize_ = 250000;
void PartitionAssignment(const cppkafka::TopicPartitionList &partitions); void PartitionAssignment(const cppkafka::TopicPartitionList &partitions);
void PartitionRevocation(const cppkafka::TopicPartitionList &partitions); void PartitionRevocation(const cppkafka::TopicPartitionList &partitions);

View File

@@ -29,29 +29,13 @@
#include "framework/WebSocketLogger.h" #include "framework/WebSocketLogger.h"
#include "framework/utils.h" #include "framework/utils.h"
#ifdef USE_MEDUSA_CLIENT
#include <medusa/MedusaClient.h>
#endif
namespace OpenWifi { namespace OpenWifi {
static std::string MakeServiceListString(const Types::MicroServiceMetaMap &Services) { void MicroService::Exit(int Reason) { std::exit(Reason); }
std::string SvcList;
for (const auto &Svc : Services) {
if (SvcList.empty())
SvcList = Svc.second.Type;
else
SvcList += ", " + Svc.second.Type;
}
return SvcList;
}
void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key, void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key,
const std::string &Payload) { const std::string &Payload) {
std::lock_guard G(InfraMutex_); std::lock_guard G(InfraMutex_);
Poco::Logger &BusLogger = EventBusManager()->Logger();
try { try {
Poco::JSON::Parser P; Poco::JSON::Parser P;
auto Object = P.parse(Payload).extract<Poco::JSON::Object::Ptr>(); auto Object = P.parse(Payload).extract<Poco::JSON::Object::Ptr>();
@@ -71,10 +55,13 @@ namespace OpenWifi {
Object->has(KafkaTopics::ServiceEvents::Fields::KEY)) { Object->has(KafkaTopics::ServiceEvents::Fields::KEY)) {
auto PrivateEndPoint = auto PrivateEndPoint =
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(); Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString();
if (Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) { 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); Services_.erase(PrivateEndPoint);
poco_information( poco_debug(
BusLogger, logger(),
fmt::format( fmt::format(
"Service {} ID={} leaving system.", "Service {} ID={} leaving system.",
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE) Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
@@ -82,7 +69,14 @@ namespace OpenWifi {
ID)); ID));
} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN || } else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN ||
Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) { Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) {
auto ServiceInfo = Types::MicroServiceMeta{ poco_debug(
logger(),
fmt::format(
"Service {} ID={} joining system.",
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
Services_[PrivateEndPoint] = Types::MicroServiceMeta{
.Id = ID, .Id = ID,
.Type = Poco::toLower( .Type = Poco::toLower(
Object->get(KafkaTopics::ServiceEvents::Fields::TYPE) Object->get(KafkaTopics::ServiceEvents::Fields::TYPE)
@@ -100,46 +94,20 @@ namespace OpenWifi {
.toString(), .toString(),
.LastUpdate = Utils::Now()}; .LastUpdate = Utils::Now()};
auto s1 = MakeServiceListString(Services_); std::string SvcList;
auto PreviousSize = Services_.size(); for (const auto &Svc : Services_) {
Services_[PrivateEndPoint] = ServiceInfo; if (SvcList.empty())
auto CurrentSize = Services_.size(); SvcList = Svc.second.Type;
if(Event == KafkaTopics::ServiceEvents::EVENT_JOIN) { else
if(!s1.empty()) { SvcList += ", " + Svc.second.Type;
poco_information(
BusLogger,
fmt::format(
"Service {} ID={} is joining the system.",
Object
->get(
KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
}
std::string SvcList;
for (const auto &Svc : Services_) {
if (SvcList.empty())
SvcList = Svc.second.Type;
else
SvcList += ", " + Svc.second.Type;
}
poco_information(
BusLogger,
fmt::format("Current list of microservices: {}", SvcList));
} else if(CurrentSize!=PreviousSize) {
poco_information(
BusLogger,
fmt::format(
"Service {} ID={} is being added back in.",
Object
->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
} }
poco_information(
logger(),
fmt::format("Current list of microservices: {}", SvcList));
} }
} else { } else {
poco_information( poco_error(
BusLogger, logger(),
fmt::format("KAFKA-MSG: invalid event '{}', missing a field.", fmt::format("KAFKA-MSG: invalid event '{}', missing a field.",
Event)); Event));
} }
@@ -150,39 +118,32 @@ namespace OpenWifi {
Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString()); Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString());
#endif #endif
} else { } else {
poco_information( poco_error(
BusLogger, logger(),
fmt::format("KAFKA-MSG: invalid event '{}', missing token", Event)); fmt::format("KAFKA-MSG: invalid event '{}', missing token", Event));
} }
} else { } else {
poco_information(BusLogger, poco_error(logger(),
fmt::format("Unknown Event: {} Source: {}", Event, ID)); fmt::format("Unknown Event: {} Source: {}", Event, ID));
} }
} }
} else { } else {
std::ostringstream os; poco_error(logger(), "Bad bus message.");
Object->stringify(std::cout); std::ostringstream os;
poco_error(BusLogger, fmt::format("Bad bus message: {}", os.str())); Object->stringify(std::cout);
} }
auto ServiceHint = Services_.begin(); auto i = Services_.begin();
auto now = Utils::Now(); auto now = Utils::Now();
auto si1 = Services_.size(); for (; i != Services_.end();) {
auto ss1 = MakeServiceListString(Services_); if ((now - i->second.LastUpdate) > 60) {
while(ServiceHint!=Services_.end()) { i = Services_.erase(i);
if ((now - ServiceHint->second.LastUpdate) > 120) {
poco_information(BusLogger, fmt::format("ZombieService: Removing service {}, ", ServiceHint->second.PublicEndPoint));
ServiceHint = Services_.erase(ServiceHint);
} else } else
++ServiceHint; ++i;
} }
if(Services_.size() != si1) {
auto ss2 = MakeServiceListString(Services_);
poco_information(BusLogger, fmt::format("Current list of microservices: {} -> {}", ss1, ss2));
}
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
BusLogger.log(E); logger().log(E);
} }
} }
@@ -206,29 +167,25 @@ namespace OpenWifi {
Res.push_back(ServiceRec); Res.push_back(ServiceRec);
} }
return Res; return Res;
} }
void MicroService::LoadConfigurationFile() { void MicroService::LoadConfigurationFile() {
if(ConfigContent_.empty()) { std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR, ".");
std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR, "."); ConfigFileName_ =
ConfigFileName_ = ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_;
ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_; Poco::Path ConfigFile(ConfigFileName_);
Poco::Path ConfigFile(ConfigFileName_);
if (!ConfigFile.isFile()) { if (!ConfigFile.isFile()) {
std::cerr << DAEMON_APP_NAME << ": Configuration " << ConfigFile.toString() std::cerr << DAEMON_APP_NAME << ": Configuration " << ConfigFile.toString()
<< " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR + << " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR +
" env variable the path of the " + DAEMON_PROPERTIES_FILENAME + " env variable the path of the " + DAEMON_PROPERTIES_FILENAME +
" file." " file."
<< std::endl; << std::endl;
std::exit(Poco::Util::Application::EXIT_CONFIG); std::exit(Poco::Util::Application::EXIT_CONFIG);
} }
PropConfigurationFile_ = new Poco::Util::PropertyFileConfiguration(ConfigFile.toString());
} else { // loadConfiguration(ConfigFile.toString());
std::istringstream is(ConfigContent_); PropConfigurationFile_ = new Poco::Util::PropertyFileConfiguration(ConfigFile.toString());
PropConfigurationFile_ = new Poco::Util::PropertyFileConfiguration(is);
}
configPtr()->addWriteable(PropConfigurationFile_, PRIO_DEFAULT); configPtr()->addWriteable(PropConfigurationFile_, PRIO_DEFAULT);
} }
@@ -431,59 +388,49 @@ namespace OpenWifi {
void DaemonPostInitialization(Poco::Util::Application &self); void DaemonPostInitialization(Poco::Util::Application &self);
void MicroService::StartEverything(Poco::Util::Application &self) { void MicroService::initialize(Poco::Util::Application &self) {
LoadConfigurationFile(); // add the default services
InitializeLoggingSystem(); LoadConfigurationFile();
InitializeLoggingSystem();
static bool InitializedBaseService=false; SubSystems_.push_back(KafkaManager());
if(!InitializedBaseService) { SubSystems_.push_back(ALBHealthCheckServer());
InitializedBaseService = true; SubSystems_.push_back(RESTAPI_ExtServer());
SubSystems_.push_back(KafkaManager()); SubSystems_.push_back(RESTAPI_IntServer());
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()); SubSystems_.push_back(AuthClient());
#endif #endif
Poco::Net::initializeSSL();
Poco::Net::HTTPStreamFactory::registerFactory();
Poco::Net::HTTPSStreamFactory::registerFactory();
Poco::Net::FTPStreamFactory::registerFactory();
Poco::Net::FTPSStreamFactory::registerFactory();
Poco::Net::initializeSSL(); Poco::File DataDir(ConfigPath("openwifi.system.data"));
Poco::Net::HTTPStreamFactory::registerFactory(); DataDir_ = DataDir.path();
Poco::Net::HTTPSStreamFactory::registerFactory(); if (!DataDir.exists()) {
Poco::Net::FTPStreamFactory::registerFactory(); try {
Poco::Net::FTPSStreamFactory::registerFactory(); DataDir.createDirectory();
} } catch (const Poco::Exception &E) {
logger().log(E);
}
}
WWWAssetsDir_ = ConfigPath("openwifi.restapi.wwwassets", "");
if (WWWAssetsDir_.empty())
WWWAssetsDir_ = DataDir_;
Poco::File DataDir(ConfigPath("openwifi.system.data")); LoadMyConfig();
DataDir_ = DataDir.path();
if (!DataDir.exists()) {
try {
DataDir.createDirectory();
} catch (const Poco::Exception &E) {
Logger_.log(E);
}
}
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);
InitializeSubSystemServers(); Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) {
ServerApplication::initialize(self); this->BusMessageReceived(Key, Payload);
DaemonPostInitialization(self); };
KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F);
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) {
this->BusMessageReceived(Key, Payload);
};
KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F);
}
void MicroService::initialize([[maybe_unused]] Poco::Util::Application &self) {
#ifndef USE_MEDUSA_CLIENT
StartEverything(self);
#endif
} }
void MicroService::uninitialize() { void MicroService::uninitialize() {
@@ -583,12 +530,14 @@ namespace OpenWifi {
for (auto i : SubSystems_) { for (auto i : SubSystems_) {
i->Start(); i->Start();
} }
EventBusManager()->Start(); EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create(
"EventBusManager", Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel()));
EventBusManager_->Start();
} }
void MicroService::StopSubSystemServers() { void MicroService::StopSubSystemServers() {
AddActivity("Stopping"); AddActivity("Stopping");
EventBusManager()->Stop(); EventBusManager_->Stop();
for (auto i = SubSystems_.rbegin(); i != SubSystems_.rend(); ++i) { for (auto i = SubSystems_.rbegin(); i != SubSystems_.rend(); ++i) {
(*i)->Stop(); (*i)->Stop();
} }
@@ -748,7 +697,7 @@ namespace OpenWifi {
auto APIKEY = Request.get("X-API-KEY"); auto APIKEY = Request.get("X-API-KEY");
return APIKEY == MyHash_; return APIKEY == MyHash_;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
Logger_.log(E); logger().log(E);
} }
return false; return false;
} }
@@ -769,8 +718,6 @@ namespace OpenWifi {
MicroServiceErrorHandler ErrorHandler(*this); MicroServiceErrorHandler ErrorHandler(*this);
Poco::ErrorHandler::set(&ErrorHandler); Poco::ErrorHandler::set(&ErrorHandler);
Args_ = args;
if (!HelpRequested_) { if (!HelpRequested_) {
SavePID(); SavePID();
@@ -786,18 +733,11 @@ namespace OpenWifi {
poco_information(logger, "Starting as a daemon."); poco_information(logger, "Starting as a daemon.");
} }
#ifdef USE_MEDUSA_CLIENT
MedusaClient::instance()->SetSubSystems(SubSystems_);
MedusaClient::instance()->Start();
waitForTerminationRequest();
MedusaClient::instance()->Stop();
#else
poco_information(logger, fmt::format("System ID set to {}", ID_)); poco_information(logger, fmt::format("System ID set to {}", ID_));
StartSubSystemServers(); StartSubSystemServers();
waitForTerminationRequest(); waitForTerminationRequest();
StopSubSystemServers(); StopSubSystemServers();
logger.notice(fmt::format("Stopped {}...", DAEMON_APP_NAME)); logger.notice(fmt::format("Stopped {}...", DAEMON_APP_NAME));
#endif
} }
return Application::EXIT_OK; return Application::EXIT_OK;

View File

@@ -55,6 +55,9 @@ namespace OpenWifi {
#include "nlohmann/json.hpp" #include "nlohmann/json.hpp"
#include "ow_version.h" #include "ow_version.h"
#define _OWDEBUG_ std::cout << __FILE__ << ":" << __LINE__ << std::endl;
// #define _OWDEBUG_ Logger().debug(Poco::format("%s: %lu",__FILE__,__LINE__));
namespace OpenWifi { namespace OpenWifi {
class MicroService : public Poco::Util::ServerApplication { class MicroService : public Poco::Util::ServerApplication {
@@ -67,6 +70,7 @@ namespace OpenWifi {
SubSystems_(std::move(Subsystems)), Logger_(Poco::Logger::get("FRAMEWORK")) { SubSystems_(std::move(Subsystems)), Logger_(Poco::Logger::get("FRAMEWORK")) {
instance_ = this; instance_ = this;
RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count()); 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";
@@ -88,7 +92,7 @@ namespace OpenWifi {
inline uint64_t DaemonBusTimer() const { return DAEMON_BUS_TIMER; }; 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(); }; static inline uint64_t GetPID() { return Poco::Process::id(); };
[[nodiscard]] inline std::string GetPublicAPIEndPoint() const { [[nodiscard]] inline const std::string GetPublicAPIEndPoint() {
return MyPublicEndPoint_ + "/api/v1"; return MyPublicEndPoint_ + "/api/v1";
}; };
[[nodiscard]] inline const std::string &GetUIURI() const { return UIURI_; }; [[nodiscard]] inline const std::string &GetUIURI() const { return UIURI_; };
@@ -103,8 +107,7 @@ namespace OpenWifi {
} }
static MicroService &instance() { return *instance_; } static MicroService &instance() { return *instance_; }
inline void Exit(int Reason) { std::exit(Reason); } inline void Exit(int Reason);
void BusMessageReceived(const std::string &Key, const std::string &Payload); void BusMessageReceived(const std::string &Key, const std::string &Payload);
Types::MicroServiceMetaVec GetServices(const std::string &Type); Types::MicroServiceMetaVec GetServices(const std::string &Type);
Types::MicroServiceMetaVec GetServices(); Types::MicroServiceMetaVec GetServices();
@@ -112,7 +115,6 @@ namespace OpenWifi {
void Reload(); void Reload();
void LoadMyConfig(); void LoadMyConfig();
void initialize(Poco::Util::Application &self) override; void initialize(Poco::Util::Application &self) override;
void StartEverything(Poco::Util::Application &self);
void uninitialize() override; void uninitialize() override;
void reinitialize(Poco::Util::Application &self) override; void reinitialize(Poco::Util::Application &self) override;
void defineOptions(Poco::Util::OptionSet &options) override; void defineOptions(Poco::Util::OptionSet &options) override;
@@ -130,7 +132,7 @@ namespace OpenWifi {
void Reload(const std::string &Sub); void Reload(const std::string &Sub);
Types::StringVec GetSubSystems() const; Types::StringVec GetSubSystems() const;
Types::StringPairVec GetLogLevels(); Types::StringPairVec GetLogLevels();
static const Types::StringVec &GetLogLevelNames(); const Types::StringVec &GetLogLevelNames();
uint64_t ConfigGetInt(const std::string &Key, uint64_t Default); uint64_t ConfigGetInt(const std::string &Key, uint64_t Default);
uint64_t ConfigGetInt(const std::string &Key); 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);
@@ -164,16 +166,12 @@ namespace OpenWifi {
const std::string &FormatterPattern, const std::string &FormatterPattern,
const std::string &root_env_var); const std::string &root_env_var);
inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; } inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; }
const ArgVec &Args() const { return Args_; }
inline void SetConfigContent(const std::string &Content) { ConfigContent_ = Content; }
private: private:
static MicroService *instance_; static MicroService *instance_;
bool HelpRequested_ = false; bool HelpRequested_ = false;
std::string LogDir_; std::string LogDir_;
std::string ConfigFileName_; std::string ConfigFileName_;
std::string ConfigContent_;
uint64_t ID_ = 1; uint64_t ID_ = 1;
Poco::SharedPtr<Poco::Crypto::RSAKey> AppKey_; Poco::SharedPtr<Poco::Crypto::RSAKey> AppKey_;
bool DebugMode_ = false; bool DebugMode_ = false;
@@ -203,7 +201,7 @@ namespace OpenWifi {
Poco::JWT::Signer Signer_; Poco::JWT::Signer Signer_;
Poco::Logger &Logger_; Poco::Logger &Logger_;
Poco::ThreadPool TimerPool_{"timer:pool", 2, 32}; Poco::ThreadPool TimerPool_{"timer:pool", 2, 32};
ArgVec Args_; std::unique_ptr<EventBusManager> EventBusManager_;
}; };
inline MicroService *MicroService::instance_ = nullptr; inline MicroService *MicroService::instance_ = nullptr;

View File

@@ -47,8 +47,6 @@ namespace OpenWifi {
} }
Poco::Data::SessionPool &Pool() { return *Pool_; }
private: private:
inline int Setup_SQLite(); inline int Setup_SQLite();
inline int Setup_MySQL(); inline int Setup_MySQL();

View File

@@ -58,9 +58,11 @@ namespace OpenWifi {
void UI_WebSocketClientServer::run() { void UI_WebSocketClientServer::run() {
Running_ = true; Running_ = true;
while (Running_) { while (Running_) {
if(!Poco::Thread::trySleep(2000)) { Poco::Thread::trySleep(2000);
break;
} if (!Running_)
break;
std::lock_guard G(LocalMutex_); std::lock_guard G(LocalMutex_);
for (const auto i : ToBeRemoved_) { for (const auto i : ToBeRemoved_) {
// std::cout << "Erasing old WS UI connection..." << std::endl; // std::cout << "Erasing old WS UI connection..." << std::endl;

View File

@@ -576,8 +576,8 @@ namespace ORM {
bool UpdateRecord(field_name_t FieldName, const T &Value, const RecordType &R) { bool UpdateRecord(field_name_t FieldName, const T &Value, const RecordType &R) {
try { try {
assert(ValidFieldName(FieldName)); assert(ValidFieldName(FieldName));
Poco::Data::Session Session = Pool_.get(); Poco::Data::Session Session = Pool_.get();
Session.begin();
Poco::Data::Statement Update(Session); Poco::Data::Statement Update(Session);
RecordTuple RT; RecordTuple RT;
@@ -593,7 +593,6 @@ namespace ORM {
Update.execute(); Update.execute();
if (Cache_) if (Cache_)
Cache_->UpdateCache(R); Cache_->UpdateCache(R);
Session.commit();
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
Logger_.log(E); Logger_.log(E);
@@ -663,7 +662,6 @@ namespace ORM {
assert(ValidFieldName(FieldName)); assert(ValidFieldName(FieldName));
Poco::Data::Session Session = Pool_.get(); Poco::Data::Session Session = Pool_.get();
Session.begin();
Poco::Data::Statement Delete(Session); Poco::Data::Statement Delete(Session);
std::string St = "delete from " + TableName_ + " where " + FieldName + "=?"; std::string St = "delete from " + TableName_ + " where " + FieldName + "=?";
@@ -673,7 +671,6 @@ namespace ORM {
Delete.execute(); Delete.execute();
if (Cache_) if (Cache_)
Cache_->Delete(FieldName, Value); Cache_->Delete(FieldName, Value);
Session.commit();
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
Logger_.log(E); Logger_.log(E);
@@ -685,13 +682,11 @@ namespace ORM {
try { try {
assert(!WhereClause.empty()); assert(!WhereClause.empty());
Poco::Data::Session Session = Pool_.get(); Poco::Data::Session Session = Pool_.get();
Session.begin();
Poco::Data::Statement Delete(Session); Poco::Data::Statement Delete(Session);
std::string St = "delete from " + TableName_ + " where " + WhereClause; std::string St = "delete from " + TableName_ + " where " + WhereClause;
Delete << St; Delete << St;
Delete.execute(); Delete.execute();
Session.commit();
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
Logger_.log(E); Logger_.log(E);

View File

@@ -565,7 +565,6 @@ namespace OpenWifi::RESTAPI::Protocol {
static const char *TRANSFER = "transfer"; static const char *TRANSFER = "transfer";
static const char *CERTUPDATE = "certupdate"; static const char *CERTUPDATE = "certupdate";
static const char *POWERCYCLE = "powercycle";
static const char *RRM = "rrm"; static const char *RRM = "rrm";
static const char *REQUIREMENTS = "requirements"; static const char *REQUIREMENTS = "requirements";
@@ -688,7 +687,6 @@ namespace OpenWifi::uCentralProtocol {
static const char *TRANSFER = "transfer"; static const char *TRANSFER = "transfer";
static const char *CERTUPDATE = "certupdate"; static const char *CERTUPDATE = "certupdate";
static const char *POWERCYCLE = "powercycle";
static const char *RRM = "rrm"; static const char *RRM = "rrm";
static const char *ACTIONS = "actions"; static const char *ACTIONS = "actions";
@@ -787,7 +785,6 @@ namespace OpenWifi::APCommands {
rrm, rrm,
certupdate, certupdate,
transfer, transfer,
powercycle,
unknown unknown
}; };
@@ -802,7 +799,7 @@ namespace OpenWifi::APCommands {
RESTAPI::Protocol::EVENTQUEUE, RESTAPI::Protocol::TELEMETRY, RESTAPI::Protocol::EVENTQUEUE, RESTAPI::Protocol::TELEMETRY,
RESTAPI::Protocol::PING, RESTAPI::Protocol::SCRIPT, RESTAPI::Protocol::PING, RESTAPI::Protocol::SCRIPT,
RESTAPI::Protocol::RRM, RESTAPI::Protocol::CERTUPDATE, RESTAPI::Protocol::RRM, RESTAPI::Protocol::CERTUPDATE,
RESTAPI::Protocol::TRANSFER, RESTAPI::Protocol::POWERCYCLE RESTAPI::Protocol::TRANSFER
}; };
inline const char *to_string(Commands Cmd) { return uCentralAPCommands[(uint8_t)Cmd]; } inline const char *to_string(Commands Cmd) { return uCentralAPCommands[(uint8_t)Cmd]; }

View File

@@ -316,90 +316,5 @@ namespace OpenWifi::Utils {
uint32_t Port; uint32_t Port;
}; };
class CompressedString {
public:
CompressedString() {
DecompressedSize_ = 0;
};
explicit CompressedString(const std::string &Data) : DecompressedSize_(Data.size()) {
CompressIt(Data);
}
CompressedString(const CompressedString &Data) {
this->DecompressedSize_ = Data.DecompressedSize_;
this->CompressedData_ = Data.CompressedData_;
}
CompressedString& operator=(const CompressedString& rhs) {
if (this != &rhs) {
this->DecompressedSize_ = rhs.DecompressedSize_;
this->CompressedData_ = rhs.CompressedData_;
}
return *this;
}
CompressedString& operator=(CompressedString&& rhs) {
if (this != &rhs) {
this->DecompressedSize_ = rhs.DecompressedSize_;
this->CompressedData_ = rhs.CompressedData_;
}
return *this;
}
~CompressedString() = default;
operator std::string() const {
return DecompressIt();
}
CompressedString &operator=(const std::string &Data) {
DecompressedSize_ = Data.size();
CompressIt(Data);
return *this;
}
auto CompressedSize() const { return CompressedData_.size(); }
auto DecompressedSize() const { return DecompressedSize_; }
private:
std::string CompressedData_;
std::size_t DecompressedSize_;
inline void CompressIt(const std::string &Data) {
z_stream strm; // = {0};
CompressedData_.resize(Data.size());
strm.next_in = (Bytef *)Data.data();
strm.avail_in = Data.size();
strm.next_out = (Bytef *)CompressedData_.data();
strm.avail_out = Data.size();
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);
deflate(&strm, Z_FINISH);
deflateEnd(&strm);
CompressedData_.resize(strm.total_out);
}
[[nodiscard]] std::string DecompressIt() const {
std::string Result;
if(DecompressedSize_!=0) {
Result.resize(DecompressedSize_);
z_stream strm ; //= {0};
strm.next_in = (Bytef *)CompressedData_.data();
strm.avail_in = CompressedData_.size();
strm.next_out = (Bytef *)Result.data();
strm.avail_out = Result.size();
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
inflateInit2(&strm, 15 + 32);
inflate(&strm, Z_FINISH);
inflateEnd(&strm);
}
return Result;
}
};
} // namespace OpenWifi::Utils } // namespace OpenWifi::Utils