Mở rộng Kubernetes: CRD và Operator pattern
Bài trước cho thấy API server là một kho REST tổng quát và controller là vòng lặp watch rồi reconcile. Bài này đi tiếp một bước: bạn sẽ thêm một kiểu object mới vào chính API đó bằng CustomResourceDefinition (CRD), rồi viết một controller hiểu kiểu object ấy. Ghép hai thứ lại là Operator pattern, cách cả hệ sinh thái Kubernetes (cert-manager, Prometheus Operator, Argo CD…) mở rộng cluster.
Vì sao cần mở rộng Kubernetes
Kubernetes có sẵn những khái niệm chung: Pod, Deployment, Service, Job. Nhưng nó không biết "một cụm PostgreSQL có primary, replica, backup mỗi đêm và failover" là gì. Ở chương 8 bạn tự chạy postgres bằng StatefulSet; backup, khôi phục, nâng cấp phiên bản vẫn là việc của bạn, làm bằng tay theo một runbook.
Ở thế giới Docker, bạn giải quyết bằng script cron trên máy chủ cộng tài liệu hướng dẫn. Kubernetes cho cách tốt hơn:
- Dạy API một danh từ mới:
NotesBackupvớischedulevàretention. Người dùng chỉ khai báo "tôi muốn backup notes mỗi đêm, giữ 7 bản". - Thêm một robot vận hành: một controller watch các
NotesBackupvà liên tục làm đúng việc mà runbook mô tả.
Bạn đã dùng CRD suốt khóa học mà có thể không để ý: Certificate của cert-manager, HTTPRoute của Gateway API (chương 6), Application của Argo CD (chương 12), ServiceMonitor của Prometheus Operator (chương 13). Xem trên cluster của bạn:
kubectl get crdNAME CREATED AT
certificates.cert-manager.io 2026-11-20T03:12:44Z
gatewayclasses.gateway.networking.k8s.io 2026-11-19T08:01:10Z
httproutes.gateway.networking.k8s.io 2026-11-19T08:01:10Z
...Cơ chế: CRD và custom resource
Khi bạn tạo một CRD, API server tự động phục vụ một endpoint REST mới, ví dụ /apis/notes.example.com/v1alpha1/namespaces/notes/notesbackups. Mọi thứ đã học ở bài trước áp dụng nguyên vẹn cho kiểu mới: xác thực, RBAC, admission, lưu vào etcd (ở dạng JSON), watch, server-side apply, garbage collection, kubectl get/describe/edit. Object tạo từ CRD gọi là custom resource (CR).
Nhưng CRD chỉ là dữ liệu. Tạo một NotesBackup không làm gì xảy ra cả, giống như ghi một dòng vào database mà không có chương trình nào đọc. Phải có controller watch CR và hành động:
Các phần chính của một CRD:
| Field | Ý nghĩa |
|---|---|
metadata.name | Bắt buộc có dạng <plural>.<group> |
spec.group | Nhóm API, thường là tên miền bạn sở hữu: notes.example.com |
spec.names | plural (dùng trong URL), singular, kind (dùng trong YAML), shortNames |
spec.scope | Namespaced hoặc Cluster |
spec.versions[] | Mỗi version có served (API có phục vụ không) và storage (version dùng để lưu vào etcd; đúng một version là true) |
schema.openAPIV3Schema | Schema kiểu dữ liệu và ràng buộc: type, required, enum, minimum, maximum, maxLength, pattern, default |
x-kubernetes-validations | Quy tắc CEL (như ValidatingAdmissionPolicy) cho ràng buộc mà schema không diễn đạt được; oldSelf cho phép viết quy tắc chuyển trạng thái, ví dụ field bất biến self == oldSelf |
subresources.status | Tách /status: người dùng sửa spec, controller sửa status |
subresources.scale | Cho kubectl scale và HPA dùng được với CR (chỉ ra đường dẫn specReplicasPath, statusReplicasPath) |
additionalPrinterColumns | Cột hiển thị trong kubectl get |
Schema là bắt buộc với apiextensions.k8s.io/v1 và phải là structural schema (mọi field đều khai báo kiểu). Field không có trong schema bị cắt bỏ (pruning) khi lưu, nên gõ sai tên field sẽ không âm thầm lọt vào etcd.
Thực hành: tạo CRD NotesBackup
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: notesbackups.notes.example.com
spec:
group: notes.example.com
scope: Namespaced
names:
plural: notesbackups
singular: notesbackup
kind: NotesBackup
shortNames: ["nb"]
versions:
- name: v1alpha1
served: true
storage: true
subresources:
status: {}
additionalPrinterColumns:
- name: Schedule
type: string
jsonPath: .spec.schedule
- name: Retention
type: integer
jsonPath: .spec.retention
- name: Last Backup
type: date
jsonPath: .status.lastBackupTime
- name: Age
type: date
jsonPath: .metadata.creationTimestamp
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required: ["schedule"]
properties:
schedule:
type: string
description: Lịch cron 5 trường, ví dụ "0 2 * * *" (2 giờ sáng mỗi ngày).
maxLength: 64
x-kubernetes-validations:
- rule: "self.split(' ').size() == 5"
message: "schedule phải gồm đúng 5 trường cron"
retention:
type: integer
description: Số bản backup gần nhất được giữ lại.
minimum: 1
maximum: 30
default: 7
status:
type: object
properties:
lastBackupTime:
type: string
format: date-timekubectl apply -f notesbackup-crd.yaml
kubectl api-resources --api-group=notes.example.comcustomresourcedefinition.apiextensions.k8s.io/notesbackups.notes.example.com created
NAME SHORTNAMES APIVERSION NAMESPACED KIND
notesbackups nb notes.example.com/v1alpha1 true NotesBackupGiờ tạo một custom resource giống hệt cách tạo Deployment:
apiVersion: notes.example.com/v1alpha1
kind: NotesBackup
metadata:
name: nightly
namespace: notes
spec:
schedule: "0 2 * * *"kubectl apply -f notesbackup-nightly.yaml
kubectl -n notes get notesbackups
kubectl explain notesbackup.specnotesbackup.notes.example.com/nightly created
NAME SCHEDULE RETENTION LAST BACKUP AGE
nightly 0 2 * * * 7 <none> 4s
GROUP: notes.example.com
KIND: NotesBackup
VERSION: v1alpha1
FIELD: spec <Object>
...
FIELDS:
retention <integer>
Số bản backup gần nhất được giữ lại.
schedule <string> -required-
Lịch cron 5 trường, ví dụ "0 2 * * *" (2 giờ sáng mỗi ngày).Để ý: retention được điền 7 nhờ default, cột hiển thị lấy từ additionalPrinterColumns, và kubectl explain đọc mô tả từ schema. Thử một CR sai:
kubectl -n notes apply -f - <<'EOF'
apiVersion: notes.example.com/v1alpha1
kind: NotesBackup
metadata:
name: hong
spec:
schedule: "0 2 * *"
retention: 90
EOFThe NotesBackup "hong" is invalid:
* spec.retention: Invalid value: 90: spec.retention in body should be less than or equal to 30
* spec.schedule: Invalid value: "string": schedule phải gồm đúng 5 trường cronAPI server từ chối ngay ở bước kiểm tra schema, trước khi bất kỳ controller nào phải đoán ý người dùng.
Đóng vai controller: cập nhật status
Vì bật subresource status, kubectl apply hay edit lên object chính bỏ qua mọi thay đổi trong status. Controller ghi status qua đường /status; bạn có thể làm thử bằng tay:
kubectl -n notes patch notesbackup nightly --subresource=status --type=merge \
-p '{"status":{"lastBackupTime":"2026-11-28T02:00:00Z"}}'
kubectl -n notes get nb
kubectl get --raw /apis/notes.example.com/v1alpha1/namespaces/notes/notesbackups/nightly | jq .statusnotesbackup.notes.example.com/nightly patched
NAME SCHEDULE RETENTION LAST BACKUP AGE
nightly 0 2 * * * 7 7h 6m
{
"lastBackupTime": "2026-11-28T02:00:00Z"
}Tách spec và status còn có ý nghĩa phân quyền: RBAC cấp quyền cho resource notesbackups và notesbackups/status riêng biệt, nên người dùng sửa được mong muốn mà không giả mạo được trạng thái.
Operator pattern: CRD + controller mang kiến thức vận hành
Thuật ngữ operator (CoreOS đặt ra năm 2016) chỉ một controller mã hóa kiến thức của người vận hành: thay vì một người đọc runbook lúc 2 giờ sáng, một chương trình trong cluster làm việc đó liên tục. Controller của NotesBackup sẽ chạy vòng lặp:
- Quan sát: đọc
NotesBackupvà các Job nó đã tạo (lọc theo labelnotes.example.com/backup=<tên>). - So sánh: theo
schedulevàstatus.lastBackupTime, đã tới lượt backup chưa? Có bao nhiêu Job cũ vượtretention? - Hành động: tạo Job chạy
pg_dump(có ownerReference trỏ về CR, nên xóa CR thì garbage collector dọn luôn Job), xóa Job cũ, cập nhậtstatus. - Hẹn lại: yêu cầu được gọi lại đúng lúc tới lượt kế tiếp (requeue).
Những nguyên tắc làm nên một controller tốt:
- Idempotent: chạy reconcile 1 lần hay 10 lần với cùng trạng thái phải cho cùng kết quả. Đặt tên Job xác định theo thời điểm lịch (
nightly-1764295200) để lần chạy lặp lại gặpAlreadyExiststhay vì tạo bản trùng. - Level-triggered: không dựa vào việc "vừa nhận sự kiện gì", luôn đọc trạng thái hiện tại rồi tính lại từ đầu.
- Status chỉ phản ánh điều quan sát được: không bao giờ sửa
speccủa người dùng; đó là cách chắc chắn nhất để đánh nhau với GitOps. - Lỗi thì trả lỗi: kể cả
409 Conflictkhi ghi status. Framework sẽ requeue với backoff, lần sau đọc bản mới nhất.
Viết controller bằng Go với Kubebuilder
Kubebuilder là bộ khung chính thức (dự án của SIG API Machinery) dựng sẵn mọi thứ quanh thư viện controller-runtime: informer, cache, work queue, leader election, metrics. Bạn chỉ viết kiểu dữ liệu và hàm Reconcile.
kubebuilder init --domain example.com --repo example.com/notes-operator
kubebuilder create api --group notes --version v1alpha1 --kind NotesBackupnotes-operator/
├── api/v1alpha1/notesbackup_types.go # struct Go: nguồn sinh ra CRD
├── internal/controller/notesbackup_controller.go
├── config/crd/bases/ # CRD YAML do controller-gen sinh
├── config/rbac/ # Role sinh từ marker +kubebuilder:rbac
├── cmd/main.go # khởi động manager
└── MakefileKiểu dữ liệu viết bằng Go; các comment +kubebuilder: (marker) sinh ra schema, validation và printer column giống hệt CRD YAML ở trên:
type NotesBackupSpec struct {
// Lịch cron 5 trường, ví dụ "0 2 * * *".
// +kubebuilder:validation:MaxLength=64
// +kubebuilder:validation:XValidation:rule="self.split(' ').size() == 5",message="schedule phải gồm đúng 5 trường cron"
Schedule string `json:"schedule"`
// Số bản backup gần nhất được giữ lại.
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=30
// +kubebuilder:default=7
// +optional
Retention int32 `json:"retention,omitempty"`
}
type NotesBackupStatus struct {
LastBackupTime *metav1.Time `json:"lastBackupTime,omitempty"`
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Schedule",type=string,JSONPath=`.spec.schedule`
type NotesBackup struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec NotesBackupSpec `json:"spec,omitempty"`
Status NotesBackupStatus `json:"status,omitempty"`
}Hàm Reconcile (rút gọn; newBackupJob dựng Job chạy pg_dump và gắn label, deleteOldJobs xóa Job cũ vượt retention, cron parser là thư viện robfig/cron):
// +kubebuilder:rbac:groups=notes.example.com,resources=notesbackups,verbs=get;list;watch
// +kubebuilder:rbac:groups=notes.example.com,resources=notesbackups/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch;create;delete
func (r *NotesBackupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
// 1. Quan sát (đọc từ cache của informer)
var nb notesv1alpha1.NotesBackup
if err := r.Get(ctx, req.NamespacedName, &nb); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err) // CR đã bị xóa: GC dọn Job con
}
var jobs batchv1.JobList
if err := r.List(ctx, &jobs, client.InNamespace(nb.Namespace),
client.MatchingLabels{"notes.example.com/backup": nb.Name}); err != nil {
return ctrl.Result{}, err
}
// 2. So sánh
sched, err := cron.ParseStandard(nb.Spec.Schedule)
if err != nil {
return ctrl.Result{}, nil // spec sai: chờ người dùng sửa, không requeue vô ích
}
last := nb.CreationTimestamp.Time
if nb.Status.LastBackupTime != nil {
last = nb.Status.LastBackupTime.Time
}
now := time.Now()
// 3. Hành động
if due := sched.Next(last); !now.Before(due) {
job := newBackupJob(&nb, due) // tên xác định theo due: chạy lại không tạo trùng
if err := ctrl.SetControllerReference(&nb, job, r.Scheme); err != nil {
return ctrl.Result{}, err
}
if err := r.Create(ctx, job); err != nil && !apierrors.IsAlreadyExists(err) {
return ctrl.Result{}, err
}
nb.Status.LastBackupTime = &metav1.Time{Time: now}
if err := r.Status().Update(ctx, &nb); err != nil {
return ctrl.Result{}, err // kể cả 409 Conflict: trả lỗi để được requeue
}
}
if err := r.deleteOldJobs(ctx, jobs.Items, int(nb.Spec.Retention)); err != nil {
return ctrl.Result{}, err
}
// 4. Hẹn lần sau
return ctrl.Result{RequeueAfter: sched.Next(now).Sub(now)}, nil
}
func (r *NotesBackupReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(¬esv1alpha1.NotesBackup{}). // watch CR
Owns(&batchv1.Job{}). // watch Job có ownerReference trỏ về CR
Complete(r)
}make manifests # controller-gen sinh CRD và RBAC từ marker
make install # apply CRD vào cluster hiện tại (kind-hoc-k8s)
make run # chạy controller trên máy bạn bằng kubeconfigOwns(&batchv1.Job{}) nghĩa là khi một Job con đổi trạng thái (xong, lỗi, bị xóa), key của NotesBackup cha được đưa vào queue: đúng mô hình informer và work queue của bài trước. Khi ổn, make docker-build và make deploy IMG=... đưa controller vào cluster như một Deployment.
Không dùng Go? Operator SDK (dự án Operator Framework) xây trên Kubebuilder và cho thêm operator viết bằng Helm chart hoặc Ansible; kopf cho viết operator bằng Python với decorator như @kopf.on.create("notes.example.com", "v1alpha1", "notesbackups").
Học từ các operator thật
| Operator | CR chính | Kiến thức vận hành được mã hóa |
|---|---|---|
| cert-manager | Certificate, Issuer | Xin chứng chỉ ACME, gia hạn trước khi hết hạn, ghi Secret (chương 6) |
| Prometheus Operator | Prometheus, ServiceMonitor, PrometheusRule | Sinh cấu hình scrape và rule từ CR (chương 13) |
| CloudNativePG | Cluster, Backup, ScheduledBackup | PostgreSQL HA: primary/replica, failover, backup lên object storage, khôi phục theo thời điểm |
| Strimzi | Kafka, KafkaTopic, KafkaUser | Dựng cụm Kafka, quản lý topic và user, restart broker đúng thứ tự |
| Argo CD | Application, ApplicationSet | Đồng bộ Git vào cluster (chương 12) |
So sánh StatefulSet postgres tự viết ở chương 8 với một Cluster của CloudNativePG là cách nhanh nhất để thấy giá trị của operator: vài dòng YAML đổi lấy failover tự động và backup có kiểm chứng. ScheduledBackup của nó chính là phiên bản trưởng thành của NotesBackup.
Operator Framework chia operator theo 5 mức năng lực (capability levels), hữu ích khi đánh giá một operator có sẵn:
| Mức | Tên | Operator làm được |
|---|---|---|
| 1 | Basic Install | Cài đặt và cấu hình tự động |
| 2 | Seamless Upgrades | Nâng cấp phiên bản phần mềm |
| 3 | Full Lifecycle | Backup, khôi phục, xử lý sự cố |
| 4 | Deep Insights | Metrics, cảnh báo, phân tích log |
| 5 | Auto Pilot | Tự co giãn, tự tinh chỉnh, phát hiện bất thường |
Khi nào nên viết operator
| Nhu cầu | Lựa chọn hợp lý |
|---|---|
| Đóng gói và tham số hóa manifest cho nhiều môi trường | Helm, Kustomize (chương 12) |
| Chạy một việc theo lịch cố định | CronJob (chương 4) |
| Chạy phần mềm phổ biến (PostgreSQL, Kafka, Redis) | Operator có sẵn, đã được cộng đồng kiểm chứng |
| Logic vận hành riêng, phản ứng liên tục theo trạng thái, nhiều team tự phục vụ qua một API | Tự viết operator |
Nói thật: NotesBackup trong bài hoàn toàn có thể chỉ là một CronJob. Operator đáng công khi logic vượt quá "chạy lệnh theo giờ": chọn replica để backup, kiểm tra backup khôi phục được, xoay vòng theo dung lượng, báo trạng thái cho hàng trăm team. Operator là phần mềm bạn phải bảo trì, nâng cấp và giám sát như mọi phần mềm khác.
Bẫy thường gặp
1. Đổi schema CRD làm hỏng object cũ. Thêm field tùy chọn thì an toàn; đổi kiểu, đổi tên, thêm required là thay đổi phá vỡ. Cách đúng: thêm version mới (v1beta1) với served: true, chuyển storage sang version mới, ghi lại các object cũ (storage version migration), rồi mới thôi phục vụ version cũ. API server từ chối gỡ một version vẫn còn trong status.storedVersions của CRD.
2. Conversion webhook chết. Khi các version khác nhau về cấu trúc, CRD cần conversion.strategy: Webhook để chuyển đổi qua lại. Webhook này chết thì mọi request cần chuyển đổi giữa các version đều lỗi, kể cả của garbage collector và kubectl. Đối xử với nó như admission webhook: nhiều replica, giám sát chặt.
3. Gỡ cài đặt sai thứ tự. Xóa CRD sẽ xóa mọi custom resource của nó. Nếu CR có finalizer mà operator đã bị gỡ trước, CR và cả CRD kẹt ở Terminating. Thứ tự đúng: xóa CR, chờ operator dọn dẹp, gỡ operator, cuối cùng mới xóa CRD. Lưu ý Helm cài CRD trong thư mục crds/ nhưng không nâng cấp hay xóa chúng.
4. Quy tắc CEL bị từ chối vì "vượt chi phí". API server ước lượng chi phí xấu nhất của quy tắc; chuỗi hoặc danh sách không giới hạn độ dài làm ước lượng vượt ngưỡng. Luôn đặt maxLength, maxItems, maxProperties cho field mà quy tắc CEL đụng tới.
5. Operator quyền quá rộng. Marker RBAC sinh Role theo đúng những gì bạn khai báo; đừng "sửa nhanh" bằng cách gán cluster-admin. Operator là một tiến trình chạy lâu dài trong cluster, bị chiếm quyền là mất cả cluster.
Tóm tắt
- CRD dạy API server một kiểu object mới: endpoint REST, lưu etcd, RBAC, watch, kubectl đều có sẵn. CRD một mình chỉ là dữ liệu.
- CRD gồm
group,names,scope,versions(một versionstorage),openAPIV3Schema(structural, có validation và default),x-kubernetes-validations(CEL), subresourcestatus/scale,additionalPrinterColumns. - Subresource
statustách mong muốn (spec, người dùng sửa) khỏi trạng thái (status, controller ghi), có RBAC riêng. - Operator = CRD + controller mã hóa kiến thức vận hành: quan sát → so sánh → hành động → cập nhật status → requeue; idempotent, level-triggered, gắn ownerReference cho object con.
- Kubebuilder/controller-runtime (Go) là bộ khung chuẩn; Operator SDK và kopf (Python) là lựa chọn khác.
- Học từ cert-manager, Prometheus Operator, CloudNativePG, Strimzi, Argo CD; ưu tiên operator có sẵn và chỉ tự viết khi Helm, Kustomize, CronJob không đủ.
- Cẩn thận khi nâng cấp CRD, với conversion webhook và thứ tự gỡ cài đặt (xóa CRD là xóa mọi CR).
Comments