Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
dsh2dsh committed Mar 6, 2024
0 parents commit 7992fa7
Show file tree
Hide file tree
Showing 14 changed files with 753 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
- package-ecosystem: "github-actions" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
27 changes: 27 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# This workflow will build a golang project
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go

name: Go

on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: 'go.mod'

- name: Build
run: make build

- name: Test
run: make test
69 changes: 69 additions & 0 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
name: golangci-lint
on:
push:
branches:
- master
- main
pull_request:

permissions:
contents: read
# Optional: allow read access to pull request. Use with `only-new-issues`
# option.
# pull-requests: read

jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: 'go.mod'
cache: false
- name: golangci-lint
uses: golangci/golangci-lint-action@v4
with:
# Require: The version of golangci-lint to use.
#
# When `install-mode` is `binary` (default) the value can be v1.2 or
# v1.2.3 or `latest` to use the latest version.
#
# When `install-mode` is `goinstall` the value can be v1.2.3,
# `latest`, or the hash of a commit.
version: 'latest'

# Optional: working directory, useful for monorepos
# working-directory: somedir

# Optional: golangci-lint command line arguments.
#
# Note: By default, the `.golangci.yml` file should be at the root of
# the repository.
#
# The location of the configuration file can be changed by using
# `--config=`.
#
# args: --timeout=30m --config=/my/path/.golangci.yml --issues-exit-code=0

# Optional: show only new issues if it's a pull request. The default
# value is `false`.
# only-new-issues: true

# Optional: if set to true, then all caching functionality will be
# completely disabled, takes precedence over all other caching
# options.
# skip-cache: true

# Optional: if set to true, then the action won't cache or restore
# ~/go/pkg.
# skip-pkg-cache: true

# Optional: if set to true, then the action won't cache or restore
# ~/.cache/go-build.
# skip-build-cache: true

# Optional: The mode to install golangci-lint. It can be 'binary' or
# 'goinstall'.
# install-mode: "goinstall"
50 changes: 50 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
run:
timeout: 5m

linters:
enable:
- asciicheck
- bidichk
- errorlint
- goconst
- gocritic
# - gofmt # we are using gofumpt instead
- gofumpt
- goimports
- makezero
- misspell
- nolintlint
- perfsprint
- prealloc
- testifylint
- unconvert
- usestdlibvars
- wastedassign
- wrapcheck

linters-settings:
goimports:
# A comma-separated list of prefixes, which, if set, checks import paths
# with the given prefixes are grouped after 3rd-party packages.
# Default: ""
local-prefixes: "github.com/dsh2dsh/check_wg"

nolintlint:
# Enable to require an explanation of nonzero length after each nolint directive.
# Default: false
require-explanation: true
# Enable to require nolint directives to mention the specific linter being suppressed.
# Default: false
require-specific: true

revive:
rules:
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#receiver-naming
- name: receiver-naming
disabled: true

issues:
exclude-rules:
- path: _test\.go
linters:
- wrapcheck
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Denis Shaposhnikov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
10 changes: 10 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
TEST_ARGS=

test:
go test ${TEST_ARGS} ./...

build:
go build -ldflags="-s -w" ./

clean:
rm -f check_wg
84 changes: 84 additions & 0 deletions cmd/handshake.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package cmd

import (
"fmt"
"io"
"time"

"github.com/inexio/go-monitoringplugin"
"github.com/spf13/cobra"

"github.com/dsh2dsh/check_wg/wg"
)

var (
handshakeWarn, handshakeCrit time.Duration

handshakeCmd = cobra.Command{
Use: "handshake [-w 5m] [-c 15m] [wg show wg0 dump]",
Short: "check oldest latest handshake",
Long: `It executes given wg(8) command and reads its output or stdin, if no
command was given at all.
It analizes latest handshake of every peer and outputs warning or critical
status if any of them is greater of given threshold.`,

Run: func(cmd *cobra.Command, args []string) {
CheckLatestHandshake(args)
},
}
)

func init() {
handshakeCmd.Flags().DurationVarP(&handshakeWarn, "warn", "w", 5*time.Minute,
"warning threshold")
handshakeCmd.Flags().DurationVarP(&handshakeCrit, "crit", "c", 15*time.Minute,
"critical threshold")
}

func CheckLatestHandshake(args []string) {
resp := monitoringplugin.NewResponse("oldest latest handshake is OK")
resp.SetOutputDelimiter(" / ")
defer resp.OutputAndExit()

peer, err := OldestHandshake(args)
if resp.UpdateStatusOnError(err, monitoringplugin.WARNING, "", true) {
return
} else if !peer.Valid() {
resp.UpdateStatus(monitoringplugin.WARNING, "no valid peer found")
return
}

d := time.Since(peer.LatestHandshake).Truncate(time.Second).Seconds()
point := monitoringplugin.NewPerformanceDataPoint("latest-handshake", d).
SetUnit("s").
SetThresholds(monitoringplugin.NewThresholds(
nil, handshakeWarn.Seconds(), nil, handshakeCrit.Seconds()))

if err := resp.AddPerformanceDataPoint(point); err != nil {
resp.UpdateStatusOnError(
fmt.Errorf("failed add performance data: %w", err),
monitoringplugin.WARNING, "", true)
return
}
resp.UpdateStatus(monitoringplugin.OK, fmt.Sprintf("peer=%v", peer.Name()))
}

func OldestHandshake(args []string) (wg.DumpPeer, error) {
var peer wg.DumpPeer
err := withWgCmd(args, func(r io.Reader) error {
wgDump, err := wg.NewDump(r)
if err != nil {
if len(args) == 0 {
return fmt.Errorf("with input from stdin: %w", err)
}
return fmt.Errorf("with input from %v: %w", args, err)
}

if oldestPeer := wgDump.OldestHandshake(); oldestPeer != nil {
peer = *oldestPeer
}
return nil
})
return peer, err
}
69 changes: 69 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package cmd

import (
"fmt"
"io"
"os"
"os/exec"

"github.com/spf13/cobra"
)

var rootCmd = cobra.Command{
Use: "check_wg",
Short: "Icinga2 health check of wireguard peers, using output of wg(8).",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// Don't show usage on app errors.
// https://github.com/spf13/cobra/issues/340#issuecomment-378726225
cmd.SilenceUsage = true
},
}

func init() {
rootCmd.AddCommand(&handshakeCmd)
}

func Execute() error {
return rootCmd.Execute() //nolint:wrapcheck // main() doesn't need it
}

func withWgCmd(args []string, fn func(r io.Reader) error) error {
r, cmd, err := startWgCmd(args)
if err != nil {
return err
}

if err := fn(r); err != nil {
return err
}

if cmd != nil {
if err := cmd.Wait(); err != nil {
return fmt.Errorf("wait for %v: %w", args, err)
}
}
return nil
}

func startWgCmd(args []string) (io.Reader, *exec.Cmd, error) {
if len(args) == 0 {
return os.Stdin, nil, nil
}

var cmdArgs []string
if len(args) > 1 {
cmdArgs = args[1:]
}

cmd := exec.Command(args[0], cmdArgs...)
cmd.Stderr = os.Stderr

stdout, err := cmd.StdoutPipe()
const errMsg = "exec %v: %w"
if err != nil {
return nil, nil, fmt.Errorf(errMsg, args, err)
} else if err := cmd.Start(); err != nil {
return nil, nil, fmt.Errorf(errMsg, args, err)
}
return stdout, cmd, nil
}
18 changes: 18 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module github.com/dsh2dsh/check_wg

go 1.22.0

require (
github.com/inexio/go-monitoringplugin v1.0.13
github.com/spf13/cobra v1.8.0
github.com/stretchr/testify v1.9.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/pkg/errors v0.8.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
26 changes: 26 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/inexio/go-monitoringplugin v1.0.13 h1:Mbd1pe/hOMHpy1ihF1eKG9pRRaEA/j38za3rG16we/U=
github.com/inexio/go-monitoringplugin v1.0.13/go.mod h1:kzHRJGZ2iE/0IElB4NYI38h3h0HM5wqTTH7KyUCjkM8=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Loading

0 comments on commit 7992fa7

Please sign in to comment.