Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Use fsnotify to detect model/policy files change in casbin plugin #614

Merged
merged 40 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
66d0cb7
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 27, 2024
fe5182e
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 27, 2024
1bfb1d4
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 27, 2024
3120753
Merge branch 'mosn:main' into main
lyt122 Jun 27, 2024
7bf2834
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 27, 2024
d0dc175
Merge branch 'main' of github.com:lyt122/htnn
lyt122 Jun 27, 2024
17ed368
feat: Use fsnotify to detect model/policy files change in casbin plugin
lyt122 Jun 30, 2024
99bf29d
format go
lyt122 Jun 30, 2024
57329f4
Merge branch 'mosn:main' into main
lyt122 Jul 3, 2024
6eb6b03
refactor codes
lyt122 Jul 6, 2024
5c99c69
refactor codes
lyt122 Jul 6, 2024
846ff5b
refactor codes
lyt122 Jul 6, 2024
f330ec6
refactor codes
lyt122 Jul 6, 2024
29822b8
add test codes
lyt122 Jul 7, 2024
a7bf59d
add test codes
lyt122 Jul 7, 2024
6719586
add test codes
lyt122 Jul 7, 2024
daf2c24
add test codes
lyt122 Jul 7, 2024
7120888
add test codes
lyt122 Jul 7, 2024
c2ffc2e
fix: avoid data race
lyt122 Jul 8, 2024
46d90e6
refactor codes
lyt122 Jul 9, 2024
2b01940
fix golangci-lint error
lyt122 Jul 9, 2024
c1522d2
add test codes
lyt122 Jul 9, 2024
c7cdd4a
Merge branch 'mosn:main' into main
lyt122 Jul 9, 2024
4c686e2
refactor codes
lyt122 Jul 10, 2024
cc84ebd
refactor codes
lyt122 Jul 10, 2024
5e32bea
fix: avoid data race
lyt122 Jul 10, 2024
930b568
fix: avoid data race
lyt122 Jul 10, 2024
1eaa4e7
refactor codes
lyt122 Jul 10, 2024
e34511d
Merge branch 'main' of github.com:lyt122/htnn
lyt122 Jul 10, 2024
7a1551f
refactor codes
lyt122 Jul 11, 2024
bbefd66
refactor codes
lyt122 Jul 12, 2024
f239cf5
refactor codes
lyt122 Jul 12, 2024
75d00da
refactor codes
lyt122 Jul 12, 2024
b9d7d06
refactor: watch the dir of file
lyt122 Jul 14, 2024
0b03da5
refactor codes
lyt122 Jul 14, 2024
8ca375a
use file's abspath
lyt122 Jul 15, 2024
363dd1d
refactor codes
lyt122 Jul 15, 2024
b81b325
refactor codes
lyt122 Jul 15, 2024
c879870
refactor codes
lyt122 Jul 16, 2024
ac85bd9
refactor codes
lyt122 Jul 16, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions plugins/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ require (
github.com/casbin/casbin/v2 v2.88.0
github.com/coreos/go-oidc/v3 v3.10.0
github.com/envoyproxy/envoy v1.29.4
github.com/fsnotify/fsnotify v1.7.0
github.com/google/cel-go v0.20.1
github.com/google/uuid v1.6.0
github.com/gorilla/securecookie v1.1.2
Expand Down
2 changes: 2 additions & 0 deletions plugins/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
github.com/foxcpp/go-mockdns v1.1.0 h1:jI0rD8M0wuYAxL7r/ynTrCQQq0BVqfB99Vgk7DlmewI=
github.com/foxcpp/go-mockdns v1.1.0/go.mod h1:IhLeSFGed3mJIAXPH2aiRQB+kqz7oqu8ld2qVbOu7Wk=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/go-jose/go-jose/v4 v4.0.1 h1:QVEPDE3OluqXBQZDcnNvQrInro2h0e4eqNbnZSWqS6U=
Expand Down
127 changes: 66 additions & 61 deletions plugins/pkg/file/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
package file

import (
"errors"
"fmt"
"os"
"sync"
"time"

"github.com/jellydator/ttlcache/v3"
"github.com/fsnotify/fsnotify"

"mosn.io/htnn/api/pkg/log"
)
Expand Down Expand Up @@ -48,65 +50,87 @@
f.lock.Unlock()
}

type fs struct {
cache *ttlcache.Cache[string, os.FileInfo]
type Fsnotify struct {
Watcher *fsnotify.Watcher
}

func newFS(ttl time.Duration) *fs {
loader := ttlcache.LoaderFunc[string, os.FileInfo](
func(c *ttlcache.Cache[string, os.FileInfo], key string) *ttlcache.Item[string, os.FileInfo] {
info, err := os.Stat(key)
if err != nil {
logger.Error(err, "reload file info to cache", "file", key)
return nil
}
item := c.Set(key, info, ttlcache.DefaultTTL)
logger.Info("update file mtime", "file", key, "mtime", item.Value().ModTime())
return item
},
)
cache := ttlcache.New(
ttlcache.WithTTL[string, os.FileInfo](ttl),
ttlcache.WithLoader[string, os.FileInfo](loader),
)
go cache.Start()

return &fs{
cache: cache,
func newFsnotify() (fs *Fsnotify) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
logger.Error(err, "create watcher failed")
return

Check warning on line 61 in plugins/pkg/file/fs.go

View check run for this annotation

Codecov / codecov/patch

plugins/pkg/file/fs.go#L60-L61

Added lines #L60 - L61 were not covered by tests
}
fs = &Fsnotify{
Watcher: watcher,
}
return
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need this return?

}

var (
// TODO: rewrite it to use inotify
defaultFs = newFS(10 * time.Second)
defaultFsnotify = newFsnotify()
)

func IsChanged(files ...*File) bool {
func Update(onChange func(), files ...*File) (err error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Update is redundant, use WatchFiles is enough.

err = WatchFiles(onChange, files...)
return
}

func WatchFiles(onChange func(), files ...*File) (err error) {
if len(files) < 1 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about using param file, otherFiles ... so the check is done by compiler?

err = errors.New("must specify at least one file to watch")
logger.Error(err, "")
return

Check warning on line 82 in plugins/pkg/file/fs.go

View check run for this annotation

Codecov / codecov/patch

plugins/pkg/file/fs.go#L80-L82

Added lines #L80 - L82 were not covered by tests
}

watcher := newFsnotify().Watcher
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why don't we use defaultFsnotify?

if err != nil {

spacewander marked this conversation as resolved.
Show resolved Hide resolved
logger.Error(err, "failed to create watcher")
return

Check warning on line 89 in plugins/pkg/file/fs.go

View check run for this annotation

Codecov / codecov/patch

plugins/pkg/file/fs.go#L88-L89

Added lines #L88 - L89 were not covered by tests
}

// Add files to watcher.
for _, file := range files {
changed := defaultFs.isChanged(file)
if changed {
return true
}
go defaultFsnotify.watchFiles(onChange, watcher, file)
}
return false

return
spacewander marked this conversation as resolved.
Show resolved Hide resolved
}

func (f *fs) isChanged(file *File) bool {
item := f.cache.Get(file.Name)
if item == nil {
// As a protection, failed to fetch the real file means file not changed
return false
func (f *Fsnotify) watchFiles(onChange func(), w *fsnotify.Watcher, files *File) {
defer func(w *fsnotify.Watcher) {
err := w.Close()
if err != nil {
logger.Error(err, "failed to close fsnotify watcher")

Check warning on line 104 in plugins/pkg/file/fs.go

View check run for this annotation

Codecov / codecov/patch

plugins/pkg/file/fs.go#L104

Added line #L104 was not covered by tests
}
}(w)
err := w.Add(files.Name)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider a case: people remove the file and then create a new file with the same name. The fsnotify won't be triggered in this case. What about watching the file's directory and filtering according to the name?

if err != nil {
logger.Error(err, "add file to watcher failed")

Check warning on line 109 in plugins/pkg/file/fs.go

View check run for this annotation

Codecov / codecov/patch

plugins/pkg/file/fs.go#L109

Added line #L109 was not covered by tests
}
for {
spacewander marked this conversation as resolved.
Show resolved Hide resolved
select {
case event, ok := <-w.Events:
if !ok {
return

Check warning on line 115 in plugins/pkg/file/fs.go

View check run for this annotation

Codecov / codecov/patch

plugins/pkg/file/fs.go#L115

Added line #L115 was not covered by tests
}
logger.Info(fmt.Sprintf("event: %v", event))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just put the event as an argument is enough, we don't need to use Sprintf

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I use logger.Info("event: %v", event), an error is occurred:
DPANIC file file/fs.go:100 odd number of arguments passed as key-value pairs for logging {"ignored key": "WRITE \"example3760250304\""}
so I use Sprintf.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As the error message indicated, the arguments should be key-value pairs, which have even numbers, for example:

logger.Info("register plugin type", "name", name)

onChange()
return
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should keep watching, and should not exit after the first event. This is a waste of goroutine and watcher, and force the user to rewatch each time.

case err, ok := <-w.Errors:
if !ok {
return

Check warning on line 122 in plugins/pkg/file/fs.go

View check run for this annotation

Codecov / codecov/patch

plugins/pkg/file/fs.go#L120-L122

Added lines #L120 - L122 were not covered by tests
}
logger.Error(err, "error watching files")

Check warning on line 124 in plugins/pkg/file/fs.go

View check run for this annotation

Codecov / codecov/patch

plugins/pkg/file/fs.go#L124

Added line #L124 was not covered by tests
}
}

return file.Mtime().Before(item.Value().ModTime())
}

func (f *fs) Stat(path string) (*File, error) {
func (f *Fsnotify) Stat(path string) (*File, error) {
info, err := os.Stat(path)
if err != nil {
return nil, err
}
f.cache.Set(path, info, ttlcache.DefaultTTL)

return &File{
Name: path,
Expand All @@ -115,24 +139,5 @@
}

func Stat(path string) (*File, error) {
return defaultFs.Stat(path)
}

func Update(files ...*File) bool {
for _, file := range files {
if !defaultFs.update(file) {
return false
}
}
return true
}

func (f *fs) update(file *File) bool {
item := f.cache.Get(file.Name)
if item == nil {
return false
}

file.SetMtime(item.Value().ModTime())
return true
return defaultFsnotify.Stat(path)
}
47 changes: 32 additions & 15 deletions plugins/pkg/file/fs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,45 @@ package file

import (
"os"
"sync"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestFileMtimeDetection(t *testing.T) {
defaultFs = newFS(2000 * time.Millisecond)
func TestFileIsChanged(t *testing.T) {
var mu sync.Mutex
i := 1
tmpfile, _ := os.CreateTemp("./", "example")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
tmpfile, _ := os.CreateTemp("./", "example")
tmpfile, _ := os.CreateTemp("", "example")

would be better so that the test case won't pollute the git repo.

defer func(name string) {
err := os.Remove(name)
if err != nil {
t.Logf("%v", err)
}
}(tmpfile.Name())

tmpfile, _ := os.CreateTemp("", "example")
defer os.Remove(tmpfile.Name()) // clean up

f, err := Stat(tmpfile.Name())
assert.Nil(t, err)
assert.False(t, IsChanged(f))
time.Sleep(1000 * time.Millisecond)
file := &File{Name: tmpfile.Name()}
_ = WatchFiles(func() {
mu.Lock()
i = 2
mu.Unlock()
}, file)
time.Sleep(1 * time.Millisecond)
tmpfile.Write([]byte("bls"))
tmpfile.Close()
assert.False(t, IsChanged(f))
tmpfile.Sync()
mu.Lock()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the lock here guarantee the callback in WatchFiles run before assertion? The assertion may get the lock first.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lock can be removed?

assert.Equal(t, 2, i)
mu.Unlock()

time.Sleep(2500 * time.Millisecond)
assert.True(t, IsChanged(f))
assert.True(t, Update(f))
assert.False(t, IsChanged(f))
_ = WatchFiles(func() {
mu.Lock()
i = 1
mu.Unlock()
}, file)
time.Sleep(1 * time.Millisecond)
tmpfile.Sync()
mu.Lock()
assert.Equal(t, 2, i)
mu.Unlock()
}
27 changes: 20 additions & 7 deletions plugins/plugins/casbin/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,9 @@
config *config
}

func (f *filter) DecodeHeaders(headers api.RequestHeaderMap, endStream bool) api.ResultAction {
func (f *filter) reloadEnforcer() {
conf := f.config
role, _ := headers.Get(conf.Token.Name) // role can be ""
url := headers.Url()

policyChanged := file.IsChanged(conf.modelFile, conf.policyFile)
if policyChanged && !conf.updating.Load() {
if !conf.updating.Load() {
conf.updating.Store(true)
api.LogWarnf("policy %s or model %s changed, reload enforcer", conf.policyFile.Name, conf.modelFile.Name)

Expand All @@ -58,11 +54,28 @@
conf.enforcer = e
conf.lock.Unlock()

file.Update(conf.modelFile, conf.policyFile)
err = file.Update(func() {
f.reloadEnforcer()
}, conf.modelFile, conf.policyFile)

Check warning on line 59 in plugins/plugins/casbin/filter.go

View check run for this annotation

Codecov / codecov/patch

plugins/plugins/casbin/filter.go#L58-L59

Added lines #L58 - L59 were not covered by tests
if err != nil {
api.LogErrorf("failed to update Enforcer: %v", err)

Check warning on line 61 in plugins/plugins/casbin/filter.go

View check run for this annotation

Codecov / codecov/patch

plugins/plugins/casbin/filter.go#L61

Added line #L61 was not covered by tests
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The msg is not precise. The code above doesn't update Enforcer

}
api.LogWarnf("policy %s or model %s changed, enforcer reloaded", conf.policyFile.Name, conf.modelFile.Name)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This log should move up, just after we change the enforcer

}
}()
}
}
func (f *filter) DecodeHeaders(headers api.RequestHeaderMap, endStream bool) api.ResultAction {
conf := f.config
role, _ := headers.Get(conf.Token.Name) // role can be ""
url := headers.Url()

err := file.WatchFiles(f.reloadEnforcer, conf.modelFile, conf.policyFile)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add file to watcher when init the conf:

func (conf *config) Init(cb api.ConfigCallbackHandler) error {

The DecodeHeaders is called per req.


if err != nil {
api.LogErrorf("failed to watch files: %v", err)
return &api.LocalResponse{Code: 500}

Check warning on line 77 in plugins/plugins/casbin/filter.go

View check run for this annotation

Codecov / codecov/patch

plugins/plugins/casbin/filter.go#L76-L77

Added lines #L76 - L77 were not covered by tests
}

conf.lock.RLock()
ok, err := f.config.enforcer.Enforce(role, url.Path, headers.Method())
Expand Down