ADD: beautified the class and removed unnecessary class

This commit is contained in:
hwinkel
2024-03-15 10:58:56 +01:00
parent ada77d0e45
commit d265cb67f0
13 changed files with 186 additions and 440 deletions

View File

@@ -11,21 +11,21 @@ steps:
- CC=clang-11 CXX=clang++-11 cmake -DCMAKE_BUILD_TYPE=DEBUG ..
- make -j
- name: CodeChecker
image: kmaster.ti.unibw-hamburg.de:30808/drone-ftewa-codechecker
pull: always
settings:
CODECHECKER_URL: "http://codechecker:8001"
CODECHECKER_PRODUCT: "kubecontrol"
CODECHECKER_USER:
from_secret: CODECHECKER_USER_SECRET
CODECHECKER_PASS:
from_secret: CODECHECKER_PASS_SECRET
when:
event:
include:
- push
- pull_request
# - name: CodeChecker
# image: kmaster.ti.unibw-hamburg.de:30808/drone-ftewa-codechecker
# pull: always
# settings:
# CODECHECKER_URL: "http://codechecker:8001"
# CODECHECKER_PRODUCT: "kubecontrol"
# CODECHECKER_USER:
# from_secret: CODECHECKER_USER_SECRET
# CODECHECKER_PASS:
# from_secret: CODECHECKER_PASS_SECRET
# when:
# event:
# include:
# - push
# - pull_request
---
kind: secret

View File

@@ -45,14 +45,8 @@ ENDIF()
ENDIF()
# build with CC=clang-15 CXX=clang++-15 cmake -D CMAKE_BUILD_TYPE=DEBUG ..
add_library(kubecontrol STATIC
include/kubecontrol/kubecontrol.hpp
src/kubecontrol/kubecontrol.cpp
include/kubecontrol/KubePod.hpp
src/kubecontrol/KubePod.cpp
@@ -99,12 +93,6 @@ option(TEST_KUBECONTROL_LIBRARY "Turn running of application template specific t
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)
target_link_libraries(test_KubePod Catch2::Catch2 kubecontrol )
catch_discover_tests(test_KubePod)

View File

@@ -63,11 +63,17 @@ namespace kubecontrol
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

@@ -12,9 +12,9 @@
#include <fstream>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#define LOGURU_WITH_STREAMS 1
#include <loguru.hpp>
#include <nlohmann/json.hpp>
#include <curlpp/cURLpp.hpp>
#include <filesystem>
#include <kubecontrol/Container.hpp>
@@ -198,32 +198,45 @@ namespace kubecontrol
private:
/// @brief maximum time to wait of the response when creating a pod
static const int MaxWaitTimeInSeconds;
/// @brief uuid of the owner
std::string Owner_;
/// @brief uuid of the pod
std::string Uuid_;
/// @brief name of the pod
std::string Name_;
/// @brief component the pod represents
std::string Component_;
/// @brief vector of images the pod contains
std::vector<Container> ContainerImages_;
// std::string ContainerImage_;
/// @brief url of the container registry
std::string ContainerRegistry_;
/// @brief path to kube yaml
std::string PathToYaml_;
/// @brief namespace the pod is designated
std::string Namespace_;
/// @brief IP of the pod
std::string Ip_;
/// @brief status of the pod
std::string Status_;
/// @brief uuid of pod this pod is part of
std::string PartOf_;
/// @brief vector of child pods
std::vector<PodChild> ChildPods;
/// @brief command the pod schould execute when created
std::string PodCommand_;
/// @brief yaml node of the pod which is used for creation
YAML::Node YAMLNode_;
/// @brief environment vars of the pod
std::map<std::string, std::string> EnvirmonentVars_;
/// @brief arguments for the pod
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();
/**

View File

@@ -1,6 +1,8 @@
#pragma once
#include <yaml-cpp/node/node.h>
#include <string>
#define LOGURU_WITH_STREAMS 1
#include <loguru.hpp>
namespace kubecontrol
@@ -10,23 +12,69 @@ class KubernetesAPI
{
public:
KubernetesAPI();
/**
* 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);
/**
* @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");
/**
* @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);
/**
* @brief adds address of the kubernetes api
* @param address - string
*/
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();
/**
* @brief add the bearer token which is necessary to access the api
* @param Token - string
*/
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);
/**
* @brief returns the namespace the object uses
* @return string
*/
std::string getNamespace();
private:
/// @brief api adress
std::string APIAddress_;
/// @brief bearer token
std::string Token_;
/// @brief namespace
std::string Namespace_;
};

View File

@@ -14,32 +14,77 @@ namespace kubecontrol
class PodController
{
public:
explicit PodController(std::string pathToKubectlConfig);
/**
* @brief constructs the podcontroller
* @param pathToKubectlConfig - string path to the kubectl config file
*/
explicit PodController(std::string pathToKubectlConfig);
/**
* @brief returns the Server Address of the given kubernetes api
* @return string
*/
std::string getServerAddress();
std::string getServerAddress();
/**
* @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 );
/**
* @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 );
void startPod(KubePod Pod,bool WaitTillRunning = true );
void startPod(std::shared_ptr<KubePod> Pod,bool WaitTillRunning = true );
/**
* @brief stops a pod referenced by its uuid
* @param uuid - string
*/
void stopPod(std::string uuid);
void stopPod(std::string uuid);
void stopAllPods();
/**
* @brief stops all pods the controller knows
*/
void stopAllPods();
std::vector<PodInfos> getInfoForAllPods();
PodInfos getInfoForPod(std::string uuid);
/**
* @brief returns a vector of PodInfos of all pod
* @return std::vector<PodInfos>
*/
std::vector<PodInfos> getInfoForAllPods();
KubernetesAPI getKubernetesAPI();
/**
* @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:
KubernetesAPI APIInterface_;
std::vector<std::unique_ptr<KubePod>> PodList_;
/// @brief object of the kubernetes api object
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_;
std::string ApiCall_;
PodInfos extractInfosFromKubePod(KubePod *pod);
mutable std::mutex mx_;
/// @brief mutex
mutable std::mutex mx_;
};
} // namespace ku

View File

@@ -8,15 +8,17 @@ namespace kubecontrol
{
enum PullPolicy: uint32_t
enum PullPolicy: uint32_t
{
ALWAYS,
IFNOTPRESENT,
NEVER
};
inline std::string toString(const PullPolicy &kind)
/**
* @brief translate PullPolicy enum to string
*/
inline std::string toString(const PullPolicy &kind)
{
switch (kind)
{
@@ -29,7 +31,10 @@ namespace kubecontrol
class Utils
{
public:
public:
/**
* @brief lowercase a 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:
explicit 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

@@ -1,5 +1,5 @@
#include <kubecontrol/PodController.hpp>
#include <kubecontrol/KubePod.hpp>
#include "curlpp/Options.hpp"
#include "kubecontrol/Container.hpp"
#include "kubecontrol/Utils.hpp"
@@ -10,15 +10,11 @@
#include <fstream>
#include <future>
#include <iterator>
#include <kubecontrol/KubePod.hpp>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <thread>
#include <filesystem>
#include "loguru.hpp"
#include "yaml-cpp/node/node.h"
@@ -37,7 +33,7 @@ namespace kubecontrol
// EnvirmonentVars_ = std::map<std::string, std::string>();
this->PathToYaml_ = "config/pods/" + this->Uuid_ + ".yaml";
if( !std::filesystem::directory_entry("config").exists())

View File

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

View File

@@ -19,10 +19,8 @@ namespace kubecontrol
{
PodController::PodController(std::string pathToKubectlConfig):
APIInterface_( YAML::LoadFile(pathToKubectlConfig))
{
ApiCall_ = "/api/v1/namespaces/"+APIInterface_.getNamespace()+"/pods/";
{
ApiCall_ = "/api/v1/namespaces/"+APIInterface_.getNamespace()+"/pods/";
}
std::string PodController::getServerAddress()
@@ -37,14 +35,16 @@ namespace kubecontrol
void PodController::startPod(KubePod Pod,bool WaitTillRunning )
{
LOG_S(INFO)<< "starting pod: "<<Pod.getUUID();
// 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_);
PodList_.emplace_back(std::make_unique<KubePod>(Pod));
// LOG_S(INFO)<<response;
@@ -55,8 +55,11 @@ namespace kubecontrol
{
LOG_S(INFO)<< "starting pod: "<<Pod->getUUID();
// 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_);
PodList_.emplace_back(std::make_unique<KubePod>(*Pod));
}
@@ -65,18 +68,15 @@ namespace kubecontrol
void PodController::stopPod(std::string uuid)
{
std::lock_guard<std::mutex>lock(mx_);
// PodList_
for (std::vector<std::unique_ptr<KubePod>>::iterator it = PodList_.begin(); it != PodList_.end();)
{
if (uuid == it->get()->getUUID())
{
it->get()->stop(APIInterface_);
it = PodList_.erase(it);
}
else
{
if (uuid == it->get()->getUUID())
{
it++;
it->get()->stop(APIInterface_);
it = PodList_.erase(it);
}else
{
it++;
}
}
@@ -111,7 +111,6 @@ namespace kubecontrol
return infosOfAllPods;
}
@@ -146,50 +145,4 @@ namespace kubecontrol
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,239 +0,0 @@
#include <nlohmann/json.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 <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(curlpp::options::HttpHeader(headers));
request.setOpt( curlpp::options::Url(curlURL));
request.setOpt( curlpp::options::SslEngineDefault());
request.setOpt( curlpp::options::CaPath("config/ca.crt"));
request.setOpt( 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.emplace_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( curlpp::options::HttpHeader(headers));
request.setOpt( curlpp::options::Url(curlURL));
request.setOpt( curlpp::options::SslEngineDefault());
request.setOpt( curlpp::options::CaPath("config/ca.crt"));
request.setOpt( curlpp::options::SslVerifyPeer(false));
request.setOpt( 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( 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( curlpp::options::HttpHeader(headers));
request.setOpt( curlpp::options::Url(curlURL));
request.setOpt( curlpp::options::SslEngineDefault());
request.setOpt( curlpp::options::CaPath("config/ca.crt"));
request.setOpt( curlpp::options::SslVerifyPeer(false));
// request.setOpt(new curlpp::options::Post(true));
// request.setOpt(new curlpp::options::PostFields("DELETE"));
request.setOpt( 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 sstream;
sstream <<node;
LOG_S(INFO)<< node;
fout << sstream.str();
fout.close();
return "config/pods_deployment.yaml";
}
}

View File

@@ -1,42 +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 kubecontrol")
{
std::string file= "../docs/config";
kubecontrol::kubecontrol kubecontroler(file);
GIVEN("different Attributes for a Track in different forms")
{
kubecontroler.createYAML();
kubecontroler.startPod();
// kc.getPods();
// kc.deletePod("debug-debian");
kubecontroler.getPods();
WHEN("constructing Track Object with data")
{
THEN("check if Track attributes are correct")
{
REQUIRE(true == true);
} //THEN
} // WHEN
} // GIVEN
} //SCENARIO