StatefulSet

简要概述

staging/src/k8s.io/api/apps/v1/types.go

查看官方介绍

常用指令

TODO;

配置示例

  • 通过 kubectl 创建

无法通过 kubectl 命令行直接创建该资源,可先创建 Deployment 资源然后在更改 yaml 文件。

kubectl create deployment nginx \
	--image=registry.cn-hangzhou.aliyuncs.com/kube-image-repo/nginx:1.23.2 \
	--dry-run=client \
	-o yaml

更改 kindStatefulSet 同时移除生成 yaml 中 strategystatus,在添加 serviceName 属性。

  • 通过 yaml 创建
apiVersion: apps/v1
kind: StatefulSet
metadata:
  creationTimestamp: null
  labels:
    app: nginx
  name: nginx 
spec:
  replicas: 1
  serviceName: nginx
  selector:
    matchLabels:
      app: nginx
  #strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
    spec:
      containers:
      - image: registry.cn-hangzhou.aliyuncs.com/kube-image-repo/nginx:1.23.2
        name: nginx
        resources: {}

一般均配合不分配 VIP 的 Service 类型(无头服务)使用:

apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  ports:
  - port: 80
    name: web
  clusterIP: None
  selector:
    app: nginx

此时可以使用 DNS 格式解析各个 POD:

{POD_NAME}.{serviceName}.{namespace}.svc.{cluster_domain}

既以上一个 POD 域名为:

nginx-0.nginx.default.svc.cluster.local

数据结构

StatefulSet

// StatefulSet represents a set of pods with consistent identities.
// Identities are defined as:
//  - Network: A single stable DNS and hostname.
//  - Storage: As many VolumeClaims as requested.
// The StatefulSet guarantees that a given network identity will always
// map to the same storage identity.
type StatefulSet struct {
    metav1.TypeMeta `json:",inline"`
    // Standard object's metadata.
    // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
    // +optional
    metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

    // Spec defines the desired identities of pods in this set.
    // +optional
    Spec StatefulSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`

    // Status is the current status of Pods in this StatefulSet. This data
    // may be out of date by some window of time.
    // +optional
    Status StatefulSetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

StatefulSetSpec

// A StatefulSetSpec is the specification of a StatefulSet.
type StatefulSetSpec struct {
    // replicas is the desired number of replicas of the given Template.
    // These are replicas in the sense that they are instantiations of the
    // same Template, but individual replicas also have a consistent identity.
    // If unspecified, defaults to 1.
    // TODO: Consider a rename of this field.
    // +optional
    Replicas *int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"`

    // selector is a label query over pods that should match the replica count.
    // It must match the pod template's labels.
    // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
    Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,2,opt,name=selector"`

    // template is the object that describes the pod that will be created if
    // insufficient replicas are detected. Each pod stamped out by the StatefulSet
    // will fulfill this Template, but have a unique identity from the rest
    // of the StatefulSet.
    Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,3,opt,name=template"`

    // volumeClaimTemplates is a list of claims that pods are allowed to reference.
    // The StatefulSet controller is responsible for mapping network identities to
    // claims in a way that maintains the identity of a pod. Every claim in
    // this list must have at least one matching (by name) volumeMount in one
    // container in the template. A claim in this list takes precedence over
    // any volumes in the template, with the same name.
    // TODO: Define the behavior if a claim already exists with the same name.
    // +optional
    VolumeClaimTemplates []v1.PersistentVolumeClaim `json:"volumeClaimTemplates,omitempty" protobuf:"bytes,4,rep,name=volumeClaimTemplates"`

    // serviceName is the name of the service that governs this StatefulSet.
    // This service must exist before the StatefulSet, and is responsible for
    // the network identity of the set. Pods get DNS/hostnames that follow the
    // pattern: pod-specific-string.serviceName.default.svc.cluster.local
    // where "pod-specific-string" is managed by the StatefulSet controller.
    ServiceName string `json:"serviceName" protobuf:"bytes,5,opt,name=serviceName"`

    // podManagementPolicy controls how pods are created during initial scale up,
    // when replacing pods on nodes, or when scaling down. The default policy is
    // `OrderedReady`, where pods are created in increasing order (pod-0, then
    // pod-1, etc) and the controller will wait until each pod is ready before
    // continuing. When scaling down, the pods are removed in the opposite order.
    // The alternative policy is `Parallel` which will create pods in parallel
    // to match the desired scale without waiting, and on scale down will delete
    // all pods at once.
    // +optional
    PodManagementPolicy PodManagementPolicyType `json:"podManagementPolicy,omitempty" protobuf:"bytes,6,opt,name=podManagementPolicy,casttype=PodManagementPolicyType"`

    // updateStrategy indicates the StatefulSetUpdateStrategy that will be
    // employed to update Pods in the StatefulSet when a revision is made to
    // Template.
    UpdateStrategy StatefulSetUpdateStrategy `json:"updateStrategy,omitempty" protobuf:"bytes,7,opt,name=updateStrategy"`

    // revisionHistoryLimit is the maximum number of revisions that will
    // be maintained in the StatefulSet's revision history. The revision history
    // consists of all revisions not represented by a currently applied
    // StatefulSetSpec version. The default value is 10.
    RevisionHistoryLimit *int32 `json:"revisionHistoryLimit,omitempty" protobuf:"varint,8,opt,name=revisionHistoryLimit"`

    // Minimum number of seconds for which a newly created pod should be ready
    // without any of its container crashing for it to be considered available.
    // Defaults to 0 (pod will be considered available as soon as it is ready)
    // This is an alpha field and requires enabling StatefulSetMinReadySeconds feature gate.
    // +optional
    MinReadySeconds int32 `json:"minReadySeconds,omitempty" protobuf:"varint,9,opt,name=minReadySeconds"`
}

metav1.LabelSelector

TODO;

v1.PodTemplateSpec

参考 Pods 资源。

v1.PersistentVolumeClaim

TODO;

PodManagementPolicyType

// PodManagementPolicyType defines the policy for creating pods under a stateful set.
type PodManagementPolicyType string

const (
    // OrderedReadyPodManagement will create pods in strictly increasing order on
    // scale up and strictly decreasing order on scale down, progressing only when
    // the previous pod is ready or terminated. At most one pod will be changed
    // at any time.
    OrderedReadyPodManagement PodManagementPolicyType = "OrderedReady"
    // ParallelPodManagement will create and delete pods as soon as the stateful set
    // replica count is changed, and will not wait for pods to be ready or complete
    // termination.
    ParallelPodManagement PodManagementPolicyType = "Parallel"
)

StatefulSetUpdateStrategy

// StatefulSetUpdateStrategy indicates the strategy that the StatefulSet
// controller will use to perform updates. It includes any additional parameters
// necessary to perform the update for the indicated strategy.
type StatefulSetUpdateStrategy struct {
    // Type indicates the type of the StatefulSetUpdateStrategy.
    // Default is RollingUpdate.
    // +optional
    Type StatefulSetUpdateStrategyType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type,casttype=StatefulSetStrategyType"`
    // RollingUpdate is used to communicate parameters when Type is RollingUpdateStatefulSetStrategyType.
    // +optional
    RollingUpdate *RollingUpdateStatefulSetStrategy `json:"rollingUpdate,omitempty" protobuf:"bytes,2,opt,name=rollingUpdate"`
}

// StatefulSetUpdateStrategyType is a string enumeration type that enumerates
// all possible update strategies for the StatefulSet controller.
type StatefulSetUpdateStrategyType string

const (
    // RollingUpdateStatefulSetStrategyType indicates that update will be
    // applied to all Pods in the StatefulSet with respect to the StatefulSet
    // ordering constraints. When a scale operation is performed with this
    // strategy, new Pods will be created from the specification version indicated
    // by the StatefulSet's updateRevision.
    RollingUpdateStatefulSetStrategyType StatefulSetUpdateStrategyType = "RollingUpdate"
    // OnDeleteStatefulSetStrategyType triggers the legacy behavior. Version
    // tracking and ordered rolling restarts are disabled. Pods are recreated
    // from the StatefulSetSpec when they are manually deleted. When a scale
    // operation is performed with this strategy,specification version indicated
    // by the StatefulSet's currentRevision.
    OnDeleteStatefulSetStrategyType StatefulSetUpdateStrategyType = "OnDelete"
)

// RollingUpdateStatefulSetStrategy is used to communicate parameter for RollingUpdateStatefulSetStrategyType.
type RollingUpdateStatefulSetStrategy struct {
    // Partition indicates the ordinal at which the StatefulSet should be
    // partitioned.
    // Default value is 0.
    // +optional
    Partition *int32 `json:"partition,omitempty" protobuf:"varint,1,opt,name=partition"`
}

StatefulSetStatus

// StatefulSetStatus represents the current state of a StatefulSet.
type StatefulSetStatus struct {
    // observedGeneration is the most recent generation observed for this StatefulSet. It corresponds to the
    // StatefulSet's generation, which is updated on mutation by the API Server.
    // +optional
    ObservedGeneration int64 `json:"observedGeneration,omitempty" protobuf:"varint,1,opt,name=observedGeneration"`

    // replicas is the number of Pods created by the StatefulSet controller.
    Replicas int32 `json:"replicas" protobuf:"varint,2,opt,name=replicas"`

    // readyReplicas is the number of Pods created by the StatefulSet controller that have a Ready Condition.
    ReadyReplicas int32 `json:"readyReplicas,omitempty" protobuf:"varint,3,opt,name=readyReplicas"`

    // currentReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version
    // indicated by currentRevision.
    CurrentReplicas int32 `json:"currentReplicas,omitempty" protobuf:"varint,4,opt,name=currentReplicas"`

    // updatedReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version
    // indicated by updateRevision.
    UpdatedReplicas int32 `json:"updatedReplicas,omitempty" protobuf:"varint,5,opt,name=updatedReplicas"`

    // currentRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the
    // sequence [0,currentReplicas).
    CurrentRevision string `json:"currentRevision,omitempty" protobuf:"bytes,6,opt,name=currentRevision"`

    // updateRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the sequence
    // [replicas-updatedReplicas,replicas)
    UpdateRevision string `json:"updateRevision,omitempty" protobuf:"bytes,7,opt,name=updateRevision"`

    // collisionCount is the count of hash collisions for the StatefulSet. The StatefulSet controller
    // uses this field as a collision avoidance mechanism when it needs to create the name for the
    // newest ControllerRevision.
    // +optional
    CollisionCount *int32 `json:"collisionCount,omitempty" protobuf:"varint,9,opt,name=collisionCount"`

    // Represents the latest available observations of a statefulset's current state.
    // +optional
    // +patchMergeKey=type
    // +patchStrategy=merge
    Conditions []StatefulSetCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,10,rep,name=conditions"`

    // Total number of available pods (ready for at least minReadySeconds) targeted by this statefulset.
    // This is an alpha field and requires enabling StatefulSetMinReadySeconds feature gate.
    // Remove omitempty when graduating to beta
    // +optional
    AvailableReplicas int32 `json:"availableReplicas,omitempty" protobuf:"varint,11,opt,name=availableReplicas"`
}

StatefulSetCondition

type StatefulSetConditionType string

// StatefulSetCondition describes the state of a statefulset at a certain point.
type StatefulSetCondition struct {
    // Type of statefulset condition.
    Type StatefulSetConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=StatefulSetConditionType"`
    // Status of the condition, one of True, False, Unknown.
    Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"`
    // Last time the condition transitioned from one status to another.
    // +optional
    LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"`
    // The reason for the condition's last transition.
    // +optional
    Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"`
    // A human readable message indicating details about the transition.
    // +optional
    Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"`
}

v1.ConditionStatus

参考 Pods 资源。