github.com/netdata/go.d.plugin@v0.58.1/agent/filestatus/store.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package filestatus
     4  
     5  import (
     6  	"encoding/json"
     7  	"fmt"
     8  	"os"
     9  	"slices"
    10  	"sync"
    11  
    12  	"github.com/netdata/go.d.plugin/agent/confgroup"
    13  )
    14  
    15  func LoadStore(path string) (*Store, error) {
    16  	var s Store
    17  
    18  	f, err := os.Open(path)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  	defer func() { _ = f.Close() }()
    23  
    24  	return &s, json.NewDecoder(f).Decode(&s.items)
    25  }
    26  
    27  type Store struct {
    28  	mux   sync.Mutex
    29  	items map[string]map[string]string // [module][name:hash]status
    30  }
    31  
    32  func (s *Store) Contains(cfg confgroup.Config, statuses ...string) bool {
    33  	status, ok := s.lookup(cfg)
    34  	if !ok {
    35  		return false
    36  	}
    37  
    38  	return slices.Contains(statuses, status)
    39  }
    40  
    41  func (s *Store) lookup(cfg confgroup.Config) (string, bool) {
    42  	s.mux.Lock()
    43  	defer s.mux.Unlock()
    44  
    45  	jobs, ok := s.items[cfg.Module()]
    46  	if !ok {
    47  		return "", false
    48  	}
    49  
    50  	status, ok := jobs[storeJobKey(cfg)]
    51  
    52  	return status, ok
    53  }
    54  
    55  func (s *Store) add(cfg confgroup.Config, status string) {
    56  	s.mux.Lock()
    57  	defer s.mux.Unlock()
    58  
    59  	if s.items == nil {
    60  		s.items = make(map[string]map[string]string)
    61  	}
    62  
    63  	if s.items[cfg.Module()] == nil {
    64  		s.items[cfg.Module()] = make(map[string]string)
    65  	}
    66  
    67  	s.items[cfg.Module()][storeJobKey(cfg)] = status
    68  }
    69  
    70  func (s *Store) remove(cfg confgroup.Config) {
    71  	s.mux.Lock()
    72  	defer s.mux.Unlock()
    73  
    74  	delete(s.items[cfg.Module()], storeJobKey(cfg))
    75  
    76  	if len(s.items[cfg.Module()]) == 0 {
    77  		delete(s.items, cfg.Module())
    78  	}
    79  }
    80  
    81  func (s *Store) bytes() ([]byte, error) {
    82  	s.mux.Lock()
    83  	defer s.mux.Unlock()
    84  
    85  	return json.MarshalIndent(s.items, "", " ")
    86  }
    87  
    88  func storeJobKey(cfg confgroup.Config) string {
    89  	return fmt.Sprintf("%s:%d", cfg.Name(), cfg.Hash())
    90  }