summaryrefslogtreecommitdiff
path: root/internal/clients/healthclient.go
blob: 7313583724a82e404a902144bf5578dd9be0e03a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package clients

import (
	"context"
	"fmt"
	"runtime"
	"strings"
	"time"

	"github.com/mimecast/dtail/internal/clients/handlers"
	"github.com/mimecast/dtail/internal/clients/remote"
	"github.com/mimecast/dtail/internal/config"
	"github.com/mimecast/dtail/internal/omode"

	gossh "golang.org/x/crypto/ssh"
)

// HealthClient is used for health checking (e.g. via Nagios)
type HealthClient struct {
	// Client operating mode
	mode omode.Mode
	// The remote server address
	server string
	// SSH user name
	userName string
	// SSH auth methods to use to connect to the remote servers.
	sshAuthMethods []gossh.AuthMethod
}

// NewHealthClient returns a new healh client.
func NewHealthClient(mode omode.Mode) (*HealthClient, error) {
	c := HealthClient{
		mode:     mode,
		server:   fmt.Sprintf("%s:%d", config.Server.SSHBindAddress, config.Common.SSHPort),
		userName: config.ControlUser,
	}
	c.initSSHAuthMethods()

	return &c, nil
}

// Start the health client.
func (c *HealthClient) Start(ctx context.Context) (status int) {
	receive := make(chan string)

	throttleCh := make(chan struct{}, runtime.NumCPU())
	statsCh := make(chan struct{}, 1)

	conn := remote.NewOneOffConnection(c.server, c.userName, c.sshAuthMethods)
	conn.Handler = handlers.NewHealthHandler(c.server, receive)
	conn.Commands = []string{c.mode.String()}

	connCtx, cancel := conn.Handler.WithCancel(ctx)
	go conn.Start(connCtx, cancel, throttleCh, statsCh)

	for {
		select {
		case data := <-receive:
			// Parse recieved data.
			s := strings.Split(data, "|")
			message := s[len(s)-1]
			if strings.HasPrefix(message, "done;") {
				return
			}

			// Set severity.
			s = strings.Split(message, ":")
			switch s[0] {
			case "OK":
			case "WARNING":
				if status < 1 {
					status = 1
				}
			case "CRITICAL":
				status = 2
			case "UNKNOWN":
				status = 3
			default:
				fmt.Printf("CRITICAL: Unexpected server response: '%s'\n", message)
				status = 2
				return
			}
			fmt.Print(message)

		case <-time.After(time.Second * 2):
			status = 2
			fmt.Println("CRITICAL: Could not communicate with DTail server")
			return
		}
	}
}

// Initialize SSH auth methods.
func (c *HealthClient) initSSHAuthMethods() {
	c.sshAuthMethods = append(c.sshAuthMethods, gossh.Password(config.ControlUser))
}