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

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package proxysql
     4  
     5  import (
     6  	"database/sql"
     7  	_ "embed"
     8  	_ "github.com/go-sql-driver/mysql"
     9  	"sync"
    10  	"time"
    11  
    12  	"github.com/netdata/go.d.plugin/agent/module"
    13  	"github.com/netdata/go.d.plugin/pkg/web"
    14  )
    15  
    16  //go:embed "config_schema.json"
    17  var configSchema string
    18  
    19  func init() {
    20  	module.Register("proxysql", module.Creator{
    21  		JobConfigSchema: configSchema,
    22  		Create:          func() module.Module { return New() },
    23  	})
    24  }
    25  
    26  func New() *ProxySQL {
    27  	return &ProxySQL{
    28  		Config: Config{
    29  			DSN:     "stats:stats@tcp(127.0.0.1:6032)/",
    30  			Timeout: web.Duration{Duration: time.Second * 2},
    31  		},
    32  
    33  		charts: baseCharts.Copy(),
    34  		once:   &sync.Once{},
    35  		cache: &cache{
    36  			commands: make(map[string]*commandCache),
    37  			users:    make(map[string]*userCache),
    38  			backends: make(map[string]*backendCache),
    39  		},
    40  	}
    41  }
    42  
    43  type Config struct {
    44  	DSN     string       `yaml:"dsn"`
    45  	MyCNF   string       `yaml:"my.cnf"`
    46  	Timeout web.Duration `yaml:"timeout"`
    47  }
    48  
    49  type (
    50  	ProxySQL struct {
    51  		module.Base
    52  		Config `yaml:",inline"`
    53  
    54  		db *sql.DB
    55  
    56  		charts *module.Charts
    57  
    58  		once  *sync.Once
    59  		cache *cache
    60  	}
    61  )
    62  
    63  func (p *ProxySQL) Init() bool {
    64  	if p.DSN == "" {
    65  		p.Error("'dsn' not set")
    66  		return false
    67  	}
    68  
    69  	p.Debugf("using DSN [%s]", p.DSN)
    70  	return true
    71  }
    72  
    73  func (p *ProxySQL) Check() bool {
    74  	return len(p.Collect()) > 0
    75  }
    76  
    77  func (p *ProxySQL) Charts() *module.Charts {
    78  	return p.charts
    79  }
    80  
    81  func (p *ProxySQL) Collect() map[string]int64 {
    82  	mx, err := p.collect()
    83  	if err != nil {
    84  		p.Error(err)
    85  	}
    86  
    87  	if len(mx) == 0 {
    88  		return nil
    89  	}
    90  	return mx
    91  }
    92  
    93  func (p *ProxySQL) Cleanup() {
    94  	if p.db == nil {
    95  		return
    96  	}
    97  	if err := p.db.Close(); err != nil {
    98  		p.Errorf("cleanup: error on closing the ProxySQL instance [%s]: %v", p.DSN, err)
    99  	}
   100  	p.db = nil
   101  }