MCPcopy
hub / github.com/grafana/grafana / Run

Method Run

pkg/infra/leaderelection/leader_election.go:139–193  ·  view source on GitHub ↗

Run participates in leader election and calls fn when leadership is acquired. fn receives a context that is cancelled when leadership is lost. Run blocks until ctx is cancelled.

(ctx context.Context, fn func(ctx context.Context), opts ...RunOption)

Source from the content-addressed store, hash-verified

137// fn receives a context that is cancelled when leadership is lost.
138// Run blocks until ctx is cancelled.
139func (k *KubernetesElector) Run(ctx context.Context, fn func(ctx context.Context), opts ...RunOption) error {
140 o := ResolveRunOptions([]RunOption{
141 WithReleaseOnCancel(true),
142 WithOnStartedLeading(func(ctx context.Context) {
143 k.logger.Info("Acquired leader lease, starting leader work",
144 "identity", k.identity,
145 "lease", k.leaseName,
146 "namespace", k.namespace,
147 )
148 }),
149 WithOnStoppedLeading(func() {
150 k.logger.Info("Lost leader lease, stopping leader work",
151 "identity", k.identity,
152 )
153 }),
154 WithOnNewLeader(func(identity string) {
155 if identity != k.identity {
156 k.logger.Info("New leader elected", "leader", identity)
157 }
158 }),
159 }, opts)
160
161 lock := &resourcelock.LeaseLock{
162 LeaseMeta: metav1.ObjectMeta{
163 Name: k.leaseName,
164 Namespace: k.namespace,
165 },
166 Client: k.kubeClient.CoordinationV1(),
167 LockConfig: resourcelock.ResourceLockConfig{
168 Identity: k.identity,
169 },
170 }
171
172 le, err := leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{
173 Lock: lock,
174 LeaseDuration: k.leaseDuration,
175 RenewDeadline: k.renewDeadline,
176 RetryPeriod: k.retryPeriod,
177 ReleaseOnCancel: o.ReleaseOnCancel,
178 Callbacks: leaderelection.LeaderCallbacks{
179 OnStartedLeading: func(ctx context.Context) {
180 o.OnStartedLeading(ctx)
181 fn(ctx)
182 },
183 OnStoppedLeading: o.OnStoppedLeading,
184 OnNewLeader: o.OnNewLeader,
185 },
186 })
187 if err != nil {
188 return fmt.Errorf("failed to create leader elector: %w", err)
189 }
190
191 le.Run(ctx)
192 return ctx.Err()
193}

Callers

nothing calls this directly

Calls 10

ResolveRunOptionsFunction · 0.85
WithReleaseOnCancelFunction · 0.85
WithOnStartedLeadingFunction · 0.85
WithOnStoppedLeadingFunction · 0.85
WithOnNewLeaderFunction · 0.85
InfoMethod · 0.65
ErrorfMethod · 0.65
RunMethod · 0.65
ErrMethod · 0.65
fnFunction · 0.50

Tested by

no test coverage detected