@@ -5,12 +5,14 @@ package elect
55
66import (
77 "context"
8+ "strings"
89 "sync/atomic"
910 "time"
1011
1112 "github.com/pingcap/tiproxy/lib/util/errors"
1213 "github.com/pingcap/tiproxy/lib/util/retry"
1314 "github.com/pingcap/tiproxy/lib/util/waitgroup"
15+ "github.com/pingcap/tiproxy/pkg/metrics"
1416 "github.com/pingcap/tiproxy/pkg/util/etcd"
1517 "github.com/siddontang/go/hack"
1618 "go.etcd.io/etcd/api/v3/mvccpb"
@@ -21,7 +23,9 @@ import (
2123)
2224
2325const (
24- logInterval = 10
26+ logInterval = 10
27+ ownerKeyPrefix = "/tiproxy/"
28+ ownerKeySuffix = "/owner"
2529)
2630
2731type Member interface {
@@ -65,26 +69,29 @@ var _ Election = (*election)(nil)
6569type election struct {
6670 cfg ElectionConfig
6771 // id is typically the instance address
68- id string
69- key string
70- lg * zap.Logger
71- etcdCli * clientv3.Client
72- elec atomic.Pointer [concurrency.Election ]
73- wg waitgroup.WaitGroup
74- cancel context.CancelFunc
75- member Member
72+ id string
73+ key string
74+ // trimedKey is shown as a label in grafana
75+ trimedKey string
76+ lg * zap.Logger
77+ etcdCli * clientv3.Client
78+ elec atomic.Pointer [concurrency.Election ]
79+ wg waitgroup.WaitGroup
80+ cancel context.CancelFunc
81+ member Member
7682}
7783
7884// NewElection creates an Election.
7985func NewElection (lg * zap.Logger , etcdCli * clientv3.Client , cfg ElectionConfig , id , key string , member Member ) * election {
8086 lg = lg .With (zap .String ("key" , key ), zap .String ("id" , id ))
8187 return & election {
82- lg : lg ,
83- etcdCli : etcdCli ,
84- cfg : cfg ,
85- id : id ,
86- key : key ,
87- member : member ,
88+ lg : lg ,
89+ etcdCli : etcdCli ,
90+ cfg : cfg ,
91+ id : id ,
92+ key : key ,
93+ trimedKey : strings .TrimSuffix (strings .TrimPrefix (key , ownerKeyPrefix ), ownerKeySuffix ),
94+ member : member ,
8895 }
8996}
9097
@@ -186,12 +193,15 @@ func (m *election) campaignLoop(ctx context.Context) {
186193func (m * election ) onElected (elec * concurrency.Election ) {
187194 m .member .OnElected ()
188195 m .elec .Store (elec )
196+ metrics .OwnerGauge .WithLabelValues (m .trimedKey ).Set (1 )
189197 m .lg .Info ("elected as the owner" )
190198}
191199
192200func (m * election ) onRetired () {
193201 m .member .OnRetired ()
194202 m .elec .Store (nil )
203+ // Delete the metric so that it doesn't show on Grafana.
204+ metrics .OwnerGauge .MetricVec .DeletePartialMatch (map [string ]string {metrics .LblType : m .trimedKey })
195205 m .lg .Info ("the owner retires" )
196206}
197207
0 commit comments