| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package nagios |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "errors" |
| 8 | ) |
| 9 | |
| 10 | var errNagiosCheckTimeout = errors.New("nagios: check timed out") |
| 11 | |
| 12 | func exitCodeFromError(err error) int { |
| 13 | if err == nil { |
| 14 | return 0 |
| 15 | } |
| 16 | var exitErr interface{ ExitCode() int } |
| 17 | if errors.As(err, &exitErr) { |
| 18 | return exitErr.ExitCode() |
| 19 | } |
| 20 | return -1 |
| 21 | } |
| 22 | |
| 23 | func serviceStateFromExecution(exitCode int, err error) string { |
| 24 | if errors.Is(err, errNagiosCheckTimeout) || errors.Is(err, context.DeadlineExceeded) { |
| 25 | return nagiosStateUnknown |
| 26 | } |
| 27 | switch exitCode { |
| 28 | case 0: |
| 29 | return nagiosStateOK |
| 30 | case 1: |
| 31 | return nagiosStateWarning |
| 32 | case 2: |
| 33 | return nagiosStateCritical |
| 34 | case 3: |
| 35 | return nagiosStateUnknown |
| 36 | default: |
| 37 | return nagiosStateUnknown |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | func jobStateFromExecution(exitCode int, err error) string { |
| 42 | if errors.Is(err, errNagiosCheckTimeout) || errors.Is(err, context.DeadlineExceeded) { |
| 43 | return jobStateTimeout |
| 44 | } |
| 45 | return serviceStateFromExecution(exitCode, err) |
| 46 | } |
| 47 | |
| 48 | func classifyRunError(ctx context.Context, exitCode int, err error) error { |
| 49 | if err == nil { |
| 50 | return nil |
| 51 | } |
| 52 | if errors.Is(err, context.Canceled) { |
| 53 | if ctxErr := ctx.Err(); ctxErr != nil { |
| 54 | return ctxErr |
| 55 | } |
| 56 | return err |
| 57 | } |
| 58 | if errors.Is(err, errNagiosCheckTimeout) { |
| 59 | return nil |
| 60 | } |
| 61 | if exitCode >= 0 && exitCode <= 3 { |
| 62 | return nil |
| 63 | } |
| 64 | if errors.Is(err, context.DeadlineExceeded) { |
| 65 | if ctxErr := ctx.Err(); ctxErr != nil { |
| 66 | return ctxErr |
| 67 | } |
| 68 | } |
| 69 | return err |
| 70 | } |