Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ func init() {
Cmd.AddCommand(updateCmd)
Cmd.AddCommand(describeCmd)
Cmd.AddCommand(editCmd)
Cmd.AddCommand(doctorCmd)
}
73 changes: 73 additions & 0 deletions cmd/agent/doctor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
Copyright (c) Tobias Schäfer. All rights reserved.
Licensed under the MIT license, see LICENSE in the project root for details.
*/
package agent

import (
"encoding/json"
"fmt"
"os"
"strconv"
"time"

"github.com/spf13/cobra"
"github.com/tschaefer/finchctl/cmd/completion"
"github.com/tschaefer/finchctl/cmd/errors"
"github.com/tschaefer/finchctl/internal/agent"
"github.com/tschaefer/finchctl/internal/target"

"github.com/olekukonko/tablewriter"
)

var doctorCmd = &cobra.Command{
Use: "doctor [user@]host[:port]",
Short: "Verify target is healthy",
Args: cobra.ExactArgs(1),
Run: runDoctorCmd,
ValidArgsFunction: completion.CompleteHostName,
}

func init() {
doctorCmd.Flags().Bool("output.json", false, "output in JSON format")
doctorCmd.Flags().Bool("check.ports", false, "check agent listen ports")
doctorCmd.Flags().Bool("check.optionals", false, "check agent optional tools (remote setup)")
}

func runDoctorCmd(cmd *cobra.Command, args []string) {
targetUrl := args[0]

jsonOutput, _ := cmd.Flags().GetBool("output.json")
if jsonOutput {
_ = os.Setenv("NO_COLOR", "1")
}

timeout, _ := cmd.Flags().GetUint("run.cmd-timeout")
a, err := agent.New(cmd.Context(), agent.Options{
TargetURL: targetUrl,
Format: target.FormatQuiet,
CmdTimeout: time.Duration(timeout) * time.Second,
})
errors.CheckErr(err, target.FormatQuiet)

checkPorts, _ := cmd.Flags().GetBool("check.ports")
checkOptionals, _ := cmd.Flags().GetBool("check.optionals")
list, ok := a.Doctor(checkOptionals, checkPorts)

if jsonOutput {
out, e := json.MarshalIndent(list, "", " ")
errors.CheckErr(e, target.FormatJSON)
fmt.Println(string(out))
} else {
t := tablewriter.NewWriter(os.Stdout)
t.Header([]string{"Requirement", "Status", "Optional"})
for _, item := range *list {
_ = t.Append([]string{item.Requirement, item.Status, strconv.FormatBool(item.Optional)})
}
_ = t.Render()
}

if !ok {
os.Exit(1)
}
}
2 changes: 1 addition & 1 deletion cmd/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func CheckErr(msg any, format target.Format) {
}
fmt.Println(string(jsonData))
default:
fmt.Println(msg)
fmt.Fprintf(os.Stderr, "%s\n", msg)
}

os.Exit(1)
Expand Down
98 changes: 98 additions & 0 deletions cmd/service/doctor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
Copyright (c) Tobias Schäfer. All rights reserved.
Licensed under the MIT license, see LICENSE in the project root for details.
*/
package service

import (
"encoding/json"
"fmt"
"net/url"
"os"
"strconv"
"strings"
"time"

"github.com/spf13/cobra"
"github.com/tschaefer/finchctl/cmd/completion"
"github.com/tschaefer/finchctl/cmd/errors"
"github.com/tschaefer/finchctl/internal/service"
"github.com/tschaefer/finchctl/internal/target"

"github.com/olekukonko/tablewriter"
)

var doctorCmd = &cobra.Command{
Use: "doctor [user@]host[:port]",
Short: "Verify target is healthy",
Args: cobra.ExactArgs(1),
Run: runDoctorCmd,
ValidArgsFunction: completion.CompleteHostName,
}

func init() {
doctorCmd.Flags().Bool("output.json", false, "output in JSON format")
}

func runDoctorCmd(cmd *cobra.Command, args []string) {
targetUrl := args[0]

jsonOutput, _ := cmd.Flags().GetBool("output.json")
if jsonOutput {
_ = os.Setenv("NO_COLOR", "1")
}

cfg, err := doctorConfig(cmd, args, target.FormatQuiet)
errors.CheckErr(err, target.FormatQuiet)

timeout, _ := cmd.Flags().GetUint("run.cmd-timeout")
s, err := service.New(cmd.Context(), service.Options{
Config: cfg,
TargetURL: targetUrl,
Format: target.FormatQuiet,
DryRun: false,
CmdTimeout: time.Duration(timeout) * time.Second,
})
errors.CheckErr(err, target.FormatQuiet)


list, ok := s.Doctor()

if jsonOutput {
out, e := json.MarshalIndent(list, "", " ")
errors.CheckErr(e, target.FormatJSON)
fmt.Println(string(out))
} else {
t := tablewriter.NewWriter(os.Stdout)
t.Header([]string{"Requirement", "Status", "Optional"})
for _, item := range *list {
_ = t.Append([]string{item.Requirement, item.Status, strconv.FormatBool(item.Optional)})
}
_ = t.Render()
}

if !ok {
os.Exit(1)
}
}

func doctorConfig(cmd *cobra.Command, args []string, formatType target.Format) (*service.ServiceConfig, error) {
config := &service.ServiceConfig{}
targetUrl := args[0]

if !strings.HasPrefix(targetUrl, "ssh://") {
targetUrl = "ssh://" + targetUrl
}
target, err := url.Parse(targetUrl)
if err != nil {
errors.CheckErr(fmt.Errorf("invalid target: %w", err), formatType)
}

hostname, _ := cmd.Flags().GetString("service.host")
if hostname == "" {
hostname = target.Hostname()
}
config.Hostname = hostname

return config, nil
}
1 change: 1 addition & 0 deletions cmd/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ func init() {
Cmd.AddCommand(rotateCertificateCmd)
Cmd.AddCommand(registerCmd)
Cmd.AddCommand(deregisterCmd)
Cmd.AddCommand(doctorCmd)
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.26.3
require (
github.com/brianvoe/gofakeit/v7 v7.5.1
github.com/denisbrodbeck/machineid v1.0.1
github.com/fatih/color v1.15.0
github.com/goccy/go-yaml v1.19.2
github.com/melbahja/goph v1.4.0
github.com/olekukonko/tablewriter v1.1.0
Expand All @@ -19,7 +20,6 @@ require (

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fatih/color v1.15.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
Expand Down
4 changes: 4 additions & 0 deletions internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,7 @@ func (a *Agent) Describe(service, resourceID string) (*DescribeData, error) {
func (a *Agent) Edit(service string, data *EditData) error {
return a.editAgent(service, data)
}

func (a *Agent) Doctor(checkOptionals, checkPorts bool) (*[]Health, bool) {
return a.examineTarget(checkOptionals, checkPorts)
}
157 changes: 157 additions & 0 deletions internal/agent/doctor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*
Copyright (c) Tobias Schäfer. All rights reserved.
Licensed under the MIT license, see LICENSE in the project root for details.
*/
package agent

import (
"github.com/fatih/color"
)

type Health struct {
Requirement string
Status string
Optional bool
Ok bool
}

const (
ALLOY_HTTP_PORT = "12345"
ALLOY_LOKI_PORT = "3100"
ALLOY_MIMIR_PORT = "9091"
ALLOY_PYROSCOPE_PORT = "4040"
)

func (a *Agent) __examineRequirements() (*[]Health, bool) {
var list []Health
ok := true

verify := func(f func() error, r, s, d string) {
t := color.GreenString(s)
o := true

if err := f(); err != nil {
t = color.RedString(d)
o = false
}

ok = ok && o
list = append(list, Health{r, t, false, o})
}

verify(a.__requirementsHasSudo, "sudo", "available", "not available")
verify(a.__requirementsHasSudoPermission, "superuser permission", "sufficient", "insufficient")

return &list, ok
}

func (a *Agent) __examineOptionals() (*[]Health, bool) {
var list []Health
ok := true

verify := func(f func() bool, r, s, d string) {
t := color.GreenString(s)
o := true

if !f() {
t = color.RedString(d)
o = false
}

ok = ok && o
list = append(list, Health{r, t, true, o})
}

verify(a.__additionsHasCurl, "curl", "available", "not available")
verify(a.__additionsHasUnzip, "unzip", "available", "not available")
verify(a.__additionsGitHubConnection, "GitHub connection", "established", "not established")

return &list, ok
}

func (a *Agent) __examinePorts(machine *MachineInfo) (*[]Health, bool) {
var list []Health

var cmd string
var exec string
var port string
var status string

switch machine.Kernel {
case "linux":
cmd = "ss"
exec = "sudo ss -H -tlpn sport = :" + port + " | grep -q ''"
case "freebsd":
cmd = "sockstat"
exec = "sudo sockstat -q -P tcp -p " + port + " -l | grep -q ''"
case "darwin":
cmd = "lsof"
exec = "sudo lsof -i :" + port + " | grep -q LISTEN"
default:
// pass
}

if _, err := a.target.Run(a.ctx, "command -v "+cmd); err != nil {
list = append(list, Health{"port check", color.RedString(cmd + " not found"), false, false})
return &list, false
}

ports := map[string]bool{
ALLOY_HTTP_PORT: false,
ALLOY_LOKI_PORT: false,
ALLOY_MIMIR_PORT: true,
ALLOY_PYROSCOPE_PORT: true,
}
ok := true

for port, optional := range ports {
o := true
_, err := a.target.Run(a.ctx, exec)
if err == nil {
o = false
status = color.RedString("bound")
} else {
status = color.GreenString("unbound")
}

ok = ok && o
list = append(list, Health{"port " + port, status, optional, o})
}

return &list, ok
}

func (a *Agent) examineTarget(checkOptionals, checkPorts bool) (*[]Health, bool) {
var list []Health

machine, err := a.machineInfo()
if err != nil {
list = append(list, Health{"os", color.RedString("unsupported"), false, false})
return &list, false
}
list = append(list, Health{"os", color.GreenString("supported"), false, true})

requirements, ok := a.__examineRequirements()
list = append(list, *requirements...)
if !ok {
return &list, false
}

if checkOptionals {
optionals, ok := a.__examineOptionals()
list = append(list, *optionals...)
if !ok {
return &list, false
}
}

if checkPorts {
ports, ok := a.__examinePorts(machine)
list = append(list, *ports...)
if !ok {
return &list, false
}
}

return &list, true
}
9 changes: 9 additions & 0 deletions internal/agent/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,15 @@ func (e *EditAgentError) Error() string {
return strings.TrimSpace(fmt.Sprintf("Failed to edit agent: %s %s", e.Message, e.Reason))
}

type DoctorAgentError struct {
Message string
Reason string
}

func (e *DoctorAgentError) Error() string {
return strings.TrimSpace(fmt.Sprintf("Target not healthy: %s %s", e.Message, e.Reason))
}

func convertError(err error, to any) error {
if err == nil {
return nil
Expand Down
Loading