fleet/cmd/fleetctl/query_output.go
keepwn b42d213689
Support close the websocket of LiveQueryResultsHandler (#1006)
* Support close `LiveQueryResultsHandler`

* Start adding test

* Make LiveQuery exit when the context is Done

* Fix lint and remove debug print

* Update server/service/client_live_query.go

Co-authored-by: Zach Wasserman <zach@fleetdm.com>

* Revert "Update server/service/client_live_query.go"

This reverts commit be67ca1512fe502503e821393c2b9e84f5e6e82e.

Co-authored-by: Tomas Touceda <chiiph@gmail.com>
Co-authored-by: Zach Wasserman <zach@fleetdm.com>
2021-09-10 16:26:39 -03:00

95 lines
1.9 KiB
Go

package main
import (
"encoding/json"
"io"
"os"
"sort"
"github.com/fleetdm/fleet/v4/server/fleet"
"github.com/gosuri/uilive"
"github.com/olekukonko/tablewriter"
)
type outputWriter interface {
WriteResult(res fleet.DistributedQueryResult) error
}
type resultOutput struct {
HostIdentifier string `json:"host"`
Rows []map[string]string `json:"rows"`
Error *string `json:"error,omitempty"`
}
type jsonWriter struct {
w io.Writer
}
func newJsonWriter(w io.Writer) *jsonWriter {
if w == nil {
w = os.Stdout
}
return &jsonWriter{w: w}
}
func (w *jsonWriter) WriteResult(res fleet.DistributedQueryResult) error {
out := resultOutput{
HostIdentifier: res.Host.Hostname,
Rows: res.Rows,
Error: res.Error,
}
return json.NewEncoder(w.w).Encode(out)
}
type prettyWriter struct {
results []fleet.DistributedQueryResult
columns map[string]bool
writer *uilive.Writer
}
func newPrettyWriter() *prettyWriter {
return &prettyWriter{
columns: make(map[string]bool),
writer: uilive.New(),
}
}
func (w *prettyWriter) WriteResult(res fleet.DistributedQueryResult) error {
w.results = append(w.results, res)
// Recompute columns
for _, row := range res.Rows {
delete(row, "host_hostname")
for col := range row {
w.columns[col] = true
}
}
columns := []string{}
for col := range w.columns {
columns = append(columns, col)
}
sort.Strings(columns)
table := tablewriter.NewWriter(w.writer.Newline())
table.SetRowLine(true)
table.SetHeader(append([]string{"hostname"}, columns...))
// Extract columns from the results in the appropriate order
for _, res := range w.results {
for _, row := range res.Rows {
cols := []string{res.Host.Hostname}
for _, col := range columns {
cols = append(cols, row[col])
}
table.Append(cols)
}
}
table.Render()
// Actually write the output
w.writer.Flush()
return nil
}