Merge pull request #157 from safing/feature/debug-data-improvements

Improve debug data
This commit is contained in:
Daniel 2022-03-21 16:11:29 +01:00 committed by GitHub
commit ba802b25c6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 142 additions and 53 deletions

View file

@ -65,6 +65,7 @@ func registerConfig() error {
Name: "API Keys",
Key: CfgAPIKeys,
Description: "Define API keys for priviledged access to the API. Every entry is a separate API key with respective permissions. Format is `<key>?read=<perm>&write=<perm>`. Permissions are `anyone`, `user` and `admin`, and may be omitted.",
Sensitive: true,
OptType: config.OptTypeStringArray,
ExpertiseLevel: config.ExpertiseLevelDeveloper,
ReleaseLevel: config.ReleaseLevelStable,

View file

@ -4,12 +4,15 @@ import (
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"sort"
"github.com/safing/portbase/dataroot"
"github.com/safing/portbase/modules"
"github.com/safing/portbase/utils"
"github.com/safing/portbase/utils/debug"
)
const (
@ -80,3 +83,32 @@ func exportConfigCmd() error {
_, err = os.Stdout.Write(data)
return err
}
// AddToDebugInfo adds all changed global config options to the given debug.Info.
func AddToDebugInfo(di *debug.Info) {
var lines []string
// Collect all changed settings.
_ = ForEachOption(func(opt *Option) error {
opt.Lock()
defer opt.Unlock()
if opt.ReleaseLevel <= getReleaseLevel() && opt.activeValue != nil {
if opt.Sensitive {
lines = append(lines, fmt.Sprintf("%s: [redacted]", opt.Key))
} else {
lines = append(lines, fmt.Sprintf("%s: %v", opt.Key, opt.activeValue.getData(opt)))
}
}
return nil
})
sort.Strings(lines)
// Add data as section.
di.AddSection(
fmt.Sprintf("Config: %d", len(lines)),
debug.UseCodeSection|debug.AddContentLineBreaks,
lines...,
)
}

View file

@ -190,6 +190,9 @@ type Option struct {
// Help is considered immutable after the option has
// been created.
Help string
// Sensitive signifies that the configuration values may contain sensitive
// content, such as authentication keys.
Sensitive bool
// OptType defines the type of the option.
// OptType is considered immutable after the option has
// been created.

View file

@ -41,6 +41,7 @@ func prepConfig() error {
Name: "Metrics Instance Name",
Key: CfgOptionInstanceKey,
Description: "Define the prometheus instance label for exported metrics. Please note that changing the instance name will reset persisted metrics.",
Sensitive: true,
OptType: config.OptTypeString,
ExpertiseLevel: config.ExpertiseLevelExpert,
ReleaseLevel: config.ReleaseLevelStable,
@ -61,6 +62,7 @@ func prepConfig() error {
Name: "Push Prometheus Metrics",
Key: CfgOptionPushKey,
Description: "Push metrics to this URL in the prometheus format.",
Sensitive: true,
OptType: config.OptTypeString,
ExpertiseLevel: config.ExpertiseLevelExpert,
ReleaseLevel: config.ReleaseLevelStable,

View file

@ -157,7 +157,7 @@ func (di *Info) AddLastReportedModuleError() {
}
di.AddSection(
fmt.Sprintf("%s Module Error", strings.Title(me.ModuleName)),
fmt.Sprintf("%s Module Error", strings.Title(me.ModuleName)), //nolint:staticcheck
UseCodeSection,
me.Format(),
)

View file

@ -76,7 +76,7 @@ func GenerateBinaryNameFromPath(path string) string {
// Title-case name-only parts.
if nameOnly.MatchString(nameParts[i]) {
nameParts[i] = strings.Title(nameParts[i])
nameParts[i] = strings.Title(nameParts[i]) //nolint:staticcheck
}
}

View file

@ -16,7 +16,7 @@ func GetBinaryNameFromSystem(path string) (string, error) {
}
// Clean name.
binName := cleanFileDescription(output)
binName := cleanFileDescription(string(output))
if binName != "" {
return binName, nil
}
@ -74,5 +74,5 @@ func GetBinaryIconFromSystem(path string) (string, error) {
return "", fmt.Errorf("failed to get file properties of %s: %s", path, err)
}
return "data:image/png;base64," + output, nil
return "data:image/png;base64," + string(output), nil
}

51
utils/osdetail/command.go Normal file
View file

@ -0,0 +1,51 @@
package osdetail
import (
"bytes"
"errors"
"os/exec"
"strings"
)
// RunCmd runs the given command and run error checks on the output.
func RunCmd(command ...string) (output []byte, err error) {
// Create command to execute.
var cmd *exec.Cmd
switch len(command) {
case 0:
return nil, errors.New("no command supplied")
case 1:
cmd = exec.Command(command[0])
default:
cmd = exec.Command(command[0], command[1:]...)
}
// Create and assign output buffers.
var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
// Run command and collect output.
err = cmd.Run()
stdout, stderr := stdoutBuf.Bytes(), stderrBuf.Bytes()
if err != nil {
return nil, err
}
// Command might not return an error, but just write to stdout instead.
if len(stderr) > 0 {
return nil, errors.New(strings.SplitN(string(stderr), "\n", 2)[0])
}
// Debugging output:
// fmt.Printf("command stdout: %s\n", stdout)
// fmt.Printf("command stderr: %s\n", stderr)
// Finalize stdout.
cleanedOutput := bytes.TrimSpace(stdout)
if len(cleanedOutput) == 0 {
return nil, ErrEmptyOutput
}
return cleanedOutput, nil
}

View file

@ -1,49 +0,0 @@
package osdetail
import (
"bytes"
"errors"
"os/exec"
"strings"
)
// RunPowershellCmd runs a powershell command and returns its output.
func RunPowershellCmd(script string) (output string, err error) {
// Create command to execute.
cmd := exec.Command(
"powershell.exe",
"-ExecutionPolicy", "Bypass",
"-NoProfile",
"-NonInteractive",
"[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n"+script,
)
// Create and assign output buffers.
var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
// Run command and collect output.
err = cmd.Run()
stdout, stderr := stdoutBuf.String(), stderrBuf.String()
if err != nil {
return "", err
}
// Powershell might not return an error, but just write to stdout instead.
if stderr != "" {
return "", errors.New(strings.SplitN(stderr, "\n", 2)[0])
}
// Debugging output:
// fmt.Printf("powershell stdout: %s\n", stdout)
// fmt.Printf("powershell stderr: %s\n", stderr)
// Finalize stdout.
cleanedOutput := strings.TrimSpace(stdout)
if cleanedOutput == "" {
return "", ErrEmptyOutput
}
return cleanedOutput, nil
}

View file

@ -0,0 +1,49 @@
package osdetail
import (
"bytes"
"errors"
)
// RunPowershellCmd runs a powershell command and returns its output.
func RunPowershellCmd(script string) (output []byte, err error) {
// Create command to execute.
return RunCmd(
"powershell.exe",
"-ExecutionPolicy", "Bypass",
"-NoProfile",
"-NonInteractive",
"[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n"+script,
)
}
const outputSeparator = "pwzzhtuvpwdgozhzbnjj"
// RunTerminalCmd runs a Windows cmd command and returns its output.
// It sets the output of the cmd to UTF-8 in order to avoid encoding errors.
func RunTerminalCmd(command ...string) (output []byte, err error) {
output, err = RunCmd(append([]string{
"cmd.exe",
"/c",
"chcp", // Set output encoding...
"65001", // ...to UTF-8.
"&",
"echo",
outputSeparator,
"&",
},
command...,
)...)
if err != nil {
return nil, err
}
// Find correct start of output and shift start.
index := bytes.IndexAny(output, outputSeparator+"\r\n")
if index < 0 {
return nil, errors.New("failed to post-process output: could not find output separator")
}
output = output[index+len(outputSeparator)+2:]
return output, nil
}