概要
Kubernetes的核心对象是Pod,我们最常和Pod打交道,但是很少仔细看看Pod到底包含了哪些字段,又有什么细节值得了解,本篇尝试说明Pod的核心细节。
细节
Pod结构体
type Pod struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
Spec PodSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
Status PodStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
Pod包含4个大字段,其中2个内嵌,2个非内嵌,划分也非常简单,内嵌的有
- TypeMeta: kind, apiVersion
- ObjectMeta: name, namespace, uid, resourceVersion, annotations, labels等 非内嵌的有
- Spec: initContainers, containers, volumes, hostname, priority, priorityClassName等
- Status: phase, conditions, message, reason, hostIP, podIP, initContainerStatuses, containerStatuses等
内嵌的用处
一些字段和方法集成过来了,比如获取PodName,我们有3种方式:
- pod.GetName()
- pod.Name
- pod.ObjectMeta.Name
3个时间戳
- ObjectMeta.CreationTimestamp Time
- ObjectMeta.DeletionTimestamp *Time
- PodStatus.StartTime *metav1.Time
type Time struct {time.Time
protobuf:"-"}
需要注意Kubernetes中指针表示字段可能为空,因此Pod只有CreationTime是明确有的,而DeletionTimestamp决定了Pod处于Terminating状态。
资源量
注意Pod只是容器的集合,Pod本身没有资源量,资源量字段存储在容器中。
以普通容器为例,存放在PodSpec.[]Container.ResourceRequirements,其中包含:
type ResourceRequirements struct {
Limits ResourceList `json:"limits,omitempty" protobuf:"bytes,1,rep,name=limits,casttype=ResourceList,castkey=ResourceName"`
Requests ResourceList `json:"requests,omitempty" protobuf:"bytes,2,rep,name=requests,casttype=ResourceList,castkey=ResourceName"`
}
type ResourceList map[ResourceName]resource.Quantity
type Quantity struct {
i int64Amount
d infDecAmount
s string
Format
}
可见,Resources字段是一个原生Map,虽然Quantity看起来有点复杂,但是提供了便捷的方法获取值,例如
- func (q *Quantity) Value() int64
- func (q *Quantity) MilliValue() int64
- func (q *Quantity) Add(y Quantity)
- func (q *Quantity) Sub(y Quantity)
基于这些方法,可以很容易计算出一个Pod总的资源量,事实上,kubelet已经有一个方法做了: k8s.io/kubectl/pkg/util/resource.PodRequestsAndLimits
总结
Pod对象是Kubernetes定义API对象的极简模板,它包含了必须的TypeMeta和ObjectMeta,也把Pod分为了PodSpec和PodStatus。