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

feat(internal): Introduce 'metrics' command for instances #1857

Open
wants to merge 7 commits into
base: staging
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ require (
github.com/anchore/stereoscope v0.0.3
github.com/briandowns/spinner v1.23.1
github.com/cavaliergopher/cpio v1.0.1
github.com/charmbracelet/bubbles v0.18.0
github.com/charmbracelet/bubbles v0.20.0
github.com/charmbracelet/bubbletea v1.1.0
github.com/charmbracelet/lipgloss v0.13.0
github.com/cli/cli/v2 v2.55.0
Expand Down Expand Up @@ -82,7 +82,7 @@ require (
k8s.io/apimachinery v0.31.0
k8s.io/apiserver v0.30.3
oras.land/oras-go/v2 v2.5.0
sdk.kraft.cloud v0.5.10-0.20240821072613-b850da091d2d
sdk.kraft.cloud v0.5.10-0.20240830150932-eb1532db227c
sigs.k8s.io/kustomize/kyaml v0.17.2
)

Expand Down
12 changes: 8 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn
github.com/aws/aws-sdk-go v1.15.11/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
github.com/becheran/wildmatch-go v1.0.0 h1:mE3dGGkTmpKtT4Z+88t8RStG40yN9T+kFEGj2PZFSzA=
github.com/becheran/wildmatch-go v1.0.0/go.mod h1:gbMvj0NtVdJ15Mg/mH9uxk2R1QCistMyU7d9KFzroX4=
github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
Expand Down Expand Up @@ -169,8 +171,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chainguard-dev/git-urls v1.0.2 h1:pSpT7ifrpc5X55n4aTTm7FFUE+ZQHKiqpiwNkJrVcKQ=
github.com/chainguard-dev/git-urls v1.0.2/go.mod h1:rbGgj10OS7UgZlbzdUQIQpT0k/D4+An04HJY7Ol+Y/o=
github.com/charmbracelet/bubbles v0.18.0 h1:PYv1A036luoBGroX6VWjQIE9Syf2Wby2oOl/39KLfy0=
github.com/charmbracelet/bubbles v0.18.0/go.mod h1:08qhZhtIwzgrtBjAcJnij1t1H0ZRjwHyGsy6AL11PSw=
github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE=
github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU=
github.com/charmbracelet/bubbletea v1.1.0 h1:FjAl9eAL3HBCHenhz/ZPjkKdScmaS5SK69JAK2YJK9c=
github.com/charmbracelet/bubbletea v1.1.0/go.mod h1:9Ogk0HrdbHolIKHdjfFpyXJmiCzGwy+FesYkZr7hYU4=
github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=
Expand All @@ -179,6 +181,8 @@ github.com/charmbracelet/lipgloss v0.13.0 h1:4X3PPeoWEDCMvzDvGmTajSyYPcZM4+y8sCA
github.com/charmbracelet/lipgloss v0.13.0/go.mod h1:nw4zy0SBX/F/eAO1cWdcvy6qnkDUxr8Lw7dvFrAIbbY=
github.com/charmbracelet/x/ansi v0.2.3 h1:VfFN0NUpcjBRd4DnKfRaIRo53KRgey/nhOoEqosGDEY=
github.com/charmbracelet/x/ansi v0.2.3/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=
github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b h1:MnAMdlwSltxJyULnrYbkZpp4k58Co7Tah3ciKhSNo0Q=
github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0=
github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0=
github.com/checkpoint-restore/go-criu/v4 v4.1.0/go.mod h1:xUQBLp4RLc5zJtWY++yjOoMoB5lihDt7fai+75m+rGw=
Expand Down Expand Up @@ -1791,8 +1795,8 @@ oras.land/oras-go/v2 v2.5.0/go.mod h1:z4eisnLP530vwIOUOJeBIj0aGI0L1C3d53atvCBqZH
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
sdk.kraft.cloud v0.5.10-0.20240821072613-b850da091d2d h1:WSy3+37vK/nP/BTe4XFow3oy+HE53hqitamERPHPuBs=
sdk.kraft.cloud v0.5.10-0.20240821072613-b850da091d2d/go.mod h1:7Q1tBqVp8r7vtqUQhgRan26cUSx/A1uEYXhjQ/bqhiw=
sdk.kraft.cloud v0.5.10-0.20240830150932-eb1532db227c h1:MkwevLKnvuh4/kYM3mPj+BYQUagbiBT6NPX10cdZTKg=
sdk.kraft.cloud v0.5.10-0.20240830150932-eb1532db227c/go.mod h1:7Q1tBqVp8r7vtqUQhgRan26cUSx/A1uEYXhjQ/bqhiw=
sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.14/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg=
sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.15/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg=
sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.29.0 h1:/U5vjBbQn3RChhv7P11uhYvCSm5G2GaIi5AIGBS6r4c=
Expand Down
2 changes: 2 additions & 0 deletions internal/cli/kraft/cloud/instance/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"kraftkit.sh/internal/cli/kraft/cloud/instance/get"
"kraftkit.sh/internal/cli/kraft/cloud/instance/list"
"kraftkit.sh/internal/cli/kraft/cloud/instance/logs"
"kraftkit.sh/internal/cli/kraft/cloud/instance/metrics"
"kraftkit.sh/internal/cli/kraft/cloud/instance/remove"
"kraftkit.sh/internal/cli/kraft/cloud/instance/start"
"kraftkit.sh/internal/cli/kraft/cloud/instance/stop"
Expand All @@ -42,6 +43,7 @@ func NewCmd() *cobra.Command {
cmd.AddCommand(create.NewCmd())
cmd.AddCommand(list.NewCmd())
cmd.AddCommand(logs.NewCmd())
cmd.AddCommand(metrics.NewCmd())
cmd.AddCommand(remove.NewCmd())
cmd.AddCommand(start.NewCmd())
cmd.AddCommand(get.NewCmd())
Expand Down
255 changes: 255 additions & 0 deletions internal/cli/kraft/cloud/instance/metrics/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2024, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.

package metrics

import (
"context"
"fmt"
"sort"
"time"

"github.com/MakeNowJust/heredoc"
"github.com/dustin/go-humanize"
"github.com/spf13/cobra"

kraftcloud "sdk.kraft.cloud"
kcinstances "sdk.kraft.cloud/instances"

"kraftkit.sh/cmdfactory"
"kraftkit.sh/config"
"kraftkit.sh/internal/cli/kraft/cloud/utils"
"kraftkit.sh/iostreams"
"kraftkit.sh/log"
"kraftkit.sh/tui/pstable"
)

type MetricsOptions struct {
Auth *config.AuthConfig `noattribute:"true"`
Client kraftcloud.KraftCloud `noattribute:"true"`
Metro string `noattribute:"true"`
Token string `noattribute:"true"`
Output string `long:"output" short:"o" usage:"Set output format. Options: top,table,yaml,json,list"`
}

func NewCmd() *cobra.Command {
cmd, err := cmdfactory.New(&MetricsOptions{}, cobra.Command{
Short: "Show instance metrics",
Use: "top [FLAGS] [UUID|NAME [UUID|NAME]...]",
Aliases: []string{"metrics", "metric", "m", "meter"},
Args: cobra.ArbitraryArgs,
Example: heredoc.Doc(`
# Return metrics for all instances
$ kraft cloud instance top

# Return metrics for an instance by UUID
$ kraft cloud instance top fd1684ea-7970-4994-92d6-61dcc7905f2b

# Return metrics for an instance by name
$ kraft cloud instance top my-instance-431342
`),
Annotations: map[string]string{
cmdfactory.AnnotationHelpGroup: "kraftcloud-instance",
},
})
if err != nil {
panic(err)
}

return cmd
}

func (opts *MetricsOptions) printTop(ctx context.Context) error {
instanceStateColor := utils.InstanceStateColor
if config.G[config.KraftKit](ctx).NoColor {
instanceStateColor = utils.InstanceStateColorNil
}

previousMetrics := make(map[string]kcinstances.MetricsResponseItem)
table, err := pstable.NewPSTable(ctx,
"kraft cloud instance top",
[]pstable.Column{
{Title: "NAME"},
{Title: "STATE"},
{Title: "UPTIME"},
{Title: "CPU"},
{Title: "MEMORY"},
{Title: "NET RX / TX"},
},
func(ctx context.Context) ([]pstable.Row, error) {
instListResp, err := opts.Client.Instances().WithMetro(opts.Metro).List(ctx)
if err != nil {
return nil, fmt.Errorf("could not list instances: %w", err)
}

instList, err := instListResp.AllOrErr()
if err != nil {
return nil, fmt.Errorf("could not list instances: %w", err)
}

if len(instList) == 0 {
return nil, nil
}

var uuids []string
for _, instItem := range instList {
uuids = append(uuids, instItem.UUID)
}

metricsReps, err := opts.Client.Instances().WithMetro(opts.Metro).Metrics(ctx, uuids...)
if err != nil {
return nil, fmt.Errorf("getting metrics of %d instance(s): %w", len(instList), err)
}

metrics, err := metricsReps.AllOrErr()
if err != nil {
return nil, fmt.Errorf("getting metrics of %d instance(s): %w", len(instList), err)
}

instanceResps, err := opts.Client.Instances().WithMetro(opts.Metro).Get(ctx, uuids...)
if err != nil {
return nil, fmt.Errorf("getting details of %d instance(s): %w", len(instList), err)
}

instances, err := instanceResps.AllOrErr()
if err != nil {
return nil, fmt.Errorf("getting details of %d instance(s): %w", len(instList), err)
}

rows := make(map[string]pstable.Row)
instancesMap := make(map[string]kcinstances.GetResponseItem)

for _, instance := range instances {
instancesMap[instance.UUID] = instance
if _, ok := previousMetrics[instance.UUID]; !ok {
previousMetrics[instance.UUID] = kcinstances.MetricsResponseItem{}
}
rows[instance.UUID] = make([]pstable.Cell, 6)
rows[instance.UUID][0] = pstable.StringCell(instance.Name)
rows[instance.UUID][1] = pstable.StringCell(instanceStateColor[instance.State](string(instance.State)))
duration, err := time.ParseDuration(fmt.Sprintf("%dms", instance.UptimeMs))
if err != nil {
return nil, fmt.Errorf("could not parse uptime for '%s': %w", instance.UUID, err)
}
timeParsed := duration.Seconds()
timeUnit := "s"
if timeParsed > 60 {
timeParsed = duration.Minutes()
timeUnit = "m"
}
if timeParsed > 60 {
timeParsed = duration.Hours()
timeUnit = "h"
}
rows[instance.UUID][2] = pstable.StringCell(iostreams.Bold(fmt.Sprintf("%.2f%s", timeParsed, timeUnit)))
}

for _, metric := range metrics {
if _, ok := rows[metric.UUID]; !ok {
continue
}

rows[metric.UUID][3] = pstable.GuageCell{
Cs: iostreams.G(ctx).ColorScheme(),
Current: int(metric.CPUTimeMs - previousMetrics[metric.UUID].CPUTimeMs),
Max: 1000,
Width: 5,
}

rows[metric.UUID][4] = pstable.GuageCell{
Cs: iostreams.G(ctx).ColorScheme(),
Current: int(metric.RSS),
Max: int(instancesMap[metric.UUID].MemoryMB) * 1024 * 1024,
Width: 5,
}
rows[metric.UUID][5] = pstable.StringCell(iostreams.Bold(fmt.Sprintf("%s / %s", humanize.Bytes(metric.RxBytes), humanize.Bytes(metric.TxBytes))))

previousMetrics[metric.UUID] = metric
}

var keys []string
for key := range rows {
keys = append(keys, key)
}

// Sort ret by keys
sort.Strings(keys)
var ret []pstable.Row
for _, key := range keys {
ret = append(ret, rows[key])
}

return ret, nil
})
if err != nil {
return fmt.Errorf("could not create table: %w", err)
}

return table.Start(ctx)
}

func (opts *MetricsOptions) Pre(cmd *cobra.Command, _ []string) error {
err := utils.PopulateMetroToken(cmd, &opts.Metro, &opts.Token)
if err != nil {
return fmt.Errorf("could not populate metro and token: %w", err)
}

if !utils.IsValidOutputFormat(opts.Output) {
return fmt.Errorf("invalid output format: %s", opts.Output)
}

return nil
}

func (opts *MetricsOptions) Run(ctx context.Context, args []string) error {
auth, err := config.GetKraftCloudAuthConfig(ctx, opts.Token)
if err != nil {
return fmt.Errorf("could not retrieve credentials: %w", err)
}

opts.Client = kraftcloud.NewClient(
kraftcloud.WithToken(config.GetKraftCloudTokenAuthConfig(*auth)),
)

instances := args
if len(instances) == 0 {
resp, err := opts.Client.Instances().WithMetro(opts.Metro).List(ctx)
if err != nil {
return fmt.Errorf("could not list instances: %w", err)
}

insts, err := resp.AllOrErr()
if err != nil {
return fmt.Errorf("could not list instances: %w", err)
}

for _, inst := range insts {
instances = append(instances, inst.UUID)
}
}

if len(instances) > 0 {
if opts.Output == "" {
opts.Output = "list"
if log.LoggerTypeFromString(config.G[config.KraftKit](ctx).Log.Type) == log.FANCY {
opts.Output = "top"
} else if len(instances) > 1 {
opts.Output = "table"
}
}

if opts.Output == "top" {
return opts.printTop(ctx)
}

resp, err := opts.Client.Instances().WithMetro(opts.Metro).Metrics(ctx, instances...)
if err != nil {
return fmt.Errorf("could not get instance %s: %w", instances, err)
}
return utils.PrintMetrics(ctx, opts.Output, *resp)
}

return fmt.Errorf("no instances found")
}
Loading
Loading