You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/pkg/conf/paladin/file.go

204 lines
4.2 KiB

6 years ago
package paladin
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
6 years ago
"sync"
"time"
"github.com/fsnotify/fsnotify"
)
const (
defaultChSize = 10
)
6 years ago
var _ Client = &file{}
// file is file config client.
type file struct {
values *Map
rawVal map[string]*Value
watchChs map[string][]chan Event
mx sync.Mutex
wg sync.WaitGroup
base string
done chan struct{}
6 years ago
}
func isHiddenFile(name string) bool {
// TODO: support windows.
return strings.HasPrefix(filepath.Base(name), ".")
6 years ago
}
func readAllPaths(base string) ([]string, error) {
fi, err := os.Stat(base)
if err != nil {
return nil, fmt.Errorf("check local config file fail! error: %s", err)
6 years ago
}
// dirs or file to paths
var paths []string
if fi.IsDir() {
files, err := ioutil.ReadDir(base)
if err != nil {
return nil, fmt.Errorf("read dir %s error: %s", base, err)
}
for _, file := range files {
if !file.IsDir() && !isHiddenFile(file.Name()) {
paths = append(paths, path.Join(base, file.Name()))
}
6 years ago
}
} else {
paths = append(paths, base)
6 years ago
}
return paths, nil
6 years ago
}
func loadValuesFromPaths(paths []string) (map[string]*Value, error) {
// laod config file to values
var err error
values := make(map[string]*Value, len(paths))
for _, fpath := range paths {
if values[path.Base(fpath)], err = loadValue(fpath); err != nil {
return nil, err
}
6 years ago
}
return values, nil
6 years ago
}
func loadValue(fpath string) (*Value, error) {
data, err := ioutil.ReadFile(fpath)
if err != nil {
return nil, err
}
content := string(data)
return &Value{val: content, raw: content}, nil
6 years ago
}
// NewFile new a config file client.
// conf = /data/conf/app/
// conf = /data/conf/app/xxx.toml
func NewFile(base string) (Client, error) {
// platform slash
6 years ago
base = filepath.FromSlash(base)
paths, err := readAllPaths(base)
6 years ago
if err != nil {
return nil, err
}
if len(paths) == 0 {
return nil, fmt.Errorf("empty config path")
}
rawVal, err := loadValuesFromPaths(paths)
6 years ago
if err != nil {
return nil, err
}
valMap := &Map{}
valMap.Store(rawVal)
fc := &file{
values: valMap,
rawVal: rawVal,
watchChs: make(map[string][]chan Event),
base: base,
done: make(chan struct{}, 1),
6 years ago
}
fc.wg.Add(1)
go fc.daemon()
return fc, nil
6 years ago
}
// Get return value by key.
func (f *file) Get(key string) *Value {
return f.values.Get(key)
}
// GetAll return value map.
func (f *file) GetAll() *Map {
return f.values
}
// WatchEvent watch multi key.
6 years ago
func (f *file) WatchEvent(ctx context.Context, keys ...string) <-chan Event {
f.mx.Lock()
defer f.mx.Unlock()
ch := make(chan Event, defaultChSize)
for _, key := range keys {
f.watchChs[key] = append(f.watchChs[key], ch)
}
return ch
6 years ago
}
// Close close watcher.
func (f *file) Close() error {
f.done <- struct{}{}
f.wg.Wait()
6 years ago
return nil
}
// file config daemon to watch file modification
func (f *file) daemon() {
defer f.wg.Done()
fswatcher, err := fsnotify.NewWatcher()
if err != nil {
log.Printf("create file watcher fail! reload function will lose efficacy error: %s", err)
return
}
if err = fswatcher.Add(f.base); err != nil {
log.Printf("create fsnotify for base path %s fail %s, reload function will lose efficacy", f.base, err)
6 years ago
return
}
log.Printf("start watch filepath: %s", f.base)
for event := range fswatcher.Events {
switch event.Op {
6 years ago
// use vim edit config will trigger rename
case fsnotify.Write, fsnotify.Create:
f.reloadFile(event.Name)
case fsnotify.Chmod:
6 years ago
default:
log.Printf("unsupport event %s ingored", event)
6 years ago
}
}
}
func (f *file) reloadFile(name string) {
if isHiddenFile(name) {
return
}
6 years ago
// NOTE: in some case immediately read file content after receive event
// will get old content, sleep 100ms make sure get correct content.
time.Sleep(200 * time.Millisecond)
key := filepath.Base(name)
val, err := loadValue(name)
6 years ago
if err != nil {
log.Printf("load file %s error: %s, skipped", name, err)
6 years ago
return
}
f.rawVal[key] = val
f.values.Store(f.rawVal)
f.mx.Lock()
chs := f.watchChs[key]
f.mx.Unlock()
for _, ch := range chs {
select {
case ch <- Event{Event: EventUpdate, Key: key, Value: val.raw}:
default:
log.Printf("event channel full discard file %s update event", name)
}
}
6 years ago
}