diff --git a/CMakeLists.txt b/CMakeLists.txt index c8b0781..1e6f982 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -62,8 +62,8 @@ ENDIF() include/kubecontrol/Utils.hpp src/kubecontrol/Utils.cpp - include/kubecontrol/PodInfo.hpp - src/kubecontrol/PodInfo.cpp + # include/kubecontrol/PodInfo.hpp + # src/kubecontrol/PodInfo.cpp include/kubecontrol/KubernetesAPI.hpp @@ -118,8 +118,5 @@ IF (${TEST_KUBECONTROL_LIBRARY}) target_link_libraries(test_massivPodHandling Catch2::Catch2 kubecontrol ) 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() diff --git a/include/kubecontrol/KubePod.hpp b/include/kubecontrol/KubePod.hpp index d58522a..d54df12 100644 --- a/include/kubecontrol/KubePod.hpp +++ b/include/kubecontrol/KubePod.hpp @@ -1,7 +1,6 @@ #pragma once #include "kubecontrol/KubernetesAPI.hpp" -#include "kubecontrol/PodInfo.hpp" #include "nlohmann/json_fwd.hpp" #include "yaml-cpp/node/node.h" #include @@ -26,11 +25,13 @@ namespace kubecontrol class KubePod { 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"); std::string getUUID(); std::string getOwner(); + std::string getIp(); + std::string getStatus(); void setEnvironmentVar(std::string key, std::string val); std::map GetEnvironmentVars(); @@ -44,37 +45,20 @@ namespace kubecontrol void setComponent(std::string component); std::string getComponent(); - - - - // [[deprecated("replace with start(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); + int start(KubernetesAPI APIInterface,bool WaitTillRunning = true); + int stop(KubernetesAPI APIInterface); + int stopChilds(KubernetesAPI APIInterface); + + int updateInfoForThisPod(KubernetesAPI APIInterface); - std::vector getUUIDForRelatedPods(KubernetesAPI APIInterface); + std::vector getUUIDsForChildPods(KubernetesAPI APIInterface); - - - PodInfo InfoPod; - - private: - + static const int MaxWaitTimeInSeconds; std::string Owner_; std::string Uuid_; @@ -98,10 +82,14 @@ namespace kubecontrol 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); }; } \ No newline at end of file diff --git a/include/kubecontrol/KubernetesAPI.hpp b/include/kubecontrol/KubernetesAPI.hpp index ba75777..d9783c1 100644 --- a/include/kubecontrol/KubernetesAPI.hpp +++ b/include/kubecontrol/KubernetesAPI.hpp @@ -19,8 +19,11 @@ class KubernetesAPI std::string performRequest(std::string request,std::string Methode,std::string PostFields); void addAddress(std::string address); + std::string getAddress(); void addToken(std::string Token); void addYaml(YAML::Node config); + + std::string getNamespace(); private: std::string APIAddress_; std::string Token_; diff --git a/include/kubecontrol/PodController.hpp b/include/kubecontrol/PodController.hpp index 222e887..ce53db4 100644 --- a/include/kubecontrol/PodController.hpp +++ b/include/kubecontrol/PodController.hpp @@ -1,6 +1,5 @@ #pragma once #include "kubecontrol/KubernetesAPI.hpp" -#include "kubecontrol/PodInfo.hpp" #include #include #include @@ -10,6 +9,16 @@ namespace kubecontrol { + + struct PodInfos + { + std::string UUID; + std::string IP; + std::string Status; + std::string Component; + std::string Owner; + std::vector UUIDOfChilds; + }; class PodController { public: @@ -21,33 +30,21 @@ namespace kubecontrol void stopPod(std::string uuid); void stopAllPods(); - std::string getInfoForAllPods(); - // std::string getInfoForOwnPod(); - std::string getInfoForPod(std::string uuid); - size_t getListOfChildPods(); + std::vector getInfoForAllPods(); + PodInfos getInfoForPod(std::string uuid); - void checkPodsHierarchy(); + KubernetesAPI getKubernetesAPI(); - std::string getPodsInfoForAll(); - std::shared_ptr getPodsInfo(std::string uuid); private: KubernetesAPI APIInterface_; - std::vector PodList_; + std::vector> PodList_; - std::string performRequest(std::string url); - - void performForceStopRequest(std::string uuid); - - - std::string BearerToken_; - std::string ServerAddress_; std::string Namespace_; std::string ApiCall_; - // void addPodInfoToInfoList(std::shared_ptr podinfo); - std::shared_ptr getPodInfo(std::string uuid); + PodInfos extractInfosFromKubePod(KubePod *pod); - std::vector> podsInfoList_; + mutable std::mutex mx_; }; diff --git a/include/kubecontrol/PodInfo.hpp b/include/kubecontrol/PodInfo.hpp deleted file mode 100644 index 8ee9831..0000000 --- a/include/kubecontrol/PodInfo.hpp +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once -#include "nlohmann/json_fwd.hpp" -#include -#include -#include -#include -#include -#include - -namespace kubecontrol { - - class PodInfo - { - public: - - PodInfo(); - - PodInfo(std::string response); - - void update(std::string response); - - std::string ToString(); - nlohmann::json ToJson(); - - std::vector 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 relatedPods; - - - - - - - }; - - - -// struct PodInfo -// { -// std::string Uuid; -// std::string Image; -// std::string Ip; -// std::string Component; -// std::string Status; -// std::string PartOf; -// std::vector>> relatedPods; - -// bool operator==(PodInfo const &rhs ) -// { -// if (Uuid == rhs.Uuid) { -// return true; -// } -// return false; -// } -// }; -} \ No newline at end of file diff --git a/src/kubecontrol/KubePod.cpp b/src/kubecontrol/KubePod.cpp index 892391b..75c948d 100644 --- a/src/kubecontrol/KubePod.cpp +++ b/src/kubecontrol/KubePod.cpp @@ -1,5 +1,4 @@ #include "curlpp/Options.hpp" -#include "kubecontrol/PodInfo.hpp" #include "kubecontrol/Utils.hpp" #include "nlohmann/json_fwd.hpp" #include "yaml-cpp/binary.h" @@ -10,23 +9,20 @@ #include #include #include +#include +#include "loguru.hpp" + 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)),Uuid_(Utils::to_lower(Uuid)), - ContainerImage_(ContainerImage),Namespace_(Namespace),EnvirmonentVars_() + + KubePod::KubePod(std::string Owner, std::string Uuid, std::string ContainerImage,std::string Namespace) + :Owner_(Utils::to_lower(Owner)), + Uuid_(Utils::to_lower(Uuid)), + ContainerImage_(ContainerImage), + Namespace_(Namespace), + EnvirmonentVars_() { ContainerRegistry_ = "kmaster.ti.unibw-hamburg.de:30808"; EnvirmonentVars_ = std::map(); @@ -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)), - Uuid_(Utils::to_lower(Uuid)),Component_(Utils::to_lower(Component)), ContainerImage_(ContainerImage),Namespace_(Namespace),EnvirmonentVars_() + KubePod::KubePod(std::string Owner, std::string Uuid, std::string Component, std::string ContainerImage,std::string Namespace): + 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"; EnvirmonentVars_ = std::map(); @@ -77,6 +78,15 @@ namespace kubecontrol 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) { EnvirmonentVars_.emplace(key,val); @@ -190,215 +200,142 @@ 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/"; this->createYAML(); - - // LOG_S(INFO)<< this->PathToYaml_; - + std::stringstream stream; stream << YAMLNode_; std::string response = APIInterface.performRequest(request,"POST",stream.str()); + extractInformationFromResopnse(response); - InfoPod.update(response); - if (WaitTillRunning == true) { - - while (InfoPod.Status != "Running" && InfoPod.Status != "Succeeded") { + auto timeoutTime = std::chrono::system_clock::now() + std::chrono::seconds(10); + + + 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)); - response = this->getInfoForThisPod(APIInterface); - - InfoPod.update(response); + this->updateInfoForThisPod(APIInterface); } } - return response; + return 0; } - std::string KubePod::stop(std::string apiAddress,std::string token) - { - std::string curlURL = apiAddress+ this->Uuid_; - LOG_S(INFO)< 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: " < 0) - { - for(int i = 0; igetInfoForRelatedPods(APIInterface); + LOG_S(INFO)<<"stopping: " <getUUIDsForChildPods(APIInterface); + 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 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)); + } + return 0; - 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; } - - // std::string KubePod::getInfo(std::string apiAddress,std::string token) - // { - // std::string curlURL = apiAddress+Uuid_+"/"+"status"; - // std::string AuthString = "Authorization: Bearer " + token; - - // std::list 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) + int KubePod::updateInfoForThisPod(KubernetesAPI APIInterface) { std::string request = "/api/v1/namespaces/simulator/pods/"+Uuid_+"/status"; std::string result = APIInterface.performRequest(request,"GET"); - - return result; - } - - - std::string KubePod::getInfoForRelatedPods( 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 result = APIInterface.performRequest(request,"GET"); - - return result; - } - - - std::vector KubePod::getUUIDForRelatedPods(KubernetesAPI APIInterface) - { - std::vector uuids; - - auto rawResponse = getInfoForRelatedPods(APIInterface); - - if (rawResponse == "") + if (result == "") { - return uuids; + return 1; } - try { - nlohmann::json j = nlohmann::json::parse(rawResponse); - if (j.contains("items") && j["items"].is_array()) - { - for (auto i : j["items"]) - { - uuids.push_back(i["metadata"]["name"].get()); - } - } - } catch (const std::exception e) { - LOG_S(ERROR)<< "Exeption in getUUIDForRelatedPods() :" << e.what(); + if (extractInformationFromResopnse(result)!= 0) + { + return 1; + } + return 0; + } + + + std::vector KubePod::getUUIDsForChildPods( KubernetesAPI APIInterface) + { + std::string request = "/api/v1/namespaces/simulator/pods?labelSelector=app.kubernetes.io/part-of="+Uuid_; + std::string result = APIInterface.performRequest(request,"GET"); + + if (result == "") + { + return std::vector(); } - // LOG_S(INFO)<uuidsOfShildContainers; } + int KubePod::extractInformationFromResopnse(std::string response) + { + if (response == "") + { + return 1 ; + } + // LOG_S(INFO)<< response; + nlohmann::json j; + try { + j = nlohmann::json::parse(response); + if(j.contains("kind") && j["kind"] == "Pod") + { + if( j["status"].contains("podIP")) this->Ip_ = j["status"]["podIP"].get(); + this->Status_ = j["status"]["phase"].get(); + 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()); + } + + }else{ + return 1; + } + } catch (const std::exception e) { + 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)< #include @@ -13,6 +12,7 @@ #include #include #include +#include "loguru.hpp" namespace kubecontrol @@ -20,40 +20,22 @@ namespace kubecontrol PodController::PodController(std::string pathToKubectlConfig): APIInterface_( YAML::LoadFile(pathToKubectlConfig)) { - LOG_S(INFO)<< "Path To Yaml: " <(); - Namespace_ = config["contexts"][0]["context"]["namespace"].as(); - - 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(); - } - - - ApiCall_ = "/api/v1/namespaces/"+Namespace_+"/pods/"; - } catch (std::exception& e) { - LOG_S(ERROR)<< e.what(); - throw e.what(); - } + ApiCall_ = "/api/v1/namespaces/"+APIInterface_.getNamespace()+"/pods/"; + } std::string PodController::getServerAddress() { - return this->ServerAddress_; + return APIInterface_.getAddress(); } + KubernetesAPI PodController::getKubernetesAPI() + { + return APIInterface_; + } + + void PodController::startPod(KubePod Pod,bool WaitTillRunning ) @@ -64,21 +46,22 @@ namespace kubecontrol auto response = Pod.start(APIInterface_,WaitTillRunning); std::lock_guardlock(mx_); - PodList_.emplace_back(Pod); + PodList_.emplace_back(std::make_unique(Pod)); // LOG_S(INFO)<lock(mx_); // PodList_ - for (std::vector::iterator it = PodList_.begin(); it != PodList_.end();) - { - if (Label == it->getUUID()) - { - it->stop(APIInterface_); - it = PodList_.erase(it); - } + for (std::vector>::iterator it = PodList_.begin(); it != PodList_.end();) + { + + if (uuid == it->get()->getUUID()) + { + it->get()->stop(APIInterface_); + it = PodList_.erase(it); +} else { it++; @@ -91,263 +74,108 @@ namespace kubecontrol { std::lock_guardlock(mx_); - checkPodsHierarchy(); - - for (auto item : PodList_) + for (auto &item : PodList_) { - LOG_S(INFO)<stop(APIInterface_); - item.stop(APIInterface_); - - LOG_S(INFO)<< "stopping pod: "<getUUID(); } + + PodList_.clear(); } - // std::string PodController::getInfoForOwnPod() - // { - // std::string response = ""; - // for (auto item : PodList_) - // { - - // response = item.getInfoForThisPod(APIInterface_); - // } + + std::vector PodController::getInfoForAllPods() + { + std::vector infosOfAllPods; + for (auto &item : PodList_) + { + if(item->updateInfoForThisPod(APIInterface_) == 0 ) + { + infosOfAllPods.emplace_back(extractInfosFromKubePod(item.get())); + } - // return response; + } + + 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 AuthString = "Authorization: Bearer " + BearerToken_; + + // std::list headers; + // headers.push_back(AuthString); + + // auto request = std::make_unique(); + + + // // 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 podsNames; - nlohmann::json j; - try - { - - j = nlohmann::json::parse(response); - - if (j.contains("items")) - { - int i = j["items"].size(); - for (int a = 0; aperformRequest(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)<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"][a].dump()); - // LOG_S(INFO)<ToString(); - // item->Uuid = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/name"].get(); - // item->Component = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/component"].get(); - // item->Image = j["items"][a]["spec"]["containers"][0]["image"].get(); - // item->Ip = j["items"][a]["status"]["podIP"].get(); - // item->Status = j["items"][a]["status"]["phase"].get(); - // item->PartOf = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/part-of"].get(); - // // LOG_S(INFO)<podsInfoList_.push_back(std::move(item)); - } - - - i = j["items"].size(); - for (int a = 0; a(); - std::string uuid = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/name"].get(); - std::string parentName= j["items"][a]["metadata"]["labels"]["app.kubernetes.io/part-of"].get(); - - 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)<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 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) - // { - - // } - std::shared_ptr 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 headers; - headers.push_back(AuthString); - - auto request = std::make_unique(); - - - // 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) - { - - } diff --git a/src/kubecontrol/PodInfo.cpp b/src/kubecontrol/PodInfo.cpp deleted file mode 100644 index 01cc04a..0000000 --- a/src/kubecontrol/PodInfo.cpp +++ /dev/null @@ -1,114 +0,0 @@ - - -#include "nlohmann/json_fwd.hpp" -#include - - -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(); - Component = j["items"][0]["metadata"]["labels"]["app.kubernetes.io/component"].get(); - Image = j["items"][0]["spec"]["containers"][0]["image"].get(); - Ip = j["items"][0]["status"]["podIP"].get(); - Status = j["items"][0]["status"]["phase"].get(); - PartOf = j["items"][0]["metadata"]["labels"]["app.kubernetes.io/part-of"].get(); - } - - }else - { - Uuid = j["metadata"]["labels"]["app.kubernetes.io/name"].get(); - Component = j["metadata"]["labels"]["app.kubernetes.io/component"].get(); - PartOf = j["metadata"]["labels"]["app.kubernetes.io/part-of"].get(); - Image = j["spec"]["containers"][0]["image"].get(); - if (j["status"].contains("podIP")) Ip = j["status"]["podIP"].get(); - - Status = j["status"]["phase"].get(); - } - - - - - } catch (std::exception& e) - { - // LOG_S(WARNING)<< response; - LOG_S(ERROR)< 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(); - } - - - - - -} \ No newline at end of file diff --git a/tests/test_KubePod.cpp b/tests/test_KubePod.cpp index b1665e9..0711206 100644 --- a/tests/test_KubePod.cpp +++ b/tests/test_KubePod.cpp @@ -1,62 +1,71 @@ -#include "kubecontrol/KubernetesAPI.hpp" -#define CATCH_CONFIG_MAIN -#include -#include -#include -#include -#include + + +#include "kubecontrol/PodController.hpp" +#include "nlohmann/json_fwd.hpp" +#include +#define CATCH_CONFIG_MAIN +#include +#include "loguru.hpp" + 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") { - - // 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)< #include +const int podGrid = 2; + 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 *u int counter = 0; double distance = 10000; - int rasterSize = 5; + int rasterSize = podGrid; for (int i = 0; i < rasterSize; i++ ) { @@ -98,17 +100,22 @@ std::vector uuidList; createScenario(podc, &uuidList); 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) -for (auto i: uuidList) -{ - auto retrurn = std::async(std::launch::async, &kubecontrol::PodController::stopPod,podc,i); -} +// for (auto i: uuidList) +// { +// auto retrurn = std::async(std::launch::async, &kubecontrol::PodController::stopPod,podc,i); +// } // std::this_thread::sleep_for(std::chrono::milliseconds(20000)); +// Create a random number generator + std::default_random_engine generator; + std::uniform_int_distribution 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") { @@ -117,9 +124,15 @@ podc->stopAllPods(); 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 != ""); + podc->stopAllPods(); diff --git a/tests/test_podInfo.cpp b/tests/test_podInfo.cpp deleted file mode 100644 index bd7b339..0000000 --- a/tests/test_podInfo.cpp +++ /dev/null @@ -1,79 +0,0 @@ - - - -#include "kubecontrol/PodController.hpp" -#include "nlohmann/json_fwd.hpp" -#include -#define CATCH_CONFIG_MAIN -#include -#include - - -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)<