Debian Codegraph @

runtimevar/filevar/filevar.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package filevar provides a runtimevar implementation with variables
16 // backed by the filesystem. Use OpenVariable to construct a *runtimevar.Variable.
17 //
18 // Configuration files can be updated using any commands (cp, mv) or
19 // tools/editors. This package does not guarantee read consistency since
20 // it does not have control over the writes. For example, some kinds of
21 // updates might result in filevar temporarily receiving an error or an
22 // empty value.
23 //
24 // Known Issues:
25 //
26 // * On macOS, if an empty file is copied into a configuration file,
27 //
28 // filevar will not detect the change.
29 //
30 // # URLs
31 //
32 // For runtimevar.OpenVariable, filevar registers for the scheme "file".
33 // To customize the URL opener, or for more details on the URL format,
34 // see URLOpener.
35 // See https://gocloud.dev/concepts/urls/ for background information.
36 //
37 // # As
38 //
39 // filevar does not support any types for As.
40 package filevar // import "gocloud.dev/runtimevar/filevar"
41
42 import (
43 "bytes"
44 "context"
45 "errors"
46 "fmt"
47 "net/url"
48 "os"
49 "path/filepath"
50 "strings"
51 "time"
52
53 "github.com/fsnotify/fsnotify"
54 "gocloud.dev/gcerrors"
55 "gocloud.dev/runtimevar"
56 "gocloud.dev/runtimevar/driver"
57 )
58
59 func init() {
60 runtimevar.DefaultURLMux().RegisterVariable(Scheme, &URLOpener{})
61 }
62
63 // Scheme is the URL scheme filevar registers its URLOpener under on runtimevar.DefaultMux.
64 const Scheme = "file"
65
66 // URLOpener opens filevar URLs like "file:///path/to/config.json?decoder=json".
67 //
68 // The URL's host+path is used as the path to the file to watch.
69 // If os.PathSeparator != "/", any leading "/" from the path is dropped
70 // and remaining '/' characters are converted to os.PathSeparator.
71 //
72 // The following URL parameters are supported:
73 // - decoder: The decoder to use. Defaults to URLOpener.Decoder, or
74 // runtimevar.BytesDecoder if URLOpener.Decoder is nil.
75 // See runtimevar.DecoderByName for supported values.
76 // - wait: The frequency for retries after an error, in time.ParseDuration formats.
77 // Defaults to 30s.
78 type URLOpener struct {
79 // Decoder specifies the decoder to use if one is not specified in the URL.
80 // Defaults to runtimevar.BytesDecoder.
81 Decoder *runtimevar.Decoder
82
83 // Options specifies the options to pass to OpenVariable.
84 Options Options
85 }
86
87 // OpenVariableURL opens the variable at the URL's path. See the package doc
88 // for more details.
89 func (o *URLOpener) OpenVariableURL(ctx context.Context, u *url.URL) (*runtimevar.Variable, error) {
90 q := u.Query()
91
92 decoderName := q.Get("decoder")
93 q.Del("decoder")
94 decoder, err := runtimevar.DecoderByName(ctx, decoderName, o.Decoder)
95 if err != nil {
96 return nil, fmt.Errorf("open variable %v: invalid decoder: %v", u, err)
97 }
98 opts := o.Options
99 if s := q.Get("wait"); s != "" {
100 q.Del("wait")
101 d, err := time.ParseDuration(s)
102 if err != nil {
103 return nil, fmt.Errorf("open variable %v: invalid wait %q: %v", u, s, err)
104 }
105 opts.WaitDuration = d
106 }
107
108 for param := range q {
109 return nil, fmt.Errorf("open variable %v: invalid query parameter %q", u, param)
110 }
111 path := u.Path
112 if os.PathSeparator != '/' {
113 path = strings.TrimPrefix(path, "/")
114 }
115 return OpenVariable(filepath.FromSlash(path), decoder, &opts)
116 }
117
118 // Options sets options.
119 type Options struct {
120 // WaitDuration controls the frequency of retries after an error. For example,
121 // if the file does not exist. Defaults to 30 seconds.
122 WaitDuration time.Duration
123 }
124
125 // OpenVariable constructs a *runtimevar.Variable backed by the file at path.
126 // The file holds raw bytes; provide a decoder to decode the raw bytes into the
127 // appropriate type for runtimevar.Snapshot.Value.
128 // See the runtimevar package documentation for examples of decoders.
129 func OpenVariable(path string, decoder *runtimevar.Decoder, opts *Options) (*runtimevar.Variable, error) {
130 w, err := newWatcher(path, decoder, opts)
131 if err != nil {
132 return nil, err
133 }
134 return runtimevar.New(w), nil
135 }
136
137 func newWatcher(path string, decoder *runtimevar.Decoder, opts *Options) (*watcher, error) {
138 if opts == nil {
139 opts = &Options{}
140 }
141 if path == "" {
142 return nil, errors.New("path is required")
143 }
144 if decoder == nil {
145 return nil, errors.New("decoder is required")
146 }
147
148 // Use absolute file path.
149 abspath, err := filepath.Abs(path)
150 if err != nil {
151 return nil, err
152 }
153
154 // Construct a fsnotify.Watcher.
155 notifier, err := fsnotify.NewWatcher()
156 if err != nil {
157 return nil, err
158 }
159
160 // Create a ctx for the background goroutine that does all of the reading.
161 // The cancel function will be used to shut it down during Close, with the
162 // result being passed back via closeCh.
163 ctx, cancel := context.WithCancel(context.Background())
164 w := &watcher{
165 path: abspath,
166 // See struct comments for why it's buffered.
167 ch: make(chan *state, 1),
168 closeCh: make(chan error),
169 shutdown: cancel,
170 }
171 go w.watch(ctx, notifier, abspath, decoder, driver.WaitDuration(opts.WaitDuration))
172 return w, nil
173 }
174
175 // errNotExist wraps an underlying error in cases where the file likely doesn't
176 // exist.
177 type errNotExist struct {
178 err error
179 }
180
181 func (e *errNotExist) Error() string {
182 return e.err.Error()
183 }
184
185 // state implements driver.State.
186 type state struct {
187 val any
188 updateTime time.Time
189 raw []byte
190 err error
191 }
192
193 func (s *state) Value() (any, error) {
194 return s.val, s.err
195 }
196
197 func (s *state) UpdateTime() time.Time {
198 return s.updateTime
199 }
200
201 func (s *state) As(i any) bool {
202 return false
203 }
204
205 // watcher implements driver.Watcher for configurations stored in files.
206 type watcher struct {
207 // The path for the file we're watching.
208 path string
209 // The background goroutine writes new *state values to ch.
210 // It is buffered so that the background goroutine can write without
211 // blocking; it always drains the buffer before writing so that the latest
212 // write is buffered. If writes could block, the background goroutine could be
213 // blocked indefinitely from reading fsnotify events.
214 ch chan *state
215 // closeCh is used to return any errors from closing the notifier
216 // back to watcher.Close.
217 closeCh chan error
218 // shutdown tells the background goroutine to exit.
219 shutdown func()
220 }
221
222 // WatchVariable implements driver.WatchVariable.
223 func (w *watcher) WatchVariable(ctx context.Context, _ driver.State) (driver.State, time.Duration) {
224 select {
225 case <-ctx.Done():
226 return &state{err: ctx.Err()}, 0
227 case cur := <-w.ch:
228 return cur, 0
229 }
230 }
231
232 // updateState checks to see if s and prev both represent the same error.
233 // If not, it drains any previous state buffered in w.ch, then writes s to it.
234 // It always return s.
235 func (w *watcher) updateState(s, prev *state) *state {
236 if s.err != nil && prev != nil && prev.err != nil && (s.err == prev.err || s.err.Error() == prev.err.Error() || (os.IsNotExist(s.err) && os.IsNotExist(prev.err))) {
237 // s represents the same error as prev.
238 return s
239 }
240 // Drain any buffered value on ch; it is now stale.
241 select {
242 case <-w.ch:
243 default:
244 }
245 // This write can't block, since we're the only writer, ch has a buffer
246 // size of 1, and we just read anything that was buffered.
247 w.ch <- s
248 return s
249 }
250
251 // watch is run by a background goroutine.
252 // It watches file using notifier, and writes new states to w.ch.
253 // If it can't read or watch the file, it re-checks every wait.
254 // It exits when ctx is canceled, and writes any shutdown errors (or
255 // nil if there weren't any) to w.closeCh.
256 func (w *watcher) watch(ctx context.Context, notifier *fsnotify.Watcher, file string, decoder *runtimevar.Decoder, wait time.Duration) {
257 var cur *state
258
259 for {
260 // If the current state is an error, pause between attempts
261 // to avoid spin loops. In particular, this happens when the file
262 // doesn't exist.
263 if cur != nil && cur.err != nil {
264 select {
265 case <-ctx.Done():
266 w.closeCh <- notifier.Close()
267 return
268 case <-time.After(wait):
269 }
270 }
271
272 // Add the file to the notifier to be watched. It's fine to be
273 // added multiple times, and fsnotifier is a bit flaky about when
274 // it's needed during renames, so just always try.
275 if err := notifier.Add(file); err != nil {
276 // File probably does not exist. Try again later.
277 cur = w.updateState(&state{err: &errNotExist{err}}, cur)
278 continue
279 }
280
281 // Read the file.
282 b, err := os.ReadFile(file)
283 if err != nil {
284 // File probably does not exist. Try again later.
285 cur = w.updateState(&state{err: &errNotExist{err}}, cur)
286 continue
287 }
288
289 // If it's a new value, decode and return it.
290 if cur == nil || cur.err != nil || !bytes.Equal(cur.raw, b) {
291 if val, err := decoder.Decode(ctx, b); err != nil {
292 cur = w.updateState(&state{err: err}, cur)
293 } else {
294 cur = w.updateState(&state{val: val, updateTime: time.Now(), raw: b}, cur)
295 }
296 }
297
298 // Block until notifier tells us something relevant changed.
299 wait := true
300 for wait {
301 select {
302 case <-ctx.Done():
303 w.closeCh <- notifier.Close()
304 return
305
306 case event := <-notifier.Events:
307 if event.Name != file {
308 continue
309 }
310 // Ignore if not one of the following operations.
311 if event.Op&(fsnotify.Create|fsnotify.Write|fsnotify.Remove|fsnotify.Rename) == 0 {
312 continue
313 }
314 wait = false
315
316 case err := <-notifier.Errors:
317 cur = w.updateState(&state{err: err}, cur)
318 }
319 }
320 }
321 }
322
323 // Close implements driver.WatchVariable.
324 func (w *watcher) Close() error {
325 // Tell the background goroutine to shut down by canceling its ctx.
326 w.shutdown()
327 // Wait for it to return the result of closing the notifier.
328 err := <-w.closeCh
329 // Cleanup our channels.
330 close(w.ch)
331 close(w.closeCh)
332 return err
333 }
334
335 // ErrorAs implements driver.ErrorAs.
336 func (w *watcher) ErrorAs(err error, i any) bool { return false }
337
338 // ErrorCode implements driver.ErrorCode.
339 func (*watcher) ErrorCode(err error) gcerrors.ErrorCode {
340 if _, ok := err.(*errNotExist); ok {
341 return gcerrors.NotFound
342 }
343 return gcerrors.Unknown
344 }