| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package gearman |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "fmt" |
| 8 | "strings" |
| 9 | |
| 10 | "github.com/netdata/netdata/go/plugins/plugin/go.d/pkg/socket" |
| 11 | ) |
| 12 | |
| 13 | type gearmanConn interface { |
| 14 | connect() error |
| 15 | disconnect() |
| 16 | queryStatus() ([]byte, error) |
| 17 | queryPriorityStatus() ([]byte, error) |
| 18 | } |
| 19 | |
| 20 | func newGearmanConn(conf Config) gearmanConn { |
| 21 | return &gearmanClient{conn: socket.New(socket.Config{ |
| 22 | Address: conf.Address, |
| 23 | Timeout: conf.Timeout.Duration(), |
| 24 | MaxReadLines: 10000, |
| 25 | })} |
| 26 | } |
| 27 | |
| 28 | type gearmanClient struct { |
| 29 | conn socket.Client |
| 30 | } |
| 31 | |
| 32 | func (c *gearmanClient) connect() error { |
| 33 | return c.conn.Connect() |
| 34 | } |
| 35 | |
| 36 | func (c *gearmanClient) disconnect() { |
| 37 | _ = c.conn.Disconnect() |
| 38 | } |
| 39 | |
| 40 | func (c *gearmanClient) queryStatus() ([]byte, error) { |
| 41 | return c.query("status") |
| 42 | } |
| 43 | |
| 44 | func (c *gearmanClient) queryPriorityStatus() ([]byte, error) { |
| 45 | return c.query("prioritystatus") |
| 46 | } |
| 47 | |
| 48 | func (c *gearmanClient) query(cmd string) ([]byte, error) { |
| 49 | var b bytes.Buffer |
| 50 | |
| 51 | if err := c.conn.Command(cmd+"\n", func(bs []byte) (bool, error) { |
| 52 | s := string(bs) |
| 53 | |
| 54 | if strings.HasPrefix(s, "ERR") { |
| 55 | return false, fmt.Errorf("command '%s': %s", cmd, s) |
| 56 | } |
| 57 | |
| 58 | b.WriteString(s) |
| 59 | b.WriteByte('\n') |
| 60 | |
| 61 | return !strings.HasPrefix(s, "."), nil |
| 62 | }); err != nil { |
| 63 | return nil, err |
| 64 | } |
| 65 | |
| 66 | return b.Bytes(), nil |
| 67 | } |