Skip to content

Commit

Permalink
Add Support for Commands
Browse files Browse the repository at this point in the history
This ssupports sending nagios external commands to live status.
No checking is done on the content of the Commands.
  • Loading branch information
tcolgate committed Jul 1, 2016
1 parent 8865d67 commit 2943a9f
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 0 deletions.
93 changes: 93 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package livestatus

import (
"fmt"
"net"
"strings"
"time"
)

// Command is a binding command instance.
type Command struct {
cmd string
vals []string
ls *Livestatus
}

func newCommand(ls *Livestatus) *Command {
return &Command{
ls: ls,
}
}

func (c *Command) Raw(cmd string) {
c.cmd = cmd
}

func (c *Command) Arg(v interface{}) {
c.vals = append(c.vals, fmt.Sprintf("%v", v))
}

type CommandOpFunc func(*Command)

func (c *Command) Op(op CommandOpFunc) {
op(c)
}

// KeepAliveOff disables the default keepalive from Command
func (q *Query) KeepAliveOff() *Query {
q.ls.keepalive = false
return q
}

// Exec executes the query.
func (c *Command) Exec() (*Response, error) {
resp := &Response{}

var err error
var conn net.Conn

if c.ls.keepConn != nil {
conn = c.ls.keepConn
} else {
// Connect to socket
conn, err = c.dial()
if err != nil {
return nil, err
}
}

if !c.ls.keepalive {
c.ls.keepConn = nil
defer conn.Close()
} else {
c.ls.keepConn = conn
}

// Send command data
cmd, err := c.buildCmd(time.Now())
if err != nil {
return nil, err
}

conn.Write([]byte(cmd))
// You get nothing back from an external command
// no way of knowing if this has worked

return resp, nil
}

func (c *Command) buildCmd(t time.Time) (string, error) {
cmdStr := fmt.Sprintf("COMMAND [%d] %s", t.Unix(), c.cmd)
cmdStr = fmt.Sprintf("%s;%s", cmdStr, strings.Join(c.vals, ";"))

return fmt.Sprintf("%s\n", cmdStr), nil
}

func (c *Command) dial() (net.Conn, error) {
if c.ls.dialer != nil {
return c.ls.dialer()
} else {
return net.Dial(c.ls.network, c.ls.address)
}
}
6 changes: 6 additions & 0 deletions livestatus.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ func (l *Livestatus) Query(table string) *Query {
return newQuery(table, l)
}

// Command creates a new command instanc.
func (l *Livestatus) Command() *Command {
l.keepalive = true
return newCommand(l)
}

// NewLivestatus creates a new binding instance.
func NewLivestatus(network, address string) *Livestatus {
return &Livestatus{
Expand Down

0 comments on commit 2943a9f

Please sign in to comment.