Skip to content

Commit

Permalink
code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
sni committed Nov 23, 2023
1 parent 61fff64 commit 1a1cf43
Show file tree
Hide file tree
Showing 10 changed files with 52 additions and 44 deletions.
3 changes: 2 additions & 1 deletion pkg/snclient/check_eventlog_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ package snclient
import (
"context"
"fmt"
"strconv"

"pkg/eventlog"
"pkg/wmi"
"strconv"

"github.com/elastic/beats/v7/winlogbeat/sys/winevent"
)
Expand Down
35 changes: 21 additions & 14 deletions pkg/snclient/check_process_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
)

func (l *CheckProcess) Check(ctx context.Context, _ *Agent, check *CheckData, _ []Argument) (*CheckResult, error) {
procs, err := process.Processes()
procs, err := process.ProcessesWithContext(ctx)
if err != nil {
return nil, fmt.Errorf("fetching processes failed: %s", err.Error())
}
Expand All @@ -27,28 +27,30 @@ func (l *CheckProcess) Check(ctx context.Context, _ *Agent, check *CheckData, _

check.ExpandThresholdUnit([]string{"k", "m", "g", "p", "e", "ki", "mi", "gi", "pi", "ei"}, "B", []string{"rss", "virtual", "pagefile"})

userNameLookup := map[int32]string{}

for _, proc := range procs {
cmdLine, err := proc.Cmdline()
cmdLine, err := proc.CmdlineWithContext(ctx)
if err != nil {
log.Debugf("check_process: cmd line error: %s")
}

exe := ""
filename, err := proc.Exe()
filename, err := proc.ExeWithContext(ctx)
if err == nil {
// in case the binary has been removed / updated meanwhile it shows up as "".../path/bin (deleted)""
// %> ls -la /proc/857375/exe
// lrwxrwxrwx 1 user group 0 Oct 11 20:40 /proc/857375/exe -> '/usr/bin/ssh (deleted)'
filename = strings.TrimSuffix(filename, " (deleted)")
exe = filepath.Base(filename)
} else {
cmd, err := proc.CmdlineSlice()
cmd, err := proc.CmdlineSliceWithContext(ctx)
if err != nil && len(cmd) >= 1 {
exe = cmd[0]
}
}
if exe == "" {
name, err := proc.Name()
name, err := proc.NameWithContext(ctx)
if err != nil {
log.Debugf("check_process: name error: %s")
} else {
Expand All @@ -60,7 +62,7 @@ func (l *CheckProcess) Check(ctx context.Context, _ *Agent, check *CheckData, _
continue
}

states, err := proc.Status()
states, err := proc.StatusWithContext(ctx)
if err != nil {
log.Debugf("check_process: status error: %s")
}
Expand All @@ -69,23 +71,28 @@ func (l *CheckProcess) Check(ctx context.Context, _ *Agent, check *CheckData, _
state = append(state, convertStatusChar(s))
}

ctime, err := proc.CreateTime()
ctime, err := proc.CreateTimeWithContext(ctx)
if err != nil {
log.Debugf("check_process: CreateTime error: %s")
}

username, err := proc.UsernameWithContext(ctx)
if err != nil {
log.Debugf("check_process: Username error: %s")
}

uids, err := proc.Uids()
uids, err := proc.UidsWithContext(ctx)
if err != nil {
log.Debugf("check_process: uids error: %s")
uids = []int32{-1}
}

mem, err := proc.MemoryInfo()
// cache user name lookups
username := userNameLookup[uids[0]]
if username == "" {
username, err := proc.UsernameWithContext(ctx)
if err != nil {
log.Debugf("check_process: Username error: %s")
}
userNameLookup[uids[0]] = username
}

mem, err := proc.MemoryInfoWithContext(ctx)
if err != nil {
log.Debugf("check_process: Username error: %s")
mem = &process.MemoryInfoStat{}
Expand Down
3 changes: 2 additions & 1 deletion pkg/snclient/check_service_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ There is a specific [check_service for linux](check_service_linux) as well.`,
{name: "state", description: "The state of the service, one of: stopped, starting, stopping, running, continuing, pausing, paused or unknown"},
{name: "pid", description: "The pid of the service"},
{name: "delayed", description: "If the service is delayed, can be 0 or 1 "},
{name: "classification", description: "Classification of the service, one of: kernel-driver, system-driver, service-adapter, driver, service-own-process, service-shared-process, service or interactive"},
{name: "classification", description: "Classification of the service, one of: " +
"kernel-driver, system-driver, service-adapter, driver, service-own-process, service-shared-process, service or interactive"},
{name: "start_type", description: "The configured start type, one of: boot, system, delayed, auto, demand, disabled or unknown"},
{name: "rss", description: "Memory rss in bytes"},
{name: "vms", description: "Memory vms in bytes"},
Expand Down
6 changes: 3 additions & 3 deletions pkg/snclient/cmd/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ It will also change some basic settings from the setup dialog. Ex. the initial p
snc.Log.Errorf("failed to add firewall: %s", err.Error())
}
snc.Log.Infof("installer finished successfully")
os.Exit(0)
snc.CleanExit(0)
},
})

Expand All @@ -113,7 +113,7 @@ It will also change some basic settings from the setup dialog. Ex. the initial p
}
}
snc.Log.Infof("pre script finished successfully")
os.Exit(0)
snc.CleanExit(0)
},
})

Expand All @@ -131,7 +131,7 @@ It will also change some basic settings from the setup dialog. Ex. the initial p
snc.Log.Errorf("failed to add firewall: %s", err.Error())
}
snc.Log.Infof("firewall setup ready")
os.Exit(0)
snc.CleanExit(0)
},
})
}
Expand Down
5 changes: 2 additions & 3 deletions pkg/snclient/cmd/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cmd
import (
"fmt"
"math"
"os"
"strings"

"pkg/snclient"
Expand Down Expand Up @@ -57,14 +56,14 @@ snclient do check_files path=/tmp crit='count > 100'
if cmd.CalledAs() != "test" {
cmd.Usage()

os.Exit(snclient.ExitCodeUnknown)
snc.CleanExit(snclient.ExitCodeUnknown)
}
testPrompt(cmd, snc)

return
}
rc := testRunCheck(cmd, snc, args)
os.Exit(rc)
snc.CleanExit(rc)
},
}
rootCmd.AddCommand(testCmd)
Expand Down
8 changes: 4 additions & 4 deletions pkg/snclient/cmd/uninstall.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func init() {
snc.Log.Errorf("failed to remove service: %s", err.Error())
}

os.Exit(0)
snc.CleanExit(0)
},
})

Expand All @@ -58,7 +58,7 @@ func init() {
installConfig := parseInstallerArgs(args)
if installConfig["REMOVE"] != "ALL" || installConfig["UPGRADINGPRODUCTCODE"] != "" {
snc.Log.Infof("skipping uninstall: %#v", installConfig)
os.Exit(0)
snc.CleanExit(0)
}

snc.Log.Infof("starting uninstaller: %#v", installConfig)
Expand Down Expand Up @@ -91,7 +91,7 @@ func init() {
_ = os.Remove(filepath.Join(installConfig["INSTALLDIR"], "snclient.ini"))
_ = os.Remove(filepath.Join(installConfig["INSTALLDIR"], "snclient.log"))

os.Exit(0)
snc.CleanExit(0)
},
})

Expand All @@ -107,7 +107,7 @@ func init() {
removeFireWallRules(snc)

snc.Log.Infof("firewall exceptions removed")
os.Exit(0)
snc.CleanExit(0)
},
})
}
10 changes: 5 additions & 5 deletions pkg/snclient/cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ snclient update --downgrade=0.2
executable := snclient.GlobalMacros["exe-full"]
if strings.Contains(executable, ".update") {
snc.CheckUpdateBinary("update")
os.Exit(0)
snc.CleanExit(0)
}
task := snc.Tasks.Get("Updates")
switch mod := task.(type) {
Expand All @@ -64,18 +64,18 @@ snclient update --downgrade=0.2
)
if err != nil {
fmt.Fprintf(os.Stderr, "update check failed: %s\n", err.Error())
os.Exit(3)
snc.CleanExit(3)
}
if version == "" {
fmt.Fprintf(os.Stdout, "no new updates available\n")
os.Exit(0)
snc.CleanExit(0)
}
if checkOnly {
fmt.Fprintf(os.Stdout, "new update available to version: %s\n", version)
os.Exit(1)
snc.CleanExit(1)
}
fmt.Fprintf(os.Stdout, "update to version %s applied successfully\n", version)
os.Exit(0)
snc.CleanExit(0)
}
},
}
Expand Down
8 changes: 4 additions & 4 deletions pkg/snclient/listen_prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ var (
},
[]string{"version", "build", "os"})

promHTTPRequestsTotal = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
promHTTPRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "total http requests",
},
Expand All @@ -35,8 +35,8 @@ var (
Help: "Duration of HTTP requests.",
}, []string{"code", "path"})

promTCPRequestsTotal = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
promTCPRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "tcp_requests_total",
Help: "total tcp requests",
},
Expand Down
16 changes: 8 additions & 8 deletions pkg/snclient/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,16 +375,16 @@ func (l *Listener) startListenerHTTP(handler []RequestHandler) {
Handler: mux,
ErrorLog: NewStandardLog("WARN"),
ConnState: func(con net.Conn, state http.ConnState) {
switch state {
case http.StateNew:
log.Tracef("incoming %s connection from %s", l.connType, con.RemoteAddr().String())
if state != http.StateNew {
return
}

if !l.CheckConnection(con) {
con.Close()
log.Tracef("incoming %s connection from %s", l.connType, con.RemoteAddr().String())

return
}
default:
if !l.CheckConnection(con) {
con.Close()

return
}
},
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/snclient/snclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"io"
"io/fs"
"net/http"
_ "net/http/pprof"
_ "net/http/pprof" //nolint:gosec // default muxer is not exposed by default
"os"
"os/exec"
"os/signal"
Expand Down

0 comments on commit 1a1cf43

Please sign in to comment.