ADD: add a simple working version of a pod controler class

This commit is contained in:
Henry Winkel
2023-08-07 17:31:23 +02:00
parent ca1e714c51
commit bc6617e100
15 changed files with 731 additions and 13 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
build build
.clangd .clangd
compile_commands.json compile_commands.json
.cache

3
.gitmodules vendored
View File

@@ -7,3 +7,6 @@
[submodule "libs/curlcpp"] [submodule "libs/curlcpp"]
path = libs/curlcpp path = libs/curlcpp
url = https://github.com/JosephP91/curlcpp.git url = https://github.com/JosephP91/curlcpp.git
[submodule "libs/nlohmann_json"]
path = libs/nlohmann_json
url = https://github.com/nlohmann/json.git

View File

@@ -1,5 +1,5 @@
cmake_minimum_required (VERSION 3.1 FATAL_ERROR) cmake_minimum_required (VERSION 3.1 FATAL_ERROR)
project (Ship VERSION 0.1.0 LANGUAGES CXX C) project (kubecontrol VERSION 0.1.0 LANGUAGES CXX C)
set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/Modules) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/Modules)
include(defaultOptions) include(defaultOptions)
@@ -20,6 +20,11 @@ IF(NOT TARGET Catch2)
add_subdirectory(libs/CLI11 EXCLUDE_FROM_ALL) add_subdirectory(libs/CLI11 EXCLUDE_FROM_ALL)
ENDIF() ENDIF()
IF(NOT TARGET nlohmann_json)
set(JSON_BuildTests_INIT OFF CACHE INTERNAL "")
add_subdirectory(libs/nlohmann_json EXCLUDE_FROM_ALL)
ENDIF()
IF (NOT TARGET yaml-cpp) IF (NOT TARGET yaml-cpp)
set(YAML_CPP_BUILD_TESTS OFF CACHE INTERNAL "") set(YAML_CPP_BUILD_TESTS OFF CACHE INTERNAL "")
set(YAML_CPP_BUILD_TOOLS OFF CACHE INTERNAL "") set(YAML_CPP_BUILD_TOOLS OFF CACHE INTERNAL "")
@@ -45,16 +50,24 @@ ENDIF()
add_library(kubecontrol STATIC add_library(kubecontrol STATIC
include/kubecontrol/kubecontrol.hpp include/kubecontrol/kubecontrol.hpp
src/kubecontrol/kubecontrol.cpp src/kubecontrol/kubecontrol.cpp
) include/kubecontrol/KubePod.hpp
src/kubecontrol/KubePod.cpp
include/kubecontrol/WriterMemoryClass.hpp
)
target_link_libraries(kubecontrol target_link_libraries(kubecontrol
yaml-cpp yaml-cpp
curlcpp curl
curlpp
loguru loguru
nlohmann_json
pthread pthread
) )
target_include_directories(kubecontrol PUBLIC target_include_directories(kubecontrol PUBLIC
@@ -64,7 +77,9 @@ target_include_directories(kubecontrol PUBLIC
add_custom_command(TARGET kubecontrol POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_SOURCE_DIR}/config $<TARGET_FILE_DIR:${PROJECT_NAME}>/config)
# #
# Everything TEST related # Everything TEST related
# #
@@ -78,6 +93,9 @@ IF (${TEST_KUBECONTROL_LIBRARY})
target_link_libraries(test_kubecontrol Catch2::Catch2 kubecontrol loguru) target_link_libraries(test_kubecontrol Catch2::Catch2 kubecontrol loguru)
catch_discover_tests(test_kubecontrol) catch_discover_tests(test_kubecontrol)
add_executable(test_KubePod tests/test_KubePod.cpp)
target_link_libraries(test_KubePod Catch2::Catch2 kubecontrol loguru)
catch_discover_tests(test_KubePod)

27
config/ca.crt Normal file
View File

@@ -0,0 +1,27 @@
-----BEGIN CERTIFICATE-----
MIIEozCCAwugAwIBAgIBATANBgkqhkiG9w0BAQsFADA+MRwwGgYDVQQKDBNUSS5V
TklCVy1IQU1CVVJHLkRFMR4wHAYDVQQDDBVDZXJ0aWZpY2F0ZSBBdXRob3JpdHkw
HhcNMjIwOTA4MTMyNTE2WhcNNDIwOTA4MTMyNTE2WjA+MRwwGgYDVQQKDBNUSS5V
TklCVy1IQU1CVVJHLkRFMR4wHAYDVQQDDBVDZXJ0aWZpY2F0ZSBBdXRob3JpdHkw
ggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQDY1Q3atDj9YtgC1ktcGD7Y
7frSmtspbP1W+rjJr/E5/Jm83tc0nSnE9BqnzGaEF/tuAq2yJRxf+vJlgcyUkd19
XY6+Ow8d1XJuUKuuN0P3Lq9RtdTAhhQuYU5RmuQGQ5cy+PCm6Xy4BY3j+/T4z/Tf
extD4DHsm63bNK9fRgrFIy4KtwXRlCOYSzT60jPjDArNBzYHLkFpN+U1h1cdBgYk
ynA2hiPv86X96l5aMqXCNjMR2RuksGD+tkwOamSL+YwdK0wh7Szy7B+hMX3EPMBj
6+c6VM/N84K/RoGks7eXR3I/nGPk0BBPmDlx1n86segQOFFgLC1e+ZZMHS7FRt7E
3Pa7YL/l2rocoyxq3Y1ScVue7ffCJ11kjW+kVf7XpAl23cF6yxtfn7yY9CSXIaMH
UcUeAF9hplYE9yluygWnHGJ8jQ62OB6Z6J2R8FuE9jxWtZcdpPec6TvwLbH3z4xz
nJBUvcalKC7rpagvMkiK3HR/ReQo2L6cnYTJmAyXWm8CAwEAAaOBqzCBqDAfBgNV
HSMEGDAWgBTAhqAZ30RPD9W8Dkk/fAAGWRH56zAPBgNVHRMBAf8EBTADAQH/MA4G
A1UdDwEB/wQEAwIBxjAdBgNVHQ4EFgQUwIagGd9ETw/VvA5JP3wABlkR+eswRQYI
KwYBBQUHAQEEOTA3MDUGCCsGAQUFBzABhilodHRwOi8vaXBhLWNhLnRpLnVuaWJ3
LWhhbWJ1cmcuZGUvY2Evb2NzcDANBgkqhkiG9w0BAQsFAAOCAYEAdb89O6+MmSHM
gF2YBBQRXpuZzeWFvcDOai+mhBW5yT2a7ycQt6vL1jiGbdP8HDi0p++ELqNYoGM+
0sCjFFM4Su6I0qUSeXAWgGip/b0Yba1zGm+fQSMqVRtlFZduAVb+sIvWciYjXY7h
VQrCkjAa8khj9dqPV1Yndx9dUR7qv4KluUNLc6SMEZ4WdGL4xGIvSc/Mp49UwP3f
p7kio88qGTygpvO6rMcfwtkvhz1rb5s1tg+c9OkPBkTSyWIzg/6sNVB2n2I3mSJz
F7fruyS6SfmgK+FWtKBvyD6htFPuBJrS9HFVHSHIgvE36xIOCWC50L1k4ZVOykoq
dhu/v4HRrGZp9AkQjMzm3bqoua62YitF5LOAQb9idz7w2b7KwwqINHti186cxsv3
9dpMlJVPIrf9Y97YAK2aV4OdEaDjWXVjfuJ2jrqOAV9gWqUCx6AxN4kCaaZ70NIp
PtsUQZvheUOcmH/XWA+3R5iv6bFUfUYKBCagc5f7N9I+0p/OovwH
-----END CERTIFICATE-----

1
config/config.yaml Normal file
View File

@@ -0,0 +1 @@
docker-registry: kmaster.ti.unibw-hamburg.de:30808

14
config/pods_default.yaml Normal file
View File

@@ -0,0 +1,14 @@
apiVersion: v1
kind: Pod
metadata:
name: debug-debian
labels:
app.kubernetes.io/name: plaindebian
spec:
containers:
- name: debug-debian-container
image: kmaster.ti.unibw-hamburg.de:30808/debugdebianhenry:0.1.2
env:
- name: OWN_SHIP_SERVER
value: "127.0.0.1"
restartPolicy: Never

99
docs/test.json Normal file
View File

@@ -0,0 +1,99 @@
{"annotations":{"kubectl.kubernetes.io/last-applied-configuration":"{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"labels\":{\"app.kubernetes.io/name\":\"plaindebian\"},\"name\":\"debug-debian\",\"namespace\":\"hwinkel\"},\"spec\":{\"containers\":[{\"args\":[\"-c\",\"while true; do echo hello; sleep 5;done\"],\"command\":[\"/bin/sh\"],\"env\":[{\"name\":\"OWN_SHIP_SERVER\",\"value\":\"127.0.0.1\"}],\"image\":\"kmaster.ti.unibw-hamburg.de:30808/debugdebianhenry:0.1.2\",\"name\":\"debug-debian-container\"}],\"restartPolicy\":\"Never\"}}\n"},
"creationTimestamp":"2023-08-07T09:01:18Z",
"labels":{"app.kubernetes.io/name":"plaindebian"},
"managedFields":[
{"apiVersion":"v1",
"fieldsType":"FieldsV1",
"fieldsV1":{
"f:metadata":{
"f:annotations":{
".":{},
"f:kubectl.kubernetes.io/last-applied-configuration":{}
},
"f:labels":{
".":{},
"f:app.kubernetes.io/name":{}
}
},
"f:spec":{
"f:containers":{
"k:{\"name\":\"debug-debian-container\"}":{
".":{},
"f:args":{},
"f:command":{},
"f:env":{
".":{},
"k:{\"name\":\"OWN_SHIP_SERVER\"}":{
".":{},"f:name":{},"f:value":{}
}
},
"f:image":{},
"f:imagePullPolicy":{},
"f:name":{},
"f:resources":{},
"f:terminationMessagePath":{},
"f:terminationMessagePolicy":{}
}
},
"f:dnsPolicy":{},
"f:enableServiceLinks":{},
"f:restartPolicy":{},
"f:schedulerName":{},
"f:securityContext":{},
"f:terminationGracePeriodSeconds":{}
}
},
"manager":"kubectl-client-side-apply",
"operation":"Update",
"time":"2023-08-07T09:01:18Z"
},
{"apiVersion":"v1",
"fieldsType":"FieldsV1",
"fieldsV1":{
"f:status":{
"f:conditions":{
"k:{\"type\":\"ContainersReady\"}":{
".":{},
"f:lastProbeTime":{},
"f:lastTransitionTime":{},
"f:status":{},
"f:type":{}
},
"k:{\"type\":\"Initialized\"}":{
".":{},
"f:lastProbeTime":{},
"f:lastTransitionTime":{},
"f:status":{},
"f:type":{}
},
"k:{\"type\":\"Ready\"}":{
".":{},
"f:lastProbeTime":{},
"f:lastTransitionTime":{},
"f:status":{},
"f:type":{}
}
},
"f:containerStatuses":{},
"f:hostIP":{},
"f:phase":{},
"f:podIP":{},
"f:podIPs":{
".":{},
"k:{\"ip\":\"10.0.3.70\"}":{
".":{},
"f:ip":{}
}
},
"f:startTime":{}
}
},
"manager":"kubelet",
"operation":"Update",
"subresource":"status",
"time":"2023-08-07T09:01:20Z"}
],
"name":"debug-debian",
"namespace":"hwinkel",
"resourceVersion":"170886884",
"uid":"f9df752e-2404-433f-b377-6e03721a5044"}

View File

@@ -0,0 +1,45 @@
#pragma once
#include "nlohmann/json_fwd.hpp"
#include <map>
#include <string>
#include <vector>
#include <yaml-cpp/yaml.h>
#include <fstream>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <kubecontrol/WriterMemoryClass.hpp>
#include <loguru.hpp>
#include <nlohmann/json.hpp>
namespace kubecontrol
{
class KubePod
{
public:
KubePod(std::string Label, std::string Uuid, std::string ContainerImage);
void setEnvironmentVar(std::string key, std::string val);
std::map<std::string, std::string> GetEnvironmentVars();
std::string* GetEnvironmentVar(std::string key);
std::string createYAML();
nlohmann::json start(std::string apiAddress,std::string token);
nlohmann::json stop(std::string apiAddress,std::string token);
nlohmann::json getInfo(std::string apiAddress,std::string token);
private:
std::string Label_;
std::string Uuid_;
std::string ContainerImage_;
std::string ContainerRegistry_;
std::string PathToYaml_;
std::map<std::string, std::string> EnvirmonentVars_;
};
}

View File

@@ -0,0 +1,70 @@
#pragma once
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <iostream>
#define MAX_FILE_LENGTH 20000
class WriterMemoryClass
{
public:
// Helper Class for reading result from remote host
WriterMemoryClass()
{
this->m_pBuffer = NULL;
this->m_pBuffer = (char*) malloc(MAX_FILE_LENGTH * sizeof(char));
this->m_Size = 0;
};
~WriterMemoryClass()
{
if (this->m_pBuffer)
free(this->m_pBuffer);
};
void* Realloc(void* ptr, size_t size)
{
if(ptr)
return realloc(ptr, size);
else
return malloc(size);
};
// Callback must be declared static, otherwise it won't link...
size_t WriteMemoryCallback(char* ptr, size_t size, size_t nmemb)
{
// Calculate the real size of the incoming buffer
size_t realsize = size * nmemb;
// (Re)Allocate memory for the buffer
m_pBuffer = (char*) Realloc(m_pBuffer, m_Size + realsize);
// Test if Buffer is initialized correctly & copy memory
if (m_pBuffer == NULL) {
realsize = 0;
}
memcpy(&(m_pBuffer[m_Size]), ptr, realsize);
m_Size += realsize;
// return the real size of the buffer...
return realsize;
};
std::string getResponse()
{
return m_pBuffer;
}
void print()
{
std::cout << "Size: " << m_Size << std::endl;
std::cout << "Content: " << std::endl << m_pBuffer << std::endl;
}
// Public member vars
char* m_pBuffer;
size_t m_Size;
};

View File

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

1
libs/nlohmann_json Submodule

Submodule libs/nlohmann_json added at 5d2754306d

185
src/kubecontrol/KubePod.cpp Normal file
View File

@@ -0,0 +1,185 @@
#include <filesystem>
#include <kubecontrol/KubePod.hpp>
#include <map>
#include <vector>
namespace kubecontrol
{
KubePod::KubePod(std::string Label, std::string Uuid, std::string ContainerImage):Label_(Label),Uuid_(Uuid),
ContainerImage_(ContainerImage),EnvirmonentVars_()
{
ContainerRegistry_ = "kmaster.ti.unibw-hamburg.de:30808";
EnvirmonentVars_ = std::map<std::string, std::string>();
this->PathToYaml_ = "config/pods/" + this->Label_ + ".yaml";
std::filesystem::directory_entry entry("config/pods");
if(entry.exists() != true)
{
std::filesystem::create_directory("config/pods");
}
}
void KubePod::setEnvironmentVar(std::string key, std::string val)
{
EnvirmonentVars_.emplace(key,val);
}
std::map<std::string, std::string> KubePod::GetEnvironmentVars()
{
return EnvirmonentVars_;
}
std::string* KubePod::GetEnvironmentVar(std::string key)
{
if(EnvirmonentVars_.contains(key)) {
return &EnvirmonentVars_[key];
} else {
return nullptr;
}
}
std::string KubePod::createYAML()
{
YAML::Node node;
node["apiVersion"] = "v1";
node["kind"] = "Pod";
node["metadata"]["name"] = this->Uuid_;
node["metadata"]["labels"]["app.kubernetes.io/name"] = this->Label_;
node["spec"]["containers"][0]["name"] = this->Label_+"-container";
node["spec"]["containers"][0]["image"] = this->ContainerRegistry_ + "/" + this->ContainerImage_;
int i = 0;
for (auto item :EnvirmonentVars_) {
node["spec"]["containers"][0]["env"][i]["name"] = item.first;
node["spec"]["containers"][0]["env"][i]["value"] = R"(item.second)";
}
node["spec"]["restartPolicy"] = "Never";
std::ofstream fout(this->PathToYaml_);
fout << node;
fout.close();
return this->PathToYaml_;
}
nlohmann::json KubePod::start(std::string apiAddress,std::string token)
{
std::string curlURL = apiAddress;
std::string AuthString = "Authorization: Bearer " + token;
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);
request.setOpt(new curlpp::options::HttpHeader(headers));
request.setOpt(new curlpp::options::Url(curlURL));
request.setOpt(new curlpp::options::SslVerifyPeer(false));
request.setOpt(new curlpp::options::Post(true));
std::ifstream is;
is.open (this->PathToYaml_, std::ios::binary );
is.seekg (0, std::ios::end);
long length = is.tellg();
is.seekg (0, std::ios::beg);
char *buffer = new char [length];
is.read (buffer,length);
request.setOpt(new curlpp::options::PostFields(buffer));
request.perform();
auto response = mWriterChunk.getResponse();
return nlohmann::json::parse(response);
}
nlohmann::json KubePod::stop(std::string apiAddress,std::string token)
{
std::string curlURL = apiAddress+ this->Uuid_;
std::string AuthString = "Authorization: Bearer " + token;
std::list<std::string> headers;
headers.push_back(AuthString);
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 *writefunction = new curlpp::options::WriteFunction(functor);
request.setOpt(writefunction);
request.setOpt(new curlpp::options::HttpHeader(headers));
request.setOpt(new curlpp::options::Url(curlURL));
request.setOpt(new curlpp::options::SslVerifyPeer(false));
request.setOpt(new curlpp::options::CustomRequest("DELETE"));
// request.setOpt(new curlpp::options::Verbose(true));
request.perform();
auto response = mWriterChunk.getResponse();
return nlohmann::json::parse(response);
}
nlohmann::json KubePod::getInfo(std::string apiAddress,std::string token)
{
std::string curlURL = apiAddress;
std::string AuthString = "Authorization: Bearer " + token;
std::list<std::string> headers;
headers.push_back(AuthString);
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);
request.setOpt(new curlpp::options::HttpHeader(headers));
request.setOpt(new curlpp::options::Url(curlURL));
request.setOpt(new curlpp::options::SslVerifyPeer(false));
request.perform();
auto response = mWriterChunk.getResponse();
return nlohmann::json::parse(response);
}
}

View File

@@ -1,27 +1,221 @@
#include "nlohmann/json_fwd.hpp"
#include "yaml-cpp/emitter.h"
#include "yaml-cpp/emitterstyle.h"
#include "yaml-cpp/node/node.h"
#include <kubecontrol/kubecontrol.hpp> #include <kubecontrol/kubecontrol.hpp>
#include <curl_easy.h>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <curlpp/Exception.hpp>
#include <string>
#include <yaml-cpp/yaml.h> #include <yaml-cpp/yaml.h>
#include <loguru.hpp> #include <loguru.hpp>
#include <nlohmann/json.hpp>
#include <kubecontrol/WriterMemoryClass.hpp>
#include <iostream>
#include <fstream>
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);
LOG_S(INFO)<< "test";
curl::curl_easy easy; BearerToken_ = config["users"][0]["user"]["token"].as<std::string>();
easy.add<CURLOPT_URL>("http://<your_url_here>"); ServerAddress_ = config["clusters"][0]["cluster"]["server"].as<std::string>();
easy.add<CURLOPT_FOLLOWLOCATION>(1L);
} }
void kubecontrol::getPods() void kubecontrol::getPods()
{ {
std::string curlURL = ServerAddress_+"/api/v1/namespaces/hwinkel/pods/";
std::string AuthString = "Authorization: Bearer " + BearerToken_;
std::list<std::string> headers;
headers.push_back(AuthString);
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);
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 = mWriterChunk.getResponse();
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/hwinkel/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);
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();
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 = mWriterChunk.getResponse();
// LOG_S(INFO)<<response;
}
void kubecontrol::deletePod(std::string uid)
{
std::string curlURL = ServerAddress_+"/api/v1/namespaces/hwinkel/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;
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);
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 = mWriterChunk.getResponse();
// 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.2";
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]["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");
fout << node;
fout.close();
return "config/pods_deployment.yaml";
}
} }

44
tests/test_KubePod.cpp Normal file
View File

@@ -0,0 +1,44 @@
#define CATCH_CONFIG_MAIN
#include <string>
#include <catch2/catch.hpp>
#include <loguru.hpp>
#include <kubecontrol/KubePod.hpp>
SCENARIO("Testing the SimCore Sensor")
{
GIVEN("different Attributes for a Track in different forms")
{
std::string api = "https://192.168.252.5:6443/api/v1/namespaces/hwinkel/pods/";
std::string token = "eyJhbGciOiJSUzI1NiIsImtpZCI6InJwN2R3a2NEWHJva0ptLVNFUnAxMnUxNEF3VUdmdURRTmw5VWZuM0NCZ3MifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJod2lua2VsIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6Imh3aW5rZWwtc2VjcmV0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6Imh3aW5rZWwiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiJmNDNkNTc5NS1lNDFhLTQxOTYtODVkMS01YmNkZGIxNzFkYjkiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6aHdpbmtlbDpod2lua2VsIn0.TQCBkEIY0sEQjpy-3BP1SdXl94Ct-oAeD4VGNEOJEzDYBuU4Cn1fG32k2wAIgZemh6P-DcBhPk0VtCWCLYhWWwIe6FNo3FpqOxcDbu8QHlyD-Y3VnfSzKRHg9OKgUSWnc_Z5P9iBtilNQxnZp_wLOBW6TL8ZeECxeVtBBxUpYfoywSWS7mNpwxHcecP_U__LUU1tP7pYZ8OgDiSIH04CaTrQisTL-FGdcqOEYQhx4zoOyVQFWWYkfjG9oD-5zjtS29O0gckfvKLOu2y_K6RVR51szsquiJiHP1s_AcS-qq1-rXRqEpYRsLxRxr-dflL3aAjnLlPSYCwheQhjCa0fjQ";
int random = rand() % 100 + 1;
std::string uuid = "random" + std::to_string(random);
kubecontrol::KubePod pod1("debug-debian","debug-debian","debugdebianhenry:0.1.2");
pod1.setEnvironmentVar("OWN_SHIP_SERVER", "127.0.0.1");
LOG_S(INFO)<<pod1.createYAML();
pod1.start(api,token);
LOG_S(INFO)<< pod1.getInfo(api, token).dump();
pod1.stop(api,token);
WHEN("constructing Track Object with data")
{
THEN("check if Track attributes are correct")
{
REQUIRE(true == true);
} //THEN
} // WHEN
} // GIVEN
} //SCENARIO

View File

@@ -13,6 +13,11 @@ kubecontrol::kubecontrol kc("../docs/config");
GIVEN("different Attributes for a Track in different forms") 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") WHEN("constructing Track Object with data")
{ {