-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
file.go
184 lines (160 loc) · 4.96 KB
/
file.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Copyright 2021 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package denylist
import (
"context"
"io"
"os"
"time"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"gopkg.in/yaml.v2"
)
const (
defaultPollingInterval = time.Minute
defaultEmptyDenylistText = "SequenceNumber: 0"
)
// File represents a on-disk version of the denylist config.
// This also serves as a spec of expected yaml file format.
type File struct {
Seq int64 `yaml:"SequenceNumber"`
Denylist []*DenyEntry `yaml:"denylist"`
}
// Deserialize constructs a new DenylistFile from reader
func Deserialize(reader io.Reader) (*File, error) {
decoder := yaml.NewDecoder(reader)
var denylistFile File
err := decoder.Decode(&denylistFile)
if err != nil {
return nil, err
}
return &denylistFile, nil
}
// Serialize a File into raw bytes
func (dlf *File) Serialize() ([]byte, error) {
return yaml.Marshal(dlf)
}
// DenyEntry records info about one denied entity,
// the reason and the expiration time.
// This also serves as spec for the yaml config format.
type DenyEntry struct {
Entity DenyEntity `yaml:"entity"`
Expiration time.Time `yaml:"expiration"`
Reason string `yaml:"reason"`
}
// Denylist represents an in-memory cache for the current denylist.
// It also handles the logic of deciding what to be denied.
type Denylist struct {
mu struct {
entries map[DenyEntity]*DenyEntry
*syncutil.RWMutex
}
pollingInterval time.Duration
timeSource timeutil.TimeSource
ctx context.Context
}
// NewDenylistWithFile returns a new denylist that automatically watches updates to a file.
// Note: this currently does not return an error. This is by design, since even if we trouble
// initiating a denylist with file, we can always update the file with correct content during
// runtime. We don't want sqlproxy fail to start just because there's something wrong with
// contents of a denylist file.
func NewDenylistWithFile(ctx context.Context, filename string, opts ...Option) *Denylist {
ret := &Denylist{
pollingInterval: defaultPollingInterval,
timeSource: timeutil.DefaultTimeSource{},
ctx: ctx,
}
ret.mu.entries = make(map[DenyEntity]*DenyEntry)
ret.mu.RWMutex = &syncutil.RWMutex{}
for _, opt := range opts {
opt(ret)
}
err := ret.update(filename)
if err != nil {
// don't return just yet; sqlproxy should be able to carry on without a proper denylist
// and we still have a chance to recover.
// TODO(ye): add monitoring for failed updates; we don't want silent failures
log.Errorf(ctx, "error when reading from file %s: %v", filename, err)
}
ret.watchForUpdate(filename)
return ret
}
// Option allows configuration of a denylist service.
type Option func(*Denylist)
// WithPollingInterval specifies interval between polling for config file changes.
func WithPollingInterval(d time.Duration) Option {
return func(dl *Denylist) {
dl.pollingInterval = d
}
}
// update the Denylist with content of the file
func (dl *Denylist) update(filename string) error {
handle, err := os.Open(filename)
if err != nil {
log.Errorf(dl.ctx, "open file %s: %v", filename, err)
return err
}
defer handle.Close()
dlf, err := Deserialize(handle)
if err != nil {
stat, _ := handle.Stat()
if stat != nil {
log.Errorf(dl.ctx, "error updating denylist from file %s modified at %s: %v",
filename, stat.ModTime(), err)
} else {
log.Errorf(dl.ctx, "error updating denylist from file %s: %v",
filename, err)
}
return err
}
dl.updateWithDenylistFile(dlf)
return nil
}
func (dl *Denylist) updateWithDenylistFile(dlf *File) {
newEntries := make(map[DenyEntity]*DenyEntry)
for _, entry := range dlf.Denylist {
newEntries[entry.Entity] = entry
}
dl.mu.Lock()
defer dl.mu.Unlock()
dl.mu.entries = newEntries
}
// Denied implements the Service interface
func (dl *Denylist) Denied(entity DenyEntity) (*Entry, error) {
dl.mu.RLock()
defer dl.mu.RUnlock()
if ent, ok := dl.mu.entries[entity]; ok && !ent.Expiration.Before(dl.timeSource.Now()) {
return &Entry{ent.Reason}, nil
}
return nil, nil
}
// WatchForUpdates periodically reloads the denylist file. The daemon is
// canceled on ctx cancellation.
func (dl *Denylist) watchForUpdate(filename string) {
go func() {
// TODO(ye): use notification via SIGHUP instead
t := timeutil.NewTimer()
defer t.Stop()
for {
t.Reset(dl.pollingInterval)
select {
case <-dl.ctx.Done():
log.Errorf(dl.ctx, "WatchList daemon stopped: %v", dl.ctx.Err())
return
case <-t.C:
t.Read = true
err := dl.update(filename)
if err != nil {
// TODO(ye): add monitoring for update failures
continue
}
}
}
}()
}