Skip to content

monitor: support affinity and topologySpreadConstraints for TidbMonitor - #7179

Open
time-and-fate wants to merge 2 commits into
pingcap:release-1.xfrom
time-and-fate:261204-tidbmonitor-scheduling
Open

time-and-fate wants to merge 2 commits into
pingcap:release-1.xfrom
time-and-fate:261204-tidbmonitor-scheduling

Conversation

@time-and-fate

@time-and-fate time-and-fate commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

TidbMonitor has no way to control where monitoring replicas are scheduled. The monitor pods carry neither affinity nor topologySpreadConstraints, so when replicas is greater than 1 the replicas of one monitor can land on the same node or in the same zone and share a single failure domain.

TidbCluster and DMCluster already expose both fields. This PR adds them to TidbMonitor with the same types and semantics.

While reusing the topology spread conversion for TidbMonitor, I found that setting topologySpreadConstraints on TidbDashboard or TidbNGMonitoring makes tidb-controller-manager panic with assignment to entry in nil map: the label selector of a constraint is built from the base labels of the CR kind, and those two kinds were not handled. This PR fixes it as well.

What is changed and how does it work?

  • Two optional fields are added to TidbMonitorSpec, next to nodeSelector and tolerations:
    • affinity (core/v1 Affinity) is passed through to the monitor StatefulSet pod template as is.
    • topologySpreadConstraints uses the same type as TidbCluster. whenUnsatisfiable is always DoNotSchedule and the labelSelector is generated by the operator, so a constraint only needs topologyKey. The selector matches the instance label of the monitor shard, i.e. replicas are spread within a shard.
  • Both fields have no default. When they are unset the rendered pod template is identical to before and existing monitors are not rolled.
  • The conversion loop in componentAccessorImpl.TopologySpreadConstraints() is extracted into buildPodTopologySpreadConstraints(), which is now shared with the new TidbMonitor.PodTopologySpreadConstraints().
  • Fix: TidbDashboard and TidbNGMonitoring get their base labels (label.NewTiDBDashboard() / label.NewTiDBNGMonitoring()) when building the selector, and TidbDashboard gets its component label value.

Notes for the documentation PR:

  • Constraints are hard constraints. A replica that cannot satisfy them stays Pending; soft requirements can be expressed with affinity.
  • whenUnsatisfiable, labelSelector, nodeTaintsPolicy and matchLabelKeys are not part of the type. Unknown fields are pruned by the API server (recent kubectl reports an error in its default strict mode).
  • Once a pod declares a constraint, the built-in default cluster constraints no longer apply to it, so declare both the zone and the hostname constraint if both are needed.
  • With persistent: true, a volume that is already bound to one zone pins its replica to that zone. Check the storage class before adding a zone constraint to an existing monitor.
  • The CRD must be upgraded before the fields are used; an old CRD prunes them silently.

Code changes

  • Has Go code change
  • Has CI related scripts change

Tests

  • Unit test
  • E2E test
  • Manual test

Unit tests:

  • pkg/apis/pingcap/v1alpha1: the generated constraints of every kind that uses the accessor (TidbCluster, DMCluster incl. discovery, TidbNGMonitoring, TidbDashboard), the matchLabels override, and TidbMonitor.PodTopologySpreadConstraints() for shard 0 and shard N.
  • pkg/monitor/monitor: the monitor StatefulSet gets affinity and the constraints (selector equals the pod labels), and each shard gets its own selector.
  • pkg/manager/tidbdashboard, pkg/manager/tidbngmonitoring: the StatefulSet carries the constraints.

E2E test: TidbMonitor topology spread constraint in tests/e2e/tidbcluster/tidbcluster.go — two replicas with a zone constraint must end up in different zones. Verified locally via hack/e2e.sh -- --ginkgo.focus='TidbMonitor topology spread constraint' (1 Passed | 0 Failed | 0 Flaked).

Manual test on kind (operator built from this branch, 3 workers in 2 zones):

  1. A monitor with 2 replicas and no new fields: the StatefulSet template has no affinity/topologySpreadConstraints.
  2. Add a zone and a hostname constraint: the template is updated within seconds, both pods are recreated and run in different zones on different nodes.
  3. shards: 2 with replicas: 2: each shard gets its own selector and spreads over both zones.
  4. affinity.nodeAffinity shows up in the template and limits the nodes as expected.
  5. 3 replicas with zone and hostname constraints on 2 eligible nodes: all three run (2 on one node, 1 on the other).
  6. With AdvancedStatefulSet=true: the statefulsets.apps.pingcap.com object and the pods carry the constraints.

Side effects

  • Breaking backward compatibility
  • Other side effects: none when the new fields are unset. Setting or changing them updates the pod template, which rolls the monitor pods.

Related changes

  • Need to cherry-pick to the release branch
  • Need to update the documentation

Release Notes

Please refer to Release Notes Language Style Guide before writing the release note.

Add the feature of configuring `affinity` and `topologySpreadConstraints` for `TidbMonitor` pods to spread monitoring replicas across nodes and zones

Fix the panic of tidb-controller-manager when `topologySpreadConstraints` is set for `TidbDashboard` or `TidbNGMonitoring`

Summary by CodeRabbit

  • New Features
    • Added configurable pod affinity and anti-affinity for TiDB Monitor pods.
    • Added topology spread constraints for TiDB Monitor, TiDB, DM, TiDB Dashboard, and TiDB NG Monitoring workloads, helping control how pods are distributed across nodes or zones.
    • Added shard-aware selectors for TiDB Monitor topology constraints and documented the new scheduling options.
  • Tests
    • Added coverage for constraint configuration, generated workloads, and monitor pod distribution across zones.

…bDashboard/TidbNGMonitoring

The label selector of a pod topology spread constraint is built from the
base labels of the CR kind the component belongs to. Only TidbCluster and
DMCluster were handled, so setting topologySpreadConstraints on
TidbDashboard or TidbNGMonitoring assigned to a nil map and crashed
tidb-controller-manager.

Add the two missing kinds and the component label value of TidbDashboard,
and cover the conversion of every kind that uses the accessor with unit
tests.
TidbMonitor pods carry no scheduling constraints, so replicas of one
monitor can be scheduled to the same node or the same zone. Add two
optional fields to TidbMonitorSpec and propagate them to the monitor
StatefulSet pod template:

- affinity is passed through as is.
- topologySpreadConstraints uses the same type as TidbCluster. Constraints
  are always DoNotSchedule and the labelSelector is generated for the
  instance of each monitor shard, so replicas are spread within a shard.

Both fields have no default. When they are unset the rendered pod template
is unchanged, so existing monitors are not rolled by the upgrade.

The conversion loop of componentAccessorImpl.TopologySpreadConstraints()
is extracted into buildPodTopologySpreadConstraints(), which is shared
with the new TidbMonitor.PodTopologySpreadConstraints().
@ti-chi-bot

ti-chi-bot Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign hanlins for approval. For more information see the Code Review Process.
Please ensure that each of them provides their approval before proceeding.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

TidbMonitor now accepts affinity and topology spread settings. The changes add schema and API reference support, generate selectors for monitor instances, and include the settings in monitor pod specs. Tests cover StatefulSet generation and pod distribution across zones.

Changes: TidbMonitor Pod Scheduling

Layer / File(s) Summary
Scheduling fields and schema
pkg/apis/pingcap/v1alpha1/tidbmonitor_types.go, manifests/crd.yaml, manifests/crd/v1/pingcap.com_tidbmonitors.yaml, pkg/apis/pingcap/v1alpha1/openapi_generated.go, pkg/apis/pingcap/v1alpha1/zz_generated.deepcopy.go, docs/api-references/docs.md
TidbMonitorSpec adds optional Affinity and TopologySpreadConstraints fields. CRD and OpenAPI schemas, deep-copy code, and API reference entries are updated to include them.
Topology selector generation
pkg/apis/pingcap/v1alpha1/component_spec.go, pkg/apis/pingcap/v1alpha1/topology_spread_constraints_test.go
Topology spread selectors now support TiDB Dashboard and TiDB NG Monitoring base labels. MatchLabels can override component and instance label values. Tests cover label generation and per-constraint overrides.
Monitor pod integration and validation
pkg/apis/pingcap/v1alpha1/tidbmonitor_component.go, pkg/monitor/monitor/util.go, pkg/monitor/monitor/monitor_manager_test.go, pkg/manager/tidbdashboard/manager_test.go, pkg/manager/tidbngmonitoring/ng_monitoring_manager_test.go, tests/e2e/tidbcluster/tidbcluster.go
Monitor pod specs now include a deep copy of affinity and topology constraints generated for the monitor instance. Tests cover monitor shards and StatefulSet generation. The e2e test checks the zone distribution of two monitor pods.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant MonitorSpec as TidbMonitorSpec
  participant PodSpecBuilder as getMonitorStatefulSetSkeleton
  participant MonitorMethod as TidbMonitor.PodTopologySpreadConstraints
  participant ConstraintBuilder as TopologySpreadConstraints
  MonitorSpec->>PodSpecBuilder: provides affinity and topology spread settings
  PodSpecBuilder->>MonitorMethod: passes instanceName
  MonitorMethod->>ConstraintBuilder: passes configured constraints and monitor labels
  ConstraintBuilder-->>MonitorMethod: returns generated constraints
  MonitorMethod-->>PodSpecBuilder: returns instance constraints
  PodSpecBuilder->>MonitorSpec: adds affinity and constraints to generated pod spec
Loading

Suggested reviewers: liubog2008, csuzhangxc, yisaer

Merge Risk: Minimal · up to 52711

This adds optional scheduling controls to TidbMonitor and leaves existing monitors unchanged when the fields are unset. No merge-blocking risk was found. Users must upgrade the CRD before using the new fields, because older CRDs prune them silently.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: adding affinity and topologySpreadConstraints support to TidbMonitor. The raw summary confirms new TidbMonitorSpec fields, pod template wiring, CRD and deepcopy update…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: adding affinity and topologySpreadConstraints support to TidbMonitor. The raw summary confirms new TidbMonitorSpec fields, pod template wiring, CRD and deepcopy updates, and tests for that feature. The title is specific and concise, and it has no file lists or vague terms. It does not mention the TidbDashboard and TidbNGMonitoring selector fix, but that is a secondary change.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

ast-grep (0.51.3)

pkg/apis/pingcap/v1alpha1/openapi_generated.go

ast-grep timed out on this file

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the zone-bound sky,
Two monitor pods hop safely by.
Affinity finds a fitting place,
Spread labels mark each shard with grace.
The rabbit thumps: “The specs are set!”

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: eff519fb-cbdb-4df7-a28d-79989e4dc49c
Commits

Reviewing files that changed from the base of the PR and between 7f9a08b and 52711b0.

Files selected for processing: 14

  • docs/api-references/docs.md
  • manifests/crd.yaml
  • manifests/crd/v1/pingcap.com_tidbmonitors.yaml
  • pkg/apis/pingcap/v1alpha1/component_spec.go
  • pkg/apis/pingcap/v1alpha1/openapi_generated.go
  • pkg/apis/pingcap/v1alpha1/tidbmonitor_component.go
  • pkg/apis/pingcap/v1alpha1/tidbmonitor_types.go
  • pkg/apis/pingcap/v1alpha1/topology_spread_constraints_test.go
  • pkg/apis/pingcap/v1alpha1/zz_generated.deepcopy.go
  • pkg/manager/tidbdashboard/manager_test.go
  • pkg/manager/tidbngmonitoring/ng_monitoring_manager_test.go
  • pkg/monitor/monitor/monitor_manager_test.go
  • pkg/monitor/monitor/util.go
  • tests/e2e/tidbcluster/tidbcluster.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@ti-chi-bot ti-chi-bot Bot added the size/XXL label Dec 4, 2026
@time-and-fate

Copy link
Copy Markdown
Member Author

/retest

1 similar comment
@time-and-fate

Copy link
Copy Markdown
Member Author

/retest

@ti-chi-bot

ti-chi-bot Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

@time-and-fate: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
pull-e2e-kind-serial 52711b0 link false /test pull-e2e-kind-serial
pull-e2e-kind-basic 52711b0 link false /test pull-e2e-kind-basic
pull-e2e-kind-br 52711b0 link false /test pull-e2e-kind-br
pull-e2e-kind-tidbcluster 52711b0 link false /test pull-e2e-kind-tidbcluster
pull-e2e-kind-across-kubernetes 52711b0 link false /test pull-e2e-kind-across-kubernetes

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant