Compare commits

...

10 Commits

Author SHA1 Message Date
hwinkel
d265cb67f0 ADD: beautified the class and removed unnecessary class 2024-03-15 10:58:56 +01:00
Henry Winkel
ada77d0e45 FIX: Changed to const reference 2024-03-14 17:43:56 +01:00
Henry Winkel
b645005aeb ADD: added container class and adapted test 2024-03-14 09:46:37 +01:00
Henry Winkel
37627a16ca removed line 2024-03-13 17:13:14 +01:00
Henry Winkel
36ac94738d removed make test 2024-03-13 16:54:44 +01:00
Henry Winkel
81cf88f13c FIX:removed test from cmakelists 2024-03-13 16:47:23 +01:00
Henry Winkel
0e05106d1e ADD: added updated drone.yml and changed some function calls 2024-03-13 16:41:56 +01:00
Henry Winkel
48101a673a ADD: added more extracted details for a child pod and changed the data type for the child information 2024-03-12 18:08:55 +01:00
Henry Winkel
263aaa6a71 ADD: add posibility to start a pod with multiple containers 2024-03-12 15:23:37 +01:00
Henry Winkel
e38214f4d0 Updated submodules 2024-03-07 18:29:47 +01:00
22 changed files with 753 additions and 601 deletions

View File

@@ -6,26 +6,26 @@ 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
- make test
- name: CodeChecker # - name: CodeChecker
image: kmaster.ti.unibw-hamburg.de:30808/drone-ftewa-codechecker # image: kmaster.ti.unibw-hamburg.de:30808/drone-ftewa-codechecker
pull: always # pull: always
settings: # settings:
CODECHECKER_URL: "http://codechecker:8001" # CODECHECKER_URL: "http://codechecker:8001"
CODECHECKER_PRODUCT: "Kubecontrol" # CODECHECKER_PRODUCT: "kubecontrol"
CODECHECKER_USER: # CODECHECKER_USER:
from_secret: CODECHECKER_USER_SECRET # from_secret: CODECHECKER_USER_SECRET
CODECHECKER_PASS: # CODECHECKER_PASS:
from_secret: CODECHECKER_PASS_SECRET # from_secret: CODECHECKER_PASS_SECRET
when: # when:
event: # event:
include: # include:
- push # - push
- pull_request # - pull_request
--- ---
kind: secret kind: secret

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

6
.gitignore vendored
View File

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

View File

@@ -45,14 +45,8 @@ ENDIF()
ENDIF() ENDIF()
# build with CC=clang-15 CXX=clang++-15 cmake -D CMAKE_BUILD_TYPE=DEBUG ..
add_library(kubecontrol STATIC add_library(kubecontrol STATIC
include/kubecontrol/kubecontrol.hpp
src/kubecontrol/kubecontrol.cpp
include/kubecontrol/KubePod.hpp include/kubecontrol/KubePod.hpp
src/kubecontrol/KubePod.cpp src/kubecontrol/KubePod.cpp
@@ -62,9 +56,8 @@ ENDIF()
include/kubecontrol/Utils.hpp include/kubecontrol/Utils.hpp
src/kubecontrol/Utils.cpp src/kubecontrol/Utils.cpp
# include/kubecontrol/PodInfo.hpp include/kubecontrol/Container.hpp
# src/kubecontrol/PodInfo.cpp src/kubecontrol/Container.cpp
include/kubecontrol/KubernetesAPI.hpp include/kubecontrol/KubernetesAPI.hpp
src/kubecontrol/KubernetesAPI.cpp src/kubecontrol/KubernetesAPI.cpp
@@ -100,12 +93,6 @@ option(TEST_KUBECONTROL_LIBRARY "Turn running of application template specific t
IF (${TEST_KUBECONTROL_LIBRARY}) IF (${TEST_KUBECONTROL_LIBRARY})
add_executable(test_kubecontrol tests/test_kubecontrol.cpp)
target_link_libraries(test_kubecontrol Catch2::Catch2 kubecontrol )
catch_discover_tests(test_kubecontrol)
add_executable(test_KubePod tests/test_KubePod.cpp) add_executable(test_KubePod tests/test_KubePod.cpp)
target_link_libraries(test_KubePod Catch2::Catch2 kubecontrol ) target_link_libraries(test_KubePod Catch2::Catch2 kubecontrol )
catch_discover_tests(test_KubePod) catch_discover_tests(test_KubePod)

View File

@@ -0,0 +1,81 @@
#pragma once
#include <map>
#include <string>
#include <utility>
#include <kubecontrol/Utils.hpp>
#include <yaml-cpp/yaml.h>
namespace kubecontrol
{
class Container
{
public:
/**
* @brief Construct a new Container object
*
* @param Owner
* @param Uuid
* @param ContainerImage
*/
Container(const std::string &Owner, const std::string &Uuid,const std::string &Image, const PullPolicy &policy, const std::string &registry = "kmaster.ti.unibw-hamburg.de:30808");
/**
* @brief adds env to container
*
* @param env
*/
void addEnv(const std::pair<std::string, std::string> &env);
/**
* @brief add map of envs
*
* @param envs
*/
void addEnv(const std::map<std::string, std::string> &envs);
/**
* @brief Get the Owner
*
* @return
*/
std::string getOwner() { return owner_;};
/**
* @brief get the uuid
*
* @return
*/
std::string getUUID() { return uuid_;};
/**
* @brief Get the Image
*
* @return
*/
std::string getImage() { return image_;};
YAML::Node toYAML();
private:
/// @brief uuid of the container owner
std::string owner_;
/// @brief uuid of the container
std::string uuid_;
/// @brief image of the container
std::string image_;
/// @brief registry of the container
std::string registry_;
/// @brief pull Policy is a enum
PullPolicy pullPolicy_;
/// @brief environment variables
std::map<std::string, std::string> envs_;
};
}

View File

@@ -1,56 +1,179 @@
#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>
#include <cstdint>
#include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
#include <yaml-cpp/yaml.h> #include <yaml-cpp/yaml.h>
#include <fstream> #include <fstream>
#include <curlpp/Easy.hpp> #include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp> #include <curlpp/Options.hpp>
#define LOGURU_WITH_STREAMS 1
#include <loguru.hpp> #include <loguru.hpp>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <curlpp/cURLpp.hpp> #include <curlpp/cURLpp.hpp>
#include <filesystem> #include <filesystem>
#include <map> #include <kubecontrol/Container.hpp>
#include <vector>
namespace kubecontrol namespace kubecontrol
{ {
struct PodChild
{
std::string UUID;
std::string IP;
std::string Component;
std::string Status;
};
struct PodInfos
{
std::string UUID;
std::string IP;
std::string Status;
std::string Component;
std::string Owner;
std::vector<PodChild> Childs;
};
class KubePod class KubePod
{ {
public: public:
KubePod(std::string Owner, std::string Uuid, std::string ContainerImage,std::string Namespace = "simulator") ; KubePod(const std::string &Owner, const std::string &Uuid, const std::string &ContainerImage, const std::string &Namespace = "simulator") ;
KubePod(std::string Owner, std::string Uuid, std::string Component, std::string ContainerImage,std::string Namespace = "simulator"); KubePod(const std::string &Owner, const std::string &Uuid, const std::string &Component, const std::string &ContainerImage, const std::string &Namespace = "simulator");
/**
* @brief returns the uuid of the pod
*
* @return std::string
*/
std::string getUUID(); std::string getUUID();
/**
* @brief Get the Owner of the pods
*
* @return std::string
*/
std::string getOwner(); std::string getOwner();
/**
* @brief Get the Ip of the pod
*
* @return std::string
*/
std::string getIp(); std::string getIp();
/**
* @brief Get the Status
*
* @return std::string
*/
std::string getStatus(); std::string getStatus();
/**
* @brief Set the Environment Vars for pod
*
* @param key
* @param val
*/
void setEnvironmentVar(std::string key, std::string val); void setEnvironmentVar(std::string key, std::string val);
/**
* @brief Get the Environment Vars
*
* @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
*
* @param key std::string
* @return std::string
*/
std::string GetEnvironmentVar(std::string key); std::string GetEnvironmentVar(std::string key);
void setArgs(std::string args); /**
* @brief Set CMD args
*
* @param args
*/
void setArgs(const std::string &args);
/**
* @brief Get the Args
*
* @return std::vector<std::string>
*/
std::vector<std::string> GetArgs(); std::vector<std::string> GetArgs();
void setCommand(std::string command); /**
* @brief Set the Command for a pod
*
* @param command
*/
void setCommand(const std::string &command);
/**
* @brief Get the Command
*
* @return std::string
*/
std::string getCommand(); std::string getCommand();
void setComponent(std::string component); /**
* @brief Set the Component var for the pod
*
* @param component
*/
void setComponent(const std::string &component);
/**
* @brief Get the Component var
*
* @return std::string
*/
std::string getComponent(); std::string getComponent();
/**
* @brief add a Container to a pod
*
* @param name std::string
* @param image std::string
* @param envs std::map<std::string,std:.string>
* @param PullPolicy std::string (defualt: Always) possible:( IfNotPresent, Never)
*/
void addContainer(std::string name,std::string image, std::map<std::string, std::string> &envs , kubecontrol::PullPolicy pullPolicy = ALWAYS);
/**
* @brief add container object
*
* @param containter
*/
void addContainer(Container containter);
/**
* @brief
*
* @param containerUUID
* @param envs
*/
void addEnvValuesToContainer(std::string containerUUID, std::map<std::string, std::string> envs);
/** /**
* @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
@@ -71,34 +194,49 @@ namespace kubecontrol
*/ */
int updateInfoForThisPod(KubernetesAPI APIInterface); int updateInfoForThisPod(KubernetesAPI APIInterface);
std::vector<std::string> getUUIDsForChildPods(KubernetesAPI APIInterface); std::vector<PodChild> getPodsChilds(KubernetesAPI APIInterface);
private: private:
/// @brief maximum time to wait of the response when creating a pod
static const int MaxWaitTimeInSeconds; static const int MaxWaitTimeInSeconds;
/// @brief uuid of the owner
std::string Owner_; std::string Owner_;
/// @brief uuid of the pod
std::string Uuid_; std::string Uuid_;
/// @brief name of the pod
std::string Name_; std::string Name_;
/// @brief component the pod represents
std::string Component_; std::string Component_;
std::string ContainerImage_; /// @brief vector of images the pod contains
std::vector<Container> ContainerImages_;
/// @brief url of the container registry
std::string ContainerRegistry_; std::string ContainerRegistry_;
/// @brief path to kube yaml
std::string PathToYaml_; std::string PathToYaml_;
/// @brief namespace the pod is designated
std::string Namespace_; std::string Namespace_;
/// @brief IP of the pod
std::string Ip_; std::string Ip_;
/// @brief status of the pod
std::string Status_; std::string Status_;
/// @brief uuid of pod this pod is part of
std::string PartOf_; std::string PartOf_;
std::vector<std::string> uuidsOfShildContainers; /// @brief vector of child pods
std::vector<PodChild> ChildPods;
/// @brief command the pod schould execute when created
std::string PodCommand_; std::string PodCommand_;
/// @brief yaml node of the pod which is used for creation
YAML::Node YAMLNode_; YAML::Node YAMLNode_;
/// @brief environment vars of the pod
std::map<std::string, std::string> EnvirmonentVars_; std::map<std::string, std::string> EnvirmonentVars_;
/// @brief arguments for the pod
std::vector<std::string> Args_; std::vector<std::string> Args_;
/**
* @brief function to create the yaml string for the pod creation
* @return std::string - returns a serialized yaml
*/
std::string createYAML(); std::string createYAML();
/** /**

View File

@@ -1,6 +1,8 @@
#pragma once #pragma once
#include <yaml-cpp/node/node.h> #include <yaml-cpp/node/node.h>
#include <string> #include <string>
#define LOGURU_WITH_STREAMS 1
#include <loguru.hpp>
namespace kubecontrol namespace kubecontrol
@@ -10,23 +12,69 @@ class KubernetesAPI
{ {
public: public:
KubernetesAPI(); KubernetesAPI();
KubernetesAPI(YAML::Node config); /**
* constructor of the Kubernetes API
* @param config - yaml node of the designated users kubectl yaml
*/
explicit KubernetesAPI(YAML::Node config);
/**
* @brief costructor of Kuernetes API object
*/
KubernetesAPI(std::string APIAddress, std::string Token); KubernetesAPI(std::string APIAddress, std::string Token);
/**
* @brief performs a request to the kubernetes API
* @param request - string of the request
* @param Methode - string (eg. GET, POST)
* @result string - respone of the requestS
*/
std::string performRequest(std::string request,std::string Methode = "GET"); std::string performRequest(std::string request,std::string Methode = "GET");
/**
* @brief performs a request to the kubernetes API
* @param request - string of the request
* @param Methode - string (eg. GET, POST)
* @param PostFields - string of the post fields which are sended in the request
* @return string - respone of the requestS
*/
std::string performRequest(std::string request,std::string Methode,std::string PostFields); std::string performRequest(std::string request,std::string Methode,std::string PostFields);
/**
* @brief adds address of the kubernetes api
* @param address - string
*/
void addAddress(std::string address); void addAddress(std::string address);
/**
* @brief returns the address of the kubrnetes api stored in the object
* @return std::string returns the address
*/
std::string getAddress(); std::string getAddress();
/**
* @brief add the bearer token which is necessary to access the api
* @param Token - string
*/
void addToken(std::string Token); void addToken(std::string Token);
/**
* @brief adds the yaml node which is required to hold all necessary data to access the api
* @param conifg - YAML::Node object of the parsed file
*/
void addYaml(YAML::Node config); void addYaml(YAML::Node config);
/**
* @brief returns the namespace the object uses
* @return string
*/
std::string getNamespace(); std::string getNamespace();
private: private:
/// @brief api adress
std::string APIAddress_; std::string APIAddress_;
/// @brief bearer token
std::string Token_; std::string Token_;
/// @brief namespace
std::string Namespace_; std::string Namespace_;
}; };

View File

@@ -10,44 +10,81 @@
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:
PodController(std::string pathToKubectlConfig); /**
* @brief constructs the podcontroller
* @param pathToKubectlConfig - string path to the kubectl config file
*/
explicit PodController(std::string pathToKubectlConfig);
std::string getServerAddress(); /**
* @brief returns the Server Address of the given kubernetes api
* @return string
*/
std::string getServerAddress();
void startPod(KubePod Pod,bool WaitTillRunning = true ); /**
void startPod(std::shared_ptr<KubePod> Pod,bool WaitTillRunning = true ); * @brief starts a pod
* @param Pod - pod objet
* @param WaitTillRunning - bool (default: true) indicates if the controller should wait till the pod is startet
*/
void startPod(KubePod Pod,bool WaitTillRunning = true );
void stopPod(std::string uuid); /**
void stopAllPods(); * @brief starts a pod
* @param Pod - std::shared_ptr<KubePod> objet
* @param WaitTillRunning - bool (default: true) indicates if the controller should wait till the pod is startet
*/
void startPod(std::shared_ptr<KubePod> Pod,bool WaitTillRunning = true );
std::vector<PodInfos> getInfoForAllPods(); /**
PodInfos getInfoForPod(std::string uuid); * @brief stops a pod referenced by its uuid
* @param uuid - string
*/
void stopPod(std::string uuid);
KubernetesAPI getKubernetesAPI(); /**
* @brief stops all pods the controller knows
*/
void stopAllPods();
/**
* @brief returns a vector of PodInfos of all pod
* @return std::vector<PodInfos>
*/
std::vector<PodInfos> getInfoForAllPods();
/**
* @brief returns a PodInfo object of a specific pod
* @param uuid - string
* @return PodInfo
*/
PodInfos getInfoForPod(std::string uuid);
/**
* @brief retursn a copy of ne current used kubernetes API
*/
KubernetesAPI getKubernetesAPI();
private: private:
KubernetesAPI APIInterface_; /// @brief object of the kubernetes api object
std::vector<std::unique_ptr<KubePod>> PodList_; KubernetesAPI APIInterface_;
/// @brief vector of unique poitners of owned KubePod objects
std::vector<std::unique_ptr<KubePod>> PodList_;
/// @brief current namespace
std::string Namespace_;
/// @brief base apiCall (default: "/api/v1/namespaces/Simulator/pods/")
std::string ApiCall_;
/**
* @brief gets infos for specific pod
*/
PodInfos extractInfosFromKubePod(KubePod *pod);
std::string Namespace_; /// @brief mutex
std::string ApiCall_; mutable std::mutex mx_;
PodInfos extractInfosFromKubePod(KubePod *pod);
mutable std::mutex mx_;
}; };
} // namespace ku } // namespace ku

View File

@@ -1,15 +1,40 @@
#pragma once #pragma once
#include <kubecontrol/KubePod.hpp>
#include <string> #include <string>
#include <algorithm> #include <algorithm>
namespace kubecontrol namespace kubecontrol
{ {
enum PullPolicy: uint32_t
{
ALWAYS,
IFNOTPRESENT,
NEVER
};
/**
* @brief translate PullPolicy enum to string
*/
inline std::string toString(const PullPolicy &kind)
{
switch (kind)
{
case PullPolicy::ALWAYS: return "Always";
case PullPolicy::IFNOTPRESENT: return "IfNotPresent";
case PullPolicy::NEVER: return "Never";
default: return "Always";
}
}
class Utils class Utils
{ {
public: public:
/**
* @brief lowercase a string
*/
static std::string to_lower(std::string); static std::string to_lower(std::string);
}; };

View File

@@ -1,25 +0,0 @@
#pragma once
#include <string>
#include <yaml-cpp/yaml.h>
namespace kubecontrol
{
class kubecontrol
{
public:
kubecontrol(std::string pathToKubectlConfig);
void getPods();
void startPod();
void deletePod(std::string uid);
std::string createYAML();
private:
std::string BearerToken_;
std::string ServerAddress_;
std::string NameSpace_;
};
}

View File

@@ -0,0 +1,55 @@
#include <kubecontrol/Container.hpp>
namespace kubecontrol
{
Container::Container(const std::string &Owner, const std::string &Uuid, const std::string &Image, const PullPolicy &policy, const std::string &registry ):
owner_(Utils::to_lower(Owner)),
uuid_(Utils::to_lower(Uuid)),
image_(Utils::to_lower(Image)),
pullPolicy_(policy),
registry_(registry)
{
}
void Container::addEnv(const std::pair<std::string, std::string> &env)
{
this->envs_.emplace(env);
}
void Container::addEnv(const std::map<std::string, std::string> &envs)
{
this->envs_ = envs;
}
YAML::Node Container::toYAML()
{
YAML::Node container;
container["name"] = uuid_+"-container";
container["image"] = this->registry_ + "/"+image_;
container["imagePullPolicy"] = toString(pullPolicy_);
if (!envs_.empty())
{
int lauf = 0;
for(auto [key,value] : envs_)
{
container["env"][lauf]["name"] = key;
container["env"][lauf]["value"] = value;
lauf++;
}
}
return container;
}
}

View File

@@ -1,72 +1,115 @@
#include <kubecontrol/KubePod.hpp>
#include "curlpp/Options.hpp" #include "curlpp/Options.hpp"
#include "kubecontrol/Container.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"
#include <cctype>
#include <exception> #include <exception>
#include <fstream> #include <fstream>
#include <future>
#include <iterator> #include <iterator>
#include <kubecontrol/KubePod.hpp> #include <map>
#include <memory>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <thread> #include <thread>
#include <filesystem>
#include "loguru.hpp"
namespace kubecontrol namespace kubecontrol
{ {
KubePod::KubePod(std::string Owner, std::string Uuid, std::string ContainerImage,std::string Namespace)
KubePod::KubePod(const std::string &Owner, const std::string &Uuid, const std::string &ContainerImage, const std::string &Namespace)
:Owner_(Utils::to_lower(Owner)), :Owner_(Utils::to_lower(Owner)),
Uuid_(Utils::to_lower(Uuid)), Uuid_(Utils::to_lower(Uuid)),
ContainerImage_(ContainerImage), ContainerRegistry_("kmaster.ti.unibw-hamburg.de:30808"),
Namespace_(Namespace), Namespace_(Namespace)
EnvirmonentVars_()
{ {
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");
} }
auto map = std::map<std::string, std::string>();
addContainer(Uuid, ContainerImage,map);
} }
KubePod::KubePod(std::string Owner, std::string Uuid, std::string Component, std::string ContainerImage,std::string Namespace): KubePod::KubePod(const std::string &Owner, const std::string &Uuid, const std::string &Component, const std::string &ContainerImage, const 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)),
ContainerImage_(ContainerImage), ContainerRegistry_("kmaster.ti.unibw-hamburg.de:30808"),
Namespace_(Namespace), Namespace_(Namespace)
EnvirmonentVars_()
{ {
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");
} }
auto map = std::map<std::string, std::string>();
addContainer(Uuid, ContainerImage,map);
} }
void KubePod::addContainer(std::string name,std::string image, std::map<std::string, std::string> &envs, PullPolicy pullPolicy )
{
Container container(Owner_,name,image,pullPolicy);
container.addEnv(envs);
ContainerImages_.push_back(container);
}
void KubePod::addContainer(Container containter)
{
ContainerImages_.push_back(containter);
}
void KubePod::addEnvValuesToContainer(std::string containerUUID, std::map<std::string, std::string> envs)
{
for (auto container: ContainerImages_)
{
if (container.getUUID() == containerUUID +"-container")
{
container.addEnv(envs);
}
}
}
std::string KubePod::getUUID() std::string KubePod::getUUID()
{ {
@@ -101,12 +144,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(const std::string &args)
{ {
Args_.emplace_back(Utils::to_lower(args)); Args_.emplace_back(Utils::to_lower(args));
} }
@@ -116,7 +159,7 @@ namespace kubecontrol
return Args_; return Args_;
} }
void KubePod::setCommand(std::string command) void KubePod::setCommand(const std::string &command)
{ {
PodCommand_ = Utils::to_lower(command); PodCommand_ = Utils::to_lower(command);
} }
@@ -126,7 +169,7 @@ namespace kubecontrol
return PodCommand_; return PodCommand_;
} }
void KubePod::setComponent(std::string component) void KubePod::setComponent(const std::string &component)
{ {
this->Component_ = Utils::to_lower(component); this->Component_ = Utils::to_lower(component);
} }
@@ -136,7 +179,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;
} }
@@ -164,24 +207,34 @@ 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_;
node["spec"]["containers"][0]["name"] = this->Uuid_+"-container";
node["spec"]["containers"][0]["image"] = this->ContainerRegistry_ + "/" + this->ContainerImage_; for (int i = 0; i< this->ContainerImages_.size(); i++)
node["spec"]["containers"][0]["imagePullPolicy"] = "Always"; {
node["spec"]["containers"][0]["ports"][0]["containerPort"] = 10000; node["spec"]["containers"][i] = this->ContainerImages_[i].toYAML();
node["spec"]["containers"][0]["ports"][0]["protocol"] = "UDP"; // node["spec"]["containers"][i]["name"] = this->Uuid_+"-container";
// node["spec"]["containers"][i]["image"] = this->ContainerRegistry_ + "/" + this->ContainerImages_[i];
// node["spec"]["containers"][i]["imagePullPolicy"] = imagePullPolicy;
// node["spec"]["containers"][i]["ports"][0]["containerPort"] = 10000;
// 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);
} }
} }
@@ -224,7 +277,7 @@ 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_;
@@ -257,14 +310,14 @@ namespace kubecontrol
int KubePod::stopChilds(KubernetesAPI APIInterface) int KubePod::stopChilds(KubernetesAPI APIInterface)
{ {
auto uuids = this->getUUIDsForChildPods(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; std::string request = "/api/v1/namespaces/simulator/pods/"+uuid.UUID;
std::string result = APIInterface.performRequest(request,"DELETE"); std::string result = APIInterface.performRequest(request,"DELETE");
} }
@@ -279,7 +332,7 @@ 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;
} }
@@ -292,25 +345,25 @@ namespace kubecontrol
} }
std::vector<std::string> KubePod::getUUIDsForChildPods( KubernetesAPI APIInterface) std::vector<PodChild> KubePod::getPodsChilds( KubernetesAPI APIInterface)
{ {
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<std::string>(); return {};
} }
extractInformationFromResopnse(result); extractInformationFromResopnse(result);
return this->uuidsOfShildContainers; return this->ChildPods;
} }
int KubePod::extractInformationFromResopnse(std::string response) int KubePod::extractInformationFromResopnse(std::string response)
{ {
if (response == "") if (response.empty())
{ {
return 1 ; return 1 ;
} }
@@ -327,15 +380,22 @@ namespace kubecontrol
}else if(j.contains("items") && j["items"].is_array()) }else if(j.contains("items") && j["items"].is_array())
{ {
for (auto i : j["items"]) for (auto i : j["items"])
{ {
this->uuidsOfShildContainers.push_back(i["metadata"]["name"].get<std::string>()); // LOG_S(INFO)<<i;
PodChild child;
child.UUID =i["metadata"]["name"].get<std::string>();
child.IP = i["status"]["podIP"].get<std::string>();
child.Status = i["status"]["phase"].get<std::string>();
child.Component = i["metadata"]["labels"]["app.kubernetes.io/component"].get<std::string>();
this->ChildPods.push_back(child);
} }
}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();
@@ -357,4 +417,3 @@ namespace kubecontrol
} }

View File

@@ -7,8 +7,6 @@
#include <sstream> #include <sstream>
#include <yaml-cpp/yaml.h> #include <yaml-cpp/yaml.h>
#include <loguru.hpp>
@@ -108,7 +106,7 @@ namespace kubecontrol {
try { try {
curlRequest.perform(); curlRequest.perform();
} catch (const std::exception e) { } catch (const std::exception &e) {
LOG_S(ERROR)<<e.what(); LOG_S(ERROR)<<e.what();
} }
curlRequest.reset(); curlRequest.reset();

View File

@@ -20,9 +20,7 @@ namespace kubecontrol
PodController::PodController(std::string pathToKubectlConfig): PodController::PodController(std::string pathToKubectlConfig):
APIInterface_( YAML::LoadFile(pathToKubectlConfig)) APIInterface_( YAML::LoadFile(pathToKubectlConfig))
{ {
ApiCall_ = "/api/v1/namespaces/"+APIInterface_.getNamespace()+"/pods/"; ApiCall_ = "/api/v1/namespaces/"+APIInterface_.getNamespace()+"/pods/";
} }
std::string PodController::getServerAddress() std::string PodController::getServerAddress()
@@ -37,13 +35,15 @@ namespace kubecontrol
void PodController::startPod(KubePod Pod,bool WaitTillRunning ) void PodController::startPod(KubePod Pod,bool WaitTillRunning )
{ {
LOG_S(INFO)<< "starting pod: "<<Pod.getUUID(); LOG_S(INFO)<< "starting pod: "<<Pod.getUUID();
// auto response = Pod.start(ServerAddress_+ApiCall_, BearerToken_,WaitTillRunning); int response = Pod.start(APIInterface_,WaitTillRunning);
auto response = Pod.start(APIInterface_,WaitTillRunning); if (response != 0)
{
throw std::invalid_argument( "could not start pod" );
}
std::lock_guard<std::mutex>lock(mx_); std::lock_guard<std::mutex>lock(mx_);
PodList_.emplace_back(std::make_unique<KubePod>(Pod)); PodList_.emplace_back(std::make_unique<KubePod>(Pod));
@@ -55,8 +55,11 @@ namespace kubecontrol
{ {
LOG_S(INFO)<< "starting pod: "<<Pod->getUUID(); LOG_S(INFO)<< "starting pod: "<<Pod->getUUID();
// auto response = Pod.start(ServerAddress_+ApiCall_, BearerToken_,WaitTillRunning); // auto response = Pod.start(ServerAddress_+ApiCall_, BearerToken_,WaitTillRunning);
auto response = Pod->start(APIInterface_,WaitTillRunning); int response = Pod->start(APIInterface_,WaitTillRunning);
if (response != 0)
{
throw std::invalid_argument( "could not start pod" );
}
std::lock_guard<std::mutex>lock(mx_); std::lock_guard<std::mutex>lock(mx_);
PodList_.emplace_back(std::make_unique<KubePod>(*Pod)); PodList_.emplace_back(std::make_unique<KubePod>(*Pod));
} }
@@ -65,18 +68,15 @@ namespace kubecontrol
void PodController::stopPod(std::string uuid) void PodController::stopPod(std::string uuid)
{ {
std::lock_guard<std::mutex>lock(mx_); std::lock_guard<std::mutex>lock(mx_);
// PodList_
for (std::vector<std::unique_ptr<KubePod>>::iterator it = PodList_.begin(); it != PodList_.end();) for (std::vector<std::unique_ptr<KubePod>>::iterator it = PodList_.begin(); it != PodList_.end();)
{ {
if (uuid == it->get()->getUUID())
if (uuid == it->get()->getUUID())
{
it->get()->stop(APIInterface_);
it = PodList_.erase(it);
}
else
{ {
it++; it->get()->stop(APIInterface_);
it = PodList_.erase(it);
}else
{
it++;
} }
} }
@@ -111,7 +111,6 @@ namespace kubecontrol
return infosOfAllPods; return infosOfAllPods;
} }
@@ -141,55 +140,9 @@ namespace kubecontrol
info.Component =pod->getComponent(); info.Component =pod->getComponent();
info.IP = pod->getIp(); info.IP = pod->getIp();
info.Status = pod->getStatus(); info.Status = pod->getStatus();
info.UUIDOfChilds = pod->getUUIDsForChildPods(APIInterface_); info.Childs = pod->getPodsChilds(APIInterface_);
return info; return info;
} }
// 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;
// }
} }

View File

@@ -1,240 +0,0 @@
#include "nlohmann/json_fwd.hpp"
#include "yaml-cpp/binary.h"
#include "yaml-cpp/emitter.h"
#include "yaml-cpp/emitterdef.h"
#include "yaml-cpp/emittermanip.h"
#include "yaml-cpp/emitterstyle.h"
#include "yaml-cpp/node/convert.h"
#include "yaml-cpp/node/node.h"
#include <iomanip>
#include <kubecontrol/kubecontrol.hpp>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <curlpp/Exception.hpp>
#include <sstream>
#include <string>
#include <yaml-cpp/yaml.h>
#include <loguru.hpp>
#include <nlohmann/json.hpp>
#include <iostream>
#include <fstream>
namespace kubecontrol
{
kubecontrol::kubecontrol(std::string pathToKubectlConfig)
{
YAML::Node config = YAML::LoadFile(pathToKubectlConfig);
BearerToken_ = config["users"][0]["user"]["token"].as<std::string>();
ServerAddress_ = config["clusters"][0]["cluster"]["server"].as<std::string>();
}
void kubecontrol::getPods()
{
std::string curlURL = ServerAddress_+"/api/v1/namespaces/simulator/pods/";
std::string AuthString = "Authorization: Bearer " + BearerToken_;
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::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();
auto response = result.str();
auto j = nlohmann::json::parse(response);
LOG_S(INFO)<<j["items"][0]["metadata"];
// std::cout << readBuffer << std::endl;
}
void kubecontrol::startPod()
{
std::string curlURL = ServerAddress_+"/api/v1/namespaces/simulator/pods/";
std::string AuthString = "Authorization: Bearer " + BearerToken_;
std::list<std::string> headers;
headers.push_back(AuthString);
headers.push_back("Content-Type: application/yaml");
curlpp::Cleanup cleaner;
curlpp::Easy request;
// WriterMemoryClass mWriterChunk;
// 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);
// 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::Post(true));
auto yaml = createYAML();
// YAML::Node node = YAML::LoadFile("config/pods_deployment.yaml");
// YAML::Binary node = YAML::LoadFile("config/pods_deployment.yaml");
// LOG_S(INFO)<< node["spec"]["containers"][0]["imagePullPolicy"];
// YAML::Binary binary = node.as<YAML::Binary>();
std::ifstream is;
is.open ("config/pods_deployment.yaml", std::ios::binary );
// get length of file:
is.seekg (0, std::ios::end);
long length = is.tellg();
is.seekg (0, std::ios::beg);
// allocate memory:
char *buffer = new char [length];
// read data as a block:
is.read (buffer,length);
std::istringstream myStream((std::string( buffer )));
int size = myStream.str().size();
is.close();
request.setOpt(new curlpp::options::PostFields(buffer));
// request.setOpt(new curlpp::options::Verbose(true));
request.perform();
auto response = result.str();
LOG_S(INFO)<<response;
}
void kubecontrol::deletePod(std::string uid)
{
std::string curlURL = ServerAddress_+"/api/v1/namespaces/simulator/pods/"+ uid;
std::string AuthString = "Authorization: Bearer " + BearerToken_;
std::list<std::string> headers;
headers.push_back(AuthString);
// headers.push_back("Content-Type: application/yaml");
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::SslEngineDefault());
request.setOpt(new curlpp::options::CaPath("config/ca.crt"));
request.setOpt(new curlpp::options::SslVerifyPeer(false));
// request.setOpt(new curlpp::options::Post(true));
// request.setOpt(new curlpp::options::PostFields("DELETE"));
request.setOpt(new curlpp::options::CustomRequest("DELETE"));
// request.setOpt(new curlpp::options::Verbose(true));
request.perform();
auto response = result.str();
// LOG_S(INFO)<<response;
}
std::string kubecontrol::createYAML()
{
YAML::Node node;
node["apiVersion"] = "v1";
node["kind"] = "Pod";
node["metadata"]["name"] = "debug-debian";
node["metadata"]["labels"]["app.kubernetes.io/name"] = "plaindebian";
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]["imagePullPolicy"] = "\"Always\"";
node["spec"]["containers"][0]["env"][0]["name"] = "OWN_SHIP_SERVER";
node["spec"]["containers"][0]["env"][0]["value"] = "127.0.0.1";
node["spec"]["containers"][0]["env"][1]["name"] = "TOKEN";
node["spec"]["containers"][0]["env"][1]["value"] = BearerToken_;
node["spec"]["containers"][0]["args"].SetStyle(YAML::EmitterStyle::Flow);
node["spec"]["containers"][0]["args"].push_back("-c");
node["spec"]["containers"][0]["args"].push_back("while true; do echo hello; sleep 5;done");
node["spec"]["containers"][0]["command"].SetStyle(YAML::EmitterStyle::Flow);
node["spec"]["containers"][0]["command"].push_back("/bin/sh");
node["spec"]["restartPolicy"] = "Never";
std::ofstream fout("config/pods_deployment.yaml");
std::stringstream ss;
ss <<node;
LOG_S(INFO)<< node;
fout << ss.str();
fout.close();
return "config/pods_deployment.yaml";
}
}

View File

@@ -3,23 +3,29 @@
#include "kubecontrol/PodController.hpp" #include "kubecontrol/PodController.hpp"
#include "nlohmann/json_fwd.hpp" #include "nlohmann/json_fwd.hpp"
#include <memory>
#include <string>
#include <thread> #include <thread>
#define CATCH_CONFIG_MAIN #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp> #include <catch2/catch.hpp>
#include "loguru.hpp" #include "loguru.hpp"
SCENARIO("Testing the SimCore Sensor") SCENARIO("Testing KubePod")
{ {
// kubecontrol::PodController podc("docs/config"); // kubecontrol::PodController podc("docs/config");
kubecontrol::KubernetesAPI api(YAML::LoadFile("docs/config")); kubecontrol::KubernetesAPI api(YAML::LoadFile("docs/config"));
std::string name = "hamburg"; std::string name = "componenttest1";
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;
@@ -45,8 +51,42 @@ LOG_S(INFO)<<"Starting";
ShipPod1.start(api); ShipPod1.start(api);
LOG_S(INFO)<<"started"; LOG_S(INFO)<<"started";
std::string name2 = "componenttest2";
std::string controller2 = "controller";
std::string type2 = "ship";
std::string image2 = "ship:latest";
kubecontrol::KubePod ShipPod2(controller2,name2,type2,image2,"simulator");
nlohmann::json vars1;
vars1["ENTITY_ID"] = name2;
vars1["ENTITY_NAME"] = "FGS Hamburg";
vars1["ENTITY_SIDE"] = "Neutral";
vars1["POSITION"]["LAT"] = "55";
vars1["POSITION"]["LON"] = "8";
vars1["POSITION"]["Height"] = "0";
vars1["COURSE"] = "0";
vars1["SPEED"] = "0";
vars1["GROUNDTRUTH_PORT"] = std::to_string(10000);
vars1["GROUNDTRUTH_ADDR"] = "239.0.0.1";
vars1["COMMAND_PORT"] = "5555";
vars1["ENTITY_RCS"] = std::to_string(850);
vars["ENTITY_SENSORS"].push_back("radar:latest");
ShipPod2.setEnvironmentVar("CONFIG", vars1.dump());
auto envmaps2 = std::map<std::string, std::string>();
envmaps2.emplace("CONFIG", vars1.dump());
ShipPod2.addContainer("CMS", "systemprototype:latest",envmaps2);
ShipPod2.setEnvironmentVar("CONFIG", vars.dump());
LOG_S(INFO)<<"Starting multi container pod";
ShipPod2.start(api);
LOG_S(INFO)<<"started multi container pod";
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")
{ {
@@ -55,20 +95,22 @@ std::this_thread::sleep_for(std::chrono::milliseconds(5000));
THEN("check if Track attributes are correct") THEN("check if Track attributes are correct")
{ {
REQUIRE(ShipPod1.getUUID() == "hamburg"); std::this_thread::sleep_for(std::chrono::milliseconds(5000));
REQUIRE(ShipPod1.getUUID() == name);
REQUIRE(ShipPod1.getName() == name); REQUIRE(ShipPod1.getName() == name);
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.getUUIDsForChildPods(api).size() == 2); REQUIRE(ShipPod1.getPodsChilds(api).size() == 3);
// REQUIRE(info1 != ""); // REQUIRE(info1 != "");
ShipPod1.stop(api); ShipPod1.stop(api);
ShipPod2.stop(api);

View File

@@ -1,41 +0,0 @@
#include "yaml-cpp/binary.h"
#include "yaml-cpp/emitter.h"
#include "yaml-cpp/node/node.h"
#include "yaml-cpp/node/parse.h"
#include <string>
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <kubecontrol/kubecontrol.hpp>
#include <loguru.hpp>
SCENARIO("Testing the SimCore Sensor")
{
kubecontrol::kubecontrol kc("../docs/config");
GIVEN("different Attributes for a Track in different forms")
{
kc.createYAML();
kc.startPod();
// kc.getPods();
// kc.deletePod("debug-debian");
kc.getPods();
WHEN("constructing Track Object with data")
{
THEN("check if Track attributes are correct")
{
REQUIRE(true == true);
} //THEN
} // WHEN
} // GIVEN
} //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;
@@ -58,7 +63,8 @@ void createScenario(kubecontrol::PodController* podc,std::vector<std::string> *u
std::string name = "test"; std::string name = "test";
name += std::to_string(counter); name += std::to_string(counter);
double lat2, lon2; double lat2 = 0;
double lon2 = 0;
// geod.Direct(lat, lonTmp, 90, distance, lat2, lon2); // geod.Direct(lat, lonTmp, 90, distance, lat2, lon2);
lat2= lat+10; lat2= lat+10;
// SimCore::Identifier id; // SimCore::Identifier id;
@@ -89,7 +95,7 @@ void createScenario(kubecontrol::PodController* podc,std::vector<std::string> *u
SCENARIO("Testing the SimCore Sensor") SCENARIO("Testing massiv pod handling")
{ {

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>
@@ -11,15 +12,17 @@
#include <crossguid/guid.hpp> #include <crossguid/guid.hpp>
SCENARIO("Testing the SimCore Sensor") SCENARIO("Testing podcontroler ")
{ {
kubecontrol::PodController podc("docs/config"); kubecontrol::PodController podc("docs/config");
std::string name = "hamburg"; std::string name = "test1";
std::string uuid = name; std::string uuid = name;
kubecontrol::KubePod ShipPod1("controller",uuid,"ship","ship:latest","simulator"); std::string type = "ship";
std::string image = "ship:latest";
kubecontrol::KubePod ShipPod1("controller",uuid,type,image,"simulator");
nlohmann::json vars; nlohmann::json vars;
vars["ENTITY_ID"] = uuid; vars["ENTITY_ID"] = uuid;
@@ -78,6 +81,15 @@ ShipPod1.updateInfoForThisPod(podc.getKubernetesAPI());
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)
{
LOG_S(INFO)<<item.UUID;
LOG_S(INFO)<<item.IP;
LOG_S(INFO)<<item.Component;
LOG_S(INFO)<<item.Status;
}
REQUIRE(info.UUID == ShipPod1.getUUID()); REQUIRE(info.UUID == ShipPod1.getUUID());
REQUIRE(info.IP == ShipPod1.getIp()); REQUIRE(info.IP == ShipPod1.getIp());
REQUIRE(info.Owner == ShipPod1.getOwner()); REQUIRE(info.Owner == ShipPod1.getOwner());