github.com/sacloud/iaas-api-go@v1.12.0/fake/json_file_store_watcher.go (about)

     1  // Copyright 2022-2023 The sacloud/iaas-api-go Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //go:build !wasm
    16  // +build !wasm
    17  
    18  package fake
    19  
    20  import (
    21  	"log"
    22  
    23  	"github.com/fsnotify/fsnotify"
    24  )
    25  
    26  func (s *JSONFileStore) startWatcher() {
    27  	ctx := s.Ctx
    28  	watcher, err := fsnotify.NewWatcher()
    29  	if err != nil {
    30  		panic(err)
    31  	}
    32  	log.Printf("file watch start: %q", s.Path)
    33  
    34  	go func() {
    35  		defer watcher.Close()
    36  		for {
    37  			select {
    38  			case event, ok := <-watcher.Events:
    39  				if !ok {
    40  					return
    41  				}
    42  				switch {
    43  				case event.Op&fsnotify.Write == fsnotify.Write,
    44  					event.Op&fsnotify.Create == fsnotify.Create,
    45  					event.Op&fsnotify.Rename == fsnotify.Rename:
    46  
    47  					if err := s.load(); err != nil {
    48  						log.Printf("reloading %q is failed: %s\n", s.Path, err)
    49  					}
    50  
    51  					if event.Op&fsnotify.Rename == fsnotify.Rename {
    52  						if err := watcher.Add(s.Path); err != nil {
    53  							panic(err)
    54  						}
    55  					}
    56  					log.Printf("reloaded: %q\n", s.Path)
    57  				}
    58  			case err, ok := <-watcher.Errors:
    59  				if !ok {
    60  					return
    61  				}
    62  				panic(err)
    63  			case <-ctx.Done():
    64  				return
    65  			}
    66  		}
    67  	}()
    68  	if err := watcher.Add(s.Path); err != nil {
    69  		panic(err)
    70  	}
    71  }