Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add flags for handling features of advanced logs #471

Merged
merged 7 commits into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
30 changes: 10 additions & 20 deletions cmd/addons_logs.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
"errors"
"fmt"

helper "github.com/home-assistant/cli/client"
Expand All @@ -24,42 +23,33 @@ Allowing you to look at the log output generated by a Home Assistant add-on.
Run: func(cmd *cobra.Command, args []string) {
log.WithField("args", args).Debug("addons logs")

section := "addons"
command := "{slug}/logs"
section := "addons/{slug}"

url, err := helper.URLHelper(section, command)
request, err := processLogsFlags(section, cmd)

if err != nil {
fmt.Println(err)
fmt.Printf("Error: %v", err)
ExitWithError = true
return
}

request := helper.GetRequest()

slug := args[0]
request.SetPathParam("slug", slug)

request.SetPathParams(map[string]string{
"slug": slug,
})

resp, err := request.SetHeader("Accept", "text/plain").Get(url)

// returns 200 OK or 400, everything else is wrong
if err == nil && resp.StatusCode() != 200 && resp.StatusCode() != 400 {
err = errors.New("Unexpected server response")
log.Error(err)
}
resp, err := request.Send()

if err != nil {
fmt.Println(err)
ExitWithError = true
} else {
fmt.Println(string(resp.Body()))
return
}

ExitWithError = !helper.StreamTextResponse(resp)
},
}

func init() {
addLogsFlags(addonsLogsCmd)

addonsCmd.AddCommand(addonsLogsCmd)
}
14 changes: 8 additions & 6 deletions cmd/audio_logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,27 +23,29 @@ running on your Home Assistant system.`,
log.WithField("args", args).Debug("audio logs")

section := "audio"
command := "logs"

url, err := helper.URLHelper(section, command)
request, err := processLogsFlags(section, cmd)

if err != nil {
fmt.Printf("Error: %v", err)
ExitWithError = true
return
}

request := helper.GetRequest()
resp, err := request.SetHeader("Accept", "text/plain").Get(url)
resp, err := request.Send()

if err != nil {
fmt.Println(err)
ExitWithError = true
} else {
fmt.Println(resp.String())
return
}

ExitWithError = !helper.StreamTextResponse(resp)
},
}

func init() {
addLogsFlags(audioLogsCmd)

audioCmd.AddCommand(audioLogsCmd)
}
14 changes: 8 additions & 6 deletions cmd/core_logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,27 +23,29 @@ running on your Home Assistant system.`,
log.WithField("args", args).Debug("core logs")

section := "core"
command := "logs"

url, err := helper.URLHelper(section, command)
request, err := processLogsFlags(section, cmd)

if err != nil {
fmt.Printf("Error: %v", err)
ExitWithError = true
return
}

request := helper.GetRequest()
resp, err := request.SetHeader("Accept", "text/plain").Get(url)
resp, err := request.Send()

if err != nil {
fmt.Println(err)
ExitWithError = true
} else {
fmt.Println(resp.String())
return
}

ExitWithError = !helper.StreamTextResponse(resp)
},
}

func init() {
addLogsFlags(coreLogsCmd)

coreCmd.AddCommand(coreLogsCmd)
}
14 changes: 8 additions & 6 deletions cmd/dns_logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,26 +24,28 @@ Allowing you to look at the log output generated by the Home Assistant DNS serve
log.WithField("args", args).Debug("dns logs")

section := "dns"
command := "logs"

url, err := helper.URLHelper(section, command)
request, err := processLogsFlags(section, cmd)

if err != nil {
fmt.Printf("Error: %v", err)
ExitWithError = true
return
}

request := helper.GetRequest()
resp, err := request.SetHeader("Accept", "text/plain").Get(url)
resp, err := request.Send()

if err != nil {
fmt.Println(err)
ExitWithError = true
} else {
fmt.Println(resp.String())
return
}
ExitWithError = !helper.StreamTextResponse(resp)
},
}

func init() {
addLogsFlags(dnsLogsCmd)

dnsCmd.AddCommand(dnsLogsCmd)
}
44 changes: 7 additions & 37 deletions cmd/host_logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,50 +25,22 @@ across services and boots.
log.WithField("args", args).Debug("host logs")

section := "host"
command := "logs"

identifier, _ := cmd.Flags().GetString("identifier")
boot, _ := cmd.Flags().GetString("boot")
if len(boot) > 0 {
command += "/boots/{boot}"
}
if len(identifier) > 0 {
command += "/identifiers/{identifier}"
}

follow, _ := cmd.Flags().GetBool("follow")
if follow {
command += "/follow"
}

url, err := helper.URLHelper(section, command)
request, err := processLogsFlags(section, cmd)

if err != nil {
fmt.Printf("Error: %v", err)
ExitWithError = true
return
}

/* Disable timeouts to allow following forever */
request := helper.GetRequestTimeout(0).SetHeader("Accept", "text/plain").SetDoNotParseResponse(true)

lines, _ := cmd.Flags().GetInt32("lines")
if lines > 0 {
rangeHeader := fmt.Sprintf("entries=:%d:", -(lines - 1))
log.WithField("value", rangeHeader).Debug("Range header")
request.SetHeader("Range", rangeHeader)
}

if err != nil {
fmt.Printf("Error: %v", err)
ExitWithError = true
return
identifier, _ := cmd.Flags().GetString("identifier")
if len(identifier) > 0 {
request.URL += "/identifiers/{identifier}"
}

request.SetPathParam("identifier", identifier)
request.SetPathParam("boot", boot)

resp, err := request.Get(url)
resp, err := request.Send()

if err != nil {
fmt.Println(err)
Expand All @@ -81,11 +53,9 @@ across services and boots.
}

func init() {
hostLogsCmd.Flags().BoolP("follow", "f", false, "Continuously print new log entries")
hostLogsCmd.Flags().Int32P("lines", "n", 0, "Number of log entries to show")
addLogsFlags(hostLogsCmd)

hostLogsCmd.Flags().StringP("identifier", "t", "", "Show entries with the specified syslog identifier")
hostLogsCmd.Flags().StringP("boot", "b", "", "Logs of particular boot ID")
hostLogsCmd.Flags().Lookup("follow").NoOptDefVal = "true"

hostCmd.AddCommand(hostLogsCmd)
}
29 changes: 29 additions & 0 deletions cmd/host_logs_boots.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
helper "github.com/home-assistant/cli/client"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"strings"
)

var hostLogsBootsCmd = &cobra.Command{
Expand Down Expand Up @@ -39,3 +40,31 @@ Show all values that can be used with the boot arg to find logs.
func init() {
hostLogsCmd.AddCommand(hostLogsBootsCmd)
}

func hostBootCompletions(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
resp, err := helper.GenericJSONGet("host/logs/boots", "")
if err != nil || !resp.IsSuccess() {
return nil, cobra.ShellCompDirectiveNoFileComp
}

var ret []string
data := resp.Result().(*helper.Response)
if data.Result == "ok" && data.Data["boots"] != nil {
if boots, ok := data.Data["boots"].(map[string]interface{}); ok {
for bootID, bootName := range boots {
s := bootName.(string)
if toComplete == "" || strings.HasPrefix(s, toComplete) {
ret = append(ret, s)
}
if toComplete == "" || strings.HasPrefix(bootID, toComplete) {
ret = append(ret, bootID)
}
}
}
}

return ret, cobra.ShellCompDirectiveNoFileComp
}
15 changes: 9 additions & 6 deletions cmd/multicast_logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,26 +24,29 @@ Allowing you to look at the log output generated by the Home Assistant Multicast
log.WithField("args", args).Debug("multicast logs")

section := "multicast"
command := "logs"

url, err := helper.URLHelper(section, command)
request, err := processLogsFlags(section, cmd)

if err != nil {
fmt.Printf("Error: %v", err)
ExitWithError = true
return
}

request := helper.GetRequest()
resp, err := request.SetHeader("Accept", "text/plain").Get(url)
resp, err := request.Send()

if err != nil {
fmt.Println(err)
ExitWithError = true
} else {
fmt.Println(resp.String())
return
}

ExitWithError = !helper.StreamTextResponse(resp)
},
}

func init() {
addLogsFlags(multicastLogsCmd)

multicastCmd.AddCommand(multicastLogsCmd)
}
56 changes: 56 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cmd

import (
"fmt"
"github.com/go-resty/resty/v2"
"os"
"path"
"strings"
Expand Down Expand Up @@ -156,3 +158,57 @@ func initConfig() {
func boolCompletions(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"true", "false"}, cobra.ShellCompDirectiveNoFileComp
}

func addLogsFlags(cmd *cobra.Command) {
cmd.Flags().BoolP("follow", "f", false, "Continuously print new log entries")
cmd.Flags().Int32P("lines", "n", 0, "Number of log entries to show")
cmd.Flags().StringP("boot", "b", "", "Logs of particular boot ID")
cmd.Flags().BoolP("verbose", "v", false, "Return logs in verbose format")
cmd.Flags().Lookup("follow").NoOptDefVal = "true"
cmd.Flags().Lookup("verbose").NoOptDefVal = "true"

cmd.RegisterFlagCompletionFunc("follow", boolCompletions)
cmd.RegisterFlagCompletionFunc("verbose", boolCompletions)
cmd.RegisterFlagCompletionFunc("lines", cobra.NoFileCompletions)
cmd.RegisterFlagCompletionFunc("boot", hostBootCompletions)
}

func processLogsFlags(section string, cmd *cobra.Command) (*resty.Request, error) {
command := "logs"

boot, _ := cmd.Flags().GetString("boot")
if len(boot) > 0 {
command += "/boots/{boot}"
}

follow, _ := cmd.Flags().GetBool("follow")
if follow {
command += "/follow"
}

URL, err := client.URLHelper(section, command)
if err != nil {
return nil, err
}

accept := "text/plain"
verbose, _ := cmd.Flags().GetBool("verbose")
if verbose {
accept = "text/x-log"
}

/* Disable timeouts to allow following forever */
request := client.GetRequestTimeout(0).SetHeader("Accept", accept).SetDoNotParseResponse(true)

lines, _ := cmd.Flags().GetInt32("lines")
if lines > 0 {
rangeHeader := fmt.Sprintf("entries=:%d:", -(lines - 1))
log.WithField("value", rangeHeader).Debug("Range header")
request.SetHeader("Range", rangeHeader)
}

request.SetPathParam("boot", boot)
request.URL = URL

return request, nil
}
Loading