当前位置: 首页 > news >正文

KubernetesClient-C

KubernetesC-SDK

告诉编译器:

“这些函数是 C 写的,别给它们加花哨的 C++ 名字修饰,用纯 C 风格导出。”

extern "C" {
#include <kubernetes/config/kube_config.h>
#include <kubernetes/api/CoreV1API.h>
}

结构体之间的关系

image-20251014213300727

这套结构的目的是:
让不同类型的 Kubernetes 对象(Pod、Service、Namespace等)都能用统一的链表容器 list_t 来保存,从而方便解析与遍历。

  • v1_pod_list_t 只是“某一类对象”的容器(这里是 Pod)

  • list_t通用链表容器

  • listEntry_t 是链表节点结构


​ 1️⃣ v1_pod_list_t

typedef struct v1_pod_list_t {char *api_version;          // 版本,如 "v1"list_t *items;              // 这里是一个链表,存放多个 v1_pod_t 对象char *kind;                 // 类型,如 "PodList"struct v1_list_meta_t *metadata; // 元数据,如继续分页的 tokenint _library_owned;         // 标记内存是否由库管理
} v1_pod_list_t;

​ 2️⃣ list_t(链表头)

typedef struct list_t {listEntry_t *firstEntry;  // 第一个节点listEntry_t *lastEntry;   // 最后一个节点long count;               // 节点数量
} list_t;

​ 3️⃣ listEntry_t(链表节点)

typedef struct listEntry_t {listEntry_t *nextListEntry;  // 指向下一个节点listEntry_t *prevListEntry;  // 指向上一个节点void *data;                  // 指向实际数据(这里是 v1_pod_t*)
} listEntry_t;

遍历宏的设计

#define list_ForEach(element, list) \for (element = (list != NULL) ? (list)->firstEntry : NULL; \element != NULL; \element = element->nextListEntry)

等价写法:

listEntry_t *element = list->firstEntry;
while (element != NULL) {...element = element->nextListEntry;
}

Creating API Clients

常见的连接方式有两种

  1. 从kubeconfig 文件和使用集群内置配置,这是在 Kubernetes 集群之外运行应用程序时最常见的方法:

image-20251015085656866

// Initialize variables
char *basePath = NULL;
sslConfig_t *sslConfig = NULL;
list_t *apiKeys = NULL;
apiClient_t *apiClient = NULL;// Load configuration from kubeconfig file (typically ~/.kube/config)
int rc = load_kube_config(&basePath, &sslConfig, &apiKeys, NULL);
if (rc != 0) {// Handle errorreturn -1;
}// Create API client with loaded configuration
apiClient = apiClient_create_with_base_path(basePath, sslConfig, apiKeys);
if (!apiClient) {// Handle errorreturn -1;
}// Use the API client...// Clean up resources
apiClient_free(apiClient);
free_client_config(basePath, sslConfig, apiKeys);
apiClient_unsetupGlobalEnv();
  1. 使用集群内配置,在 Kubernetes Pod 中运行时,可以使用集群内配置,该配置会自动检测和使用服务帐户令牌

image-20251015085825038

// Initialize variables
char *basePath = NULL;
sslConfig_t *sslConfig = NULL;
list_t *apiKeys = NULL;
apiClient_t *apiClient = NULL;// Load in-cluster configuration
int rc = load_incluster_config(&basePath, &sslConfig, &apiKeys);
if (rc != 0) {// Handle errorreturn -1;
}// Create API client with loaded configuration
apiClient = apiClient_create_with_base_path(basePath, sslConfig, apiKeys);
if (!apiClient) {// Handle errorreturn -1;
}// Use the API client...// Clean up resources
apiClient_free(apiClient);
free_client_config(basePath, sslConfig, apiKeys);
apiClient_unsetupGlobalEnv();
  • basePath: The base URL of the Kubernetes API server
    basePath:Kubernetes API 服务器的基本 URL
  • sslConfig: SSL/TLS configuration for secure connections
    sslConfig:用于安全连接的 SSL/TLS 配置
  • dataReceived: Buffer containing the response data
    dataReceived:包含响应数据的缓冲区
  • dataReceivedLen: Length of the received data
    dataReceivedLen:接收数据的长度
  • response_code: HTTP response code from the last request
    response_code:上次请求的 HTTP 响应代码
  • apiKeys_BearerToken: Authentication tokens for the API server
    apiKeys_BearerToken:API 服务器的身份验证令牌

面向对象设计

#include <iostream>
#include <string>extern "C"
{
#include <kubernetes/config/kube_config.h>
#include <kubernetes/api/CoreV1API.h>
}using namespace std;struct kube_params_t
{char *_basePath;sslConfig_t *_sslConfig;list_t *_apiKeys;kube_params_t() : _basePath(nullptr), _sslConfig(nullptr), _apiKeys(nullptr) {}~kube_params_t(){if (_basePath || _sslConfig || _apiKeys){free_client_config(_basePath, _sslConfig, _apiKeys);_basePath = nullptr;_sslConfig = nullptr;_apiKeys = nullptr;}}
};class K8sCluster
{
private:kube_params_t *_params;apiClient_t *_apiClient;bool _connected;void initClient(){int rc = load_kube_config(&_params->_basePath, &_params->_sslConfig, &_params->_apiKeys, nullptr);if (rc != 0){cerr << "Cannot to connected k8s" << endl;return;}_apiClient = apiClient_create_with_base_path(_params->_basePath, _params->_sslConfig, _params->_apiKeys);if (!_apiClient){cerr << "Create apiclient Failed" << endl;return;}_connected = true;}public:K8sCluster() : _params(new kube_params_t), _apiClient(nullptr), _connected(false) { initClient(); }K8sCluster(kube_params_t *params) : _params(params), _apiClient(nullptr), _connected(false){if (_params){initClient();}}~K8sCluster(){apiClient_free(_apiClient);delete _params;}void list_pod(const char *);bool isConnected() const { return _connected; }
};void K8sCluster::list_pod(const char *ns)
{if (!_apiClient){printf("[-] apiClient is null, cannot list pods.\n");return;}v1_pod_list_t *pod_list = CoreV1API_listNamespacedPod(_apiClient, (char *)ns, nullptr, nullptr, nullptr,nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,nullptr, nullptr);printf("HTTP response code = %ld\n", _apiClient->response_code);if (!pod_list){printf("Cannot get any pod.\n");return;}listEntry_t *listEntry = nullptr;v1_pod_t *pod = nullptr;list_ForEach(listEntry, pod_list->items){pod = static_cast<v1_pod_t *>(listEntry->data);if (pod && pod->metadata && pod->metadata->name)printf("  Pod: %s Namespace: %s\n", pod->metadata->name, pod->metadata->_namespace);}v1_pod_list_free(pod_list);
}int main()
{kube_params_t *params = new kube_params_t;K8sCluster info(params);const char *ns = "kube-system";info.list_pod(ns);apiClient_unsetupGlobalEnv();return 0;
}

CMake 编译文件配置

cmake_minimum_required(VERSION 3.16.3)
project(k8scon)
set(CXX_STANDARD 11)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
# 如果 include 不在默认路径,还要加上
include_directories(/usr/local/include)
link_directories(/usr/local/lib)
add_executable(case case1.cc)
# 如果库在 /usr/local/lib 下
target_link_libraries(casekubernetes           # <-- 核心 SDKcurl                 # SDK 使用 libcurlssl                  # OpenSSLcrypto               # OpenSSLpthread              # 网络请求线程安全
)
http://www.jsqmd.com/news/30264/

相关文章:

  • CSP-S 2025 Self Review -- Words to be remembered 2025.11.3
  • 2025年微型减速机工厂权威推荐榜单:蜗轮蜗杆减速机/小齿减速机/谐波减速机源头厂家精选
  • 2025 年同步时钟厂家最新推荐榜,聚焦技术实力与市场口碑深度解析,涵盖卫星北斗 GPS 授时安全领域授时安全/授时防护/信号安全/时空安全同步时钟公司推荐
  • 关于combinational and sequential parts of an fsm described in same always block ,spyglass警告
  • 2025年云南好的旅行社公司权威推荐榜单:云南青年旅行社/云南正规的旅行社/云南省十大旅行社源头公司精选
  • 记录一次数据恢复,mysql8 - 义美
  • 2025年新能源水冷电机壳铝合金浇铸机批发厂家权威推荐榜单:户外围墙配件铝合金浇铸机/厨具锅铝合金浇铸机/手套模具铝合金浇铸机源头厂家精选
  • 2025年耐高温的轴承制造商权威推荐榜单:轴承耐高温源头/高速耐高温轴承/耐高温高速轴承源头厂家精选
  • Chef:开源 AI 全栈应用构建工具实践
  • 2025年哈尔滨发动机维修保养权威推荐榜单:汽车维修/汽车保养/变速箱维修保养服务商精选
  • 2025 年 11 月阻燃石墨,膨胀石墨,导热石墨母粒厂家最新推荐,产能、专利、环保三维数据透视!
  • 2025 年 11 月石墨烯,可膨胀石墨,导热石墨母粒厂家最新推荐,产能、专利、环保三维数据透视!
  • [CSP-S 2025] 社团招新 / club题解
  • La Suite Docs:开源协作文档平台,可私有部署的 Notion 替代方案
  • Cisco Jabber 15.1 (Andriod, iOS, macOS, Windows) - 面向企业的多合一通信工具
  • Shotcut 25.10 (Linux, macOS, Windows) - 免费开源视频编辑器
  • Cisco Packet Tracer 9.0 新增功能简介
  • 划分型dp
  • 2025年青石栏杆制造厂权威推荐榜单:别墅石栏杆/石栏杆/河道石栏杆源头厂家精选
  • 2025年高分子聚乙烯衬板生产商权威推荐榜单:高分子聚乙烯耐磨板/聚乙烯耐磨衬板/超高分子聚乙烯衬板源头厂家精选
  • 2025年燃气发电机组制造商权威推荐榜单:石油管道发电机组/矿山用发电机组制造企业/加油站静音发电机设备源头厂家精选
  • 2025 年 11 月 DALI 控制器厂家推荐排行榜,DALI 控制器主机,DALI 照明控制系统,智能调光控制器公司精选
  • 【2025-11-02】连岳摘抄
  • 2025年手动叠片过滤器生产厂家权威推荐榜单:全自动反冲洗叠片过滤器/离心过滤器/钢制离心过滤器设备源头厂家精选
  • session cookie token它们三个的区
  • 弧焊机器人保护气智能节气装置
  • 2025年压管机厂家权威推荐榜单:缩管机/锁管机/扣管机/啤喉机源头厂家精选
  • 2025 年窗帘品牌最新推荐榜,聚焦品牌技术创新、产品品质与市场服务能力深度解析遮光 / 智能 / 蕾丝 / 百叶窗帘推荐
  • 纳尼?自建K8s集群日志收集还能通过JMQ保存到JES
  • 2025 年艺术漆品牌最新推荐榜,综合实力与核心竞争力全面剖析,兼具品质与服务的优质之选艺术漆一线品牌公司推荐