update ping command to return error

Update the ping command to return errors instead of logging them.
This commit is contained in:
Hector 2021-08-30 07:52:38 +01:00
parent e6b7e59081
commit a764127c14
2 changed files with 11 additions and 9 deletions

View File

@ -196,8 +196,8 @@ func (e *Exporter) collectEnabledJailMetrics(ch chan<- prometheus.Metric) {
func (e *Exporter) collectServerUpMetric(ch chan<- prometheus.Metric, s *socket.Fail2BanSocket) { func (e *Exporter) collectServerUpMetric(ch chan<- prometheus.Metric, s *socket.Fail2BanSocket) {
var serverUp float64 = 0 var serverUp float64 = 0
if s != nil { if s != nil {
pingSuccess := s.Ping() pingSuccess, err := s.Ping()
if pingSuccess { if err == nil && pingSuccess {
serverUp = 1 serverUp = 1
} }
} }

View File

@ -36,21 +36,19 @@ func (s *Fail2BanSocket) Close() error {
return s.socket.Close() return s.socket.Close()
} }
func (s *Fail2BanSocket) Ping() bool { func (s *Fail2BanSocket) Ping() (bool, error) {
response, err := s.sendCommand([]string{pingCommand, "100"}) response, err := s.sendCommand([]string{pingCommand, "100"})
if err != nil { if err != nil {
log.Printf("server ping failed: %v", err) return false, newConnectionError(pingCommand, err)
return false
} }
if t, ok := response.(*types.Tuple); ok { if t, ok := response.(*types.Tuple); ok {
if (*t)[1] == "pong" { if (*t)[1] == "pong" {
return true return true, nil
} }
log.Printf("unexpected response data: %s", t) return false, fmt.Errorf("unexpected response data (expecting 'pong'): %s", (*t)[1])
} }
log.Printf("(%s) unexpected response format - cannot parse: %v", pingCommand, response) return false, newBadFormatError(pingCommand, response)
return false
} }
func (s *Fail2BanSocket) GetJails() ([]string, error) { func (s *Fail2BanSocket) GetJails() ([]string, error) {
@ -125,6 +123,10 @@ func newBadFormatError(command string, data interface{}) error {
return fmt.Errorf("(%s) unexpected response format - cannot parse: %v", command, data) return fmt.Errorf("(%s) unexpected response format - cannot parse: %v", command, data)
} }
func newConnectionError(command string, err error) error {
return fmt.Errorf("(%s) failed to send command through socket: %v", err)
}
func trimSpaceForAll(slice []string) []string { func trimSpaceForAll(slice []string) []string {
for i := range slice { for i := range slice {
slice[i] = strings.TrimSpace(slice[i]) slice[i] = strings.TrimSpace(slice[i])