Skip to content

Commit

Permalink
feat(usage): implement csv, json, json-raw printers for usage
Browse files Browse the repository at this point in the history
  • Loading branch information
trietsch committed Aug 17, 2021
1 parent bcd3803 commit 6e96b2e
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 44 deletions.
9 changes: 7 additions & 2 deletions pkg/entity/usage/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package usage
import (
"fmt"
"github.com/spf13/cobra"
"streammachine.io/strm/pkg/common"
"streammachine.io/strm/pkg/entity/stream"
"streammachine.io/strm/pkg/util"
)
Expand Down Expand Up @@ -61,8 +62,12 @@ from,count,duration,change,rate
_ = usage.RegisterFlagCompletionFunc(fromFlag, dateCompletion)
_ = usage.RegisterFlagCompletionFunc(untilFlag, dateCompletion)

//usage.PersistentFlags().Lookup(util.OutputFormatFlag).Hidden = true
flags.StringP(util.OutputFormatFlag, "o", "table", "")
flags.StringP(util.OutputFormatFlag, "o", "csv", "Usage output format [csv, json, json-raw]")
err := usage.RegisterFlagCompletionFunc(util.OutputFormatFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"csv", "json", "json-raw"}, cobra.ShellCompDirectiveNoFileComp
})

common.CliExit(err)

return usage
}
55 changes: 52 additions & 3 deletions pkg/entity/usage/printers.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
package usage

import (
"fmt"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
"github.com/streammachineio/api-definitions-go/api/usage/v1"
"google.golang.org/protobuf/proto"
"math"
"streammachine.io/strm/pkg/common"
"streammachine.io/strm/pkg/util"
)

Expand All @@ -11,11 +17,54 @@ func configurePrinter(cmd *cobra.Command) util.Printer {
outputFormat := util.GetStringAndErr(cmd.Flags(), util.OutputFormatFlag)

switch outputFormat {
case "json":
case "json-raw":
return util.GenericRawJsonPrinter{}
case "json":
return util.GenericPrettyJsonPrinter{}
case "table":
return util.GenericRawJsonPrinter{}
common.CliExit("Output format 'table' is not supported for usage.")
return nil
case "csv":
return getCsvPrinter{}
default:
return util.GenericRawJsonPrinter{}
return util.GenericPrettyJsonPrinter{}
}
}

type getCsvPrinter struct{}

func (p getCsvPrinter) Print(data proto.Message) {
streamUsage, _ := (data).(*usage.GetStreamEventUsageResponse)

rows := make([]table.Row, 0, len(streamUsage.Windows))

windowCount := int64(-1)
change := math.NaN()
for _, window := range streamUsage.Windows {
if windowCount != -1 {
change = float64(window.EventCount - windowCount)
}
windowCount = window.EventCount

windowDuration := window.EndTime.AsTime().Sub(window.StartTime.AsTime())
rate := change / windowDuration.Seconds()

rows = append(rows, table.Row{
fmt.Sprintf("%d", windowCount),
fmt.Sprintf("%.0f", windowDuration.Seconds()),
fmt.Sprintf("%v", change),
fmt.Sprintf("%.2f", rate),
})
}

util.RenderCsv(
table.Row{
"From",
"Count",
"Duration",
"Change",
"Rate",
},
rows,
)
}
40 changes: 1 addition & 39 deletions pkg/entity/usage/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package usage

import (
"context"
"encoding/csv"
"fmt"
"github.com/bykof/gostradamus"
"github.com/golang/protobuf/ptypes/duration"
Expand All @@ -11,14 +10,11 @@ import (
"github.com/streammachineio/api-definitions-go/api/entities/v1"
"github.com/streammachineio/api-definitions-go/api/usage/v1"
"google.golang.org/grpc"
"math"
"os"
"regexp"
"strconv"
"streammachine.io/strm/pkg/common"
"streammachine.io/strm/pkg/util"
"strings"
"time"
)

const (
Expand Down Expand Up @@ -73,36 +69,8 @@ func get(cmd *cobra.Command, streamName *string) {

streamUsage, err := client.GetStreamEventUsage(apiContext, req)
common.CliExit(err)
if util.GetBoolAndErr(flags, jsonFlag) {
printer.Print(streamUsage)
} else {
printCsv(streamUsage)
}
}

func printCsv(streamUsage *usage.GetStreamEventUsageResponse) {
w := csv.NewWriter(os.Stdout)
_ = w.Write([]string{"from", "count", "duration", "change", "rate"})

windowCount := int64(-1)
change := math.NaN()
for _, window := range streamUsage.Windows {
if windowCount != -1 {
change = float64(window.EventCount - windowCount)
}
windowCount = window.EventCount

windowDuration := window.EndTime.AsTime().Sub(window.StartTime.AsTime())
rate := change / windowDuration.Seconds()
record := []string{isoFormat(window.StartTime.AsTime()),
fmt.Sprintf("%d", windowCount),
fmt.Sprintf("%.0f", windowDuration.Seconds()),
fmt.Sprintf("%v", change),
fmt.Sprintf("%.2f", rate),
}
_ = w.Write(record)
}
w.Flush()
printer.Print(streamUsage)
}

func interpretInterval(by string) int64 {
Expand Down Expand Up @@ -134,12 +102,6 @@ func interpretInterval(by string) int64 {
return interval
}

func isoFormat(t time.Time) string {
n := gostradamus.DateTimeFromTime(t)
return n.InTimezone(tz).IsoFormatTZ()
//return t.Format(time.RFC3339)
}

func dateCompletion(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
endTime := gostradamus.NowInTimezone(tz).FloorHour()
hourRange := 48
Expand Down
12 changes: 12 additions & 0 deletions pkg/util/printers.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ func RenderTable(headers table.Row, rows []table.Row) {
}
}

func RenderCsv(headers table.Row, rows []table.Row) {
if len(rows) == 0 {
fmt.Println("No usage in the provided time period.")
} else {
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.AppendHeader(headers)
t.AppendRows(rows)
t.RenderCSV()
}
}

var noBordersStyle = table.Style{
Name: "StyleNoBorders",
Options: table.OptionsNoBorders,
Expand Down

0 comments on commit 6e96b2e

Please sign in to comment.