ADD: added a general kubenetes API and integrated that in the classes and remodeled the info management

This commit is contained in:
hwinkel
2023-12-22 13:14:40 +01:00
parent 351cf9ec69
commit 4045f21786
13 changed files with 363 additions and 833 deletions

View File

@@ -62,8 +62,8 @@ ENDIF()
include/kubecontrol/Utils.hpp include/kubecontrol/Utils.hpp
src/kubecontrol/Utils.cpp src/kubecontrol/Utils.cpp
include/kubecontrol/PodInfo.hpp # include/kubecontrol/PodInfo.hpp
src/kubecontrol/PodInfo.cpp # src/kubecontrol/PodInfo.cpp
include/kubecontrol/KubernetesAPI.hpp include/kubecontrol/KubernetesAPI.hpp
@@ -118,8 +118,5 @@ IF (${TEST_KUBECONTROL_LIBRARY})
target_link_libraries(test_massivPodHandling Catch2::Catch2 kubecontrol ) target_link_libraries(test_massivPodHandling Catch2::Catch2 kubecontrol )
catch_discover_tests(test_massivPodHandling) catch_discover_tests(test_massivPodHandling)
add_executable(test_podInfo tests/test_podInfo.cpp)
target_link_libraries(test_podInfo Catch2::Catch2 kubecontrol )
catch_discover_tests(test_podInfo)
ENDIF() ENDIF()

View File

@@ -1,7 +1,6 @@
#pragma once #pragma once
#include "kubecontrol/KubernetesAPI.hpp" #include "kubecontrol/KubernetesAPI.hpp"
#include "kubecontrol/PodInfo.hpp"
#include "nlohmann/json_fwd.hpp" #include "nlohmann/json_fwd.hpp"
#include "yaml-cpp/node/node.h" #include "yaml-cpp/node/node.h"
#include <map> #include <map>
@@ -26,11 +25,13 @@ namespace kubecontrol
class KubePod class KubePod
{ {
public: public:
KubePod(std::string Owner, std::string Uuid, std::string ContainerImage,std::string Namespace = "simulator"); KubePod(std::string Owner, std::string Uuid, std::string ContainerImage,std::string Namespace = "simulator") ;
KubePod(std::string Owner, std::string Uuid, std::string Component, std::string ContainerImage,std::string Namespace = "simulator"); KubePod(std::string Owner, std::string Uuid, std::string Component, std::string ContainerImage,std::string Namespace = "simulator");
std::string getUUID(); std::string getUUID();
std::string getOwner(); std::string getOwner();
std::string getIp();
std::string getStatus();
void setEnvironmentVar(std::string key, std::string val); void setEnvironmentVar(std::string key, std::string val);
std::map<std::string, std::string> GetEnvironmentVars(); std::map<std::string, std::string> GetEnvironmentVars();
@@ -46,35 +47,18 @@ namespace kubecontrol
std::string getComponent(); std::string getComponent();
int start(KubernetesAPI APIInterface,bool WaitTillRunning = true);
int stop(KubernetesAPI APIInterface);
int stopChilds(KubernetesAPI APIInterface);
// [[deprecated("replace with start(KubernetesAPI APIInterface)")]] int updateInfoForThisPod(KubernetesAPI APIInterface);
// std::string start(std::string apiAddress,std::string token,bool WaitTillRunning = true);
std::string start(KubernetesAPI APIInterface,bool WaitTillRunning = true);
[[deprecated("replace with stop(KubernetesAPI APIInterface)")]]
std::string stop(std::string apiAddress,std::string token);
std::string stop(KubernetesAPI APIInterface);
// [[deprecated("replace with getInfo(KubernetesAPI APIInterface)")]]
// std::string getInfo(std::string apiAddress,std::string token);
std::string getInfoForThisPod(KubernetesAPI APIInterface);
std::string getInfoForRelatedPods(KubernetesAPI APIInterface);
std::vector<std::string> getUUIDForRelatedPods(KubernetesAPI APIInterface);
PodInfo InfoPod;
std::vector<std::string> getUUIDsForChildPods(KubernetesAPI APIInterface);
private: private:
static const int MaxWaitTimeInSeconds;
std::string Owner_; std::string Owner_;
std::string Uuid_; std::string Uuid_;
@@ -98,10 +82,14 @@ namespace kubecontrol
std::string createYAML(); std::string createYAML();
// std::string read; /**
* @brief extracts the asked inforamtion from the kubernetes response
*
*
*/
int extractInformationFromResopnse(std::string response);
std::string StopChilds(std::string apiAddress,std::string token,std::string uuid);
}; };
} }

View File

@@ -19,8 +19,11 @@ class KubernetesAPI
std::string performRequest(std::string request,std::string Methode,std::string PostFields); std::string performRequest(std::string request,std::string Methode,std::string PostFields);
void addAddress(std::string address); void addAddress(std::string address);
std::string getAddress();
void addToken(std::string Token); void addToken(std::string Token);
void addYaml(YAML::Node config); void addYaml(YAML::Node config);
std::string getNamespace();
private: private:
std::string APIAddress_; std::string APIAddress_;
std::string Token_; std::string Token_;

View File

@@ -1,6 +1,5 @@
#pragma once #pragma once
#include "kubecontrol/KubernetesAPI.hpp" #include "kubecontrol/KubernetesAPI.hpp"
#include "kubecontrol/PodInfo.hpp"
#include <cstddef> #include <cstddef>
#include <kubecontrol/KubePod.hpp> #include <kubecontrol/KubePod.hpp>
#include <memory> #include <memory>
@@ -10,6 +9,16 @@
namespace kubecontrol namespace kubecontrol
{ {
struct PodInfos
{
std::string UUID;
std::string IP;
std::string Status;
std::string Component;
std::string Owner;
std::vector<std::string> UUIDOfChilds;
};
class PodController class PodController
{ {
public: public:
@@ -21,33 +30,21 @@ namespace kubecontrol
void stopPod(std::string uuid); void stopPod(std::string uuid);
void stopAllPods(); void stopAllPods();
std::string getInfoForAllPods(); std::vector<PodInfos> getInfoForAllPods();
// std::string getInfoForOwnPod(); PodInfos getInfoForPod(std::string uuid);
std::string getInfoForPod(std::string uuid);
size_t getListOfChildPods();
void checkPodsHierarchy(); KubernetesAPI getKubernetesAPI();
std::string getPodsInfoForAll();
std::shared_ptr<PodInfo> getPodsInfo(std::string uuid);
private: private:
KubernetesAPI APIInterface_; KubernetesAPI APIInterface_;
std::vector<KubePod> PodList_; std::vector<std::unique_ptr<KubePod>> PodList_;
std::string performRequest(std::string url);
void performForceStopRequest(std::string uuid);
std::string BearerToken_;
std::string ServerAddress_;
std::string Namespace_; std::string Namespace_;
std::string ApiCall_; std::string ApiCall_;
// void addPodInfoToInfoList(std::shared_ptr<PodInfo> podinfo); PodInfos extractInfosFromKubePod(KubePod *pod);
std::shared_ptr<PodInfo> getPodInfo(std::string uuid);
std::vector<std::shared_ptr<PodInfo>> podsInfoList_;
mutable std::mutex mx_; mutable std::mutex mx_;
}; };

View File

@@ -1,66 +0,0 @@
#pragma once
#include "nlohmann/json_fwd.hpp"
#include <memory>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
#include <string>
#include <loguru.hpp>
namespace kubecontrol {
class PodInfo
{
public:
PodInfo();
PodInfo(std::string response);
void update(std::string response);
std::string ToString();
nlohmann::json ToJson();
std::vector<std::string> getRelatedPods();
std::string Uuid;
std::string Image;
std::string Ip;
std::string Component;
std::string Status;
std::string PartOf;
void addRelatedPods(std::string uuid);
size_t relatedPodsSize();
private:
std::vector<std::string> relatedPods;
};
// struct PodInfo
// {
// std::string Uuid;
// std::string Image;
// std::string Ip;
// std::string Component;
// std::string Status;
// std::string PartOf;
// std::vector<std::pair<std::string,std::shared_ptr<KubePod>>> relatedPods;
// bool operator==(PodInfo const &rhs )
// {
// if (Uuid == rhs.Uuid) {
// return true;
// }
// return false;
// }
// };
}

View File

@@ -1,5 +1,4 @@
#include "curlpp/Options.hpp" #include "curlpp/Options.hpp"
#include "kubecontrol/PodInfo.hpp"
#include "kubecontrol/Utils.hpp" #include "kubecontrol/Utils.hpp"
#include "nlohmann/json_fwd.hpp" #include "nlohmann/json_fwd.hpp"
#include "yaml-cpp/binary.h" #include "yaml-cpp/binary.h"
@@ -10,23 +9,20 @@
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <thread> #include <thread>
#include <filesystem>
#include "loguru.hpp"
namespace kubecontrol namespace kubecontrol
{ {
int getFileSize(std::string filename) { // path to file
FILE *p_file = NULL;
p_file = fopen(filename.c_str(),"rb");
fseek(p_file,0,SEEK_END);
int size = ftell(p_file);
fclose(p_file);
return size;
}
KubePod::KubePod(std::string Owner, std::string Uuid, std::string ContainerImage,std::string Namespace)
:Owner_(Utils::to_lower(Owner)),
KubePod::KubePod(std::string Owner, std::string Uuid, std::string ContainerImage,std::string Namespace):Owner_(Utils::to_lower(Owner)),Uuid_(Utils::to_lower(Uuid)), Uuid_(Utils::to_lower(Uuid)),
ContainerImage_(ContainerImage),Namespace_(Namespace),EnvirmonentVars_() ContainerImage_(ContainerImage),
Namespace_(Namespace),
EnvirmonentVars_()
{ {
ContainerRegistry_ = "kmaster.ti.unibw-hamburg.de:30808"; ContainerRegistry_ = "kmaster.ti.unibw-hamburg.de:30808";
EnvirmonentVars_ = std::map<std::string, std::string>(); EnvirmonentVars_ = std::map<std::string, std::string>();
@@ -45,8 +41,13 @@ namespace kubecontrol
} }
KubePod::KubePod(std::string Owner, std::string Uuid, std::string Component, std::string ContainerImage,std::string Namespace):Owner_(Utils::to_lower(Owner)), KubePod::KubePod(std::string Owner, std::string Uuid, std::string Component, std::string ContainerImage,std::string Namespace):
Uuid_(Utils::to_lower(Uuid)),Component_(Utils::to_lower(Component)), ContainerImage_(ContainerImage),Namespace_(Namespace),EnvirmonentVars_() Owner_(Utils::to_lower(Owner)),
Uuid_(Utils::to_lower(Uuid)),
Component_(Utils::to_lower(Component)),
ContainerImage_(ContainerImage),
Namespace_(Namespace),
EnvirmonentVars_()
{ {
ContainerRegistry_ = "kmaster.ti.unibw-hamburg.de:30808"; ContainerRegistry_ = "kmaster.ti.unibw-hamburg.de:30808";
EnvirmonentVars_ = std::map<std::string, std::string>(); EnvirmonentVars_ = std::map<std::string, std::string>();
@@ -77,6 +78,15 @@ namespace kubecontrol
return this->Owner_; return this->Owner_;
} }
std::string KubePod::getIp()
{
return this->Ip_;
}
std::string KubePod::getStatus()
{
return this->Status_;
}
void KubePod::setEnvironmentVar(std::string key, std::string val) void KubePod::setEnvironmentVar(std::string key, std::string val)
{ {
EnvirmonentVars_.emplace(key,val); EnvirmonentVars_.emplace(key,val);
@@ -190,210 +200,136 @@ namespace kubecontrol
std::string KubePod::start(KubernetesAPI APIInterface,bool WaitTillRunning) int KubePod::start(KubernetesAPI APIInterface,bool WaitTillRunning)
{ {
std::string request = "/api/v1/namespaces/simulator/pods/"; std::string request = "/api/v1/namespaces/simulator/pods/";
this->createYAML(); this->createYAML();
// LOG_S(INFO)<< this->PathToYaml_;
std::stringstream stream; std::stringstream stream;
stream << YAMLNode_; stream << YAMLNode_;
std::string response = APIInterface.performRequest(request,"POST",stream.str()); std::string response = APIInterface.performRequest(request,"POST",stream.str());
extractInformationFromResopnse(response);
InfoPod.update(response); auto timeoutTime = std::chrono::system_clock::now() + std::chrono::seconds(10);
if (WaitTillRunning == true) {
while (InfoPod.Status != "Running" && InfoPod.Status != "Succeeded") {
if (WaitTillRunning == true ) {
while ((this->Status_ != "Running" && this->Status_ != "Succeeded") || std::chrono::system_clock::now() >= timeoutTime) {
// LOG_S(INFO)<<"wainting till running " << this->Status_;
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
response = this->getInfoForThisPod(APIInterface); this->updateInfoForThisPod(APIInterface);
InfoPod.update(response);
} }
} }
return response; return 0;
} }
std::string KubePod::stop(std::string apiAddress,std::string token) int KubePod::stop(KubernetesAPI APIInterface)
{
std::string curlURL = apiAddress+ this->Uuid_;
LOG_S(INFO)<<curlURL;
std::string AuthString = "Authorization: Bearer " + token;
std::list<std::string> headers;
headers.push_back(AuthString);
curlpp::Cleanup cleaner;
curlpp::Easy request;
std::stringstream result;
request.setOpt(cURLpp::Options::WriteStream(&result));
request.setOpt(new curlpp::options::HttpHeader(headers));
request.setOpt(new curlpp::options::Url(curlURL));
request.setOpt(new curlpp::options::SslVerifyPeer(false));
request.setOpt(new curlpp::options::CustomRequest("DELETE"));
// request.setOpt(new curlpp::options::Verbose(true));
request.perform();
auto response = result.str();
// std::this_thread::sleep_for(std::chrono::milliseconds(5000));
// InfoPod.update(this->getInfo(apiAddress, token));
LOG_S(INFO)<<"Related pods: " <<InfoPod.getRelatedPods().size();
if (InfoPod.getRelatedPods().size() > 0)
{
for(int i = 0; i<InfoPod.getRelatedPods().size(); i++)
{
StopChilds(apiAddress, token, InfoPod.getRelatedPods()[i]);
}
}
return response;
}
std::string KubePod::stop(KubernetesAPI APIInterface)
{ {
std::string request = "/api/v1/namespaces/simulator/pods/"+Uuid_; std::string request = "/api/v1/namespaces/simulator/pods/"+Uuid_;
std::string result = APIInterface.performRequest(request,"DELETE"); std::string result = APIInterface.performRequest(request,"DELETE");
LOG_S(INFO)<<"stopping: " <<Uuid_;
this->getInfoForRelatedPods(APIInterface); return 0;
return result;
} }
std::string KubePod::StopChilds(std::string apiAddress,std::string token,std::string uuid) int KubePod::stopChilds(KubernetesAPI APIInterface)
{ {
std::string curlURL = apiAddress+ uuid; auto uuids = this->getUUIDsForChildPods(APIInterface);
std::string AuthString = "Authorization: Bearer " + token; if (uuids.size() == 0)
{
return 1;
}
for(auto i: uuids)
{
std::string request = "/api/v1/namespaces/simulator/pods/"+i;
std::string result = APIInterface.performRequest(request,"DELETE");
std::list<std::string> headers; }
headers.push_back(AuthString);
return 0;
curlpp::Cleanup cleaner;
curlpp::Easy request;
std::stringstream result;
request.setOpt(cURLpp::Options::WriteStream(&result));
request.setOpt(new curlpp::options::HttpHeader(headers));
request.setOpt(new curlpp::options::Url(curlURL));
request.setOpt(new curlpp::options::SslVerifyPeer(false));
request.setOpt(new curlpp::options::CustomRequest("DELETE"));
// request.setOpt(new curlpp::options::Verbose(true));
request.perform();
auto response = result.str();
return response;
} }
int KubePod::updateInfoForThisPod(KubernetesAPI APIInterface)
// std::string KubePod::getInfo(std::string apiAddress,std::string token)
// {
// std::string curlURL = apiAddress+Uuid_+"/"+"status";
// std::string AuthString = "Authorization: Bearer " + token;
// std::list<std::string> headers;
// headers.push_back(AuthString);
// curlpp::Cleanup cleaner;
// curlpp::Easy request;
// std::stringstream result;
// request.setOpt(cURLpp::Options::WriteStream(&result));
// request.setOpt(new curlpp::options::HttpHeader(headers));
// request.setOpt(new curlpp::options::Url(curlURL));
// request.setOpt(new curlpp::options::SslVerifyPeer(false));
// request.perform();
// return result.str();
// }
std::string KubePod::getInfoForThisPod(KubernetesAPI APIInterface)
{ {
std::string request = "/api/v1/namespaces/simulator/pods/"+Uuid_+"/status"; std::string request = "/api/v1/namespaces/simulator/pods/"+Uuid_+"/status";
std::string result = APIInterface.performRequest(request,"GET"); std::string result = APIInterface.performRequest(request,"GET");
if (result == "")
{
return 1;
}
return result; if (extractInformationFromResopnse(result)!= 0)
{
return 1;
}
return 0;
} }
std::string KubePod::getInfoForRelatedPods( KubernetesAPI APIInterface) std::vector<std::string> KubePod::getUUIDsForChildPods( KubernetesAPI APIInterface)
{ {
// std::string curlURL = apiAddress+"?labelSelector=app.kubernetes.io/part-of="+Uuid_;
std::string request = "/api/v1/namespaces/simulator/pods?labelSelector=app.kubernetes.io/part-of="+Uuid_; std::string request = "/api/v1/namespaces/simulator/pods?labelSelector=app.kubernetes.io/part-of="+Uuid_;
std::string result = APIInterface.performRequest(request,"GET"); std::string result = APIInterface.performRequest(request,"GET");
return result; if (result == "")
{
return std::vector<std::string>();
}
extractInformationFromResopnse(result);
return this->uuidsOfShildContainers;
} }
std::vector<std::string> KubePod::getUUIDForRelatedPods(KubernetesAPI APIInterface)
int KubePod::extractInformationFromResopnse(std::string response)
{ {
std::vector<std::string> uuids; if (response == "")
auto rawResponse = getInfoForRelatedPods(APIInterface);
if (rawResponse == "")
{ {
return uuids; return 1 ;
} }
// LOG_S(INFO)<< response;
try { nlohmann::json j;
nlohmann::json j = nlohmann::json::parse(rawResponse); try {
if (j.contains("items") && j["items"].is_array()) j = nlohmann::json::parse(response);
if(j.contains("kind") && j["kind"] == "Pod")
{ {
for (auto i : j["items"]) if( j["status"].contains("podIP")) this->Ip_ = j["status"]["podIP"].get<std::string>();
{ this->Status_ = j["status"]["phase"].get<std::string>();
uuids.push_back(i["metadata"]["name"].get<std::string>()); this->PartOf_ = j["metadata"]["labels"]["app.kubernetes.io/part-of"];
}
}else if(j.contains("items") && j["items"].is_array())
{
for (auto i : j["items"])
{
this->uuidsOfShildContainers.push_back(i["metadata"]["name"].get<std::string>());
}
}else{
return 1;
} }
} catch (const std::exception e) { } catch (const std::exception e) {
LOG_S(ERROR)<< "Exeption in getUUIDForRelatedPods() :" << e.what(); LOG_S(ERROR)<< "Exeption in extractInformationFromResopnse() :" << e.what();
std::exception_ptr p = std::current_exception();
LOG_S(ERROR)<< "Exeption :" << p.__cxa_exception_type()->name();
LOG_S(INFO)<<j;
return 1;
} }
return 0;
// LOG_S(INFO)<<rawResponse;
return uuids;
} }
@@ -405,5 +341,6 @@ namespace kubecontrol
} }

View File

@@ -36,10 +36,23 @@ namespace kubecontrol {
{ {
APIAddress_ = address; APIAddress_ = address;
} }
std::string KubernetesAPI::getAddress()
{
return APIAddress_;
}
void KubernetesAPI::addToken(std::string token) void KubernetesAPI::addToken(std::string token)
{ {
Token_ = token; Token_ = token;
} }
std::string KubernetesAPI::getNamespace()
{
return Namespace_;
}
void KubernetesAPI::addYaml(YAML::Node config) void KubernetesAPI::addYaml(YAML::Node config)
{ {
try { try {

View File

@@ -2,7 +2,6 @@
#include "curlpp/Options.hpp" #include "curlpp/Options.hpp"
#include "kubecontrol/KubePod.hpp" #include "kubecontrol/KubePod.hpp"
#include "kubecontrol/KubernetesAPI.hpp" #include "kubecontrol/KubernetesAPI.hpp"
#include "kubecontrol/PodInfo.hpp"
#include "nlohmann/json_fwd.hpp" #include "nlohmann/json_fwd.hpp"
#include <cstddef> #include <cstddef>
#include <cstdlib> #include <cstdlib>
@@ -13,6 +12,7 @@
#include <mutex> #include <mutex>
#include <string> #include <string>
#include <vector> #include <vector>
#include "loguru.hpp"
namespace kubecontrol namespace kubecontrol
@@ -20,40 +20,22 @@ namespace kubecontrol
PodController::PodController(std::string pathToKubectlConfig): PodController::PodController(std::string pathToKubectlConfig):
APIInterface_( YAML::LoadFile(pathToKubectlConfig)) APIInterface_( YAML::LoadFile(pathToKubectlConfig))
{ {
LOG_S(INFO)<< "Path To Yaml: " <<pathToKubectlConfig;
try { ApiCall_ = "/api/v1/namespaces/"+APIInterface_.getNamespace()+"/pods/";
YAML::Node config = YAML::LoadFile(pathToKubectlConfig);
BearerToken_ = config["users"][0]["user"]["token"].as<std::string>();
Namespace_ = config["contexts"][0]["context"]["namespace"].as<std::string>();
char * KUBERNETES_SERVICE_HOST = std::getenv("KUBERNETES_SERVICE_HOST");
char * KUBERNETES_SERVICE_PORT = std::getenv("KUBERNETES_SERVICE_PORT");
if (KUBERNETES_SERVICE_HOST != nullptr && KUBERNETES_SERVICE_PORT!= nullptr)
{
ServerAddress_ = "https://" +std::string(KUBERNETES_SERVICE_HOST)+":"+std::string(KUBERNETES_SERVICE_PORT);
} else
{
LOG_S(INFO)<<"Taking Serveraddress out of the provided YAML file";
ServerAddress_ = config["clusters"][0]["cluster"]["server"].as<std::string>();
}
ApiCall_ = "/api/v1/namespaces/"+Namespace_+"/pods/";
} catch (std::exception& e) {
LOG_S(ERROR)<< e.what();
throw e.what();
}
} }
std::string PodController::getServerAddress() std::string PodController::getServerAddress()
{ {
return this->ServerAddress_; return APIInterface_.getAddress();
} }
KubernetesAPI PodController::getKubernetesAPI()
{
return APIInterface_;
}
void PodController::startPod(KubePod Pod,bool WaitTillRunning ) void PodController::startPod(KubePod Pod,bool WaitTillRunning )
@@ -64,21 +46,22 @@ namespace kubecontrol
auto response = Pod.start(APIInterface_,WaitTillRunning); auto response = Pod.start(APIInterface_,WaitTillRunning);
std::lock_guard<std::mutex>lock(mx_); std::lock_guard<std::mutex>lock(mx_);
PodList_.emplace_back(Pod); PodList_.emplace_back(std::make_unique<KubePod>(Pod));
// LOG_S(INFO)<<response; // LOG_S(INFO)<<response;
} }
void PodController::stopPod(std::string Label) void PodController::stopPod(std::string uuid)
{ {
std::lock_guard<std::mutex>lock(mx_); std::lock_guard<std::mutex>lock(mx_);
// PodList_ // PodList_
for (std::vector<KubePod>::iterator it = PodList_.begin(); it != PodList_.end();) for (std::vector<std::unique_ptr<KubePod>>::iterator it = PodList_.begin(); it != PodList_.end();)
{ {
if (Label == it->getUUID())
{ if (uuid == it->get()->getUUID())
it->stop(APIInterface_); {
it = PodList_.erase(it); it->get()->stop(APIInterface_);
} it = PodList_.erase(it);
}
else else
{ {
it++; it++;
@@ -91,263 +74,108 @@ namespace kubecontrol
{ {
std::lock_guard<std::mutex>lock(mx_); std::lock_guard<std::mutex>lock(mx_);
checkPodsHierarchy(); for (auto &item : PodList_)
for (auto item : PodList_)
{ {
LOG_S(INFO)<<item.InfoPod.Uuid; item->stop(APIInterface_);
item.InfoPod = *getPodInfo(item.getUUID()).get();
item.stop(APIInterface_); LOG_S(INFO)<< "stopping pod: "<<item->getUUID();
LOG_S(INFO)<< "stopping pod: "<<item.getUUID();
} }
PodList_.clear();
} }
// std::string PodController::getInfoForOwnPod()
std::vector<PodInfos> PodController::getInfoForAllPods()
{
std::vector<PodInfos> infosOfAllPods;
for (auto &item : PodList_)
{
if(item->updateInfoForThisPod(APIInterface_) == 0 )
{
infosOfAllPods.emplace_back(extractInfosFromKubePod(item.get()));
}
}
return infosOfAllPods;
}
PodInfos PodController::getInfoForPod(std::string uuid)
{
PodInfos info;
for (auto &item : PodList_)
{
if(item->getUUID() == uuid )
{
LOG_S(INFO)<<"pod found: "<< item->getUUID();
item->updateInfoForThisPod(APIInterface_);
return extractInfosFromKubePod(item.get());
}
}
return info;
}
PodInfos PodController::extractInfosFromKubePod(KubePod * pod)
{
PodInfos info;
info.UUID = pod->getUUID();
info.Owner = pod->getOwner();
info.Component =pod->getComponent();
info.IP = pod->getIp();
info.Status = pod->getStatus();
info.UUIDOfChilds = pod->getUUIDsForChildPods(APIInterface_);
return info;
}
// std::string PodController::performRequest(std::string curlURL)
// { // {
// std::string response = "";
// for (auto item : PodList_)
// {
// response = item.getInfoForThisPod(APIInterface_); // std::string AuthString = "Authorization: Bearer " + BearerToken_;
// }
// return response; // std::list<std::string> headers;
// headers.push_back(AuthString);
// auto request = std::make_unique<curlpp::Easy>();
// // request->setOpt(test);
// std::stringstream result;
// request->setOpt(cURLpp::Options::WriteStream(&result));
// request->setOpt(new curlpp::options::HttpHeader(headers));
// request->setOpt(new curlpp::options::Url(curlURL));
// // request.setOpt(new curlpp::options::SslEngineDefault());
// // request.setOpt(new curlpp::options::CaPath("config/ca.crt"));
// request->setOpt(new curlpp::options::SslVerifyPeer(false));
// // request->setOpt(new curlpp::options::Verbose(true));
// request->perform();
// // std::string response = mWriterChunk.getResponse();
// std::string response = result.str();
// return response;
// } // }
std::string PodController::getInfoForAllPods()
{
std::string curlURL = ServerAddress_+ApiCall_;
std::string response = this->performRequest(curlURL);
std::vector<std::string> podsNames;
nlohmann::json j;
try
{
j = nlohmann::json::parse(response);
if (j.contains("items"))
{
int i = j["items"].size();
for (int a = 0; a<i; a++)
{
if (!j["items"][a]["metadata"]["name"].empty())
{
podsNames.emplace_back(j["items"][a]["metadata"]["name"]);
}
}
}
j.clear();
for (auto item: podsNames)
{
std::string curlURL = ServerAddress_+ApiCall_+item+"/status";
auto response = this->performRequest(curlURL);
j["items"].emplace_back(nlohmann::json::parse(response));
}
return j.dump();
}catch(const std::exception e)
{
LOG_S(ERROR)<< e.what()<< " IN PodController::getPodsInfo() Function";
}
return j.dump();
}
std::string PodController::getInfoForPod(std::string uid)
{
bool found = false;
for (auto item : PodList_)
{
if (uid == item.getUUID())
{
found = true;
// checkPodsHierarchy();
item.InfoPod = *getPodInfo(item.getUUID()).get();
// LOG_S(INFO)<<item.InfoPod.getRelatedPods().size();
item.getInfoForRelatedPods(APIInterface_);
// return item.getInfo(ServerAddress_+ApiCall_, BearerToken_);
return item.getInfoForThisPod(APIInterface_);
}
}
if (found == false)
{
std::string curlURL = ServerAddress_+ApiCall_+uid;
auto response = this->performRequest(curlURL);
return response;
}
return nullptr;
}
void PodController::checkPodsHierarchy()
{
auto response = this->getInfoForAllPods();
nlohmann::json j;
try
{
j = nlohmann::json::parse(response);
if (j.contains("items"))
{
LOG_S(INFO)<<j["items"].size();
int i = j["items"].size();
for (int a = 0; a<i; a++)
{
auto item = std::make_unique<PodInfo>(j["items"][a].dump());
// LOG_S(INFO)<<item->ToString();
// item->Uuid = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/name"].get<std::string>();
// item->Component = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/component"].get<std::string>();
// item->Image = j["items"][a]["spec"]["containers"][0]["image"].get<std::string>();
// item->Ip = j["items"][a]["status"]["podIP"].get<std::string>();
// item->Status = j["items"][a]["status"]["phase"].get<std::string>();
// item->PartOf = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/part-of"].get<std::string>();
// // LOG_S(INFO)<<j["items"][a]["status"]["podIP"];
// LOG_S(INFO)<<j["items"][a]["status"]["phase"];
this->podsInfoList_.push_back(std::move(item));
}
i = j["items"].size();
for (int a = 0; a<i; a++)
{
auto item = std::make_shared<PodInfo>();
std::string uuid = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/name"].get<std::string>();
std::string parentName= j["items"][a]["metadata"]["labels"]["app.kubernetes.io/part-of"].get<std::string>();
auto self = this->getPodInfo(uuid);
auto parent = this->getPodInfo(parentName);
if (parent != nullptr && self != nullptr) {
parent->addRelatedPods(self->Uuid);
}else if (parent== nullptr)
{
self->PartOf = parentName;
}
}
}
} catch (std::exception& e)
{
LOG_S(ERROR)<<e.what() << " In checkPodsHierarchy() Function";
}
}
std::string PodController::getPodsInfoForAll()
{
checkPodsHierarchy();
std::string item = "";
nlohmann::json j;
for (int i = 0; i < podsInfoList_.size(); i++) {
if(podsInfoList_[i]->relatedPodsSize() != 0 )
{
item = podsInfoList_[i]->ToJson().dump() +" Childs: ";
nlohmann::json tmp = podsInfoList_[i]->ToJson();
auto vec = podsInfoList_[i]->getRelatedPods();
for(int a = 0; a < vec.size();a++)
{
tmp["Childs"].push_back(getPodInfo(vec[a])->ToJson());
item += getPodInfo(vec[a])->ToString() +" // ";
}
j.push_back(tmp);
}
}
return j.dump();
}
std::shared_ptr<PodInfo> PodController::getPodsInfo(std::string uuid)
{
for (int i = 0; i < podsInfoList_.size(); i++) {
if (podsInfoList_[i]->Uuid == uuid)
{
return podsInfoList_[i];
}
}
checkPodsHierarchy();
LOG_S(INFO)<< "check Hierarchy";
return getPodsInfo(uuid);;
}
// void PodController::addPodInfoToInfoList(std::unique_ptr<PodInfo> podinfo)
// {
// }
std::shared_ptr<PodInfo> PodController::getPodInfo(std::string uuid)
{
for (int i = 0; i < podsInfoList_.size(); i++) {
if (podsInfoList_[i]->Uuid == uuid)
{
return podsInfoList_[i];
}
}
return nullptr;
}
size_t PodController::getListOfChildPods()
{
return PodList_.size();
}
std::string PodController::performRequest(std::string curlURL)
{
std::string AuthString = "Authorization: Bearer " + BearerToken_;
std::list<std::string> headers;
headers.push_back(AuthString);
auto request = std::make_unique<curlpp::Easy>();
// request->setOpt(test);
std::stringstream result;
request->setOpt(cURLpp::Options::WriteStream(&result));
request->setOpt(new curlpp::options::HttpHeader(headers));
request->setOpt(new curlpp::options::Url(curlURL));
// request.setOpt(new curlpp::options::SslEngineDefault());
// request.setOpt(new curlpp::options::CaPath("config/ca.crt"));
request->setOpt(new curlpp::options::SslVerifyPeer(false));
// request->setOpt(new curlpp::options::Verbose(true));
request->perform();
// std::string response = mWriterChunk.getResponse();
std::string response = result.str();
return response;
}
void PodController::performForceStopRequest(std::string uuid)
{
}

View File

@@ -1,114 +0,0 @@
#include "nlohmann/json_fwd.hpp"
#include <kubecontrol/PodInfo.hpp>
namespace kubecontrol
{
PodInfo::PodInfo()
{
Uuid = "";
Component = "";
Image = "";
Ip = "";
Status = "";
PartOf = "";
}
PodInfo::PodInfo(std::string response)
{
update(response);
}
void PodInfo::update(std::string response)
{
try
{
nlohmann::json j = nlohmann::json::parse(response);
if (j.contains("items"))
{
if (j["items"].size() == 1) {
Uuid = j["items"][0]["metadata"]["labels"]["app.kubernetes.io/name"].get<std::string>();
Component = j["items"][0]["metadata"]["labels"]["app.kubernetes.io/component"].get<std::string>();
Image = j["items"][0]["spec"]["containers"][0]["image"].get<std::string>();
Ip = j["items"][0]["status"]["podIP"].get<std::string>();
Status = j["items"][0]["status"]["phase"].get<std::string>();
PartOf = j["items"][0]["metadata"]["labels"]["app.kubernetes.io/part-of"].get<std::string>();
}
}else
{
Uuid = j["metadata"]["labels"]["app.kubernetes.io/name"].get<std::string>();
Component = j["metadata"]["labels"]["app.kubernetes.io/component"].get<std::string>();
PartOf = j["metadata"]["labels"]["app.kubernetes.io/part-of"].get<std::string>();
Image = j["spec"]["containers"][0]["image"].get<std::string>();
if (j["status"].contains("podIP")) Ip = j["status"]["podIP"].get<std::string>();
Status = j["status"]["phase"].get<std::string>();
}
} catch (std::exception& e)
{
// LOG_S(WARNING)<< response;
LOG_S(ERROR)<<e.what() << " IN PodInfo Constructor";
}
}
std::vector<std::string> PodInfo::getRelatedPods()
{
return relatedPods;
}
std::string PodInfo::ToString()
{
return "UUID: "+Uuid + " Compoment: " + Component + " Image: "+ Image+ " IP: " + Ip + " Status: "+Status + " Part Of: " +PartOf;
}
nlohmann::json PodInfo::ToJson()
{
nlohmann::json j;
j["UUID"] = Uuid;
j["Compoment"] = Component;
j["Image"] = Image;
j["Ip"] = Ip;
j["Status"] = Status;
j["Part-Of"] = PartOf;
j["Related-Pods"] ;
for (auto i : this->relatedPods ) {
j["Related-Pods"].push_back(i);
}
return j;
}
void PodInfo::addRelatedPods(std::string uuid)
{
if ( std::find(relatedPods.begin(), relatedPods.end(), uuid) == relatedPods.end() )
{
relatedPods.emplace_back(uuid);
}
}
size_t PodInfo::relatedPodsSize()
{
return relatedPods.size();
}
}

View File

@@ -1,61 +1,70 @@
#include "kubecontrol/KubernetesAPI.hpp"
#define CATCH_CONFIG_MAIN
#include <string>
#include <catch2/catch.hpp>
#include <loguru.hpp>
#include <kubecontrol/KubePod.hpp>
#include <crossguid/guid.hpp> #include "kubecontrol/PodController.hpp"
#include "nlohmann/json_fwd.hpp"
#include <thread>
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include "loguru.hpp"
SCENARIO("Testing the SimCore Sensor") SCENARIO("Testing the SimCore Sensor")
{ {
// kubecontrol::PodController podc("docs/config");
kubecontrol::KubernetesAPI api(YAML::LoadFile("docs/config"));
std::string name = "hamburg";
std::string uuid = name;
kubecontrol::KubePod ShipPod1("controller",uuid,"ship","ship:latest","simulator");
nlohmann::json vars;
vars["ENTITY_ID"] = uuid;
vars["ENTITY_NAME"] = "FGS Hamburg";
vars["ENTITY_SIDE"] = "Neutral";
vars["POSITION"]["LAT"] = "55";
vars["POSITION"]["LON"] = "8";
vars["POSITION"]["Height"] = "0";
vars["COURSE"] = "0";
vars["SPEED"] = "0";
vars["GROUNDTRUTH_PORT"] = std::to_string(10000);
vars["GROUNDTRUTH_ADDR"] = "239.0.0.1";
vars["COMMAND_PORT"] = "5555";
vars["ENTITY_RCS"] = std::to_string(850);
vars["ENTITY_SENSORS"].push_back("radar:latest");
ShipPod1.setEnvironmentVar("CONFIG", vars.dump());
LOG_S(INFO)<<"Starting";
ShipPod1.start(api);
LOG_S(INFO)<<"started";
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
GIVEN("different Attributes for a Track in different forms") GIVEN("different Attributes for a Track in different forms")
{ {
// std::string api = "https://192.168.3.11:6443/api/v1/namespaces/simulator/pods/";
// std::string token = "eyJhbGciOiJSUzI1NiIsImtpZCI6Il9tUkVrVkp5VjFKeDhtV2xDTmM4R2Y1ZkhRSlBOOWxaVnhKTkZuWVlJamMifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJzaW11bGF0b3IiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoic2ltLXNlY3JldCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJzaW11bGF0b3IiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiJlOGU5YzQ2ZS1lMzcxLTQxMTItOTgzYS1lNzM5NGJmNWE0YzEiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6c2ltdWxhdG9yOnNpbXVsYXRvciJ9.JJjzj0RCU6PJruXuyrK_mNdW4piDADXKPtEW9YP2x1R57uhTDPFfG6LPMFbZTNyeI-A7A7bmjjAt0ICJDuLeL69J8ig3TS-i54R_PB--wFr-7jZMhnNz2wueyPuXxGiIuX-36H9rZ1cA-Dgt2qtDMNhK0TvOlgwUFU_cRjb2W0NhSvH8uB0qtIqOCyVzapCVwXWinyJPGiPL3ph8VxSo6P0ZDa4UjMJ_D6IlMpUpuHriKPLjGnDwTh2oJBjMFOmC_E0Mnr6Sd0rxzsIjIeG_ST6KqoPwyCTX27CPmO74CJUguLgFXSBOjuzvxon8KRYG6VJhRawEDnTU0zx6XrPXIQ";
kubecontrol::KubernetesAPI KubeAPI(YAML::LoadFile("docs/config"));
auto guid = xg::newGuid();
std::string uuid = guid.str();
// int random = rand() % 100 + 1;
// std::string uuid = "random" + std::to_string(random);
kubecontrol::KubePod pod1("controller",uuid,"ship","ship:latest","simulator");
nlohmann::json vars;
vars["ENTITY_ID"] = uuid;
vars["ENTITY_NAME"] = "FGS Hamburg";
vars["ENTITY_SIDE"] = "Neutral";
vars["POSITION"]["LAT"] = "55";
vars["POSITION"]["LON"] = "8";
vars["POSITION"]["Height"] = "0";
vars["COURSE"] = "0";
vars["SPEED"] = "0";
vars["GROUNDTRUTH_PORT"] = std::to_string(10000);
vars["GROUNDTRUTH_ADDR"] = "239.0.0.1";
vars["COMMAND_PORT"] = "5555";
vars["ENTITY_RCS"] = std::to_string(850);
vars["ENTITY_SENSORS"].push_back("radar:latest");
pod1.setEnvironmentVar("CONFIG", vars.dump());
// LOG_S(INFO)<<pod1.createYAML();
pod1.start(KubeAPI);
// LOG_S(INFO)<< pod1.getInfoForThisPod(KubeAPI);
// LOG_S(INFO)<< pod1.getInfoForRelatedPods(KubeAPI);
pod1.getUUIDForRelatedPods(KubeAPI);
pod1.stop(KubeAPI);
WHEN("constructing Track Object with data") WHEN("constructing Track Object with data")
{ {
THEN("check if Track attributes are correct") THEN("check if Track attributes are correct")
{ {
REQUIRE(true == true); REQUIRE(ShipPod1.getUUID() == "hamburg");
REQUIRE(ShipPod1.getComponent() == "ship");
REQUIRE(ShipPod1.getOwner() == "controller");
REQUIRE(ShipPod1.getStatus() == "Running");
REQUIRE(ShipPod1.getIp() != "");
REQUIRE(ShipPod1.getUUIDsForChildPods(api).size() == 2);
// REQUIRE(info1 != "");
ShipPod1.stop(api);

View File

@@ -14,6 +14,8 @@
#include <kubecontrol/PodController.hpp> #include <kubecontrol/PodController.hpp>
#include <crossguid/guid.hpp> #include <crossguid/guid.hpp>
const int podGrid = 2;
void startShip(kubecontrol::PodController* podc,std::string uuid,std::string Name, std::string lat, std::string lon) void startShip(kubecontrol::PodController* podc,std::string uuid,std::string Name, std::string lat, std::string lon)
{ {
@@ -46,7 +48,7 @@ void createScenario(kubecontrol::PodController* podc,std::vector<std::string> *u
int counter = 0; int counter = 0;
double distance = 10000; double distance = 10000;
int rasterSize = 5; int rasterSize = podGrid;
for (int i = 0; i < rasterSize; i++ ) for (int i = 0; i < rasterSize; i++ )
{ {
@@ -98,17 +100,22 @@ std::vector<std::string> uuidList;
createScenario(podc, &uuidList); createScenario(podc, &uuidList);
LOG_S(INFO)<<"Amount Parent Pods: " << uuidList.size(); LOG_S(INFO)<<"Amount Parent Pods: " << uuidList.size();
std::this_thread::sleep_for(std::chrono::milliseconds(20000)); std::this_thread::sleep_for(std::chrono::milliseconds(4000));
// podc.stopPod(std::string Label) // podc.stopPod(std::string Label)
for (auto i: uuidList) // for (auto i: uuidList)
{ // {
auto retrurn = std::async(std::launch::async, &kubecontrol::PodController::stopPod,podc,i); // auto retrurn = std::async(std::launch::async, &kubecontrol::PodController::stopPod,podc,i);
} // }
// std::this_thread::sleep_for(std::chrono::milliseconds(20000)); // std::this_thread::sleep_for(std::chrono::milliseconds(20000));
// Create a random number generator
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0, uuidList.size()-1);
// Generate a random index
int random_index = distribution(generator);
podc->stopAllPods();
GIVEN("different Attributes for a Track in different forms") GIVEN("different Attributes for a Track in different forms")
{ {
@@ -117,9 +124,15 @@ podc->stopAllPods();
THEN("check if Track attributes are correct") THEN("check if Track attributes are correct")
{ {
REQUIRE(true == true); auto info = podc->getInfoForPod(uuidList[random_index]);
REQUIRE(info.Component == "ship");
REQUIRE(info.UUID == uuidList[random_index]);
REQUIRE(info.IP != "");
REQUIRE(info.Owner == "controller");
REQUIRE(podc->getInfoForAllPods().size() == podGrid*podGrid);
// REQUIRE(info1 != ""); // REQUIRE(info1 != "");
podc->stopAllPods();

View File

@@ -1,79 +0,0 @@
#include "kubecontrol/PodController.hpp"
#include "nlohmann/json_fwd.hpp"
#include <thread>
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <kubecontrol/PodInfo.hpp>
SCENARIO("Testing the SimCore Sensor")
{
kubecontrol::PodController podc("docs/config");
std::string name = "hamburg";
std::string uuid = name;
kubecontrol::KubePod ShipPod1("controller",uuid,"ship","ship:latest","simulator");
nlohmann::json vars;
vars["ENTITY_ID"] = uuid;
vars["ENTITY_NAME"] = "FGS Hamburg";
vars["ENTITY_SIDE"] = "Neutral";
vars["POSITION"]["LAT"] = "55";
vars["POSITION"]["LON"] = "8";
vars["POSITION"]["Height"] = "0";
vars["COURSE"] = "0";
vars["SPEED"] = "0";
vars["GROUNDTRUTH_PORT"] = std::to_string(10000);
vars["GROUNDTRUTH_ADDR"] = "239.0.0.1";
vars["COMMAND_PORT"] = "5555";
vars["ENTITY_RCS"] = std::to_string(850);
vars["ENTITY_SENSORS"].push_back("radar:latest");
ShipPod1.setEnvironmentVar("CONFIG", vars.dump());
LOG_S(INFO)<<"Starting";
podc.startPod(ShipPod1);
LOG_S(INFO)<<"started";
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
podc.checkPodsHierarchy();
auto tmp = podc.getInfoForPod(name);
// LOG_S(INFO)<<tmp;
kubecontrol::PodInfo info(tmp);
LOG_S(INFO)<<info.ToString();
LOG_S(INFO)<<info.ToJson();
podc.stopAllPods();
GIVEN("different Attributes for a Track in different forms")
{
WHEN("constructing Track Object with data")
{
THEN("check if Track attributes are correct")
{
REQUIRE(info.Uuid == "hamburg");
// REQUIRE(info1 != "");
} //THEN
} // WHEN
} // GIVEN
} //SCENARIO

View File

@@ -58,7 +58,7 @@ std::string info1 = "";
// nlohmann::json j1 = nlohmann::json::parse(info1); // nlohmann::json j1 = nlohmann::json::parse(info1);
std::this_thread::sleep_for(std::chrono::milliseconds(2000)); std::this_thread::sleep_for(std::chrono::milliseconds(2000));
ShipPod1.updateInfoForThisPod(podc.getKubernetesAPI());
// podc.checkPodsHierarchy(); // podc.checkPodsHierarchy();
// LOG_S(INFO)<<podc.PodList_.size();; // LOG_S(INFO)<<podc.PodList_.size();;
// for(auto i: podc.PodList_) // for(auto i: podc.PodList_)
@@ -77,11 +77,15 @@ std::this_thread::sleep_for(std::chrono::milliseconds(2000));
THEN("check if Track attributes are correct") THEN("check if Track attributes are correct")
{ {
REQUIRE(podc.getListOfChildPods() == 1); auto info = podc.getInfoForPod(ShipPod1.getUUID());
REQUIRE(info.UUID == ShipPod1.getUUID());
REQUIRE(info.IP == ShipPod1.getIp());
REQUIRE(info.Owner == ShipPod1.getOwner());
REQUIRE(info.Component == ShipPod1.getComponent());
LOG_S(INFO)<<"Stopping"; LOG_S(INFO)<<"Stopping";
std::this_thread::sleep_for(std::chrono::milliseconds(5000)); std::this_thread::sleep_for(std::chrono::milliseconds(5000));
podc.stopAllPods(); podc.stopAllPods();
// REQUIRE(info1 != ""); // REQUIRE(info1 != "");