mirror of
https://gitea.elkins.co/Networking/ccl.git
synced 2025-03-10 05:01:38 -05:00
Initiative is turning into a little hackathon. Trying to beautify ls output a little since the number of configured containers on my main server is growing to a large number (currently 44). text/tabwriter can't handle SGR codes correctly. Investigations led me to the "ansiterm" library. I'm not crazy about the API really, but it handles all the corners I'm concerned about.
236 lines
7.1 KiB
Go
236 lines
7.1 KiB
Go
/*
|
|
Package cmd defines user commands accessible from the cli tool.
|
|
|
|
Copyright © 2022 Joel D. Elkins <joel@elkins.co>
|
|
|
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
of this software and associated documentation files (the "Software"), to deal
|
|
in the Software without restriction, including without limitation the rights
|
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
copies of the Software, and to permit persons to whom the Software is
|
|
furnished to do so, subject to the following conditions:
|
|
|
|
The above copyright notice and this permission notice shall be included in
|
|
all copies or substantial portions of the Software.
|
|
|
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
THE SOFTWARE.
|
|
*/
|
|
package cmd
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"slices"
|
|
|
|
"gitea.elkins.co/Networking/ccl/internal/pkg/config"
|
|
"gitea.elkins.co/Networking/ccl/internal/pkg/container"
|
|
"github.com/juju/ansiterm"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var (
|
|
lsCountAll bool
|
|
lsCountRunning bool
|
|
lsCountNotRunning bool
|
|
lsJsonFormat bool
|
|
lsSortRuntime bool
|
|
lsNoColor bool
|
|
)
|
|
|
|
type lsContainerObj struct {
|
|
Category string `json:"category"`
|
|
StartGroup int `json:"group"`
|
|
Name string `json:"name"`
|
|
Image string `json:"image"`
|
|
Created bool `json:"created"`
|
|
Running bool `json:"running"`
|
|
}
|
|
|
|
type lsContainerStatsObj struct {
|
|
CPU float64 `json:"cpu_usage_pct"`
|
|
CPUNano uint64 `json:"cpu_nano"`
|
|
MemUsage uint64 `json:"mem_usage_bytes"`
|
|
MemLimit uint64 `json:"mem_limit_bytes"`
|
|
MemPerc float64 `json:"mem_usage_pct"`
|
|
NetInput uint64 `json:"net_input_bytes"`
|
|
NetOutput uint64 `json:"net_output_bytes"`
|
|
BlockInput uint64 `json:"block_input_bytes"`
|
|
BlockOutput uint64 `json:"block_output_bytes"`
|
|
UpTime uint64 `json:"uptime_sec"`
|
|
lsContainerObj
|
|
}
|
|
|
|
// lsCmd represents the ls command
|
|
var lsCmd = &cobra.Command{
|
|
Use: "ls",
|
|
Aliases: []string{"list"},
|
|
Short: "List configured containers",
|
|
Args: cobra.OnlyValidArgs,
|
|
ValidArgsFunction: validNouns,
|
|
Long: `List configured containers. You can provide one or more names
|
|
or categories to limit the list.`,
|
|
Example: `ccl ls # same as below
|
|
ccl ls all # same as above
|
|
ccl ls default sub # multiple ok
|
|
ccl ls squid`,
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
conts := config.Union(args, contMask)
|
|
w := cmd.OutOrStdout()
|
|
|
|
if lsCountAll {
|
|
fmt.Fprintf(w, "%d\n", len(conts))
|
|
return
|
|
}
|
|
|
|
if lsCountRunning || lsCountNotRunning {
|
|
if conn != nil {
|
|
r := 0
|
|
for _, c := range conts {
|
|
if c.IsRunning() {
|
|
r += 1
|
|
}
|
|
}
|
|
if lsCountRunning {
|
|
fmt.Fprintf(w, "%d\n", r)
|
|
} else {
|
|
fmt.Fprintf(w, "%d\n", len(conts)-r)
|
|
}
|
|
return
|
|
} else {
|
|
return
|
|
}
|
|
}
|
|
|
|
if lsSortRuntime {
|
|
slices.SortFunc(conts, func(a, b *container.Container) int {
|
|
if a.RunningTime().Seconds() > b.RunningTime().Seconds() {
|
|
return -1
|
|
}
|
|
if a.RunningTime().Seconds() < b.RunningTime().Seconds() {
|
|
return 1
|
|
}
|
|
return 0
|
|
})
|
|
}
|
|
|
|
if lsJsonFormat {
|
|
out := make([]interface{}, 0)
|
|
for _, c := range conts {
|
|
run, cre := false, false
|
|
if conn != nil {
|
|
run, cre = c.IsRunning(), c.IsCreated()
|
|
}
|
|
baseObj := lsContainerObj{
|
|
Category: c.Category,
|
|
StartGroup: c.StartGroup,
|
|
Name: c.Name,
|
|
Image: c.Image,
|
|
Running: run,
|
|
Created: cre,
|
|
}
|
|
if run {
|
|
if stats := c.GetStats(); stats != nil {
|
|
out = append(out, lsContainerStatsObj{
|
|
CPUNano: stats.CPUNano,
|
|
CPU: stats.CPU,
|
|
MemUsage: stats.MemUsage,
|
|
MemLimit: stats.MemLimit,
|
|
MemPerc: stats.MemPerc,
|
|
NetInput: stats.NetInput,
|
|
NetOutput: stats.NetOutput,
|
|
BlockInput: stats.BlockInput,
|
|
BlockOutput: stats.BlockOutput,
|
|
UpTime: uint64(c.RunningTime().Seconds()),
|
|
lsContainerObj: baseObj,
|
|
})
|
|
} else {
|
|
out = append(out, baseObj)
|
|
}
|
|
} else {
|
|
out = append(out, baseObj)
|
|
}
|
|
}
|
|
val, err := json.Marshal(out)
|
|
if err != nil {
|
|
fmt.Fprintf(cmd.OutOrStderr(), "Error marshalling results: %s", err)
|
|
}
|
|
fmt.Fprint(w, string(val))
|
|
return
|
|
}
|
|
|
|
tw := ansiterm.NewTabWriter(w, 0, 0, 2, ' ', 0)
|
|
defcolor := ansiterm.Foreground(ansiterm.Default)
|
|
red := ansiterm.Foreground(ansiterm.Red)
|
|
yellow := ansiterm.Foreground(ansiterm.Yellow)
|
|
bold := ansiterm.Styles(ansiterm.Bold)
|
|
ital := ansiterm.Styles(ansiterm.Italic)
|
|
defer tw.Flush()
|
|
|
|
if conn != nil {
|
|
bold.Fprint(tw, "CATEGORY\tGROUP\tNAME\tIMAGE\tCREATED\t RUNNING\t CPU%\t MEM%\t\n")
|
|
for _, c := range conts {
|
|
defcolor.Fprintf(tw, "%s\t%5d\t", c.Category, c.StartGroup)
|
|
ital.Fprintf(tw, "%s\t", c.Name)
|
|
defcolor.Fprintf(tw, "%s\t", c.Image)
|
|
if c.IsCreated() {
|
|
defcolor.Fprint(tw, " ✓\t")
|
|
} else {
|
|
red.Fprint(tw, " ✗\t")
|
|
}
|
|
if c.IsRunning() {
|
|
raw := int64(c.RunningTime().Seconds())
|
|
seconds := raw % 60
|
|
minutes := (raw / 60) % 60
|
|
hours := (raw / 60) / 60
|
|
defcolor.Fprintf(tw, "%3d:%02d:%02d\t", hours, minutes, seconds)
|
|
} else {
|
|
red.Fprint(tw, " ✗\t")
|
|
}
|
|
if stats := c.GetStats(); c.IsRunning() && stats != nil {
|
|
for _, st := range []float64{stats.CPU, stats.MemPerc} {
|
|
hi := defcolor
|
|
if st > 5.0 {
|
|
hi = yellow
|
|
}
|
|
if st > 20.0 {
|
|
hi = red
|
|
}
|
|
hi.Fprintf(tw, "%5.1f\t", st)
|
|
}
|
|
} else {
|
|
red.Fprint(tw, " -\t -\t")
|
|
}
|
|
fmt.Fprint(tw, "\n")
|
|
}
|
|
} else {
|
|
titlemsg := "CATEGORY\tGROUP\tNAME\tIMAGE\n"
|
|
bold.Fprint(tw, titlemsg)
|
|
|
|
for _, c := range conts {
|
|
data := []interface{}{c.Category, c.StartGroup, c.Name, c.Image}
|
|
defcolor.Fprintf(tw, "%s\t%5d\t%s\t%s\n", data...)
|
|
}
|
|
}
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
lsCmd.Flags().BoolVarP(&lsCountAll, "count", "C", false, "Return only the count of configured items")
|
|
lsCmd.Flags().BoolVarP(&lsCountRunning, "running", "R", false, "Return only the count of running items")
|
|
lsCmd.Flags().BoolVarP(&lsCountNotRunning, "not-running", "N", false, "Return only the count of stopped/failed items")
|
|
lsCmd.Flags().BoolVarP(&lsJsonFormat, "json", "J", false, "Output results as a json array")
|
|
lsCmd.Flags().BoolVarP(&lsSortRuntime, "sort-runtime", "T", false, "Sort by running time (descending)")
|
|
lsCmd.Flags().BoolVarP(&lsNoColor, "no-color", "K", false, "Suppress ansi color sequences in output")
|
|
lsCmd.MarkFlagsMutuallyExclusive("count", "running", "not-running")
|
|
lsCmd.MarkFlagsMutuallyExclusive("sort-runtime", "json")
|
|
lsCmd.MarkFlagsMutuallyExclusive("sort-runtime", "running")
|
|
lsCmd.MarkFlagsMutuallyExclusive("sort-runtime", "not-running")
|
|
rootCmd.AddCommand(lsCmd)
|
|
}
|