gatus/config/endpoint/condition.go

365 lines
15 KiB
Go
Raw Permalink Normal View History

package endpoint
import (
"errors"
"fmt"
2020-10-05 02:00:24 +02:00
"strconv"
"strings"
2020-11-15 18:26:35 +01:00
"time"
2020-11-16 16:10:02 +01:00
2022-12-06 07:41:09 +01:00
"github.com/TwiN/gatus/v5/jsonpath"
"github.com/TwiN/gatus/v5/pattern"
)
// Placeholders
2020-10-05 02:00:24 +02:00
const (
2020-10-07 01:07:47 +02:00
// StatusPlaceholder is a placeholder for a HTTP status.
//
// Values that could replace the placeholder: 200, 404, 500, ...
StatusPlaceholder = "[STATUS]"
2020-11-18 01:34:22 +01:00
// IPPlaceholder is a placeholder for an IP.
2020-10-07 01:07:47 +02:00
//
// Values that could replace the placeholder: 127.0.0.1, 10.0.0.1, ...
2020-11-18 01:34:22 +01:00
IPPlaceholder = "[IP]"
2020-10-07 01:07:47 +02:00
2022-12-06 07:41:09 +01:00
// DNSRCodePlaceholder is a placeholder for DNS_RCODE
2020-11-18 00:55:31 +01:00
//
// Values that could replace the placeholder: NOERROR, FORMERR, SERVFAIL, NXDOMAIN, NOTIMP, REFUSED
2020-11-19 09:31:30 +01:00
DNSRCodePlaceholder = "[DNS_RCODE]"
2020-11-18 00:55:31 +01:00
2020-11-18 01:34:22 +01:00
// ResponseTimePlaceholder is a placeholder for the request response time, in milliseconds.
2020-10-07 01:07:47 +02:00
//
// Values that could replace the placeholder: 1, 500, 1000, ...
2020-11-18 01:34:22 +01:00
ResponseTimePlaceholder = "[RESPONSE_TIME]"
2020-10-07 01:07:47 +02:00
// BodyPlaceholder is a placeholder for the Body of the response
2020-10-07 01:07:47 +02:00
//
// Values that could replace the placeholder: {}, {"data":{"name":"john"}}, ...
2020-11-18 01:34:22 +01:00
BodyPlaceholder = "[BODY]"
2020-10-07 01:07:47 +02:00
2020-11-18 01:34:22 +01:00
// ConnectedPlaceholder is a placeholder for whether a connection was successfully established.
2020-10-07 01:07:47 +02:00
//
// Values that could replace the placeholder: true, false
2020-11-18 01:34:22 +01:00
ConnectedPlaceholder = "[CONNECTED]"
2020-10-05 02:00:24 +02:00
// CertificateExpirationPlaceholder is a placeholder for the duration before certificate expiration, in milliseconds.
//
// Values that could replace the placeholder: 4461677039 (~52 days)
CertificateExpirationPlaceholder = "[CERTIFICATE_EXPIRATION]"
// DomainExpirationPlaceholder is a placeholder for the duration before the domain expires, in milliseconds.
DomainExpirationPlaceholder = "[DOMAIN_EXPIRATION]"
)
// Functions
const (
2020-10-23 22:31:49 +02:00
// LengthFunctionPrefix is the prefix for the length function
//
// Usage: len([BODY].articles) == 10, len([BODY].name) > 5
2020-10-23 22:31:49 +02:00
LengthFunctionPrefix = "len("
// HasFunctionPrefix is the prefix for the has function
//
// Usage: has([BODY].errors) == true
HasFunctionPrefix = "has("
2020-10-23 22:35:16 +02:00
// PatternFunctionPrefix is the prefix for the pattern function
//
// Usage: [IP] == pat(192.168.*.*)
2020-10-05 02:00:24 +02:00
PatternFunctionPrefix = "pat("
// AnyFunctionPrefix is the prefix for the any function
//
// Usage: [IP] == any(1.1.1.1, 1.0.0.1)
AnyFunctionPrefix = "any("
2020-10-23 22:35:16 +02:00
// FunctionSuffix is the suffix for all functions
2020-10-23 22:31:49 +02:00
FunctionSuffix = ")"
)
2020-10-23 22:31:49 +02:00
// Other constants
const (
2020-10-23 22:31:49 +02:00
// InvalidConditionElementSuffix is the suffix that will be appended to an invalid condition
2020-10-05 02:00:24 +02:00
InvalidConditionElementSuffix = "(INVALID)"
2021-03-14 21:52:59 +01:00
// maximumLengthBeforeTruncatingWhenComparedWithPattern is the maximum length an element being compared to a
// pattern can have.
//
// This is only used for aesthetic purposes; it does not influence whether the condition evaluation results in a
// success or a failure
maximumLengthBeforeTruncatingWhenComparedWithPattern = 25
2020-10-05 02:00:24 +02:00
)
2021-11-04 03:17:58 +01:00
// Condition is a condition that needs to be met in order for an Endpoint to be considered healthy.
type Condition string
// Validate checks if the Condition is valid
func (c Condition) Validate() error {
r := &Result{}
c.evaluate(r, false)
if len(r.Errors) != 0 {
return errors.New(r.Errors[0])
}
return nil
}
2020-10-02 01:57:11 +02:00
// evaluate the Condition with the Result of the health check
func (c Condition) evaluate(result *Result, dontResolveFailedConditions bool) bool {
2021-01-15 04:49:48 +01:00
condition := string(c)
success := false
conditionToDisplay := condition
if strings.Contains(condition, " == ") {
parameters, resolvedParameters := sanitizeAndResolve(strings.Split(condition, " == "), result)
success = isEqual(resolvedParameters[0], resolvedParameters[1])
if !success && !dontResolveFailedConditions {
conditionToDisplay = prettify(parameters, resolvedParameters, "==")
}
} else if strings.Contains(condition, " != ") {
parameters, resolvedParameters := sanitizeAndResolve(strings.Split(condition, " != "), result)
success = !isEqual(resolvedParameters[0], resolvedParameters[1])
if !success && !dontResolveFailedConditions {
conditionToDisplay = prettify(parameters, resolvedParameters, "!=")
}
} else if strings.Contains(condition, " <= ") {
parameters, resolvedParameters := sanitizeAndResolveNumerical(strings.Split(condition, " <= "), result)
success = resolvedParameters[0] <= resolvedParameters[1]
if !success && !dontResolveFailedConditions {
conditionToDisplay = prettifyNumericalParameters(parameters, resolvedParameters, "<=")
}
} else if strings.Contains(condition, " >= ") {
parameters, resolvedParameters := sanitizeAndResolveNumerical(strings.Split(condition, " >= "), result)
success = resolvedParameters[0] >= resolvedParameters[1]
if !success && !dontResolveFailedConditions {
conditionToDisplay = prettifyNumericalParameters(parameters, resolvedParameters, ">=")
}
} else if strings.Contains(condition, " > ") {
parameters, resolvedParameters := sanitizeAndResolveNumerical(strings.Split(condition, " > "), result)
success = resolvedParameters[0] > resolvedParameters[1]
if !success && !dontResolveFailedConditions {
conditionToDisplay = prettifyNumericalParameters(parameters, resolvedParameters, ">")
}
} else if strings.Contains(condition, " < ") {
parameters, resolvedParameters := sanitizeAndResolveNumerical(strings.Split(condition, " < "), result)
success = resolvedParameters[0] < resolvedParameters[1]
if !success && !dontResolveFailedConditions {
conditionToDisplay = prettifyNumericalParameters(parameters, resolvedParameters, "<")
}
} else {
result.AddError(fmt.Sprintf("invalid condition: %s", condition))
return false
}
if !success {
//log.Printf("[Condition.evaluate] Condition '%s' did not succeed because '%s' is false", condition, condition)
}
result.ConditionResults = append(result.ConditionResults, &ConditionResult{Condition: conditionToDisplay, Success: success})
return success
}
2020-10-02 01:57:11 +02:00
// hasBodyPlaceholder checks whether the condition has a BodyPlaceholder
// Used for determining whether the response body should be read or not
func (c Condition) hasBodyPlaceholder() bool {
return strings.Contains(string(c), BodyPlaceholder)
}
// hasDomainExpirationPlaceholder checks whether the condition has a DomainExpirationPlaceholder
// Used for determining whether a whois operation is necessary
func (c Condition) hasDomainExpirationPlaceholder() bool {
return strings.Contains(string(c), DomainExpirationPlaceholder)
}
// hasIPPlaceholder checks whether the condition has an IPPlaceholder
// Used for determining whether an IP lookup is necessary
func (c Condition) hasIPPlaceholder() bool {
return strings.Contains(string(c), IPPlaceholder)
}
2020-10-02 01:57:11 +02:00
// isEqual compares two strings.
//
// Supports the "pat" and the "any" functions.
// i.e. if one of the parameters starts with PatternFunctionPrefix and ends with FunctionSuffix, it will be treated like
// a pattern.
2020-10-02 01:57:11 +02:00
func isEqual(first, second string) bool {
firstHasFunctionSuffix := strings.HasSuffix(first, FunctionSuffix)
secondHasFunctionSuffix := strings.HasSuffix(second, FunctionSuffix)
if firstHasFunctionSuffix || secondHasFunctionSuffix {
var isFirstPattern, isSecondPattern bool
if strings.HasPrefix(first, PatternFunctionPrefix) && firstHasFunctionSuffix {
isFirstPattern = true
first = strings.TrimSuffix(strings.TrimPrefix(first, PatternFunctionPrefix), FunctionSuffix)
}
if strings.HasPrefix(second, PatternFunctionPrefix) && secondHasFunctionSuffix {
isSecondPattern = true
second = strings.TrimSuffix(strings.TrimPrefix(second, PatternFunctionPrefix), FunctionSuffix)
}
if isFirstPattern && !isSecondPattern {
return pattern.Match(first, second)
} else if !isFirstPattern && isSecondPattern {
return pattern.Match(second, first)
}
var isFirstAny, isSecondAny bool
if strings.HasPrefix(first, AnyFunctionPrefix) && firstHasFunctionSuffix {
isFirstAny = true
first = strings.TrimSuffix(strings.TrimPrefix(first, AnyFunctionPrefix), FunctionSuffix)
}
if strings.HasPrefix(second, AnyFunctionPrefix) && secondHasFunctionSuffix {
isSecondAny = true
second = strings.TrimSuffix(strings.TrimPrefix(second, AnyFunctionPrefix), FunctionSuffix)
}
if isFirstAny && !isSecondAny {
options := strings.Split(first, ",")
for _, option := range options {
if strings.TrimSpace(option) == second {
return true
}
}
return false
} else if !isFirstAny && isSecondAny {
options := strings.Split(second, ",")
for _, option := range options {
if strings.TrimSpace(option) == first {
return true
}
}
return false
}
2020-10-02 01:57:11 +02:00
}
// test if inputs are integers
firstInt, err1 := strconv.ParseInt(first, 0, 64)
secondInt, err2 := strconv.ParseInt(second, 0, 64)
if err1 == nil && err2 == nil {
return firstInt == secondInt
}
return first == second
2020-10-02 01:57:11 +02:00
}
2020-10-05 02:00:24 +02:00
// sanitizeAndResolve sanitizes and resolves a list of elements and returns the list of parameters as well as a list
// of resolved parameters
2021-01-15 04:49:48 +01:00
func sanitizeAndResolve(elements []string, result *Result) ([]string, []string) {
parameters := make([]string, len(elements))
resolvedParameters := make([]string, len(elements))
body := strings.TrimSpace(string(result.Body))
2021-01-15 04:49:48 +01:00
for i, element := range elements {
2020-10-05 02:00:24 +02:00
element = strings.TrimSpace(element)
2021-01-15 04:49:48 +01:00
parameters[i] = element
2020-10-05 02:00:24 +02:00
switch strings.ToUpper(element) {
case StatusPlaceholder:
2020-10-23 22:29:20 +02:00
element = strconv.Itoa(result.HTTPStatus)
2020-11-18 01:34:22 +01:00
case IPPlaceholder:
2020-10-23 22:29:20 +02:00
element = result.IP
2020-11-18 01:34:22 +01:00
case ResponseTimePlaceholder:
2020-10-05 02:00:24 +02:00
element = strconv.Itoa(int(result.Duration.Milliseconds()))
2020-11-18 01:34:22 +01:00
case BodyPlaceholder:
2020-10-05 02:00:24 +02:00
element = body
2020-11-19 09:31:30 +01:00
case DNSRCodePlaceholder:
2020-11-18 00:55:31 +01:00
element = result.DNSRCode
2020-11-18 01:34:22 +01:00
case ConnectedPlaceholder:
2020-10-05 02:00:24 +02:00
element = strconv.FormatBool(result.Connected)
case CertificateExpirationPlaceholder:
2020-11-18 01:34:22 +01:00
element = strconv.FormatInt(result.CertificateExpiration.Milliseconds(), 10)
case DomainExpirationPlaceholder:
element = strconv.FormatInt(result.DomainExpiration.Milliseconds(), 10)
2020-10-05 02:00:24 +02:00
default:
2020-11-18 01:34:22 +01:00
// if contains the BodyPlaceholder, then evaluate json path
if strings.Contains(element, BodyPlaceholder) {
checkingForLength := false
checkingForExistence := false
2020-10-05 02:00:24 +02:00
if strings.HasPrefix(element, LengthFunctionPrefix) && strings.HasSuffix(element, FunctionSuffix) {
checkingForLength = true
2020-10-05 02:00:24 +02:00
element = strings.TrimSuffix(strings.TrimPrefix(element, LengthFunctionPrefix), FunctionSuffix)
}
if strings.HasPrefix(element, HasFunctionPrefix) && strings.HasSuffix(element, FunctionSuffix) {
checkingForExistence = true
element = strings.TrimSuffix(strings.TrimPrefix(element, HasFunctionPrefix), FunctionSuffix)
}
resolvedElement, resolvedElementLength, err := jsonpath.Eval(strings.TrimPrefix(strings.TrimPrefix(element, BodyPlaceholder), "."), result.Body)
if checkingForExistence {
if err != nil {
element = "false"
} else {
element = "true"
}
2020-10-05 02:00:24 +02:00
} else {
if err != nil {
if err.Error() != "unexpected end of JSON input" {
2021-06-06 00:50:24 +02:00
result.AddError(err.Error())
}
if checkingForLength {
element = LengthFunctionPrefix + element + FunctionSuffix + " " + InvalidConditionElementSuffix
} else {
element = element + " " + InvalidConditionElementSuffix
}
2020-10-05 02:00:24 +02:00
} else {
if checkingForLength {
element = strconv.Itoa(resolvedElementLength)
} else {
element = resolvedElement
}
2020-10-05 02:00:24 +02:00
}
}
}
}
2021-01-15 04:49:48 +01:00
resolvedParameters[i] = element
2020-10-05 02:00:24 +02:00
}
return parameters, resolvedParameters
2020-10-05 02:00:24 +02:00
}
func sanitizeAndResolveNumerical(list []string, result *Result) (parameters []string, resolvedNumericalParameters []int64) {
parameters, resolvedParameters := sanitizeAndResolve(list, result)
for _, element := range resolvedParameters {
2020-11-16 16:10:02 +01:00
if duration, err := time.ParseDuration(element); duration != 0 && err == nil {
// If the string is a duration, convert it to milliseconds
resolvedNumericalParameters = append(resolvedNumericalParameters, duration.Milliseconds())
} else if number, err := strconv.ParseInt(element, 0, 64); err != nil {
// It's not an int, so we'll check if it's a float
if f, err := strconv.ParseFloat(element, 64); err == nil {
// It's a float, but we'll convert it to an int. We're losing precision here, but it's better than
// just returning 0.
resolvedNumericalParameters = append(resolvedNumericalParameters, int64(f))
} else {
// Default to 0 if the string couldn't be converted to an integer or a float
resolvedNumericalParameters = append(resolvedNumericalParameters, 0)
}
2020-10-05 02:00:24 +02:00
} else {
resolvedNumericalParameters = append(resolvedNumericalParameters, number)
2020-10-05 02:00:24 +02:00
}
}
return parameters, resolvedNumericalParameters
}
func prettifyNumericalParameters(parameters []string, resolvedParameters []int64, operator string) string {
return prettify(parameters, []string{strconv.Itoa(int(resolvedParameters[0])), strconv.Itoa(int(resolvedParameters[1]))}, operator)
}
2021-11-04 03:17:58 +01:00
// prettify returns a string representation of a condition with its parameters resolved between parentheses
func prettify(parameters []string, resolvedParameters []string, operator string) string {
// Since, in the event of an invalid path, the resolvedParameters also contain the condition itself,
// we'll return the resolvedParameters as-is.
if strings.HasSuffix(resolvedParameters[0], InvalidConditionElementSuffix) || strings.HasSuffix(resolvedParameters[1], InvalidConditionElementSuffix) {
2021-01-15 04:49:48 +01:00
return resolvedParameters[0] + " " + operator + " " + resolvedParameters[1]
}
2021-03-14 18:36:54 +01:00
// If using the pattern function, truncate the parameter it's being compared to if said parameter is long enough
2021-03-14 21:52:59 +01:00
if strings.HasPrefix(parameters[0], PatternFunctionPrefix) && strings.HasSuffix(parameters[0], FunctionSuffix) && len(resolvedParameters[1]) > maximumLengthBeforeTruncatingWhenComparedWithPattern {
resolvedParameters[1] = fmt.Sprintf("%.25s...(truncated)", resolvedParameters[1])
}
2021-03-14 21:52:59 +01:00
if strings.HasPrefix(parameters[1], PatternFunctionPrefix) && strings.HasSuffix(parameters[1], FunctionSuffix) && len(resolvedParameters[0]) > maximumLengthBeforeTruncatingWhenComparedWithPattern {
resolvedParameters[0] = fmt.Sprintf("%.25s...(truncated)", resolvedParameters[0])
}
// First element is a placeholder
if parameters[0] != resolvedParameters[0] && parameters[1] == resolvedParameters[1] {
2021-01-15 04:49:48 +01:00
return parameters[0] + " (" + resolvedParameters[0] + ") " + operator + " " + parameters[1]
}
// Second element is a placeholder
if parameters[0] == resolvedParameters[0] && parameters[1] != resolvedParameters[1] {
2021-01-15 04:49:48 +01:00
return parameters[0] + " " + operator + " " + parameters[1] + " (" + resolvedParameters[1] + ")"
}
// Both elements are placeholders...?
if parameters[0] != resolvedParameters[0] && parameters[1] != resolvedParameters[1] {
2021-01-15 04:49:48 +01:00
return parameters[0] + " (" + resolvedParameters[0] + ") " + operator + " " + parameters[1] + " (" + resolvedParameters[1] + ")"
}
// Neither elements are placeholders
2021-01-15 04:49:48 +01:00
return parameters[0] + " " + operator + " " + parameters[1]
2020-10-05 02:00:24 +02:00
}