Go 每日一库之 fsnotify

简介

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

快速使用

先安装:github

$ go get github.com/fsnotify/fsnotify

后使用:golang

package main

import (
  "log"

  "github.com/fsnotify/fsnotify"
)

func main() {
  watcher, err := fsnotify.NewWatcher()
  if err != nil {
    log.Fatal("NewWatcher failed: ", err)
  }
  defer watcher.Close()

  done := make(chan bool)
  go func() {
    defer close(done)

    for {
      select {
      case event, ok := <-watcher.Events:
        if !ok {
          return
        }
        log.Printf("%s %s\n", event.Name, event.Op)
      case err, ok := <-watcher.Errors:
        if !ok {
          return
        }
        log.Println("error:", err)
      }
    }
  }()

  err = watcher.Add("./")
  if err != nil {
    log.Fatal("Add failed:", err)
  }
  <-done
}

fsnotify的使用比较简单:segmentfault

  • 先调用NewWatcher建立一个监听器;
  • 而后调用监听器的Add增长监听的文件或目录;
  • 若是目录或文件有事件产生,监听器中的通道Events能够取出事件。若是出现错误,监听器中的通道Errors能够取出错误信息。

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

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

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

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

注意,fsnotify使用了操做系统接口,监听器中保存了系统资源的句柄,因此使用后须要关闭。ui

事件

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

// fsnotify/fsnotify.go
type Event struct {
  Name string
  Op   Op
}

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

// fsnotify/fsnotify.go
type Op uint32

const (
  Create Op = 1 << iota
  Write
  Remove
  Rename
  Chmod
)

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

事件中的Op是按照位来存储的,能够存储多个,能够经过&操做判断对应事件是否是发生了。

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

咱们在代码中不须要这样判断,由于OpString()方法已经帮咱们处理了这种状况了:

// fsnotify.go
func (op Op) String() string {
  // Use a buffer for efficient string concatenation
  var buffer bytes.Buffer

  if op&Create == Create {
    buffer.WriteString("|CREATE")
  }
  if op&Remove == Remove {
    buffer.WriteString("|REMOVE")
  }
  if op&Write == Write {
    buffer.WriteString("|WRITE")
  }
  if op&Rename == Rename {
    buffer.WriteString("|RENAME")
  }
  if op&Chmod == Chmod {
    buffer.WriteString("|CHMOD")
  }
  if buffer.Len() == 0 {
    return ""
  }
  return buffer.String()[1:] // Strip leading pipe
}

应用

fsnotify的应用很是普遍,在 godoc 上,咱们能够看到哪些库导入了fsnotify。只须要在fsnotify文档的 URL 后加上?imports便可:

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

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

// viper/viper.go
func WatchConfig() { v.WatchConfig() }

func (v *Viper) WatchConfig() {
  initWG := sync.WaitGroup{}
  initWG.Add(1)
  go func() {
    watcher, err := fsnotify.NewWatcher()
    if err != nil {
      log.Fatal(err)
    }
    defer watcher.Close()
    // we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
    filename, err := v.getConfigFile()
    if err != nil {
      log.Printf("error: %v\n", err)
      initWG.Done()
      return
    }

    configFile := filepath.Clean(filename)
    configDir, _ := filepath.Split(configFile)
    realConfigFile, _ := filepath.EvalSymlinks(filename)

    eventsWG := sync.WaitGroup{}
    eventsWG.Add(1)
    go func() {
      for {
        select {
        case event, ok := <-watcher.Events:
          if !ok { // 'Events' channel is closed
            eventsWG.Done()
            return
          }
          currentConfigFile, _ := filepath.EvalSymlinks(filename)
          // we only care about the config file with the following cases:
          // 1 - if the config file was modified or created
          // 2 - if the real path to the config file changed (eg: k8s ConfigMap replacement)
          const writeOrCreateMask = fsnotify.Write | fsnotify.Create
          if (filepath.Clean(event.Name) == configFile &&
            event.Op&writeOrCreateMask != 0) ||
            (currentConfigFile != "" && currentConfigFile != realConfigFile) {
            realConfigFile = currentConfigFile
            err := v.ReadInConfig()
            if err != nil {
              log.Printf("error reading config file: %v\n", err)
            }
            if v.onConfigChange != nil {
              v.onConfigChange(event)
            }
          } else if filepath.Clean(event.Name) == configFile &&
            event.Op&fsnotify.Remove&fsnotify.Remove != 0 {
            eventsWG.Done()
            return
          }

        case err, ok := <-watcher.Errors:
          if ok { // 'Errors' channel is not closed
            log.Printf("watcher error: %v\n", err)
          }
          eventsWG.Done()
          return
        }
      }
    }()
    watcher.Add(configDir)
    initWG.Done()   // done initializing the watch in this go routine, so the parent routine can move on...
    eventsWG.Wait() // now, wait for event loop to end in this go-routine...
  }()
  initWG.Wait() // make sure that the go routine above fully ended before returning
}

其实流程是类似的:

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

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

而后就是核心事件循环:

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

总结

fsnotify的接口很是简单直接,全部系统相关的复杂性都被封装起来了。这也是咱们平时设计模块和接口时能够参考的案例。

参考

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

个人博客

欢迎关注个人微信公众号【GoUpUp】,共同窗习,一块儿进步~

本文由博客一文多发平台 OpenWrite 发布!
相关文章
相关标签/搜索