Go 每日一庫之 fsnotify


簡介

上一篇文章Go 每日一庫之 viper中,我們介紹了 viper 可以監聽文件修改進而自動重新加載。
其內部使用的就是fsnotify這個庫,它是跨平台的。今天我們就來介紹一下它。

快速使用

先安裝:

$ go get github.com/fsnotify/fsnotify

后使用:

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的使用比較簡單:

  • 先調用NewWatcher創建一個監聽器;
  • 然后調用監聽器的Add增加監聽的文件或目錄;
  • 如果目錄或文件有事件產生,監聽器中的通道Events可以取出事件。如果出現錯誤,監聽器中的通道Errors可以取出錯誤信息。

上面示例中,我們在另一個 goroutine 中循環讀取發生的事件及錯誤,然后輸出它們。

編譯、運行程序。在當前目錄創建一個新建文本文檔.txt,然后重命名為file1.txt文件,輸入內容some test text,然后刪除它。觀察控制台輸出:

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使用了操作系統接口,監聽器中保存了系統資源的句柄,所以使用后需要關閉。

事件

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

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

事件只有兩個字段,Name表示發生變化的文件或目錄名,Op表示具體的變化。Op有 5 中取值:

// 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 發布!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM