简介

上一篇文章Go 每日一库之 viper中,我们介绍了 viper 可以监听文件修改进而自动重新加载。
其内部使用的就是fsnotify这个库,它是跨平台的。今天我们就来介绍一下它。

快速使用

先安装:

  1. $ go get github.com/fsnotify/fsnotify

后使用:

  1. package main
  2. import (
  3. "log"
  4. "github.com/fsnotify/fsnotify"
  5. )
  6. func main() {
  7. watcher, err := fsnotify.NewWatcher()
  8. if err != nil {
  9. log.Fatal("NewWatcher failed: ", err)
  10. }
  11. defer watcher.Close()
  12. done := make(chan bool)
  13. go func() {
  14. defer close(done)
  15. for {
  16. select {
  17. case event, ok := <-watcher.Events:
  18. if !ok {
  19. return
  20. }
  21. log.Printf("%s %s\n", event.Name, event.Op)
  22. case err, ok := <-watcher.Errors:
  23. if !ok {
  24. return
  25. }
  26. log.Println("error:", err)
  27. }
  28. }
  29. }()
  30. err = watcher.Add("./")
  31. if err != nil {
  32. log.Fatal("Add failed:", err)
  33. }
  34. <-done
  35. }

fsnotify的使用比较简单:

  • 先调用NewWatcher创建一个监听器;
  • 然后调用监听器的Add增加监听的文件或目录;
  • 如果目录或文件有事件产生,监听器中的通道Events可以取出事件。如果出现错误,监听器中的通道Errors可以取出错误信息。

上面示例中,我们在另一个 goroutine 中循环读取发生的事件及错误,然后输出它们。

编译、运行程序。在当前目录创建一个新建文本文档.txt,然后重命名为file1.txt文件,输入内容some test text,然后删除它。观察控制台输出:

  1. 2020/01/20 08:41:17 新建文本文档.txt CREATE
  2. 2020/01/20 08:41:25 新建文本文档.txt RENAME
  3. 2020/01/20 08:41:25 file1.txt CREATE
  4. 2020/01/20 08:42:28 file1.txt REMOVE

其实,重命名时会产生两个事件,一个是原文件的**RENAME**事件,一个是新文件的**CREATE**事件。

注意,fsnotify使用了操作系统接口,监听器中保存了系统资源的句柄,所以使用后需要关闭。

事件

上面示例中的事件是fsnotify.Event类型:

  1. // fsnotify/fsnotify.go
  2. type Event struct {
  3. Name string
  4. Op Op
  5. }

事件只有两个字段,Name表示发生变化的文件或目录名,Op表示具体的变化。Op有 5 种取值:

  1. // fsnotify/fsnotify.go
  2. type Op uint32
  3. const (
  4. Create Op = 1 << iota
  5. Write
  6. Remove
  7. Rename
  8. Chmod
  9. )

快速使用中,我们已经演示了前 4 种事件。Chmod事件在文件或目录的属性发生变化时触发,在 Linux 系统中可以通过chmod命令改变文件或目录属性。

事件中的Op是按照位来存储的,可以存储多个,可以通过&操作判断对应事件是不是发生了。

  1. if event.Op & fsnotify.Write != 0 {
  2. fmt.Println("Op has Write")
  3. }

我们在代码中不需要这样判断,因为OpString()方法已经帮我们处理了这种情况了:

  1. // fsnotify.go
  2. func (op Op) String() string {
  3. // Use a buffer for efficient string concatenation
  4. var buffer bytes.Buffer
  5. if op&Create == Create {
  6. buffer.WriteString("|CREATE")
  7. }
  8. if op&Remove == Remove {
  9. buffer.WriteString("|REMOVE")
  10. }
  11. if op&Write == Write {
  12. buffer.WriteString("|WRITE")
  13. }
  14. if op&Rename == Rename {
  15. buffer.WriteString("|RENAME")
  16. }
  17. if op&Chmod == Chmod {
  18. buffer.WriteString("|CHMOD")
  19. }
  20. if buffer.Len() == 0 {
  21. return ""
  22. }
  23. return buffer.String()[1:] // Strip leading pipe
  24. }

应用

fsnotify的应用非常广泛,在 godoc 上,我们可以看到哪些库导入了fsnotify。只需要在fsnotify文档的 URL 后加上?imports即可:

https://godoc.org/github.com/fsnotify/fsnotify?importers。有兴趣打开看看,要 fq。

上一篇文章中,我们介绍了调用viper.WatchConfig就可以监听配置修改,自动重新加载。下面我们就来看看WatchConfig是怎么实现的:

  1. // viper/viper.go
  2. func WatchConfig() { v.WatchConfig() }
  3. func (v *Viper) WatchConfig() {
  4. initWG := sync.WaitGroup{}
  5. initWG.Add(1)
  6. go func() {
  7. watcher, err := fsnotify.NewWatcher()
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. defer watcher.Close()
  12. // we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
  13. filename, err := v.getConfigFile()
  14. if err != nil {
  15. log.Printf("error: %v\n", err)
  16. initWG.Done()
  17. return
  18. }
  19. configFile := filepath.Clean(filename)
  20. configDir, _ := filepath.Split(configFile)
  21. realConfigFile, _ := filepath.EvalSymlinks(filename)
  22. eventsWG := sync.WaitGroup{}
  23. eventsWG.Add(1)
  24. go func() {
  25. for {
  26. select {
  27. case event, ok := <-watcher.Events:
  28. if !ok { // 'Events' channel is closed
  29. eventsWG.Done()
  30. return
  31. }
  32. currentConfigFile, _ := filepath.EvalSymlinks(filename)
  33. // we only care about the config file with the following cases:
  34. // 1 - if the config file was modified or created
  35. // 2 - if the real path to the config file changed (eg: k8s ConfigMap replacement)
  36. const writeOrCreateMask = fsnotify.Write | fsnotify.Create
  37. if (filepath.Clean(event.Name) == configFile &&
  38. event.Op&writeOrCreateMask != 0) ||
  39. (currentConfigFile != "" && currentConfigFile != realConfigFile) {
  40. realConfigFile = currentConfigFile
  41. err := v.ReadInConfig()
  42. if err != nil {
  43. log.Printf("error reading config file: %v\n", err)
  44. }
  45. if v.onConfigChange != nil {
  46. v.onConfigChange(event)
  47. }
  48. } else if filepath.Clean(event.Name) == configFile &&
  49. event.Op&fsnotify.Remove&fsnotify.Remove != 0 {
  50. eventsWG.Done()
  51. return
  52. }
  53. case err, ok := <-watcher.Errors:
  54. if ok { // 'Errors' channel is not closed
  55. log.Printf("watcher error: %v\n", err)
  56. }
  57. eventsWG.Done()
  58. return
  59. }
  60. }
  61. }()
  62. watcher.Add(configDir)
  63. initWG.Done() // done initializing the watch in this go routine, so the parent routine can move on...
  64. eventsWG.Wait() // now, wait for event loop to end in this go-routine...
  65. }()
  66. initWG.Wait() // make sure that the go routine above fully ended before returning
  67. }

其实流程是相似的:

  • 首先,调用NewWatcher创建一个监听器;
  • 调用v.getConfigFile()获取配置文件路径,抽出文件名、目录,配置文件如果是一个符号链接,获得链接指向的路径;
  • 调用watcher.Add(configDir)监听配置文件所在目录,另起一个 goroutine 处理事件。

WatchConfig不能阻塞主 goroutine,所以创建监听器也是新起 goroutine 进行的。代码中有两个sync.WaitGroup变量,initWG是为了保证监听器初始化,
eventsWG是在事件通道关闭,或配置被删除了,或遇到错误时退出事件处理循环。

然后就是核心事件循环:

  • 有事件发生时,判断变化的文件是否是在 viper 中设置的配置文件,发生的是否是创建或修改事件(只处理这两个事件);
  • 如果配置文件为符号链接,若符合链接的指向修改了,也需要重新加载配置;
  • 如果需要重新加载配置,调用v.ReadInConfig()读取新的配置;
  • 如果注册了事件回调,以发生的事件为参数执行回调。

总结

fsnotify的接口非常简单直接,所有系统相关的复杂性都被封装起来了。这也是我们平时设计模块和接口时可以参考的案例。

参考

  1. fsnotify API 设计
  2. fsnotify GitHub 仓库