You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
1.5 KiB
80 lines
1.5 KiB
package logic |
|
|
|
import ( |
|
"context" |
|
"go.etcd.io/etcd/api/v3/mvccpb" |
|
clientv3 "go.etcd.io/etcd/client/v3" |
|
"sonet/api/gen/postal" |
|
"sonet/pkg/grpc/discovery" |
|
"sonet/pkg/utils/logger" |
|
) |
|
|
|
type PostalMonitor struct { |
|
client *clientv3.Client |
|
keyPrefix string |
|
} |
|
|
|
func NewPostalMonitor(client *clientv3.Client) *PostalMonitor { |
|
return &PostalMonitor{ |
|
client: client, |
|
} |
|
} |
|
|
|
func (m *PostalMonitor) Init(ctx context.Context) (err error) { |
|
m.keyPrefix = discovery.BuildPrefix(discovery.Server{Name: postal.Postal_ServiceDesc.ServiceName}) |
|
go m.watch(ctx) |
|
m.build(ctx) |
|
return |
|
} |
|
|
|
func (m *PostalMonitor) Next() { |
|
|
|
} |
|
|
|
func (m *PostalMonitor) build(ctx context.Context) { |
|
res, err := m.client.Get(ctx, m.keyPrefix, clientv3.WithPrefix()) |
|
if err != nil { |
|
return |
|
} |
|
//for _, kv := range res.Kvs { |
|
// |
|
//} |
|
m.update(res.Kvs) |
|
|
|
} |
|
|
|
func (m *PostalMonitor) watch(ctx context.Context) { |
|
w := m.client.Watch(ctx, m.keyPrefix, clientv3.WithPrefix()) |
|
cancelCh := ctx.Done() |
|
|
|
for { |
|
select { |
|
case <-cancelCh: |
|
return |
|
case res := <-w: |
|
if err := res.Err(); err != nil { |
|
logger.Errorf("watch etcd instance error: %v\n", err) |
|
continue |
|
} |
|
rebuild := false |
|
eLoop: |
|
for _, event := range res.Events { |
|
switch event.Type { |
|
case clientv3.EventTypePut: |
|
fallthrough |
|
case clientv3.EventTypeDelete: |
|
rebuild = true |
|
break eLoop |
|
} |
|
} |
|
if rebuild { |
|
go m.build(ctx) |
|
} |
|
} |
|
} |
|
|
|
} |
|
|
|
func (m *PostalMonitor) update(value []*mvccpb.KeyValue) { |
|
|
|
}
|
|
|