Files
KubeControl/src/kubecontrol/PodController.cpp

334 lines
9.3 KiB
C++

#include "curlpp/Options.hpp"
#include "kubecontrol/PodInfo.hpp"
#include "nlohmann/json_fwd.hpp"
#include <cstddef>
#include <cstdlib>
#include <exception>
#include <kubecontrol/PodController.hpp>
#include <math.h>
#include <memory>
#include <string>
#include <vector>
namespace kubecontrol
{
PodController::PodController(std::string pathToKubectlConfig)
{
LOG_S(INFO)<< "Path To Yaml: " <<pathToKubectlConfig;
try {
YAML::Node config = YAML::LoadFile(pathToKubectlConfig);
BearerToken_ = config["users"][0]["user"]["token"].as<std::string>();
Namespace_ = config["contexts"][0]["context"]["namespace"].as<std::string>();
char * KUBERNETES_SERVICE_HOST = std::getenv("KUBERNETES_SERVICE_HOST");
char * KUBERNETES_SERVICE_PORT = std::getenv("KUBERNETES_SERVICE_PORT");
if (KUBERNETES_SERVICE_HOST != nullptr && KUBERNETES_SERVICE_PORT!= nullptr)
{
ServerAddress_ = "https://" +std::string(KUBERNETES_SERVICE_HOST)+":"+std::string(KUBERNETES_SERVICE_PORT);
} else
{
LOG_S(INFO)<<"Taking Serveraddress out of the provided YAML file";
ServerAddress_ = config["clusters"][0]["cluster"]["server"].as<std::string>();
}
ApiCall_ = "/api/v1/namespaces/"+Namespace_+"/pods/";
} catch (std::exception& e) {
LOG_S(ERROR)<< e.what();
throw e.what();
}
}
std::string PodController::getServerAddress()
{
return this->ServerAddress_;
}
void PodController::startPod(KubePod Pod)
{
PodList_.emplace_back(Pod);
LOG_S(INFO)<< "starting pod: "<<Pod.getUUID();
auto response = Pod.start(ServerAddress_+ApiCall_, BearerToken_);
// LOG_S(INFO)<<response;
}
void PodController::stopPod(std::string Label)
{
for (auto item : PodList_)
{
if (Label == item.getUUID())
{
item.stop(ServerAddress_+ApiCall_, BearerToken_);
}
}
}
void PodController::stopAllPods()
{
checkPodsHierarchy();
for (auto item : PodList_)
{
LOG_S(INFO)<<item.InfoPod.Uuid;
item.InfoPod = *getPodInfo(item.getUUID()).get();
item.stop(ServerAddress_+ApiCall_, BearerToken_);
LOG_S(INFO)<< "stopping pod: "<<item.getUUID();
}
}
std::string PodController::getInfoForOwnPod()
{
std::string response = "";
for (auto item : PodList_)
{
response = item.getInfo(ServerAddress_+ApiCall_, BearerToken_);
}
return response;
}
std::string PodController::getPodsInfo()
{
std::string curlURL = ServerAddress_+ApiCall_;
std::string response = this->performRequest(curlURL);
std::vector<std::string> podsNames;
nlohmann::json j;
try
{
j = nlohmann::json::parse(response);
if (j.contains("items"))
{
int i = j["items"].size();
for (int a = 0; a<i; a++)
{
if (!j["items"][a]["metadata"]["name"].empty())
{
podsNames.emplace_back(j["items"][a]["metadata"]["name"]);
}
}
}
j.clear();
for (auto item: podsNames)
{
std::string curlURL = ServerAddress_+ApiCall_+item+"/status";
auto response = this->performRequest(curlURL);
j["items"].emplace_back(nlohmann::json::parse(response));
}
return j.dump();
}catch(const std::exception e)
{
LOG_S(ERROR)<< e.what()<< " IN PodController::getPodsInfo() Function";
}
return j.dump();
}
std::string PodController::getInfoForPod(std::string uid)
{
bool found = false;
for (auto item : PodList_)
{
if (uid == item.getUUID())
{
found = true;
checkPodsHierarchy();
item.InfoPod = *getPodInfo(item.getUUID()).get();
// LOG_S(INFO)<<item.InfoPod.getRelatedPods().size();
return item.getInfo(ServerAddress_+ApiCall_, BearerToken_);
}
}
if (found == false)
{
std::string curlURL = ServerAddress_+ApiCall_+uid;
auto response = this->performRequest(curlURL);
return response;
}
return nullptr;
}
void PodController::checkPodsHierarchy()
{
auto response = this->getPodsInfo();
nlohmann::json j;
try
{
j = nlohmann::json::parse(response);
if (j.contains("items"))
{
LOG_S(INFO)<<j["items"].size();
int i = j["items"].size();
for (int a = 0; a<i; a++)
{
auto item = std::make_unique<PodInfo>(j["items"][a].dump());
// LOG_S(INFO)<<item->ToString();
// item->Uuid = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/name"].get<std::string>();
// item->Component = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/component"].get<std::string>();
// item->Image = j["items"][a]["spec"]["containers"][0]["image"].get<std::string>();
// item->Ip = j["items"][a]["status"]["podIP"].get<std::string>();
// item->Status = j["items"][a]["status"]["phase"].get<std::string>();
// item->PartOf = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/part-of"].get<std::string>();
// // LOG_S(INFO)<<j["items"][a]["status"]["podIP"];
// LOG_S(INFO)<<j["items"][a]["status"]["phase"];
this->podsInfoList_.push_back(std::move(item));
}
i = j["items"].size();
for (int a = 0; a<i; a++)
{
auto item = std::make_shared<PodInfo>();
std::string uuid = j["items"][a]["metadata"]["labels"]["app.kubernetes.io/name"].get<std::string>();
std::string parentName= j["items"][a]["metadata"]["labels"]["app.kubernetes.io/part-of"].get<std::string>();
auto self = this->getPodInfo(uuid);
auto parent = this->getPodInfo(parentName);
if (parent != nullptr && self != nullptr) {
parent->addRelatedPods(self->Uuid);
}else if (parent== nullptr)
{
self->PartOf = parentName;
}
}
}
} catch (std::exception& e)
{
LOG_S(ERROR)<<e.what() << " In checkPodsHierarchy() Function";
}
}
std::string PodController::getPodsInfoForAll()
{
checkPodsHierarchy();
std::string item = "";
nlohmann::json j;
for (int i = 0; i < podsInfoList_.size(); i++) {
if(podsInfoList_[i]->relatedPodsSize() != 0 )
{
item = podsInfoList_[i]->ToJson().dump() +" Childs: ";
nlohmann::json tmp = podsInfoList_[i]->ToJson();
auto vec = podsInfoList_[i]->getRelatedPods();
for(int a = 0; a < vec.size();a++)
{
tmp["Childs"].push_back(getPodInfo(vec[a])->ToJson());
item += getPodInfo(vec[a])->ToString() +" // ";
}
j.push_back(tmp);
}
}
return j.dump();
}
std::shared_ptr<PodInfo> PodController::getPodsInfo(std::string uuid)
{
for (int i = 0; i < podsInfoList_.size(); i++) {
if (podsInfoList_[i]->Uuid == uuid)
{
return podsInfoList_[i];
}
}
checkPodsHierarchy();
LOG_S(INFO)<< "check Hierarchy";
return getPodsInfo(uuid);;
}
// void PodController::addPodInfoToInfoList(std::unique_ptr<PodInfo> podinfo)
// {
// }
std::shared_ptr<PodInfo> PodController::getPodInfo(std::string uuid)
{
for (int i = 0; i < podsInfoList_.size(); i++) {
if (podsInfoList_[i]->Uuid == uuid)
{
return podsInfoList_[i];
}
}
return nullptr;
}
size_t PodController::getListOfChildPods()
{
return PodList_.size();
}
std::string PodController::performRequest(std::string curlURL)
{
std::string AuthString = "Authorization: Bearer " + BearerToken_;
std::list<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;
}
void PodController::performForceStopRequest(std::string uuid)
{
}
}