github.com/netdata/go.d.plugin@v0.58.1/modules/wireguard/wireguard.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package wireguard
     4  
     5  import (
     6  	_ "embed"
     7  	"time"
     8  
     9  	"github.com/netdata/go.d.plugin/agent/module"
    10  
    11  	"golang.zx2c4.com/wireguard/wgctrl"
    12  	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
    13  )
    14  
    15  //go:embed "config_schema.json"
    16  var configSchema string
    17  
    18  func init() {
    19  	module.Register("wireguard", module.Creator{
    20  		JobConfigSchema: configSchema,
    21  		Create:          func() module.Module { return New() },
    22  	})
    23  }
    24  
    25  func New() *WireGuard {
    26  	return &WireGuard{
    27  		newWGClient:  func() (wgClient, error) { return wgctrl.New() },
    28  		charts:       &module.Charts{},
    29  		devices:      make(map[string]bool),
    30  		peers:        make(map[string]bool),
    31  		cleanupEvery: time.Minute,
    32  	}
    33  }
    34  
    35  type (
    36  	WireGuard struct {
    37  		module.Base
    38  
    39  		charts *module.Charts
    40  
    41  		client      wgClient
    42  		newWGClient func() (wgClient, error)
    43  
    44  		cleanupLastTime time.Time
    45  		cleanupEvery    time.Duration
    46  
    47  		devices map[string]bool
    48  		peers   map[string]bool
    49  	}
    50  	wgClient interface {
    51  		Devices() ([]*wgtypes.Device, error)
    52  		Close() error
    53  	}
    54  )
    55  
    56  func (w *WireGuard) Init() bool {
    57  	return true
    58  }
    59  
    60  func (w *WireGuard) Check() bool {
    61  	return len(w.Collect()) > 0
    62  }
    63  
    64  func (w *WireGuard) Charts() *module.Charts {
    65  	return w.charts
    66  }
    67  
    68  func (w *WireGuard) Collect() map[string]int64 {
    69  	mx, err := w.collect()
    70  	if err != nil {
    71  		w.Error(err)
    72  	}
    73  
    74  	if len(mx) == 0 {
    75  		return nil
    76  	}
    77  	return mx
    78  }
    79  
    80  func (w *WireGuard) Cleanup() {
    81  	if w.client == nil {
    82  		return
    83  	}
    84  	if err := w.client.Close(); err != nil {
    85  		w.Warningf("cleanup: error on closing connection: %v", err)
    86  	}
    87  	w.client = nil
    88  }