-
Notifications
You must be signed in to change notification settings - Fork 53
/
opensearch.go
94 lines (77 loc) · 1.59 KB
/
opensearch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package util
import (
"context"
"sync"
"time"
"github.com/rancher/opni/pkg/opensearch/opensearch"
)
type AsyncOpensearchClient struct {
*opensearch.Client
initCond *sync.Cond
initialized bool
rw sync.RWMutex
}
type setterFunc func(context.Context) *opensearch.Client
func NewAsyncOpensearchClient() *AsyncOpensearchClient {
return &AsyncOpensearchClient{
initCond: sync.NewCond(&sync.Mutex{}),
}
}
func (c *AsyncOpensearchClient) WaitForInit() {
c.initCond.L.Lock()
for !c.initialized {
c.initCond.Wait()
}
c.initCond.L.Unlock()
}
func (c *AsyncOpensearchClient) WaitForInitWithTimeout(timeout time.Duration) bool {
notifier := make(chan struct{})
go func() {
c.initCond.L.Lock()
defer c.initCond.L.Unlock()
defer close(notifier)
for !c.initialized {
c.initCond.Wait()
}
}()
select {
case <-notifier:
return true
case <-time.After(timeout):
return false
}
}
func (c *AsyncOpensearchClient) SetClient(setter setterFunc) {
c.rw.Lock()
defer c.rw.Unlock()
c.initCond.L.Lock()
defer c.initCond.L.Unlock()
if c.initialized {
return
}
c.Client = setter(context.TODO())
c.initialized = true
c.initCond.Broadcast()
}
func (c *AsyncOpensearchClient) UnsetClient() {
c.rw.Lock()
defer c.rw.Unlock()
c.initCond.L.Lock()
defer c.initCond.L.Unlock()
if !c.initialized {
return
}
c.Client = nil
c.initialized = false
}
func (c *AsyncOpensearchClient) Lock() {
c.rw.RLock()
}
func (c *AsyncOpensearchClient) Unlock() {
c.rw.RUnlock()
}
func (c *AsyncOpensearchClient) IsInitialized() bool {
c.rw.RLock()
defer c.rw.RUnlock()
return c.initialized
}