-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext.go
61 lines (50 loc) · 1.29 KB
/
context.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
package soroban
import (
"context"
"sync"
"github.com/cretz/bine/tor"
log "github.com/sirupsen/logrus"
)
type ContextKey string
const (
TorClientsKeys = ContextKey("soroban-torclients")
)
type torClientsInfo struct {
sync.Mutex
clients []*tor.Tor
}
func WithTorContext(ctx context.Context) context.Context {
return context.WithValue(ctx, TorClientsKeys, &torClientsInfo{})
}
func AddTorClient(ctx context.Context, torClient *tor.Tor) {
torContext := ctx.Value(TorClientsKeys)
if torContext == nil {
panic("Create context with Tor")
}
if torClients, ok := torContext.(*torClientsInfo); ok {
torClients.Lock()
defer torClients.Unlock()
torClients.clients = append(torClients.clients, torClient)
log.Debug("Tor client added")
}
}
func Shutdown(ctx context.Context) {
log.Warning("Shutting down all tor processes")
torContext := ctx.Value(TorClientsKeys)
if torContext == nil {
panic("Create context with Tor")
}
if torClients, ok := torContext.(*torClientsInfo); ok {
torClients.Lock()
defer torClients.Unlock()
for _, torClient := range torClients.clients {
err := torClient.Close()
if err != nil {
log.WithError(err).Error("Failed to close tor client")
} else {
log.Warning("Tor client closed")
}
}
torClients.clients = torClients.clients[:0]
}
}