使用 C# 获取 Kubernetes 集群资源信息( 六 )


publicstringName { get; set; } = null!;
///<summary>
///三种类型之一 <see cref="ServiceType"/>
///</summary>
publicstring? ServiceType { get; set; }
///<summary>
///有些 Service 没有 IP , 值为 None
///</summary>
publicstringClusterIP { get; set; } = null!;
publicDateTime? CreationTime { get; set; }
publicIDictionary< string, string>? Labels { get; set; }
publicIDictionary< string, string>? Selector { get; set; }
///<summary>
///name,port
///</summary>
publicList< string> Ports { get; set; }
publicstring[]? Endpoints { get; set; }
}
Kubernetes 中的分页 , 没有 PageNo、PageSize、Skip、Take 、Limit 这些 , 并且分页可能只是预计 , 不一定完全准确 。
第一次访问获取对象列表时 , 不能使用 ContinueProperty 属性 。
第一次访问 Kubernets 后 , 获取 10 条数据 , 那么 Kubernetes 会返回一个 ContinueProperty 令牌 , 和剩余数量 RemainingItemCount 。
那么我们可以通过 RemainingItemCount 计算大概的分页数字 。 因为 Kubernetes 是不能直接分页的 , 而是通过类似游标的东西 , 记录当前访问的位置 , 然后继续向下获取对象 。 ContinueProperty 保存了当前查询游标的令牌 , 但是这个令牌有效期是几分钟 。
解析方法:
publicstaticasyncTask<SvcInfoList> GetServicesAsync( stringnamespaceName,
intpageSize = 1,
string? continueProperty = null)
{
varclient = GetClient;
V1ServiceList services;
if( string.IsNullOrEmpty(continueProperty))
{
services = awaitclient.ListNamespacedServiceAsync(namespaceName, limit: pageSize);
}
else
{
try
{
services = awaitclient.ListNamespacedServiceAsync(namespaceName,
continueParameter: continueProperty,
limit: pageSize);
}
catch (Microsoft.Rest.HttpOperationException ex)
{
throwex;
}
catch
{
throw;
}
}
SvcInfoList svcList = newSvcInfoList
{
ContinueProperty = services.Metadata.ContinueProperty,
RemainingItemCount = ( int)services.Metadata.RemainingItemCount.GetValueOrDefault,
Items = newList<SvcInfo>
};
List<SvcInfo> svcInfos = svcList.Items;
foreach( varitem inservices.Items)
{
SvcInfo service = newSvcInfo
{
Name = item.Metadata.Name,
ServiceType = item.Spec.Type,
ClusterIP = item.Spec.ClusterIP,
Labels = item.Metadata.Labels,
Selector = item.Spec.Selector,
CreationTime = item.Metadata.CreationTimestamp
};
// 处理端口
if(item.Spec.Type == nameof(ServiceType.LoadBalancer) || item.Spec.Type == nameof(ServiceType.NodePort))
{
service.Ports = newList< string>;
foreach( varport initem.Spec.Ports)
{
service.Ports.Add( $" {port.Port}: {port.NodePort}/ {port.Protocol}" );
}
}
elseif(item.Spec.Type == nameof(ServiceType.ClusterIP))
{
service.Ports = newList< string>;
foreach( varport initem.Spec.Ports)
{
service.Ports.Add( $" {port.Port}/ {port.Protocol}" );
}
}
varendpoint = awaitclient.ReadNamespacedEndpointsAsync(item.Metadata.Name, namespaceName);
if(endpoint != null&& endpoint.Subsets.Count != 0)
{
List< string> address = newList< string>;
foreach( varsub inendpoint.Subsets)
{
if(sub.Addresses == null) continue;
foreach( varaddr insub.Addresses)
{
foreach( varport insub.Ports)
{
address.Add( $" {addr.Ip}: {port.Port}/ {port.Protocol}" );
}
}
}
service.Endpoints = address.ToArray;

特别声明:本站内容均来自网友提供或互联网,仅供参考,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。