ADD: added updated drone.yml and changed some function calls

This commit is contained in:
Henry Winkel
2024-03-13 16:41:56 +01:00
parent 48101a673a
commit 0e05106d1e
13 changed files with 264 additions and 231 deletions

View File

@@ -6,6 +6,7 @@ steps:
- name: build - name: build
image: kmaster.ti.unibw-hamburg.de:30808/debianbullseye image: kmaster.ti.unibw-hamburg.de:30808/debianbullseye
commands: commands:
- git submodule update --init --recursive --jobs=4
- mkdir -p build && cd build - mkdir -p build && cd build
- CC=clang-11 CXX=clang++-11 cmake -DCMAKE_BUILD_TYPE=DEBUG .. - CC=clang-11 CXX=clang++-11 cmake -DCMAKE_BUILD_TYPE=DEBUG ..
- make -j - make -j

11
.gitattributes vendored Normal file
View File

@@ -0,0 +1,11 @@
# Set the default behavior for all files.
* text=auto eol=lf
# Normalized and converts to native line endings on checkout.
*.c text
*.cc text
*.cxx
*.cpp text
*.h text
*.hxx text
*.hpp text

5
.gitignore vendored
View File

@@ -4,3 +4,8 @@ compile_commands.json
.cache .cache
.vscode .vscode
config/pods config/pods
.github
.clang*
.cmake-format*
.pre-commit*
.editorconfig

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include "kubecontrol/KubernetesAPI.hpp" #include <kubecontrol/KubernetesAPI.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>
@@ -17,17 +17,14 @@
#include <curlpp/cURLpp.hpp> #include <curlpp/cURLpp.hpp>
#include <filesystem> #include <filesystem>
#include <map>
#include <vector>
namespace kubecontrol
namespace kubecontrol
{ {
enum PullPolicy: uint32_t enum PullPolicy: uint32_t
{ {
ALWAYS, ALWAYS,
IFNOTPRESENT, IFNOTPRESENT,
NEVER NEVER
@@ -43,10 +40,10 @@ namespace kubecontrol
case PullPolicy::NEVER: return "Never"; case PullPolicy::NEVER: return "Never";
default: return "Always"; default: return "Always";
} }
} }
struct PodChild struct PodChild
{ {
std::string UUID; std::string UUID;
@@ -55,7 +52,6 @@ namespace kubecontrol
std::string Status; std::string Status;
}; };
struct PodInfos struct PodInfos
{ {
std::string UUID; std::string UUID;
@@ -68,108 +64,109 @@ 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");
/** /**
* @brief returns the uuid of the pod * @brief returns the uuid of the pod
* *
* @return std::string * @return std::string
*/ */
std::string getUUID(); std::string getUUID();
/** /**
* @brief Get the Owner of the pods * @brief Get the Owner of the pods
* *
* @return std::string * @return std::string
*/ */
std::string getOwner(); std::string getOwner();
/** /**
* @brief Get the Ip of the pod * @brief Get the Ip of the pod
* *
* @return std::string * @return std::string
*/ */
std::string getIp(); std::string getIp();
/** /**
* @brief Get the Status * @brief Get the Status
* *
* @return std::string * @return std::string
*/ */
std::string getStatus(); std::string getStatus();
/** /**
* @brief Set the Environment Vars for pod * @brief Set the Environment Vars for pod
* *
* @param key * @param key
* @param val * @param val
*/ */
void setEnvironmentVar(std::string key, std::string val); void setEnvironmentVar(std::string key, std::string val);
/** /**
* @brief Get the Environment Vars * @brief Get the Environment Vars
* *
* @return std::map<std::string, std::string> * @return std::map<std::string, std::string>
*/ */
std::map<std::string, std::string> GetEnvironmentVars(); std::map<std::string, std::string> GetEnvironmentVars();
/** /**
* @brief Get the Environment Var for a specific key * @brief Get the Environment Var for a specific key
* *
* @param key std::string * @param key std::string
* @return std::string * @return std::string
*/ */
std::string GetEnvironmentVar(std::string key); std::string GetEnvironmentVar(std::string key);
/** /**
* @brief Set CMD args * @brief Set CMD args
* *
* @param args * @param args
*/ */
void setArgs(std::string args); void setArgs(std::string &args);
/** /**
* @brief Get the Args * @brief Get the Args
* *
* @return std::vector<std::string> * @return std::vector<std::string>
*/ */
std::vector<std::string> GetArgs(); std::vector<std::string> GetArgs();
/**
* @brief Set the Command for a pod
*
* @param command
*/
void setCommand(std::string command);
/** /**
* @brief Get the Command * @brief Set the Command for a pod
* *
* @return std::string * @param command
*/
void setCommand(std::string &command);
/**
* @brief Get the Command
*
* @return std::string
*/ */
std::string getCommand(); std::string getCommand();
/** /**
* @brief Set the Component var for the pod * @brief Set the Component var for the pod
* *
* @param component * @param component
*/ */
void setComponent(std::string component); void setComponent(std::string &component);
/** /**
* @brief Get the Component var * @brief Get the Component var
* *
* @return std::string * @return std::string
*/ */
std::string getComponent(); std::string getComponent();
/** /**
* @brief add a Container to a pod * @brief add a Container to a pod
* *
* @param name std::string * @param name std::string
* @param image std::string * @param image std::string
* @param envs std::map<std::string,std:.string> * @param envs std::map<std::string,std:.string>
@@ -178,17 +175,17 @@ namespace kubecontrol
void addContainer(std::string name,std::string image, std::shared_ptr<std::map<std::string, std::string>> envs = nullptr, PullPolicy pullPolicy = ALWAYS); void addContainer(std::string name,std::string image, std::shared_ptr<std::map<std::string, std::string>> envs = nullptr, PullPolicy pullPolicy = ALWAYS);
/** /**
* @brief sets the name of the pod * @brief sets the name of the pod
* @param string - term to be displayed * @param string - term to be displayed
*/ */
void setName(std::string name); void setName(std::string &name);
/** /**
* @brief return the name of the pod * @brief return the name of the pod
* @return std::string * @return std::string
*/ */
std::string getName(); std::string getName();
int start(KubernetesAPI APIInterface,bool WaitTillRunning = true); int start(KubernetesAPI APIInterface,bool WaitTillRunning = true);
int stop(KubernetesAPI APIInterface); int stop(KubernetesAPI APIInterface);
@@ -204,7 +201,7 @@ namespace kubecontrol
std::vector<PodChild> getPodsChilds(KubernetesAPI APIInterface); std::vector<PodChild> getPodsChilds(KubernetesAPI APIInterface);
private: private:
static const int MaxWaitTimeInSeconds; static const int MaxWaitTimeInSeconds;
@@ -222,11 +219,11 @@ namespace kubecontrol
std::string Ip_; std::string Ip_;
std::string Status_; std::string Status_;
std::string PartOf_; std::string PartOf_;
std::vector<PodChild> ChildPods; std::vector<PodChild> ChildPods;
std::string PodCommand_; std::string PodCommand_;
YAML::Node YAMLNode_; YAML::Node YAMLNode_;
std::map<std::string, std::string> EnvirmonentVars_; std::map<std::string, std::string> EnvirmonentVars_;
@@ -236,12 +233,12 @@ namespace kubecontrol
/** /**
* @brief extracts the asked inforamtion from the kubernetes response * @brief extracts the asked inforamtion from the kubernetes response
* *
* *
*/ */
int extractInformationFromResopnse(std::string response); int extractInformationFromResopnse(std::string response);
}; };
} }

View File

@@ -6,11 +6,11 @@
namespace kubecontrol namespace kubecontrol
{ {
class KubernetesAPI class KubernetesAPI
{ {
public: public:
KubernetesAPI(); KubernetesAPI();
KubernetesAPI(YAML::Node config); explicit KubernetesAPI(YAML::Node config);
KubernetesAPI(std::string APIAddress, std::string Token); KubernetesAPI(std::string APIAddress, std::string Token);
@@ -32,4 +32,4 @@ class KubernetesAPI
}; };
} }

View File

@@ -13,8 +13,8 @@ namespace kubecontrol
class PodController class PodController
{ {
public: public:
PodController(std::string pathToKubectlConfig); explicit PodController(std::string pathToKubectlConfig);
std::string getServerAddress(); std::string getServerAddress();
@@ -38,8 +38,8 @@ namespace kubecontrol
PodInfos extractInfosFromKubePod(KubePod *pod); PodInfos extractInfosFromKubePod(KubePod *pod);
mutable std::mutex mx_; mutable std::mutex mx_;
}; };
} // namespace ku } // namespace ku

View File

@@ -6,20 +6,20 @@ namespace kubecontrol
{ {
class kubecontrol class kubecontrol
{ {
public: public:
kubecontrol(std::string pathToKubectlConfig); explicit kubecontrol(std::string &pathToKubectlConfig);
void getPods(); void getPods();
void startPod(); void startPod();
void deletePod(std::string uid); void deletePod(std::string uid);
std::string createYAML(); std::string createYAML();
private: private:
std::string BearerToken_; std::string BearerToken_;
std::string ServerAddress_; std::string ServerAddress_;
std::string NameSpace_; std::string NameSpace_;
}; };
} }

View File

@@ -1,5 +1,6 @@
#include <kubecontrol/PodController.hpp>
#include "curlpp/Options.hpp" #include "curlpp/Options.hpp"
#include "kubecontrol/PodController.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"
@@ -19,27 +20,30 @@
namespace kubecontrol namespace kubecontrol
{ {
KubePod::KubePod(std::string Owner, std::string Uuid, std::string ContainerImage,std::string Namespace)
KubePod::KubePod(std::string &Owner, std::string &Uuid, std::string &ContainerImage,std::string Namespace)
:Owner_(Utils::to_lower(Owner)), :Owner_(Utils::to_lower(Owner)),
Uuid_(Utils::to_lower(Uuid)), Uuid_(Utils::to_lower(Uuid)),
Namespace_(Namespace), ContainerRegistry_("kmaster.ti.unibw-hamburg.de:30808"),
EnvirmonentVars_() Namespace_(Namespace)
{ {
ContainerRegistry_ = "kmaster.ti.unibw-hamburg.de:30808";
EnvirmonentVars_ = std::map<std::string, std::string>(); EnvirmonentVars_ = std::map<std::string, std::string>();
this->PathToYaml_ = "config/pods/" + this->Uuid_ + ".yaml"; this->PathToYaml_ = "config/pods/" + this->Uuid_ + ".yaml";
if( std::filesystem::directory_entry("config").exists() != true) if( !std::filesystem::directory_entry("config").exists())
{ {
std::filesystem::create_directory("config"); std::filesystem::create_directory("config");
} }
std::filesystem::directory_entry entry("config/pods"); std::filesystem::directory_entry entry("config/pods");
if(entry.exists() != true) if(!entry.exists())
{ {
std::filesystem::create_directory("config/pods"); std::filesystem::create_directory("config/pods");
} }
@@ -48,25 +52,25 @@ namespace kubecontrol
} }
KubePod::KubePod(std::string Owner, std::string Uuid, std::string Component, std::string ContainerImage,std::string Namespace): KubePod::KubePod(std::string &Owner, std::string &Uuid, std::string &Component, std::string &ContainerImage,std::string Namespace):
Owner_(Utils::to_lower(Owner)), Owner_(Utils::to_lower(Owner)),
Uuid_(Utils::to_lower(Uuid)), Uuid_(Utils::to_lower(Uuid)),
Component_(Utils::to_lower(Component)), Component_(Utils::to_lower(Component)),
Namespace_(Namespace), ContainerRegistry_("kmaster.ti.unibw-hamburg.de:30808"),
EnvirmonentVars_() Namespace_(Namespace)
{ {
ContainerRegistry_ = "kmaster.ti.unibw-hamburg.de:30808";
EnvirmonentVars_ = std::map<std::string, std::string>(); EnvirmonentVars_ = std::map<std::string, std::string>();
this->PathToYaml_ = "config/pods/" + this->Uuid_ + ".yaml"; this->PathToYaml_ = "config/pods/" + this->Uuid_ + ".yaml";
if( std::filesystem::directory_entry("config").exists() != true) if( !std::filesystem::directory_entry("config").exists())
{ {
std::filesystem::create_directory("config"); std::filesystem::create_directory("config");
} }
std::filesystem::directory_entry entry("config/pods"); std::filesystem::directory_entry entry("config/pods");
if(entry.exists() != true) if(!entry.exists())
{ {
std::filesystem::create_directory("config/pods"); std::filesystem::create_directory("config/pods");
} }
@@ -80,25 +84,25 @@ namespace kubecontrol
void KubePod::addContainer(std::string name,std::string image, std::shared_ptr<std::map<std::string, std::string>> envs, PullPolicy pullPolicy ) void KubePod::addContainer(std::string name,std::string image, std::shared_ptr<std::map<std::string, std::string>> envs, PullPolicy pullPolicy )
{ {
YAML::Node container; YAML::Node container;
transform(image.begin(), image.end(), image.begin(), ::tolower); transform(image.begin(), image.end(), image.begin(), ::tolower);
transform(name.begin(), name.end(), name.begin(), ::tolower); transform(name.begin(), name.end(), name.begin(), ::tolower);
container["name"] = name+"-container"; container["name"] = name+"-container";
container["image"] = this->ContainerRegistry_ + "/" + image; container["image"] = this->ContainerRegistry_ + "/" + image;
container["imagePullPolicy"] = toString(pullPolicy); container["imagePullPolicy"] = toString(pullPolicy);
if (envs != nullptr) if (envs != nullptr)
{ {
int i = 0; int lauf = 0;
for(auto [key,value] : *envs) for(auto [key,value] : *envs)
{ {
container["env"][i]["name"] = key; container["env"][lauf]["name"] = key;
container["env"][i]["value"] = value; container["env"][lauf]["value"] = value;
i++; lauf++;
} }
} }
ContainerImages_.push_back(container); ContainerImages_.push_back(container);
} }
@@ -138,12 +142,12 @@ namespace kubecontrol
{ {
if(EnvirmonentVars_.contains(key)) { if(EnvirmonentVars_.contains(key)) {
return EnvirmonentVars_[key]; return EnvirmonentVars_[key];
} else {
return nullptr;
} }
return "";
} }
void KubePod::setArgs(std::string args) void KubePod::setArgs(std::string &args)
{ {
Args_.emplace_back(Utils::to_lower(args)); Args_.emplace_back(Utils::to_lower(args));
} }
@@ -153,7 +157,7 @@ namespace kubecontrol
return Args_; return Args_;
} }
void KubePod::setCommand(std::string command) void KubePod::setCommand(std::string &command)
{ {
PodCommand_ = Utils::to_lower(command); PodCommand_ = Utils::to_lower(command);
} }
@@ -163,7 +167,7 @@ namespace kubecontrol
return PodCommand_; return PodCommand_;
} }
void KubePod::setComponent(std::string component) void KubePod::setComponent(std::string &component)
{ {
this->Component_ = Utils::to_lower(component); this->Component_ = Utils::to_lower(component);
} }
@@ -173,7 +177,7 @@ namespace kubecontrol
return this->Component_; return this->Component_;
} }
void KubePod::setName(std::string name) void KubePod::setName(std::string &name)
{ {
this->Name_ = name; this->Name_ = name;
} }
@@ -200,9 +204,9 @@ namespace kubecontrol
// if (!std::empty(this->Component_)) node["metadata"]["labels"]["app.kubernetes.io/component"] = this->Component_; // if (!std::empty(this->Component_)) node["metadata"]["labels"]["app.kubernetes.io/component"] = this->Component_;
node["metadata"]["labels"]["app.kubernetes.io/component"] = this->Component_; node["metadata"]["labels"]["app.kubernetes.io/component"] = this->Component_;
for (int i = 0; i< this->ContainerImages_.size(); i++) for (int i = 0; i< this->ContainerImages_.size(); i++)
{ {
node["spec"]["containers"][i] = this->ContainerImages_[i]; node["spec"]["containers"][i] = this->ContainerImages_[i];
// node["spec"]["containers"][i]["name"] = this->Uuid_+"-container"; // node["spec"]["containers"][i]["name"] = this->Uuid_+"-container";
@@ -212,36 +216,36 @@ namespace kubecontrol
// node["spec"]["containers"][i]["ports"][0]["protocol"] = "UDP"; // node["spec"]["containers"][i]["ports"][0]["protocol"] = "UDP";
} }
int i = 0; int i = 0;
for (auto item :EnvirmonentVars_) { for (const auto& item :EnvirmonentVars_) {
node["spec"]["containers"][0]["env"][i]["name"] = item.first; node["spec"]["containers"][0]["env"][i]["name"] = item.first;
node["spec"]["containers"][0]["env"][i]["value"] = item.second; node["spec"]["containers"][0]["env"][i]["value"] = item.second;
i++; i++;
} }
if (Args_.size() > 0) if (!Args_.empty())
{ {
node["spec"]["containers"][0]["args"].SetStyle(YAML::EmitterStyle::Flow); node["spec"]["containers"][0]["args"].SetStyle(YAML::EmitterStyle::Flow);
for (auto item : Args_) { for (const auto& item : Args_) {
node["spec"]["containers"][0]["args"].push_back(item); node["spec"]["containers"][0]["args"].push_back(item);
} }
} }
if (!PodCommand_.empty()) if (!PodCommand_.empty())
{ {
node["spec"]["containers"][0]["command"].SetStyle(YAML::EmitterStyle::Flow); node["spec"]["containers"][0]["command"].SetStyle(YAML::EmitterStyle::Flow);
node["spec"]["containers"][0]["command"].push_back(PodCommand_); node["spec"]["containers"][0]["command"].push_back(PodCommand_);
} }
node["spec"]["terminationGracePeriodSeconds"] = 5; node["spec"]["terminationGracePeriodSeconds"] = 5;
node["spec"]["restartPolicy"] = "Never"; node["spec"]["restartPolicy"] = "Never";
YAMLNode_ = node; YAMLNode_ = node;
@@ -250,19 +254,19 @@ namespace kubecontrol
fout << node; fout << node;
fout.close(); fout.close();
return this->PathToYaml_; return this->PathToYaml_;
} }
int 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();
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());
@@ -271,10 +275,10 @@ namespace kubecontrol
auto timeoutTime = std::chrono::system_clock::now() + std::chrono::seconds(10); auto timeoutTime = std::chrono::system_clock::now() + std::chrono::seconds(10);
if (WaitTillRunning == true ) { if (WaitTillRunning ) {
while ((this->Status_ != "Running" && this->Status_ != "Succeeded") || std::chrono::system_clock::now() >= timeoutTime) { while ((this->Status_ != "Running" && this->Status_ != "Succeeded") || std::chrono::system_clock::now() >= timeoutTime) {
// LOG_S(INFO)<<"wainting till running " << this->Status_; // 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));
this->updateInfoForThisPod(APIInterface); this->updateInfoForThisPod(APIInterface);
@@ -288,15 +292,15 @@ namespace kubecontrol
return 0; return 0;
} }
int KubePod::stop(KubernetesAPI APIInterface) int 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_; LOG_S(INFO)<<"stopping: " <<Uuid_;
return 0; return 0;
} }
@@ -305,19 +309,19 @@ namespace kubecontrol
int KubePod::stopChilds(KubernetesAPI APIInterface) int KubePod::stopChilds(KubernetesAPI APIInterface)
{ {
auto uuids = this->getPodsChilds(APIInterface); auto uuids = this->getPodsChilds(APIInterface);
if (uuids.size() == 0) if (uuids.empty())
{ {
return 1; return 1;
} }
for(auto i: uuids) for(const auto& uuid: uuids)
{ {
std::string request = "/api/v1/namespaces/simulator/pods/"+i.UUID; std::string request = "/api/v1/namespaces/simulator/pods/"+uuid.UUID;
std::string result = APIInterface.performRequest(request,"DELETE"); std::string result = APIInterface.performRequest(request,"DELETE");
} }
return 0; return 0;
} }
@@ -326,15 +330,15 @@ namespace kubecontrol
{ {
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 == "") if (result.empty())
{ {
return 1; return 1;
} }
if (extractInformationFromResopnse(result)!= 0) if (extractInformationFromResopnse(result)!= 0)
{ {
return 1; return 1;
} }
return 0; return 0;
} }
@@ -344,12 +348,12 @@ namespace kubecontrol
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");
if (result == "") if (result.empty())
{ {
return std::vector<PodChild>(); return {};
} }
extractInformationFromResopnse(result); extractInformationFromResopnse(result);
return this->ChildPods; return this->ChildPods;
} }
@@ -357,7 +361,7 @@ namespace kubecontrol
int KubePod::extractInformationFromResopnse(std::string response) int KubePod::extractInformationFromResopnse(std::string response)
{ {
if (response == "") if (response.empty())
{ {
return 1 ; return 1 ;
} }
@@ -366,16 +370,16 @@ namespace kubecontrol
try { try {
j = nlohmann::json::parse(response); j = nlohmann::json::parse(response);
if(j.contains("kind") && j["kind"] == "Pod") if(j.contains("kind") && j["kind"] == "Pod")
{ {
if( j["status"].contains("podIP")) this->Ip_ = j["status"]["podIP"].get<std::string>(); if( j["status"].contains("podIP")) this->Ip_ = j["status"]["podIP"].get<std::string>();
this->Status_ = j["status"]["phase"].get<std::string>(); this->Status_ = j["status"]["phase"].get<std::string>();
this->PartOf_ = j["metadata"]["labels"]["app.kubernetes.io/part-of"]; this->PartOf_ = j["metadata"]["labels"]["app.kubernetes.io/part-of"];
}else if(j.contains("items") && j["items"].is_array())
{
for (auto i : j["items"]) }else if(j.contains("items") && j["items"].is_array())
{
for (auto i : j["items"])
{ {
// LOG_S(INFO)<<i; // LOG_S(INFO)<<i;
PodChild child; PodChild child;
@@ -389,7 +393,7 @@ namespace kubecontrol
}else{ }else{
return 1; return 1;
} }
} catch (const std::exception e) { } catch (const std::exception &e) {
LOG_S(ERROR)<< "Exeption in extractInformationFromResopnse() :" << e.what(); LOG_S(ERROR)<< "Exeption in extractInformationFromResopnse() :" << e.what();
std::exception_ptr p = std::current_exception(); std::exception_ptr p = std::current_exception();
LOG_S(ERROR)<< "Exeption :" << p.__cxa_exception_type()->name(); LOG_S(ERROR)<< "Exeption :" << p.__cxa_exception_type()->name();
@@ -398,17 +402,16 @@ namespace kubecontrol
} }
return 0; return 0;
} }
} }

View File

@@ -1,4 +1,4 @@
#include "nlohmann/json_fwd.hpp" #include <nlohmann/json.hpp>
#include "yaml-cpp/binary.h" #include "yaml-cpp/binary.h"
#include "yaml-cpp/emitter.h" #include "yaml-cpp/emitter.h"
#include "yaml-cpp/emitterdef.h" #include "yaml-cpp/emitterdef.h"
@@ -22,7 +22,6 @@
#include <loguru.hpp> #include <loguru.hpp>
#include <nlohmann/json.hpp>
#include <iostream> #include <iostream>
@@ -31,11 +30,11 @@
namespace kubecontrol namespace kubecontrol
{ {
kubecontrol::kubecontrol(std::string pathToKubectlConfig) kubecontrol::kubecontrol(std::string &pathToKubectlConfig)
{ {
YAML::Node config = YAML::LoadFile(pathToKubectlConfig); YAML::Node config = YAML::LoadFile(pathToKubectlConfig);
BearerToken_ = config["users"][0]["user"]["token"].as<std::string>(); BearerToken_ = config["users"][0]["user"]["token"].as<std::string>();
ServerAddress_ = config["clusters"][0]["cluster"]["server"].as<std::string>(); ServerAddress_ = config["clusters"][0]["cluster"]["server"].as<std::string>();
@@ -53,16 +52,16 @@ namespace kubecontrol
curlpp::Cleanup cleaner; curlpp::Cleanup cleaner;
curlpp::Easy request; curlpp::Easy request;
std::stringstream result; std::stringstream result;
request.setOpt(cURLpp::Options::WriteStream(&result)); request.setOpt(cURLpp::Options::WriteStream(&result));
request.setOpt(new curlpp::options::HttpHeader(headers)); request.setOpt(curlpp::options::HttpHeader(headers));
request.setOpt(new curlpp::options::Url(curlURL)); request.setOpt( curlpp::options::Url(curlURL));
request.setOpt(new curlpp::options::SslEngineDefault()); request.setOpt( curlpp::options::SslEngineDefault());
request.setOpt(new curlpp::options::CaPath("config/ca.crt")); request.setOpt( curlpp::options::CaPath("config/ca.crt"));
request.setOpt(new curlpp::options::SslVerifyPeer(false)); request.setOpt( curlpp::options::SslVerifyPeer(false));
// request.setOpt(new curlpp::options::Verbose(true)); // request.setOpt(new curlpp::options::Verbose(true));
@@ -71,8 +70,8 @@ namespace kubecontrol
request.perform(); request.perform();
auto response = result.str(); auto response = result.str();
auto j = nlohmann::json::parse(response); auto j = nlohmann::json::parse(response);
LOG_S(INFO)<<j["items"][0]["metadata"]; LOG_S(INFO)<<j["items"][0]["metadata"];
// std::cout << readBuffer << std::endl; // std::cout << readBuffer << std::endl;
@@ -86,36 +85,36 @@ namespace kubecontrol
std::list<std::string> headers; std::list<std::string> headers;
headers.push_back(AuthString); headers.push_back(AuthString);
headers.push_back("Content-Type: application/yaml"); headers.emplace_back("Content-Type: application/yaml");
curlpp::Cleanup cleaner; curlpp::Cleanup cleaner;
curlpp::Easy request; curlpp::Easy request;
// WriterMemoryClass mWriterChunk; // WriterMemoryClass mWriterChunk;
// curlpp::types::WriteFunctionFunctor functor = std::bind(&WriterMemoryClass::WriteMemoryCallback, &mWriterChunk, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); // curlpp::types::WriteFunctionFunctor functor = std::bind(&WriterMemoryClass::WriteMemoryCallback, &mWriterChunk, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
// curlpp::options::WriteFunction *test = new curlpp::options::WriteFunction(functor); // curlpp::options::WriteFunction *test = new curlpp::options::WriteFunction(functor);
// request.setOpt(test); // request.setOpt(test);
std::stringstream result; std::stringstream result;
request.setOpt(cURLpp::Options::WriteStream(&result)); request.setOpt(cURLpp::Options::WriteStream(&result));
request.setOpt(new curlpp::options::HttpHeader(headers)); request.setOpt( curlpp::options::HttpHeader(headers));
request.setOpt(new curlpp::options::Url(curlURL)); request.setOpt( curlpp::options::Url(curlURL));
request.setOpt(new curlpp::options::SslEngineDefault()); request.setOpt( curlpp::options::SslEngineDefault());
request.setOpt(new curlpp::options::CaPath("config/ca.crt")); request.setOpt( curlpp::options::CaPath("config/ca.crt"));
request.setOpt(new curlpp::options::SslVerifyPeer(false)); request.setOpt( curlpp::options::SslVerifyPeer(false));
request.setOpt(new curlpp::options::Post(true)); request.setOpt( curlpp::options::Post(true));
auto yaml = createYAML(); auto yaml = createYAML();
// YAML::Node node = YAML::LoadFile("config/pods_deployment.yaml"); // YAML::Node node = YAML::LoadFile("config/pods_deployment.yaml");
// YAML::Binary node = YAML::LoadFile("config/pods_deployment.yaml"); // YAML::Binary node = YAML::LoadFile("config/pods_deployment.yaml");
// LOG_S(INFO)<< node["spec"]["containers"][0]["imagePullPolicy"]; // LOG_S(INFO)<< node["spec"]["containers"][0]["imagePullPolicy"];
// YAML::Binary binary = node.as<YAML::Binary>(); // YAML::Binary binary = node.as<YAML::Binary>();
@@ -133,14 +132,14 @@ namespace kubecontrol
// read data as a block: // read data as a block:
is.read (buffer,length); is.read (buffer,length);
std::istringstream myStream((std::string( buffer ))); std::istringstream myStream((std::string( buffer )));
int size = myStream.str().size(); int size = myStream.str().size();
is.close(); is.close();
request.setOpt(new curlpp::options::PostFields(buffer)); request.setOpt( curlpp::options::PostFields(buffer));
// request.setOpt(new curlpp::options::Verbose(true)); // request.setOpt(new curlpp::options::Verbose(true));
@@ -167,21 +166,21 @@ namespace kubecontrol
std::stringstream result; std::stringstream result;
request.setOpt(cURLpp::Options::WriteStream(&result)); request.setOpt(cURLpp::Options::WriteStream(&result));
request.setOpt(new curlpp::options::HttpHeader(headers));
request.setOpt(new curlpp::options::Url(curlURL)); request.setOpt( curlpp::options::HttpHeader(headers));
request.setOpt( curlpp::options::Url(curlURL));
request.setOpt(new curlpp::options::SslEngineDefault()); request.setOpt( curlpp::options::SslEngineDefault());
request.setOpt(new curlpp::options::CaPath("config/ca.crt")); request.setOpt( curlpp::options::CaPath("config/ca.crt"));
request.setOpt(new curlpp::options::SslVerifyPeer(false)); request.setOpt( curlpp::options::SslVerifyPeer(false));
// request.setOpt(new curlpp::options::Post(true)); // request.setOpt(new curlpp::options::Post(true));
// request.setOpt(new curlpp::options::PostFields("DELETE")); // request.setOpt(new curlpp::options::PostFields("DELETE"));
request.setOpt(new curlpp::options::CustomRequest("DELETE")); request.setOpt( curlpp::options::CustomRequest("DELETE"));
// request.setOpt(new curlpp::options::Verbose(true)); // request.setOpt(new curlpp::options::Verbose(true));
@@ -195,7 +194,7 @@ namespace kubecontrol
std::string kubecontrol::createYAML() std::string kubecontrol::createYAML()
{ {
YAML::Node node; YAML::Node node;
node["apiVersion"] = "v1"; node["apiVersion"] = "v1";
node["kind"] = "Pod"; node["kind"] = "Pod";
@@ -205,7 +204,7 @@ namespace kubecontrol
node["spec"]["containers"][0]["name"] = "debug-debian-container"; node["spec"]["containers"][0]["name"] = "debug-debian-container";
node["spec"]["containers"][0]["image"] = "kmaster.ti.unibw-hamburg.de:30808/debugdebianhenry:0.1.3"; node["spec"]["containers"][0]["image"] = "kmaster.ti.unibw-hamburg.de:30808/debugdebianhenry:0.1.3";
// node["spec"]["containers"][0]["imagePullPolicy"] = "\"Always\""; // node["spec"]["containers"][0]["imagePullPolicy"] = "\"Always\"";
node["spec"]["containers"][0]["env"][0]["name"] = "OWN_SHIP_SERVER"; node["spec"]["containers"][0]["env"][0]["name"] = "OWN_SHIP_SERVER";
@@ -226,15 +225,15 @@ namespace kubecontrol
std::ofstream fout("config/pods_deployment.yaml"); std::ofstream fout("config/pods_deployment.yaml");
std::stringstream ss; std::stringstream sstream;
ss <<node; sstream <<node;
LOG_S(INFO)<< node; LOG_S(INFO)<< node;
fout << ss.str(); fout << sstream.str();
fout.close(); fout.close();
return "config/pods_deployment.yaml"; return "config/pods_deployment.yaml";
} }
}
}

View File

@@ -22,7 +22,10 @@ SCENARIO("Testing the SimCore Sensor")
std::string uuid = name; std::string uuid = name;
kubecontrol::KubePod ShipPod1("controller",uuid,"ship","ship:latest","simulator"); std::string controller = "controller";
std::string type = "ship";
std::string image = "ship:latest";
kubecontrol::KubePod ShipPod1(controller,uuid,type,image,"simulator");
ShipPod1.setName(name); ShipPod1.setName(name);
nlohmann::json vars; nlohmann::json vars;
@@ -49,7 +52,10 @@ ShipPod1.start(api);
LOG_S(INFO)<<"started"; LOG_S(INFO)<<"started";
std::string name2 = "componenttest2"; std::string name2 = "componenttest2";
kubecontrol::KubePod ShipPod2("controller",name2,"CMS","ship:latest","simulator"); std::string controller2 = "controller";
std::string type2 = "ship";
std::string image2 = "ship:latest";
kubecontrol::KubePod ShipPod2(controller2,name2,type2,image2,"simulator");
nlohmann::json vars1; nlohmann::json vars1;
vars1["ENTITY_ID"] = name2; vars1["ENTITY_ID"] = name2;
@@ -68,7 +74,7 @@ nlohmann::json vars1;
vars["ENTITY_SENSORS"].push_back("radar:latest"); vars["ENTITY_SENSORS"].push_back("radar:latest");
ShipPod2.setEnvironmentVar("CONFIG", vars1.dump()); ShipPod2.setEnvironmentVar("CONFIG", vars1.dump());
auto envmaps2 = std::make_shared<std::map<std::string, std::string>>(); auto envmaps2 = std::make_shared<std::map<std::string, std::string>>();
envmaps2->emplace("CONFIG", vars1.dump()); envmaps2->emplace("CONFIG", vars1.dump());
ShipPod2.addContainer("CMS", "systemprototype:latest",envmaps2); ShipPod2.addContainer("CMS", "systemprototype:latest",envmaps2);
@@ -86,7 +92,7 @@ LOG_S(INFO)<<"started multi container pod";
{ {
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")
{ {
std::this_thread::sleep_for(std::chrono::milliseconds(5000)); std::this_thread::sleep_for(std::chrono::milliseconds(5000));
@@ -96,11 +102,11 @@ std::this_thread::sleep_for(std::chrono::milliseconds(5000));
REQUIRE(ShipPod1.getComponent() == "ship"); REQUIRE(ShipPod1.getComponent() == "ship");
REQUIRE(ShipPod1.getOwner() == "controller"); REQUIRE(ShipPod1.getOwner() == "controller");
REQUIRE(ShipPod1.getStatus() == "Running"); REQUIRE(ShipPod1.getStatus() == "Running");
REQUIRE(ShipPod1.getIp() != ""); REQUIRE(!ShipPod1.getIp().empty());
REQUIRE(ShipPod1.getPodsChilds(api).size() == 2); REQUIRE(ShipPod1.getPodsChilds(api).size() == 2);
// REQUIRE(info1 != ""); // REQUIRE(info1 != "");
ShipPod1.stop(api); ShipPod1.stop(api);
@@ -111,4 +117,4 @@ std::this_thread::sleep_for(std::chrono::milliseconds(5000));
} //THEN } //THEN
} // WHEN } // WHEN
} // GIVEN } // GIVEN
} //SCENARIO } //SCENARIO

View File

@@ -14,23 +14,24 @@
SCENARIO("Testing the SimCore Sensor") SCENARIO("Testing the SimCore Sensor")
{ {
kubecontrol::kubecontrol kc("../docs/config"); std::string file= "../docs/config";
kubecontrol::kubecontrol kubecontroler(file);
GIVEN("different Attributes for a Track in different forms") GIVEN("different Attributes for a Track in different forms")
{ {
kc.createYAML(); kubecontroler.createYAML();
kc.startPod(); kubecontroler.startPod();
// kc.getPods(); // kc.getPods();
// kc.deletePod("debug-debian"); // kc.deletePod("debug-debian");
kc.getPods(); kubecontroler.getPods();
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(true == true);
@@ -38,4 +39,4 @@ kubecontrol::kubecontrol kc("../docs/config");
} //THEN } //THEN
} // WHEN } // WHEN
} // GIVEN } // GIVEN
} //SCENARIO } //SCENARIO

View File

@@ -3,6 +3,8 @@
#include "kubecontrol/KubePod.hpp" #include "kubecontrol/KubePod.hpp"
#include "nlohmann/json_fwd.hpp" #include "nlohmann/json_fwd.hpp"
#include <math.h>
#include <string> #include <string>
#include <thread> #include <thread>
#include <vector> #include <vector>
@@ -19,7 +21,10 @@ 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)
{ {
kubecontrol::KubePod ShipPod1("controller",uuid,"ship","ship:latest","simulator"); std::string owner = "controller";
std::string type = "ship";
std::string image = "ship:latest";
kubecontrol::KubePod ShipPod1(owner,uuid,type,image,"simulator");
nlohmann::json vars; nlohmann::json vars;
vars["ENTITY_ID"] = uuid; vars["ENTITY_ID"] = uuid;
@@ -37,29 +42,30 @@ void startShip(kubecontrol::PodController* podc,std::string uuid,std::string Nam
vars["ENTITY_SENSORS"].push_back("radar:latest"); vars["ENTITY_SENSORS"].push_back("radar:latest");
ShipPod1.setEnvironmentVar("CONFIG", vars.dump()); ShipPod1.setEnvironmentVar("CONFIG", vars.dump());
podc->startPod(ShipPod1); podc->startPod(ShipPod1);
} }
void createScenario(kubecontrol::PodController* podc,std::vector<std::string> *uuidList) void createScenario(kubecontrol::PodController* podc,std::vector<std::string> *uuidList)
{ {
// GeographicLib::Geodesic geod(GeographicLib::Constants::WGS84_a(), GeographicLib::Constants::WGS84_f()); // GeographicLib::Geodesic geod(GeographicLib::Constants::WGS84_a(), GeographicLib::Constants::WGS84_f());
double lat = 54, lon = 1; double lat = 54, lon = 1;
int counter = 0; int counter = 0;
double distance = 10000; double distance = 10000;
int rasterSize = podGrid; int rasterSize = podGrid;
for (int i = 0; i < rasterSize; i++ ) for (int i = 0; i < rasterSize; i++ )
{ {
double lonTmp = lon; double lonTmp = lon;
for (int a = 0; a < rasterSize; a++) for (int a = 0; a < rasterSize; a++)
{ {
std::string name = "test"; std::string name = "test";
name += std::to_string(counter); name += std::to_string(counter);
double lat2, lon2; double lat2 = 0;
// geod.Direct(lat, lonTmp, 90, distance, lat2, lon2); double lon2 = 0;
// geod.Direct(lat, lonTmp, 90, distance, lat2, lon2);
lat2= lat+10; lat2= lat+10;
// SimCore::Identifier id; // SimCore::Identifier id;
// ids->push_back(id.getUUID()); // ids->push_back(id.getUUID());
@@ -79,7 +85,7 @@ void createScenario(kubecontrol::PodController* podc,std::vector<std::string> *u
} }
double lat2, lon2; double lat2, lon2;
// geod.Direct(lat, lon, 0, distance, lat2, lon2); // geod.Direct(lat, lon, 0, distance, lat2, lon2);
lat = lat + 10; lat = lat + 10;
@@ -92,7 +98,7 @@ void createScenario(kubecontrol::PodController* podc,std::vector<std::string> *u
SCENARIO("Testing the SimCore Sensor") SCENARIO("Testing the SimCore Sensor")
{ {
// kubecontrol::PodController podc("docs/config"); // kubecontrol::PodController podc("docs/config");
auto podc = new kubecontrol::PodController("docs/config"); auto podc = new kubecontrol::PodController("docs/config");
std::vector<std::string> uuidList; std::vector<std::string> uuidList;
@@ -121,7 +127,7 @@ std::this_thread::sleep_for(std::chrono::milliseconds(4000));
{ {
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")
{ {
auto info = podc->getInfoForPod(uuidList[random_index]); auto info = podc->getInfoForPod(uuidList[random_index]);
@@ -133,7 +139,7 @@ std::this_thread::sleep_for(std::chrono::milliseconds(4000));
// REQUIRE(info1 != ""); // REQUIRE(info1 != "");
podc->stopAllPods(); podc->stopAllPods();
@@ -141,4 +147,4 @@ std::this_thread::sleep_for(std::chrono::milliseconds(4000));
} //THEN } //THEN
} // WHEN } // WHEN
} // GIVEN } // GIVEN
} //SCENARIO } //SCENARIO

View File

@@ -3,6 +3,7 @@
#include "kubecontrol/KubePod.hpp" #include "kubecontrol/KubePod.hpp"
#include "nlohmann/json_fwd.hpp" #include "nlohmann/json_fwd.hpp"
#include <string>
#include <thread> #include <thread>
#define CATCH_CONFIG_MAIN #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp> #include <catch2/catch.hpp>
@@ -14,12 +15,15 @@
SCENARIO("Testing the SimCore Sensor") SCENARIO("Testing the SimCore Sensor")
{ {
kubecontrol::PodController podc("docs/config"); kubecontrol::PodController podc("docs/config");
std::string name = "test1"; std::string name = "test1";
std::string uuid = name; std::string uuid = name;
kubecontrol::KubePod ShipPod1("controller",uuid,"ship","ship:latest","simulator"); std::string owner = "controller";
std::string type = "ship";
std::string image = "ship:latest";
kubecontrol::KubePod ShipPod1(owner,uuid,type,image,"simulator");
nlohmann::json vars; nlohmann::json vars;
vars["ENTITY_ID"] = uuid; vars["ENTITY_ID"] = uuid;
@@ -63,9 +67,9 @@ ShipPod1.updateInfoForThisPod(podc.getKubernetesAPI());
// LOG_S(INFO)<<podc.PodList_.size();; // LOG_S(INFO)<<podc.PodList_.size();;
// for(auto i: podc.PodList_) // for(auto i: podc.PodList_)
// { // {
// LOG_S(INFO)<< i.InfoPod.Uuid; // LOG_S(INFO)<< i.InfoPod.Uuid;
// LOG_S(INFO)<< i.InfoPod.ToString(); // LOG_S(INFO)<< i.InfoPod.ToString();
// } // }
// nlohmann::json jall = nlohmann::json::parse(podc.getPodsInfo()); // nlohmann::json jall = nlohmann::json::parse(podc.getPodsInfo());
@@ -74,11 +78,11 @@ ShipPod1.updateInfoForThisPod(podc.getKubernetesAPI());
{ {
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")
{ {
auto info = podc.getInfoForPod(ShipPod1.getUUID()); auto info = podc.getInfoForPod(ShipPod1.getUUID());
for (auto item: info.Childs) for (auto item: info.Childs)
{ {
LOG_S(INFO)<<item.UUID; LOG_S(INFO)<<item.UUID;
LOG_S(INFO)<<item.IP; LOG_S(INFO)<<item.IP;
@@ -96,7 +100,7 @@ ShipPod1.updateInfoForThisPod(podc.getKubernetesAPI());
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 != "");
@@ -104,4 +108,4 @@ ShipPod1.updateInfoForThisPod(podc.getKubernetesAPI());
} //THEN } //THEN
} // WHEN } // WHEN
} // GIVEN } // GIVEN
} //SCENARIO } //SCENARIO