From 85f1806bc9f8141b662fd213acae6afdad0ca39a Mon Sep 17 00:00:00 2001 From: kezhenxu94 Date: Mon, 24 Mar 2025 12:04:24 +0800 Subject: [PATCH] Remove cli module from pkg module --- .golangci.yml | 13 ++-- Makefile | 2 +- cmd/swctl/main.go | 9 ++- internal/commands/alarm/autopleteKeys.go | 5 +- internal/commands/alarm/autopleteValues.go | 4 +- internal/commands/alarm/list.go | 8 +- internal/commands/browser/logs/list.go | 4 +- internal/commands/browser/page/list.go | 5 +- internal/commands/browser/service/list.go | 6 +- internal/commands/browser/version/list.go | 5 +- internal/commands/dashboard/global/global.go | 15 +++- internal/commands/dashboard/global/metrics.go | 20 +++-- internal/commands/dependency/endpoint.go | 5 +- internal/commands/dependency/global.go | 8 +- internal/commands/dependency/instance.go | 5 +- internal/commands/dependency/process.go | 4 +- internal/commands/dependency/service.go | 5 +- internal/commands/endpoint/get.go | 4 +- internal/commands/endpoint/list.go | 4 +- internal/commands/event/list.go | 11 +-- internal/commands/event/report.go | 2 +- internal/commands/healthcheck/healthcheck.go | 3 +- internal/commands/hierarchy/instance.go | 4 +- internal/commands/hierarchy/layers.go | 4 +- internal/commands/hierarchy/service.go | 4 +- internal/commands/instance/get.go | 4 +- internal/commands/instance/list.go | 5 +- internal/commands/instance/search.go | 5 +- internal/commands/interceptor/duration.go | 28 ++++--- internal/commands/interceptor/interceptor.go | 18 ++++- internal/commands/interceptor/service.go | 4 +- internal/commands/interceptor/timezone.go | 3 +- internal/commands/layer/list.go | 4 +- internal/commands/logs/list.go | 9 +-- internal/commands/menu/get.go | 4 +- .../commands/metrics/aggregation/metrics.go | 4 +- .../metrics/aggregation/sampled-record.go | 10 +-- internal/commands/metrics/aggregation/topn.go | 4 +- internal/commands/metrics/expression/exec.go | 4 +- .../commands/metrics/linear/linear-metrics.go | 5 +- .../metrics/linear/multiple-linear-metrics.go | 7 +- .../commands/metrics/list/list-metrics.go | 5 +- .../metrics/single/nullable-metrics.go | 5 +- .../commands/metrics/single/single-metrics.go | 5 +- .../metrics/thermodynamic/thermodynamic.go | 5 +- internal/commands/process/estimate/scale.go | 5 +- internal/commands/process/get.go | 4 +- internal/commands/process/list.go | 4 +- .../profiling/asyncprofiler/create.go | 4 +- .../profiling/asyncprofiler/getAnalyze.go | 5 +- .../profiling/asyncprofiler/getTaskList.go | 5 +- .../asyncprofiler/getTaskProgress.go | 5 +- .../commands/profiling/continuous/list.go | 4 +- .../profiling/continuous/monitoring.go | 4 +- internal/commands/profiling/continuous/set.go | 4 +- internal/commands/profiling/ebpf/analysis.go | 8 +- .../ebpf/create/createByFixedTime.go | 5 +- .../commands/profiling/ebpf/create/network.go | 7 +- .../profiling/ebpf/create/prepareCreate.go | 4 +- .../commands/profiling/ebpf/keep/network.go | 4 +- internal/commands/profiling/ebpf/list.go | 6 +- internal/commands/profiling/ebpf/schedules.go | 4 +- internal/commands/profiling/trace/create.go | 5 +- .../profiling/trace/getProfileAnalyze.go | 9 +-- .../commands/profiling/trace/getTaskList.go | 5 +- .../commands/profiling/trace/getTaskLogs.go | 5 +- .../profiling/trace/getTaskSegmentList.go | 5 +- internal/commands/service/layer.go | 4 +- internal/commands/service/list.go | 6 +- internal/commands/trace/list.go | 9 +-- internal/commands/trace/trace.go | 5 +- internal/display/display.go | 75 +++++++++++++++++++ {pkg => internal}/util/commandNotFound.go | 0 .../util/commandNotFound_test.go | 0 pkg/contextkey/contextkey.go | 38 ++++++++++ pkg/display/display.go | 44 +---------- pkg/display/graph/dashboard/global.go | 45 +++++------ pkg/display/graph/flamegraph/adapter.go | 4 +- pkg/display/graph/flamegraph/flamegraph.go | 16 ++-- pkg/display/graph/gauge/gauge.go | 12 ++- pkg/display/graph/graph.go | 5 +- pkg/display/graph/linear/linear.go | 12 ++- pkg/display/graph/tree/list.go | 35 +++++---- pkg/graphql/alarm/alarm.go | 10 +-- pkg/graphql/client/client.go | 17 ++--- pkg/graphql/common/common.go | 6 +- pkg/graphql/dashboard/global.go | 30 ++++---- pkg/graphql/dependency/dependency.go | 15 ++-- pkg/graphql/event/event.go | 6 +- pkg/graphql/healthcheck/healthcheck.go | 5 +- pkg/graphql/hierarchy/hierarchy.go | 10 +-- pkg/graphql/log/log.go | 8 +- pkg/graphql/menu/menu.go | 6 +- pkg/graphql/metadata/metadata.go | 42 +++++------ pkg/graphql/metrics/metrics.go | 28 ++++--- pkg/graphql/profiling/asyncprofiler.go | 11 +-- pkg/graphql/profiling/continuous.go | 13 ++-- pkg/graphql/profiling/ebpf.go | 26 ++++--- pkg/graphql/profiling/trace.go | 14 ++-- pkg/graphql/trace/trace.go | 7 +- pkg/heatmap/heatmap.go | 2 +- 101 files changed, 542 insertions(+), 432 deletions(-) create mode 100644 internal/display/display.go rename {pkg => internal}/util/commandNotFound.go (100%) rename {pkg => internal}/util/commandNotFound_test.go (100%) create mode 100644 pkg/contextkey/contextkey.go diff --git a/.golangci.yml b/.golangci.yml index 82a287ff..93a77e9f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -46,6 +46,13 @@ linters-settings: whitespace: multi-if: false multi-func: false + depguard: + rules: + prevent_cli_in_pkg: + files: ["**/pkg/**/*.go"] + deny: + - pkg: "github.com/urfave/cli/v2" + desc: "github.com/urfave/cli/v2 is not allowed in pkg module" linters: enable: @@ -74,8 +81,4 @@ linters: - unparam - unused - whitespace - -service: - golangci-lint-version: 1.20.x - prepare: - - echo "here I can run custom commands, but no preparation needed for this repo" + - depguard diff --git a/Makefile b/Makefile index 0cbf198e..6c036b01 100644 --- a/Makefile +++ b/Makefile @@ -55,7 +55,7 @@ build: $(BUILDS) .PHONY: deps deps: - @$(GO_GET) -v -t -d ./... + @$(GO_GET) -v -t ./... $(GO_LINT): @$(GO_LINT) version > /dev/null 2>&1 || go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.64.0 diff --git a/cmd/swctl/main.go b/cmd/swctl/main.go index 1023861d..1fd6d38a 100644 --- a/cmd/swctl/main.go +++ b/cmd/swctl/main.go @@ -44,6 +44,7 @@ import ( "github.com/apache/skywalking-cli/internal/commands/service" "github.com/apache/skywalking-cli/internal/commands/trace" "github.com/apache/skywalking-cli/internal/logger" + intutil "github.com/apache/skywalking-cli/internal/util" "github.com/apache/skywalking-cli/pkg/util" "github.com/sirupsen/logrus" @@ -51,8 +52,10 @@ import ( "github.com/urfave/cli/v2/altsrc" ) -var log *logrus.Logger -var version string // Will be initialized when building +var ( + log *logrus.Logger + version string // Will be initialized when building +) func init() { log = logger.Log @@ -119,7 +122,7 @@ services, service instances, etc.` ) app.Flags = flags - app.CommandNotFound = util.CommandNotFound + app.CommandNotFound = intutil.CommandNotFound // Enable auto-completion. app.EnableBashCompletion = true diff --git a/internal/commands/alarm/autopleteKeys.go b/internal/commands/alarm/autopleteKeys.go index 6a9b081c..44f8777c 100644 --- a/internal/commands/alarm/autopleteKeys.go +++ b/internal/commands/alarm/autopleteKeys.go @@ -57,11 +57,12 @@ $ swctl alarm autocomplete-keys Step: step.(*model.StepEnumValue).Selected, } - autocompleteKeys, err := alarm.TagAutocompleteKeys(ctx, duration) + autocompleteKeys, err := alarm.TagAutocompleteKeys(ctx.Context, duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: autocompleteKeys, Condition: duration}) + ctx.Lineage() + return display.Display(ctx.Context, &displayable.Displayable{Data: autocompleteKeys, Condition: duration}) }, } diff --git a/internal/commands/alarm/autopleteValues.go b/internal/commands/alarm/autopleteValues.go index 8876e41a..583d0bfb 100644 --- a/internal/commands/alarm/autopleteValues.go +++ b/internal/commands/alarm/autopleteValues.go @@ -66,11 +66,11 @@ $ swctl alarm autocomplete-values --key=tagKey Step: step.(*model.StepEnumValue).Selected, } - autocompleteValues, err := alarm.TagAutocompleteValues(ctx, duration, tagKey) + autocompleteValues, err := alarm.TagAutocompleteValues(ctx.Context, duration, tagKey) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: autocompleteValues, Condition: tagKey}) + return display.Display(ctx.Context, &displayable.Displayable{Data: autocompleteValues, Condition: tagKey}) }, } diff --git a/internal/commands/alarm/list.go b/internal/commands/alarm/list.go index 7137bffb..03682b71 100644 --- a/internal/commands/alarm/list.go +++ b/internal/commands/alarm/list.go @@ -89,8 +89,8 @@ $ swctl alarm list var tags []*api.AlarmTag if tagStr != "" { - tagArr := strings.Split(tagStr, ",") - for _, tag := range tagArr { + tagArr := strings.SplitSeq(tagStr, ",") + for tag := range tagArr { kv := strings.SplitN(tag, "=", 2) if len(kv) != 2 { return fmt.Errorf("invalid tag, cannot be splitted into 2 parts. %s", tag) @@ -112,11 +112,11 @@ $ swctl alarm list Tags: tags, Paging: &paging, } - alarms, err := alarm.Alarms(ctx, condition) + alarms, err := alarm.Alarms(ctx.Context, condition) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: alarms, Condition: condition}) + return display.Display(ctx.Context, &displayable.Displayable{Data: alarms, Condition: condition}) }, } diff --git a/internal/commands/browser/logs/list.go b/internal/commands/browser/logs/list.go index c1adbceb..9989b9aa 100644 --- a/internal/commands/browser/logs/list.go +++ b/internal/commands/browser/logs/list.go @@ -80,11 +80,11 @@ $ swctl browser logs list`, Paging: &paging, } - logs, err := log.BrowserLogs(ctx, condition) + logs, err := log.BrowserLogs(ctx.Context, condition) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: logs, Condition: condition}) + return display.Display(ctx.Context, &displayable.Displayable{Data: logs, Condition: condition}) }, } diff --git a/internal/commands/browser/page/list.go b/internal/commands/browser/page/list.go index 757f4003..f7c58771 100644 --- a/internal/commands/browser/page/list.go +++ b/internal/commands/browser/page/list.go @@ -58,12 +58,11 @@ $ swctl browser page ls --service-id dGVzdC11aQ==.1`, serviceID := ctx.String("service-id") limit := ctx.Int("limit") - endpoints, err := metadata.SearchEndpoints(ctx, serviceID, "", limit, nil) - + endpoints, err := metadata.SearchEndpoints(ctx.Context, serviceID, "", limit, nil) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: endpoints}) + return display.Display(ctx.Context, &displayable.Displayable{Data: endpoints}) }, } diff --git a/internal/commands/browser/service/list.go b/internal/commands/browser/service/list.go index 6fe2e38f..d676c368 100644 --- a/internal/commands/browser/service/list.go +++ b/internal/commands/browser/service/list.go @@ -56,7 +56,7 @@ $ swctl browser svc ls test-ui`, var err error if args := ctx.Args(); args.Len() == 0 { - services, err = metadata.AllBrowserServices(ctx, api.Duration{ + services, err = metadata.AllBrowserServices(ctx.Context, api.Duration{ Start: start, End: end, Step: step.(*model.StepEnumValue).Selected, @@ -65,13 +65,13 @@ $ swctl browser svc ls test-ui`, return err } } else { - service, err := metadata.SearchBrowserService(ctx, args.First()) + service, err := metadata.SearchBrowserService(ctx.Context, args.First()) if err != nil { return err } services = []api.Service{service} } - return display.Display(ctx, &displayable.Displayable{Data: services}) + return display.Display(ctx.Context, &displayable.Displayable{Data: services}) }, } diff --git a/internal/commands/browser/version/list.go b/internal/commands/browser/version/list.go index 9fb0978b..aa47ae02 100644 --- a/internal/commands/browser/version/list.go +++ b/internal/commands/browser/version/list.go @@ -56,16 +56,15 @@ $ swctl browser version ls --service-id dGVzdC11aQ==.1`, step := ctx.Generic("step") serviceID := ctx.String("service-id") - instances, err := metadata.Instances(ctx, serviceID, api.Duration{ + instances, err := metadata.Instances(ctx.Context, serviceID, api.Duration{ Start: start, End: end, Step: step.(*model.StepEnumValue).Selected, }) - if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: instances}) + return display.Display(ctx.Context, &displayable.Displayable{Data: instances}) }, } diff --git a/internal/commands/dashboard/global/global.go b/internal/commands/dashboard/global/global.go index 2bfaf0d7..4e941d0f 100644 --- a/internal/commands/dashboard/global/global.go +++ b/internal/commands/dashboard/global/global.go @@ -18,6 +18,8 @@ package global import ( + "context" + "github.com/urfave/cli/v2" api "skywalking.apache.org/repo/goapi/query" @@ -25,6 +27,7 @@ import ( "github.com/apache/skywalking-cli/internal/commands/interceptor" "github.com/apache/skywalking-cli/internal/flags" "github.com/apache/skywalking-cli/internal/model" + "github.com/apache/skywalking-cli/pkg/contextkey" "github.com/apache/skywalking-cli/pkg/display" "github.com/apache/skywalking-cli/pkg/display/displayable" "github.com/apache/skywalking-cli/pkg/graphql/dashboard" @@ -62,22 +65,28 @@ $ swctl dashboard global --template my-global-template.yml ), Before: interceptor.BeforeChain( interceptor.DurationInterceptor, + func(cliCtx *cli.Context) error { + ctx := cliCtx.Context + ctx = context.WithValue(ctx, contextkey.DashboardTemplate{}, cliCtx.String("template")) + ctx = context.WithValue(ctx, contextkey.DashboardRefreshInterval{}, cliCtx.Int("refresh")) + cliCtx.Context = ctx + return nil + }, ), Action: func(ctx *cli.Context) error { end := ctx.String("end") start := ctx.String("start") step := ctx.Generic("step") - globalData, err := dashboard.Global(ctx, api.Duration{ + globalData, err := dashboard.Global(ctx.Context, api.Duration{ Start: start, End: end, Step: step.(*model.StepEnumValue).Selected, }) - if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: globalData}) + return display.Display(ctx.Context, &displayable.Displayable{Data: globalData}) }, } diff --git a/internal/commands/dashboard/global/metrics.go b/internal/commands/dashboard/global/metrics.go index 37c9a9ac..7653c547 100644 --- a/internal/commands/dashboard/global/metrics.go +++ b/internal/commands/dashboard/global/metrics.go @@ -18,11 +18,14 @@ package global import ( + "context" + "github.com/urfave/cli/v2" "github.com/apache/skywalking-cli/internal/commands/interceptor" "github.com/apache/skywalking-cli/internal/flags" "github.com/apache/skywalking-cli/internal/model" + "github.com/apache/skywalking-cli/pkg/contextkey" "github.com/apache/skywalking-cli/pkg/display" "github.com/apache/skywalking-cli/pkg/display/displayable" "github.com/apache/skywalking-cli/pkg/graphql/dashboard" @@ -47,21 +50,24 @@ var Metrics = &cli.Command{ Before: interceptor.BeforeChain( interceptor.DurationInterceptor, ), - Action: func(ctx *cli.Context) error { - end := ctx.String("end") - start := ctx.String("start") - step := ctx.Generic("step") + Action: func(cliCtx *cli.Context) error { + end := cliCtx.String("end") + start := cliCtx.String("start") + step := cliCtx.Generic("step") + + ctx := cliCtx.Context + ctx = context.WithValue(ctx, contextkey.DashboardTemplate{}, cliCtx.String("template")) + cliCtx.Context = ctx - globalMetrics, err := dashboard.Metrics(ctx, api.Duration{ + globalMetrics, err := dashboard.Metrics(cliCtx.Context, api.Duration{ Start: start, End: end, Step: step.(*model.StepEnumValue).Selected, }) - if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: globalMetrics}) + return display.Display(cliCtx.Context, &displayable.Displayable{Data: globalMetrics}) }, } diff --git a/internal/commands/dependency/endpoint.go b/internal/commands/dependency/endpoint.go index 8901028f..92039966 100644 --- a/internal/commands/dependency/endpoint.go +++ b/internal/commands/dependency/endpoint.go @@ -57,12 +57,11 @@ var EndpointCommand = &cli.Command{ Step: step.(*model.StepEnumValue).Selected, } - dependency, err := dependency.EndpointDependency(ctx, endpointID, duration) - + dependency, err := dependency.EndpointDependency(ctx.Context, endpointID, duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: dependency}) + return display.Display(ctx.Context, &displayable.Displayable{Data: dependency}) }, } diff --git a/internal/commands/dependency/global.go b/internal/commands/dependency/global.go index c0ad7982..ae1d240d 100644 --- a/internal/commands/dependency/global.go +++ b/internal/commands/dependency/global.go @@ -62,25 +62,25 @@ var GlobalCommand = &cli.Command{ Step: step.(*model.StepEnumValue).Selected, } - major, _, err := metadata.BackendVersion(ctx) + major, _, err := metadata.BackendVersion(ctx.Context) if err != nil { return err } var topology api.Topology if major >= 10 { - topology, err = dependency.GlobalTopology(ctx, layer, duration) + topology, err = dependency.GlobalTopology(ctx.Context, layer, duration) } else { if layer != "" { return fmt.Errorf("the layer parameter only available when OAP version >= 10.0.0") } - topology, err = dependency.GlobalTopologyWithoutLayer(ctx, duration) + topology, err = dependency.GlobalTopologyWithoutLayer(ctx.Context, duration) } if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: topology}) + return display.Display(ctx.Context, &displayable.Displayable{Data: topology}) }, } diff --git a/internal/commands/dependency/instance.go b/internal/commands/dependency/instance.go index c2726011..f17d1e95 100644 --- a/internal/commands/dependency/instance.go +++ b/internal/commands/dependency/instance.go @@ -59,12 +59,11 @@ var InstanceCommand = &cli.Command{ Step: step.(*model.StepEnumValue).Selected, } - dependency, err := dependency.InstanceTopology(ctx, srcSvcID, dstSvcID, duration) - + dependency, err := dependency.InstanceTopology(ctx.Context, srcSvcID, dstSvcID, duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: dependency}) + return display.Display(ctx.Context, &displayable.Displayable{Data: dependency}) }, } diff --git a/internal/commands/dependency/process.go b/internal/commands/dependency/process.go index 8a896798..fc2a21ed 100644 --- a/internal/commands/dependency/process.go +++ b/internal/commands/dependency/process.go @@ -57,11 +57,11 @@ var ProcessCommand = &cli.Command{ Step: step.(*model.StepEnumValue).Selected, } - dependency, err := dependency.ProcessTopology(ctx, instanceID, duration) + dependency, err := dependency.ProcessTopology(ctx.Context, instanceID, duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: dependency}) + return display.Display(ctx.Context, &displayable.Displayable{Data: dependency}) }, } diff --git a/internal/commands/dependency/service.go b/internal/commands/dependency/service.go index bf176fdb..18231628 100644 --- a/internal/commands/dependency/service.go +++ b/internal/commands/dependency/service.go @@ -57,12 +57,11 @@ var ServiceCommand = &cli.Command{ Step: step.(*model.StepEnumValue).Selected, } - dependency, err := dependency.ServiceTopology(ctx, serviceID, duration) - + dependency, err := dependency.ServiceTopology(ctx.Context, serviceID, duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: dependency}) + return display.Display(ctx.Context, &displayable.Displayable{Data: dependency}) }, } diff --git a/internal/commands/endpoint/get.go b/internal/commands/endpoint/get.go index ec6a09ce..e14b37ce 100644 --- a/internal/commands/endpoint/get.go +++ b/internal/commands/endpoint/get.go @@ -40,11 +40,11 @@ $ swctl endpoint get cHJvdmlkZXI=.1_L3VzZXJz`, return fmt.Errorf("endpoint-id must be provide") } - endpointInfo, err := metadata.GetEndpointInfo(ctx, ctx.Args().First()) + endpointInfo, err := metadata.GetEndpointInfo(ctx.Context, ctx.Args().First()) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: endpointInfo}) + return display.Display(ctx.Context, &displayable.Displayable{Data: endpointInfo}) }, } diff --git a/internal/commands/endpoint/list.go b/internal/commands/endpoint/list.go index 2249b123..a24344a8 100644 --- a/internal/commands/endpoint/list.go +++ b/internal/commands/endpoint/list.go @@ -90,11 +90,11 @@ $ swctl endpoint ls --service-name business-zone::projectC --keyword projectC`, } } - endpoints, err := metadata.SearchEndpoints(ctx, serviceID, keyword, limit, duration) + endpoints, err := metadata.SearchEndpoints(ctx.Context, serviceID, keyword, limit, duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: endpoints}) + return display.Display(ctx.Context, &displayable.Displayable{Data: endpoints}) }, } diff --git a/internal/commands/event/list.go b/internal/commands/event/list.go index 63ff72bd..c0dd5a5b 100644 --- a/internal/commands/event/list.go +++ b/internal/commands/event/list.go @@ -33,8 +33,10 @@ import ( "github.com/urfave/cli/v2" ) -const DefaultPageSize = 15 -const EventTypeAll event.Type = -1 +const ( + DefaultPageSize = 15 + EventTypeAll event.Type = -1 +) func init() { event.Type_name[-1] = "All" @@ -122,12 +124,11 @@ $ swctl event list condition.Type = &t } - events, err := eventQl.Events(ctx, condition) - + events, err := eventQl.Events(ctx.Context, condition) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: events, Condition: condition}) + return display.Display(ctx.Context, &displayable.Displayable{Data: events, Condition: condition}) }, } diff --git a/internal/commands/event/report.go b/internal/commands/event/report.go index 4c7b1938..395d0cf0 100644 --- a/internal/commands/event/report.go +++ b/internal/commands/event/report.go @@ -112,6 +112,6 @@ one for starting of the event (--start-time is required) and the other one for e } logger.Log.Printf("Report the event successfully, whose uuid is %s\n", ctx.String("uuid")) - return display.Display(ctx, &displayable.Displayable{Data: reply}) + return display.Display(ctx.Context, &displayable.Displayable{Data: reply}) }, } diff --git a/internal/commands/healthcheck/healthcheck.go b/internal/commands/healthcheck/healthcheck.go index b4cb9e2e..f67efc13 100644 --- a/internal/commands/healthcheck/healthcheck.go +++ b/internal/commands/healthcheck/healthcheck.go @@ -59,8 +59,7 @@ $ swctl health --grpc=false }, }, Action: func(ctx *cli.Context) error { - healthStatus, err := hc.CheckHealth(ctx) - + healthStatus, err := hc.CheckHealth(ctx.Context) if err != nil { return err } diff --git a/internal/commands/hierarchy/instance.go b/internal/commands/hierarchy/instance.go index 7ff865f6..6d49c016 100644 --- a/internal/commands/hierarchy/instance.go +++ b/internal/commands/hierarchy/instance.go @@ -49,10 +49,10 @@ var instanceCommand = &cli.Command{ instanceID := ctx.String("instance-id") layer := ctx.String("layer") - hierarchy, err := hierarchy.InstanceHierarchy(ctx, instanceID, layer) + hierarchy, err := hierarchy.InstanceHierarchy(ctx.Context, instanceID, layer) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: hierarchy, Condition: instanceID}) + return display.Display(ctx.Context, &displayable.Displayable{Data: hierarchy, Condition: instanceID}) }, } diff --git a/internal/commands/hierarchy/layers.go b/internal/commands/hierarchy/layers.go index ffbdb20f..5f734c8b 100644 --- a/internal/commands/hierarchy/layers.go +++ b/internal/commands/hierarchy/layers.go @@ -34,10 +34,10 @@ var layerCommand = &cli.Command{ Flags: flags.Flags(), Before: interceptor.BeforeChain(), Action: func(ctx *cli.Context) error { - levels, err := hierarchy.ListLayerLevels(ctx) + levels, err := hierarchy.ListLayerLevels(ctx.Context) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: levels}) + return display.Display(ctx.Context, &displayable.Displayable{Data: levels}) }, } diff --git a/internal/commands/hierarchy/service.go b/internal/commands/hierarchy/service.go index 8d8beb71..aaccfe4d 100644 --- a/internal/commands/hierarchy/service.go +++ b/internal/commands/hierarchy/service.go @@ -48,10 +48,10 @@ var serviceCommand = &cli.Command{ serviceID := ctx.String("service-id") layer := ctx.String("layer") - hierarchy, err := hierarchy.ServiceHierarchy(ctx, serviceID, layer) + hierarchy, err := hierarchy.ServiceHierarchy(ctx.Context, serviceID, layer) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: hierarchy, Condition: serviceID}) + return display.Display(ctx.Context, &displayable.Displayable{Data: hierarchy, Condition: serviceID}) }, } diff --git a/internal/commands/instance/get.go b/internal/commands/instance/get.go index 766c2c9f..c0b57bf8 100644 --- a/internal/commands/instance/get.go +++ b/internal/commands/instance/get.go @@ -40,11 +40,11 @@ $ swctl instance get cHJvdmlkZXI=.1_cHJvdmlkZXIx`, return fmt.Errorf("instance-id must be provide") } - instance, err := metadata.GetInstance(ctx, ctx.Args().First()) + instance, err := metadata.GetInstance(ctx.Context, ctx.Args().First()) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: instance}) + return display.Display(ctx.Context, &displayable.Displayable{Data: instance}) }, } diff --git a/internal/commands/instance/list.go b/internal/commands/instance/list.go index 11ba23b1..13f304e4 100644 --- a/internal/commands/instance/list.go +++ b/internal/commands/instance/list.go @@ -56,16 +56,15 @@ $ swctl instance ls --service-id YnVzaW5lc3Mtem9uZTo6cHJvamVjdEM=.1`, step := ctx.Generic("step") serviceID := ctx.String("service-id") - instances, err := metadata.Instances(ctx, serviceID, api.Duration{ + instances, err := metadata.Instances(ctx.Context, serviceID, api.Duration{ Start: start, End: end, Step: step.(*model.StepEnumValue).Selected, }) - if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: instances}) + return display.Display(ctx.Context, &displayable.Displayable{Data: instances}) }, } diff --git a/internal/commands/instance/search.go b/internal/commands/instance/search.go index a7bee0fd..30640210 100644 --- a/internal/commands/instance/search.go +++ b/internal/commands/instance/search.go @@ -51,12 +51,11 @@ var SearchCommand = &cli.Command{ step := ctx.Generic("step") regex := ctx.String("regex") - instances, err := metadata.Instances(ctx, serviceID, api.Duration{ + instances, err := metadata.Instances(ctx.Context, serviceID, api.Duration{ Start: start, End: end, Step: step.(*model.StepEnumValue).Selected, }) - if err != nil { return err } @@ -69,6 +68,6 @@ var SearchCommand = &cli.Command{ } } } - return display.Display(ctx, &displayable.Displayable{Data: result}) + return display.Display(ctx.Context, &displayable.Displayable{Data: result}) }, } diff --git a/internal/commands/interceptor/duration.go b/internal/commands/interceptor/duration.go index 5d93c897..0d08f17b 100644 --- a/internal/commands/interceptor/duration.go +++ b/internal/commands/interceptor/duration.go @@ -18,12 +18,14 @@ package interceptor import ( + "context" "fmt" "strconv" "time" api "skywalking.apache.org/repo/goapi/query" + "github.com/apache/skywalking-cli/pkg/contextkey" "github.com/apache/skywalking-cli/pkg/graphql/utils" "github.com/urfave/cli/v2" @@ -50,11 +52,11 @@ func TryParseTime(unparsed string, userStep api.Step) (api.Step, time.Time, erro // DurationInterceptor sets the duration if absent, and formats it accordingly, // see ParseDuration -func DurationInterceptor(ctx *cli.Context) error { - start := ctx.String("start") - end := ctx.String("end") - userStep := ctx.Generic("step") - if timezone := ctx.String("timezone"); timezone != "" { +func DurationInterceptor(cliCtx *cli.Context) error { + start := cliCtx.String("start") + end := cliCtx.String("end") + userStep := cliCtx.Generic("step") + if timezone := cliCtx.String("timezone"); timezone != "" { if offset, err := strconv.Atoi(timezone); err == nil { // `offset` is in form of "+1300", while `time.FixedZone` takes offset in seconds time.Local = time.FixedZone("", offset/100*60*60) @@ -68,15 +70,23 @@ func DurationInterceptor(ctx *cli.Context) error { startTime, endTime, step, dt := ParseDuration(start, end, s) - if err := ctx.Set("start", startTime.Format(utils.StepFormats[step])); err != nil { + if err := cliCtx.Set("start", startTime.Format(utils.StepFormats[step])); err != nil { return err - } else if err := ctx.Set("end", endTime.Format(utils.StepFormats[step])); err != nil { + } else if err := cliCtx.Set("end", endTime.Format(utils.StepFormats[step])); err != nil { return err - } else if err := ctx.Set("step", step.String()); err != nil { + } else if err := cliCtx.Set("step", step.String()); err != nil { return err - } else if err := ctx.Set("duration-type", dt.String()); err != nil { + } else if err := cliCtx.Set("duration-type", dt.String()); err != nil { return err } + + ctx := cliCtx.Context + ctx = context.WithValue(ctx, contextkey.DurationStart{}, startTime.Format(utils.StepFormats[step])) + ctx = context.WithValue(ctx, contextkey.DurationEnd{}, endTime.Format(utils.StepFormats[step])) + ctx = context.WithValue(ctx, contextkey.DurationStep{}, step) + ctx = context.WithValue(ctx, contextkey.DurationType{}, utils.DurationType(dt.String())) + cliCtx.Context = ctx + return nil } diff --git a/internal/commands/interceptor/interceptor.go b/internal/commands/interceptor/interceptor.go index 572d11c1..6bf49b61 100644 --- a/internal/commands/interceptor/interceptor.go +++ b/internal/commands/interceptor/interceptor.go @@ -18,18 +18,30 @@ package interceptor import ( + "context" + + "github.com/apache/skywalking-cli/pkg/contextkey" + "github.com/urfave/cli/v2" ) // BeforeChain is a convenient function to chain up multiple cli.BeforeFunc func BeforeChain(beforeFunctions ...cli.BeforeFunc) cli.BeforeFunc { - return func(ctx *cli.Context) error { + return func(cliCtx *cli.Context) error { + ctx := cliCtx.Context + ctx = context.WithValue(ctx, contextkey.BaseURL{}, cliCtx.String("base-url")) + ctx = context.WithValue(ctx, contextkey.Username{}, cliCtx.String("username")) + ctx = context.WithValue(ctx, contextkey.Password{}, cliCtx.String("password")) + ctx = context.WithValue(ctx, contextkey.Authorization{}, cliCtx.String("authorization")) + ctx = context.WithValue(ctx, contextkey.Display{}, cliCtx.String("display")) + cliCtx.Context = ctx + // --timezone is global option, it should be applied always. - if err := TimezoneInterceptor(ctx); err != nil { + if err := TimezoneInterceptor(cliCtx); err != nil { return err } for _, beforeFunc := range beforeFunctions { - if err := beforeFunc(ctx); err != nil { + if err := beforeFunc(cliCtx); err != nil { return err } } diff --git a/internal/commands/interceptor/service.go b/internal/commands/interceptor/service.go index 72b5fbf6..e770c152 100644 --- a/internal/commands/interceptor/service.go +++ b/internal/commands/interceptor/service.go @@ -94,9 +94,9 @@ func parseService(required bool, idFlagName, nameFlagName string, nodeType nodeT var err error switch nodeType { case normal: - service, err = metadata.SearchService(ctx, name) + service, err = metadata.SearchService(ctx.Context, name) case browser: - service, err = metadata.SearchBrowserService(ctx, name) + service, err = metadata.SearchBrowserService(ctx.Context, name) } if err != nil { return err diff --git a/internal/commands/interceptor/timezone.go b/internal/commands/interceptor/timezone.go index 83fa9040..425d8ddc 100644 --- a/internal/commands/interceptor/timezone.go +++ b/internal/commands/interceptor/timezone.go @@ -35,8 +35,7 @@ func TimezoneInterceptor(ctx *cli.Context) error { return nil } - serverTimeInfo, err := metadata.ServerTimeInfo(ctx) - + serverTimeInfo, err := metadata.ServerTimeInfo(ctx.Context) if err != nil { logger.Log.Debugf("Failed to get server time info: %v\n", err) return nil diff --git a/internal/commands/layer/list.go b/internal/commands/layer/list.go index fb9d5006..dee4079d 100644 --- a/internal/commands/layer/list.go +++ b/internal/commands/layer/list.go @@ -36,11 +36,11 @@ Examples: $ swctl layer list `, Action: func(ctx *cli.Context) error { - layers, err := metadata.ListLayers(ctx) + layers, err := metadata.ListLayers(ctx.Context) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: layers}) + return display.Display(ctx.Context, &displayable.Displayable{Data: layers}) }, } diff --git a/internal/commands/logs/list.go b/internal/commands/logs/list.go index 10a33fcc..4f6c42c8 100644 --- a/internal/commands/logs/list.go +++ b/internal/commands/logs/list.go @@ -87,8 +87,8 @@ $ swctl logs list --trace-id 3d56f33f-bcd3-4e40-9e4f-5dc547998ef5`, tagStr := ctx.String("tags") var tags []*api.LogTag = nil if tagStr != "" { - tagArr := strings.Split(tagStr, ",") - for _, tag := range tagArr { + tagArr := strings.SplitSeq(tagStr, ",") + for tag := range tagArr { kv := strings.Split(tag, "=") tags = append(tags, &api.LogTag{Key: kv[0], Value: &kv[1]}) } @@ -108,12 +108,11 @@ $ swctl logs list --trace-id 3d56f33f-bcd3-4e40-9e4f-5dc547998ef5`, QueryDuration: &duration, Paging: &paging, } - logs, err := log.Logs(ctx, condition) - + logs, err := log.Logs(ctx.Context, condition) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: logs, Condition: condition}) + return display.Display(ctx.Context, &displayable.Displayable{Data: logs, Condition: condition}) }, } diff --git a/internal/commands/menu/get.go b/internal/commands/menu/get.go index 151b2b09..c7b9aac5 100644 --- a/internal/commands/menu/get.go +++ b/internal/commands/menu/get.go @@ -34,10 +34,10 @@ Examples: 1. Get the UI menu items: $swctl menu get`, Action: func(ctx *cli.Context) error { - menuItems, err := menu.GetItems(ctx) + menuItems, err := menu.GetItems(ctx.Context) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: menuItems}) + return display.Display(ctx.Context, &displayable.Displayable{Data: menuItems}) }, } diff --git a/internal/commands/metrics/aggregation/metrics.go b/internal/commands/metrics/aggregation/metrics.go index 4e1e8d14..6f4c72d5 100644 --- a/internal/commands/metrics/aggregation/metrics.go +++ b/internal/commands/metrics/aggregation/metrics.go @@ -74,11 +74,11 @@ $ swctl metrics sorted --name service_instance_sla --service-name boutique::adse } logger.Log.Debugln(condition.Name, condition.Scope, condition.TopN) - metricsValues, err := metrics.SortMetrics(ctx, *condition, *duration) + metricsValues, err := metrics.SortMetrics(ctx.Context, *condition, *duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: metricsValues}) + return display.Display(ctx.Context, &displayable.Displayable{Data: metricsValues}) }, } diff --git a/internal/commands/metrics/aggregation/sampled-record.go b/internal/commands/metrics/aggregation/sampled-record.go index 4f268817..16fddae7 100644 --- a/internal/commands/metrics/aggregation/sampled-record.go +++ b/internal/commands/metrics/aggregation/sampled-record.go @@ -70,7 +70,7 @@ $ swctl metrics sampled-record --name top_n_database_statement 5 ), Action: func(ctx *cli.Context) error { // read OAP version - major, minor, err := metadata.BackendVersion(ctx) + major, minor, err := metadata.BackendVersion(ctx.Context) if err != nil { return fmt.Errorf("read backend version failure: %v", err) } @@ -83,12 +83,12 @@ $ swctl metrics sampled-record --name top_n_database_statement 5 } logger.Log.Debugln(condition.Name, condition.TopN) - records, err1 := metrics.ReadRecords(ctx, *condition, *duration) + records, err1 := metrics.ReadRecords(ctx.Context, *condition, *duration) if err1 != nil { return err1 } - return display.Display(ctx, &displayable.Displayable{Data: records}) + return display.Display(ctx.Context, &displayable.Displayable{Data: records}) } condition, duration, err := buildSortedCondition(ctx, false) @@ -97,11 +97,11 @@ $ swctl metrics sampled-record --name top_n_database_statement 5 } logger.Log.Debugln(condition.Name, condition.Scope, condition.TopN) - sampledRecords, err := metrics.SampledRecords(ctx, *condition, *duration) + sampledRecords, err := metrics.SampledRecords(ctx.Context, *condition, *duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: sampledRecords}) + return display.Display(ctx.Context, &displayable.Displayable{Data: sampledRecords}) }, } diff --git a/internal/commands/metrics/aggregation/topn.go b/internal/commands/metrics/aggregation/topn.go index 7a537b7b..134a31c9 100644 --- a/internal/commands/metrics/aggregation/topn.go +++ b/internal/commands/metrics/aggregation/topn.go @@ -74,11 +74,11 @@ $ swctl metrics top --name service_instance_sla --service-name boutique::adservi } logger.Log.Debugln(condition.Name, condition.Scope, condition.TopN) - metricsValues, err := metrics.SortMetrics(ctx, *condition, *duration) + metricsValues, err := metrics.SortMetrics(ctx.Context, *condition, *duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: metricsValues}) + return display.Display(ctx.Context, &displayable.Displayable{Data: metricsValues}) }, } diff --git a/internal/commands/metrics/expression/exec.go b/internal/commands/metrics/expression/exec.go index 25c414e2..a40724e0 100644 --- a/internal/commands/metrics/expression/exec.go +++ b/internal/commands/metrics/expression/exec.go @@ -77,11 +77,11 @@ $ swctl metrics execute --expression="service_resp_time" --service-name business Step: step.(*model.StepEnumValue).Selected, } - result, err := metrics.Execute(ctx, expression, entity, duration) + result, err := metrics.Execute(ctx.Context, expression, entity, duration) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: result}) + return display.Display(ctx.Context, &displayable.Displayable{Data: result}) }, } diff --git a/internal/commands/metrics/linear/linear-metrics.go b/internal/commands/metrics/linear/linear-metrics.go index d6c4d9a0..359866eb 100644 --- a/internal/commands/metrics/linear/linear-metrics.go +++ b/internal/commands/metrics/linear/linear-metrics.go @@ -77,15 +77,14 @@ $ swctl metrics linear --name=service_relation_client_cpm --service-name consume Step: step.(*model.StepEnumValue).Selected, } - metricsValues, err := metrics.LinearIntValues(ctx, api.MetricsCondition{ + metricsValues, err := metrics.LinearIntValues(ctx.Context, api.MetricsCondition{ Name: metricsName, Entity: entity, }, duration) - if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: utils.MetricsValuesToMap(duration, metricsValues)}) + return display.Display(ctx.Context, &displayable.Displayable{Data: utils.MetricsValuesToMap(duration, metricsValues)}) }, } diff --git a/internal/commands/metrics/linear/multiple-linear-metrics.go b/internal/commands/metrics/linear/multiple-linear-metrics.go index c94c1b89..966af2b5 100644 --- a/internal/commands/metrics/linear/multiple-linear-metrics.go +++ b/internal/commands/metrics/linear/multiple-linear-metrics.go @@ -93,7 +93,7 @@ $ swctl metrics multiple-linear --name all_percentile --labels=0,1,2,3,4 --relab case labelsString != "" && relabelsString != "" && len(labels) != len(relabels): return fmt.Errorf(`"--labels" and "--relabels" must be in same size if both specified, but was %v != %v`, len(labels), len(relabels)) case relabelsString != "": - for i := 0; i < len(labels); i++ { + for i := range labels { labelMapping[labels[i]] = relabels[i] } } @@ -113,16 +113,15 @@ $ swctl metrics multiple-linear --name all_percentile --labels=0,1,2,3,4 --relab Step: step.(*model.StepEnumValue).Selected, } - metricsValuesArray, err := metrics.MultipleLinearIntValues(ctx, api.MetricsCondition{ + metricsValuesArray, err := metrics.MultipleLinearIntValues(ctx.Context, api.MetricsCondition{ Name: metricsName, Entity: entity, }, labels, duration) - if err != nil { return err } reshaped := utils.MetricsValuesArrayToMap(duration, metricsValuesArray, labelMapping) - return display.Display(ctx, &displayable.Displayable{Data: reshaped}) + return display.Display(ctx.Context, &displayable.Displayable{Data: reshaped}) }, } diff --git a/internal/commands/metrics/list/list-metrics.go b/internal/commands/metrics/list/list-metrics.go index cdc15e7d..7d5e46cf 100644 --- a/internal/commands/metrics/list/list-metrics.go +++ b/internal/commands/metrics/list/list-metrics.go @@ -45,12 +45,11 @@ $ swctl metrics list --regex "service_.*"`, Action: func(ctx *cli.Context) error { regex := ctx.String("regex") - metricsValue, err := metrics.ListMetrics(ctx, regex) - + metricsValue, err := metrics.ListMetrics(ctx.Context, regex) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: metricsValue}) + return display.Display(ctx.Context, &displayable.Displayable{Data: metricsValue}) }, } diff --git a/internal/commands/metrics/single/nullable-metrics.go b/internal/commands/metrics/single/nullable-metrics.go index 58ebd3cd..6d74ef3b 100644 --- a/internal/commands/metrics/single/nullable-metrics.go +++ b/internal/commands/metrics/single/nullable-metrics.go @@ -71,15 +71,14 @@ $ swctl metrics nullable --name endpoint_cpm --service-name business-zone::proje Step: step.(*model.StepEnumValue).Selected, } - metricsValue, err := metrics.NullableIntValue(ctx, api.MetricsCondition{ + metricsValue, err := metrics.NullableIntValue(ctx.Context, api.MetricsCondition{ Name: metricsName, Entity: entity, }, duration) - if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: metricsValue}) + return display.Display(ctx.Context, &displayable.Displayable{Data: metricsValue}) }, } diff --git a/internal/commands/metrics/single/single-metrics.go b/internal/commands/metrics/single/single-metrics.go index f10dac5c..3650cca9 100644 --- a/internal/commands/metrics/single/single-metrics.go +++ b/internal/commands/metrics/single/single-metrics.go @@ -71,15 +71,14 @@ $ swctl metrics single --name endpoint_cpm --service-name business-zone::project Step: step.(*model.StepEnumValue).Selected, } - metricsValue, err := metrics.IntValues(ctx, api.MetricsCondition{ + metricsValue, err := metrics.IntValues(ctx.Context, api.MetricsCondition{ Name: metricsName, Entity: entity, }, duration) - if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: metricsValue}) + return display.Display(ctx.Context, &displayable.Displayable{Data: metricsValue}) }, } diff --git a/internal/commands/metrics/thermodynamic/thermodynamic.go b/internal/commands/metrics/thermodynamic/thermodynamic.go index dbc83038..b01b550a 100644 --- a/internal/commands/metrics/thermodynamic/thermodynamic.go +++ b/internal/commands/metrics/thermodynamic/thermodynamic.go @@ -70,16 +70,15 @@ $ swctl metrics thermodynamic --scope all --name all_heatmap Step: step.(*model.StepEnumValue).Selected, } - metricsValues, err := metrics.Thermodynamic(ctx, api.MetricsCondition{ + metricsValues, err := metrics.Thermodynamic(ctx.Context, api.MetricsCondition{ Name: metricsName, Entity: entity, }, duration) - if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{ + return display.Display(ctx.Context, &displayable.Displayable{ Data: metricsValues, Duration: duration, Title: metricsName, diff --git a/internal/commands/process/estimate/scale.go b/internal/commands/process/estimate/scale.go index 77d55099..5324741d 100644 --- a/internal/commands/process/estimate/scale.go +++ b/internal/commands/process/estimate/scale.go @@ -57,12 +57,11 @@ $ swctl process estimate scale --service-name abc --labels t1,t2`, labels = strings.Split(labelString, ",") } - scale, err := metadata.EstimateProcessScale(ctx, serviceID, labels) - + scale, err := metadata.EstimateProcessScale(ctx.Context, serviceID, labels) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: scale}) + return display.Display(ctx.Context, &displayable.Displayable{Data: scale}) }, } diff --git a/internal/commands/process/get.go b/internal/commands/process/get.go index e7a035a5..85e4db33 100644 --- a/internal/commands/process/get.go +++ b/internal/commands/process/get.go @@ -40,11 +40,11 @@ $ swctl process get 2b9e46c13c91803695a4364257415e523af7cbf17bf4058e025c16b944a6 return fmt.Errorf("process-id must be provided") } - instance, err := metadata.GetProcess(ctx, ctx.Args().First()) + instance, err := metadata.GetProcess(ctx.Context, ctx.Args().First()) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: instance}) + return display.Display(ctx.Context, &displayable.Displayable{Data: instance}) }, } diff --git a/internal/commands/process/list.go b/internal/commands/process/list.go index 3fea5e03..866118e8 100644 --- a/internal/commands/process/list.go +++ b/internal/commands/process/list.go @@ -57,7 +57,7 @@ $ swctl process ls --instance-id cHJvdmlkZXI=.1_cHJvdmlkZXIx`, start := ctx.String("start") step := ctx.Generic("step") - processes, err := metadata.Processes(ctx, instanceID, api.Duration{ + processes, err := metadata.Processes(ctx.Context, instanceID, api.Duration{ Start: start, End: end, Step: step.(*model.StepEnumValue).Selected, @@ -66,6 +66,6 @@ $ swctl process ls --instance-id cHJvdmlkZXI=.1_cHJvdmlkZXIx`, return err } - return display.Display(ctx, &displayable.Displayable{Data: processes}) + return display.Display(ctx.Context, &displayable.Displayable{Data: processes}) }, } diff --git a/internal/commands/profiling/asyncprofiler/create.go b/internal/commands/profiling/asyncprofiler/create.go index 5df43279..0113a7aa 100644 --- a/internal/commands/profiling/asyncprofiler/create.go +++ b/internal/commands/profiling/asyncprofiler/create.go @@ -85,11 +85,11 @@ $ swctl profiling async create --service-name=service-name --duration=60 --event Events: eventTypes, ExecArgs: execArgs, } - task, err := profiling.CreateAsyncProfilerTask(ctx, request) + task, err := profiling.CreateAsyncProfilerTask(ctx.Context, request) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: task, Condition: request}) + return display.Display(ctx.Context, &displayable.Displayable{Data: task, Condition: request}) }, } diff --git a/internal/commands/profiling/asyncprofiler/getAnalyze.go b/internal/commands/profiling/asyncprofiler/getAnalyze.go index c1b03879..6bd7146e 100644 --- a/internal/commands/profiling/asyncprofiler/getAnalyze.go +++ b/internal/commands/profiling/asyncprofiler/getAnalyze.go @@ -74,12 +74,11 @@ $ swctl profiling async analysis --service-name=service-name --task-id=task-id \ EventType: eventType, } - analyze, err := profiling.GetAsyncProfilerAnalyze(ctx, request) - + analyze, err := profiling.GetAsyncProfilerAnalyze(ctx.Context, request) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: analyze, Condition: request}) + return display.Display(ctx.Context, &displayable.Displayable{Data: analyze, Condition: request}) }, } diff --git a/internal/commands/profiling/asyncprofiler/getTaskList.go b/internal/commands/profiling/asyncprofiler/getTaskList.go index 554fac8f..157b7ed6 100644 --- a/internal/commands/profiling/asyncprofiler/getTaskList.go +++ b/internal/commands/profiling/asyncprofiler/getTaskList.go @@ -73,12 +73,11 @@ $ swctl profiling async list --service-name=service-name`, Limit: limit, } - tasks, err := profiling.GetAsyncProfilerTaskList(ctx, request) - + tasks, err := profiling.GetAsyncProfilerTaskList(ctx.Context, request) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: tasks, Condition: request}) + return display.Display(ctx.Context, &displayable.Displayable{Data: tasks, Condition: request}) }, } diff --git a/internal/commands/profiling/asyncprofiler/getTaskProgress.go b/internal/commands/profiling/asyncprofiler/getTaskProgress.go index 3943e84c..9bfa933d 100644 --- a/internal/commands/profiling/asyncprofiler/getTaskProgress.go +++ b/internal/commands/profiling/asyncprofiler/getTaskProgress.go @@ -44,12 +44,11 @@ $ swctl profiling async progress --task-id=task-id`, Action: func(ctx *cli.Context) error { taskID := ctx.String("task-id") - data, err := profiling.GetAsyncProfilerTaskProgress(ctx, taskID) - + data, err := profiling.GetAsyncProfilerTaskProgress(ctx.Context, taskID) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: data, Condition: taskID}) + return display.Display(ctx.Context, &displayable.Displayable{Data: data, Condition: taskID}) }, } diff --git a/internal/commands/profiling/continuous/list.go b/internal/commands/profiling/continuous/list.go index 77906384..cc06ca5d 100644 --- a/internal/commands/profiling/continuous/list.go +++ b/internal/commands/profiling/continuous/list.go @@ -46,11 +46,11 @@ $ swctl profiling continuous list --service-name=business-zone::projectC Action: func(ctx *cli.Context) error { serviceID := ctx.String("service-id") - result, err := profiling.QueryContinuousProfilingServiceTargets(ctx, serviceID) + result, err := profiling.QueryContinuousProfilingServiceTargets(ctx.Context, serviceID) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: result}) + return display.Display(ctx.Context, &displayable.Displayable{Data: result}) }, } diff --git a/internal/commands/profiling/continuous/monitoring.go b/internal/commands/profiling/continuous/monitoring.go index d8d81262..fc79613f 100644 --- a/internal/commands/profiling/continuous/monitoring.go +++ b/internal/commands/profiling/continuous/monitoring.go @@ -71,11 +71,11 @@ $ swctl profiling continuous monitoring --service-name=business-zone::projectC - return fmt.Errorf("unknown target type: %s", targetString) } - instances, err := profiling.QueryContinuousProfilingMonitoringInstances(ctx, serviceID, target) + instances, err := profiling.QueryContinuousProfilingMonitoringInstances(ctx.Context, serviceID, target) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: instances}) + return display.Display(ctx.Context, &displayable.Displayable{Data: instances}) }, } diff --git a/internal/commands/profiling/continuous/set.go b/internal/commands/profiling/continuous/set.go index 72991309..f4aff4ab 100644 --- a/internal/commands/profiling/continuous/set.go +++ b/internal/commands/profiling/continuous/set.go @@ -101,12 +101,12 @@ $ swctl profiling continuous set --service-name=abc --config=/path/to/config.yam Targets: targets, } - result, err := profiling.SetContinuousProfilingPolicy(ctx, request) + result, err := profiling.SetContinuousProfilingPolicy(ctx.Context, request) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: result, Condition: request}) + return display.Display(ctx.Context, &displayable.Displayable{Data: result, Condition: request}) }, } diff --git a/internal/commands/profiling/ebpf/analysis.go b/internal/commands/profiling/ebpf/analysis.go index 6698ff4c..d560f889 100644 --- a/internal/commands/profiling/ebpf/analysis.go +++ b/internal/commands/profiling/ebpf/analysis.go @@ -72,8 +72,8 @@ $ swctl profiling ebpf analysis --schedule-id=abc --time-ranges=1648020042869-16 timeRangeStr := ctx.String("time-ranges") var timeRanges []*api.EBPFProfilingAnalyzeTimeRange = nil if timeRangeStr != "" { - tagArr := strings.Split(timeRangeStr, ",") - for _, tag := range tagArr { + tagArr := strings.SplitSeq(timeRangeStr, ",") + for tag := range tagArr { kv := strings.Split(tag, "-") start, err := strconv.ParseInt(kv[0], 10, 64) if err != nil { @@ -88,11 +88,11 @@ $ swctl profiling ebpf analysis --schedule-id=abc --time-ranges=1648020042869-16 } aggregateType := ctx.Generic("aggregate").(*ebpf.ProfilingAnalyzeAggregateTypeEnumValue).Selected - analyzation, err := profiling.AnalysisEBPFProfilingResult(ctx, scheduleIDList, timeRanges, aggregateType) + analyzation, err := profiling.AnalysisEBPFProfilingResult(ctx.Context, scheduleIDList, timeRanges, aggregateType) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: analyzation}) + return display.Display(ctx.Context, &displayable.Displayable{Data: analyzation}) }, } diff --git a/internal/commands/profiling/ebpf/create/createByFixedTime.go b/internal/commands/profiling/ebpf/create/createByFixedTime.go index 436719cd..9b7c348f 100644 --- a/internal/commands/profiling/ebpf/create/createByFixedTime.go +++ b/internal/commands/profiling/ebpf/create/createByFixedTime.go @@ -89,12 +89,11 @@ $ swctl profiling ebpf fixed --service-id=abc --process-id=abc --duration=1m --t TargetType: ctx.Generic("target-type").(*ebpf.ProfilingTargetTypeEnumValue).Selected, } - task, err := profiling.CreateEBPFProfilingFixedTimeTask(ctx, request) - + task, err := profiling.CreateEBPFProfilingFixedTimeTask(ctx.Context, request) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: task, Condition: request}) + return display.Display(ctx.Context, &displayable.Displayable{Data: task, Condition: request}) }, } diff --git a/internal/commands/profiling/ebpf/create/network.go b/internal/commands/profiling/ebpf/create/network.go index b30c86b8..541c7cfa 100644 --- a/internal/commands/profiling/ebpf/create/network.go +++ b/internal/commands/profiling/ebpf/create/network.go @@ -82,7 +82,7 @@ $ swctl profiling ebpf create network --service-instance-id=abc`, samplingConfigFile := ctx.String("sampling-config") // convert the sampling rule - var samplings = make([]*api.EBPFNetworkSamplingRule, 0) + samplings := make([]*api.EBPFNetworkSamplingRule, 0) if samplingConfigFile != "" { config, err := os.ReadFile(samplingConfigFile) if err != nil { @@ -104,13 +104,12 @@ $ swctl profiling ebpf create network --service-instance-id=abc`, Samplings: samplings, } - task, err := profiling.CreateEBPFNetworkProfilingTask(ctx, request) - + task, err := profiling.CreateEBPFNetworkProfilingTask(ctx.Context, request) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: task, Condition: request}) + return display.Display(ctx.Context, &displayable.Displayable{Data: task, Condition: request}) }, } diff --git a/internal/commands/profiling/ebpf/create/prepareCreate.go b/internal/commands/profiling/ebpf/create/prepareCreate.go index f8067f42..d5342d27 100644 --- a/internal/commands/profiling/ebpf/create/prepareCreate.go +++ b/internal/commands/profiling/ebpf/create/prepareCreate.go @@ -45,11 +45,11 @@ $ swctl profiling ebpf create prepare --service-id=abc`, Action: func(ctx *cli.Context) error { serviceID := ctx.String("service-id") - prepare, err := profiling.QueryPrepareCreateEBPFProfilingTaskData(ctx, serviceID) + prepare, err := profiling.QueryPrepareCreateEBPFProfilingTaskData(ctx.Context, serviceID) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: prepare, Condition: serviceID}) + return display.Display(ctx.Context, &displayable.Displayable{Data: prepare, Condition: serviceID}) }, } diff --git a/internal/commands/profiling/ebpf/keep/network.go b/internal/commands/profiling/ebpf/keep/network.go index 8d86f6d0..7225e445 100644 --- a/internal/commands/profiling/ebpf/keep/network.go +++ b/internal/commands/profiling/ebpf/keep/network.go @@ -47,11 +47,11 @@ $ swctl profiling ebpf keep network --task-id=abc`, Action: func(ctx *cli.Context) error { taskID := ctx.String("task-id") - keepResult, err := profiling.KeepNetworkProfilingTask(ctx, taskID) + keepResult, err := profiling.KeepNetworkProfilingTask(ctx.Context, taskID) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: keepResult}) + return display.Display(ctx.Context, &displayable.Displayable{Data: keepResult}) }, } diff --git a/internal/commands/profiling/ebpf/list.go b/internal/commands/profiling/ebpf/list.go index 35dcd4fc..429e7a79 100644 --- a/internal/commands/profiling/ebpf/list.go +++ b/internal/commands/profiling/ebpf/list.go @@ -60,11 +60,13 @@ $ swctl profiling ebpf list --service-name=service-name Action: func(ctx *cli.Context) error { serviceID := ctx.String("service-id") - processes, err := profiling.QueryEBPFProfilingTaskList(ctx, serviceID, ctx.Generic("trigger").(*ebpf.ProfilingTriggerTypeEnumValue).Selected) + processes, err := profiling.QueryEBPFProfilingTaskList( + ctx.Context, serviceID, + ctx.Generic("trigger").(*ebpf.ProfilingTriggerTypeEnumValue).Selected) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: processes}) + return display.Display(ctx.Context, &displayable.Displayable{Data: processes}) }, } diff --git a/internal/commands/profiling/ebpf/schedules.go b/internal/commands/profiling/ebpf/schedules.go index 976b3bcd..7b6fa879 100644 --- a/internal/commands/profiling/ebpf/schedules.go +++ b/internal/commands/profiling/ebpf/schedules.go @@ -48,11 +48,11 @@ $ swctl profiling ebpf schedules --task-id=abc Action: func(ctx *cli.Context) error { taskID := ctx.String("task-id") - schedules, err := profiling.QueryEBPFProfilingScheduleList(ctx, taskID) + schedules, err := profiling.QueryEBPFProfilingScheduleList(ctx.Context, taskID) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: schedules}) + return display.Display(ctx.Context, &displayable.Displayable{Data: schedules}) }, } diff --git a/internal/commands/profiling/trace/create.go b/internal/commands/profiling/trace/create.go index 75ec402a..9466392c 100644 --- a/internal/commands/profiling/trace/create.go +++ b/internal/commands/profiling/trace/create.go @@ -81,12 +81,11 @@ $ swctl profiling trace create --service-name=service-name --endpoint=endpoint - MaxSamplingCount: ctx.Int("max-sampling-count"), } - task, err := profiling.CreateTraceTask(ctx, request) - + task, err := profiling.CreateTraceTask(ctx.Context, request) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: task, Condition: request}) + return display.Display(ctx.Context, &displayable.Displayable{Data: task, Condition: request}) }, } diff --git a/internal/commands/profiling/trace/getProfileAnalyze.go b/internal/commands/profiling/trace/getProfileAnalyze.go index 676e59ed..24b7411b 100644 --- a/internal/commands/profiling/trace/getProfileAnalyze.go +++ b/internal/commands/profiling/trace/getProfileAnalyze.go @@ -52,8 +52,8 @@ var getProfiledAnalyzeCommand = &cli.Command{ tagStr := ctx.String("time-ranges") var queries []*api.SegmentProfileAnalyzeQuery = nil if tagStr != "" { - tagArr := strings.Split(tagStr, ",") - for _, tag := range tagArr { + tagArr := strings.SplitSeq(tagStr, ",") + for tag := range tagArr { kv := strings.Split(tag, "-") start, err := strconv.ParseInt(kv[0], 10, 64) if err != nil { @@ -76,12 +76,11 @@ var getProfiledAnalyzeCommand = &cli.Command{ } } - analysis, err := profiling.GetTraceProfilingAnalyze(ctx, queries) - + analysis, err := profiling.GetTraceProfilingAnalyze(ctx.Context, queries) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: analysis, Condition: segmentIDs}) + return display.Display(ctx.Context, &displayable.Displayable{Data: analysis, Condition: segmentIDs}) }, } diff --git a/internal/commands/profiling/trace/getTaskList.go b/internal/commands/profiling/trace/getTaskList.go index 840be061..9235a06e 100644 --- a/internal/commands/profiling/trace/getTaskList.go +++ b/internal/commands/profiling/trace/getTaskList.go @@ -49,12 +49,11 @@ $ swctl profiling trace list --service-name=business-zone::projectC --endpoint-n serviceID := ctx.String("service-id") endpoint := ctx.String("endpoint-name") - task, err := profiling.GetTraceProfilingTaskList(ctx, serviceID, endpoint) - + task, err := profiling.GetTraceProfilingTaskList(ctx.Context, serviceID, endpoint) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: task, Condition: serviceID}) + return display.Display(ctx.Context, &displayable.Displayable{Data: task, Condition: serviceID}) }, } diff --git a/internal/commands/profiling/trace/getTaskLogs.go b/internal/commands/profiling/trace/getTaskLogs.go index 2c23219b..8c115b39 100644 --- a/internal/commands/profiling/trace/getTaskLogs.go +++ b/internal/commands/profiling/trace/getTaskLogs.go @@ -43,12 +43,11 @@ $ swctl profiling trace logs --task-id=task-id`, Action: func(ctx *cli.Context) error { taskID := ctx.String("task-id") - task, err := profiling.GetTraceProfilingTaskLogList(ctx, taskID) - + task, err := profiling.GetTraceProfilingTaskLogList(ctx.Context, taskID) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: task, Condition: taskID}) + return display.Display(ctx.Context, &displayable.Displayable{Data: task, Condition: taskID}) }, } diff --git a/internal/commands/profiling/trace/getTaskSegmentList.go b/internal/commands/profiling/trace/getTaskSegmentList.go index 58b78dd9..e622eae8 100644 --- a/internal/commands/profiling/trace/getTaskSegmentList.go +++ b/internal/commands/profiling/trace/getTaskSegmentList.go @@ -42,12 +42,11 @@ $ swctl profiling trace segment-list --service-name=service-name --endpoint-name }, Action: func(ctx *cli.Context) error { taskID := ctx.String("task-id") - segmentList, err := profiling.GetTraceProfilingTaskSegmentList(ctx, taskID) - + segmentList, err := profiling.GetTraceProfilingTaskSegmentList(ctx.Context, taskID) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: segmentList, Condition: taskID}) + return display.Display(ctx.Context, &displayable.Displayable{Data: segmentList, Condition: taskID}) }, } diff --git a/internal/commands/service/layer.go b/internal/commands/service/layer.go index ec5ce3e4..7213d2b3 100644 --- a/internal/commands/service/layer.go +++ b/internal/commands/service/layer.go @@ -45,11 +45,11 @@ $ swctl svc ly GENERAL`, if args := ctx.Args(); args.Len() == 0 { return fmt.Errorf("layer must be provide") } - services, err := metadata.ListLayerService(ctx, ctx.Args().First()) + services, err := metadata.ListLayerService(ctx.Context, ctx.Args().First()) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: services}) + return display.Display(ctx.Context, &displayable.Displayable{Data: services}) }, } diff --git a/internal/commands/service/list.go b/internal/commands/service/list.go index 516a6a79..4c3caf0a 100644 --- a/internal/commands/service/list.go +++ b/internal/commands/service/list.go @@ -57,7 +57,7 @@ $ swctl svc ls projectC`, var err error if args := ctx.Args(); args.Len() == 0 { - services, err = metadata.AllServices(ctx, api.Duration{ + services, err = metadata.AllServices(ctx.Context, api.Duration{ Start: start, End: end, Step: step.(*model.StepEnumValue).Selected, @@ -66,13 +66,13 @@ $ swctl svc ls projectC`, return err } } else { - service, err := metadata.SearchService(ctx, args.First()) + service, err := metadata.SearchService(ctx.Context, args.First()) if err != nil { return err } services = []api.Service{service} } - return display.Display(ctx, &displayable.Displayable{Data: services}) + return display.Display(ctx.Context, &displayable.Displayable{Data: services}) }, } diff --git a/internal/commands/trace/list.go b/internal/commands/trace/list.go index b480ee7a..6160bb2a 100644 --- a/internal/commands/trace/list.go +++ b/internal/commands/trace/list.go @@ -98,8 +98,8 @@ $ swctl trace ls --trace-id "321661b1-9a31-4e12-ad64-c8f6711f108d" tagStr := ctx.String("tags") var tags []*api.SpanTag = nil if tagStr != "" { - tagArr := strings.Split(tagStr, ",") - for _, tag := range tagArr { + tagArr := strings.SplitSeq(tagStr, ",") + for tag := range tagArr { kv := strings.Split(tag, "=") tags = append(tags, &api.SpanTag{Key: kv[0], Value: &kv[1]}) } @@ -134,12 +134,11 @@ $ swctl trace ls --trace-id "321661b1-9a31-4e12-ad64-c8f6711f108d" Tags: tags, Paging: &paging, } - traces, err := trace.Traces(ctx, condition) - + traces, err := trace.Traces(ctx.Context, condition) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: traces, Condition: condition}) + return display.Display(ctx.Context, &displayable.Displayable{Data: traces, Condition: condition}) }, } diff --git a/internal/commands/trace/trace.go b/internal/commands/trace/trace.go index a6614c80..f7f31a09 100644 --- a/internal/commands/trace/trace.go +++ b/internal/commands/trace/trace.go @@ -44,13 +44,12 @@ $ swctl trace "321661b1-9a31-4e12-ad64-c8f6711f108d"`, return fmt.Errorf("command trace without sub command requires 1 trace id as argument") } - trace, err := trace.Trace(ctx, ctx.Args().First()) - + trace, err := trace.Trace(ctx.Context, ctx.Args().First()) if err != nil { return err } - return display.Display(ctx, &displayable.Displayable{Data: trace}) + return display.Display(ctx.Context, &displayable.Displayable{Data: trace}) }, Subcommands: cli.Commands{ ListCommand, diff --git a/internal/display/display.go b/internal/display/display.go new file mode 100644 index 00000000..e1b783d6 --- /dev/null +++ b/internal/display/display.go @@ -0,0 +1,75 @@ +// Licensed to Apache Software Foundation (ASF) under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Apache Software Foundation (ASF) licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package display + +import ( + "context" + + "github.com/apache/skywalking-cli/pkg/contextkey" + "github.com/apache/skywalking-cli/pkg/display" + d "github.com/apache/skywalking-cli/pkg/display/displayable" + + "github.com/urfave/cli/v2" +) + +// The variable style sets the output style for the command. +var style = map[string]string{ + "dashboard global": "graph", + "dashboard global-metrics": "graph", + "metrics top": "table", + "metrics sorted": "table", + "metrics linear": "graph", + "metrics list": "table", + "service list": "table", + "t": "graph", + "trace": "graph", + "ebpf analysis": "graph", + "trace analysis": "graph", +} + +// Display the object in the style specified in flag --display +func Display(cliCtx *cli.Context, displayable *d.Displayable) error { + displayStyle := cliCtx.String("display") + if displayStyle == "" { + commandFullName := cliCtx.Command.FullName() + if commandFullName != "" { + displayStyle = getDisplayStyle(commandFullName) + } else { + for _, c := range cliCtx.Lineage() { + if s := getDisplayStyle(c.Args().First()); s != "" { + displayStyle = s + break + } + } + } + } + if displayStyle == "" { + displayStyle = "json" + } + ctx := cliCtx.Context + ctx = context.WithValue(ctx, contextkey.Display{}, displayStyle) + return display.Display(ctx, displayable) +} + +// getDisplayStyle gets the default display settings. +func getDisplayStyle(fullName string) string { + if command, ok := style[fullName]; ok { + return command + } + return "" +} diff --git a/pkg/util/commandNotFound.go b/internal/util/commandNotFound.go similarity index 100% rename from pkg/util/commandNotFound.go rename to internal/util/commandNotFound.go diff --git a/pkg/util/commandNotFound_test.go b/internal/util/commandNotFound_test.go similarity index 100% rename from pkg/util/commandNotFound_test.go rename to internal/util/commandNotFound_test.go diff --git a/pkg/contextkey/contextkey.go b/pkg/contextkey/contextkey.go new file mode 100644 index 00000000..0f5380e2 --- /dev/null +++ b/pkg/contextkey/contextkey.go @@ -0,0 +1,38 @@ +// Licensed to Apache Software Foundation (ASF) under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Apache Software Foundation (ASF) licenses this file to you under +// the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package contextkey + +type ( + BaseURL struct{} + Username struct{} + Password struct{} + Authorization struct{} +) + +type ( + DurationStart struct{} + DurationEnd struct{} + DurationStep struct{} + DurationType struct{} +) + +type ( + Display struct{} + DashboardTemplate struct{} + DashboardRefreshInterval struct{} +) diff --git a/pkg/display/display.go b/pkg/display/display.go index 6e3f8226..8ac7f16d 100644 --- a/pkg/display/display.go +++ b/pkg/display/display.go @@ -18,16 +18,15 @@ package display import ( + "context" "fmt" - "strings" + "github.com/apache/skywalking-cli/pkg/contextkey" d "github.com/apache/skywalking-cli/pkg/display/displayable" "github.com/apache/skywalking-cli/pkg/display/graph" - "github.com/urfave/cli/v2" - "github.com/apache/skywalking-cli/pkg/display/json" "github.com/apache/skywalking-cli/pkg/display/table" "github.com/apache/skywalking-cli/pkg/display/yaml" @@ -40,36 +39,9 @@ const ( GRAPH = "graph" ) -// The variable style sets the output style for the command. -var style = map[string]string{"dashboard global": "graph", - "dashboard global-metrics": "graph", - "metrics top": "table", - "metrics sorted": "table", - "metrics linear": "graph", - "metrics list": "table", - "service list": "table", - "t": "graph", - "trace": "graph", - "ebpf analysis": "graph", - "trace analysis": "graph", -} - // Display the object in the style specified in flag --display -func Display(ctx *cli.Context, displayable *d.Displayable) error { - displayStyle := ctx.String("display") - if displayStyle == "" { - commandFullName := ctx.Command.FullName() - if commandFullName != "" { - displayStyle = getDisplayStyle(commandFullName) - } else { - for _, c := range ctx.Lineage() { - if s := getDisplayStyle(c.Args().First()); s != "" { - displayStyle = s - break - } - } - } - } +func Display(ctx context.Context, displayable *d.Displayable) error { + displayStyle := ctx.Value(contextkey.Display{}).(string) if displayStyle == "" { displayStyle = "json" } @@ -86,11 +58,3 @@ func Display(ctx *cli.Context, displayable *d.Displayable) error { return fmt.Errorf("unsupported display style: %s", displayStyle) } } - -// getDisplayStyle gets the default display settings. -func getDisplayStyle(fullName string) string { - if command, ok := style[fullName]; ok { - return command - } - return "" -} diff --git a/pkg/display/graph/dashboard/global.go b/pkg/display/graph/dashboard/global.go index b7f86823..1a5a10bb 100644 --- a/pkg/display/graph/dashboard/global.go +++ b/pkg/display/graph/dashboard/global.go @@ -27,6 +27,7 @@ import ( api "skywalking.apache.org/repo/goapi/query" "github.com/apache/skywalking-cli/internal/commands/interceptor" + "github.com/apache/skywalking-cli/pkg/contextkey" "github.com/apache/skywalking-cli/pkg/graphql/utils" lib "github.com/apache/skywalking-cli/pkg/heatmap" @@ -36,9 +37,7 @@ import ( "github.com/mum4k/termdash/linestyle" "github.com/mum4k/termdash/terminal/termbox" "github.com/mum4k/termdash/terminal/terminalapi" - "github.com/urfave/cli/v2" - "github.com/apache/skywalking-cli/internal/model" "github.com/apache/skywalking-cli/pkg/display/graph/gauge" "github.com/apache/skywalking-cli/pkg/display/graph/heatmap" "github.com/apache/skywalking-cli/pkg/display/graph/linear" @@ -88,12 +87,16 @@ var template *dashboard.GlobalTemplate var allWidgets *widgets -var initStartStr string -var initStep = api.StepMinute -var initEndStr string +var ( + initStartStr string + initStep = api.StepMinute + initEndStr string +) -var curStartTime time.Time -var curEndTime time.Time +var ( + curStartTime time.Time + curEndTime time.Time +) // setLayout sets the specified layout. func setLayout(c *container.Container, lt layoutType) error { @@ -231,7 +234,7 @@ func newWidgets(data *dashboard.GlobalData) error { return nil } -func Display(ctx *cli.Context, data *dashboard.GlobalData) error { +func Display(ctx context.Context, data *dashboard.GlobalData) error { t, err := termbox.New(termbox.ColorMode(terminalapi.ColorMode256)) if err != nil { return err @@ -247,7 +250,7 @@ func Display(ctx *cli.Context, data *dashboard.GlobalData) error { return err } - te, err := dashboard.LoadTemplate(ctx.String("template")) + te, err := dashboard.LoadTemplate(ctx.Value(contextkey.DashboardTemplate{}).(string)) if err != nil { return err } @@ -279,22 +282,23 @@ func Display(ctx *cli.Context, data *dashboard.GlobalData) error { return e } - con, cancel := context.WithCancel(context.Background()) + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) quitter := func(keyboard *terminalapi.Keyboard) { if strings.EqualFold(keyboard.Key.String(), "q") { cancel() } } - refreshInterval := time.Duration(ctx.Int("refresh")) * time.Second - dt := utils.DurationType(ctx.String("duration-type")) + refreshInterval := time.Duration(ctx.Value(contextkey.DashboardRefreshInterval{}).(int)) * time.Second + dt := ctx.Value(contextkey.DurationType{}).(utils.DurationType) // Only when users use the relative time, the duration will be adjusted to refresh. if dt != utils.BothPresent { - go refresh(con, ctx, refreshInterval) + go refresh(ctx, refreshInterval) } - err = termdash.Run(con, t, c, termdash.KeyboardSubscriber(quitter), termdash.RedrawInterval(refreshInterval)) + err = termdash.Run(ctx, t, c, termdash.KeyboardSubscriber(quitter), termdash.RedrawInterval(refreshInterval)) return err } @@ -312,16 +316,13 @@ func longestString(strs []string) (ret string) { } // refresh updates the duration and query the new data to update all of widgets, once every delay. -func refresh(con context.Context, ctx *cli.Context, interval time.Duration) { +func refresh(ctx context.Context, interval time.Duration) { ticker := time.NewTicker(interval) defer ticker.Stop() - initStartStr = ctx.String("start") - initEndStr = ctx.String("end") - - if s := ctx.Generic("step"); s != nil { - initStep = s.(*model.StepEnumValue).Selected - } + initStartStr = ctx.Value(contextkey.DurationStart{}).(string) + initEndStr = ctx.Value(contextkey.DurationEnd{}).(string) + initStep = ctx.Value(contextkey.DurationStep{}).(api.Step) _, start, err := interceptor.TryParseTime(initStartStr, initStep) if err != nil { @@ -351,7 +352,7 @@ func refresh(con context.Context, ctx *cli.Context, interval time.Duration) { if err := updateAllWidgets(data); err != nil { continue } - case <-con.Done(): + case <-ctx.Done(): return } } diff --git a/pkg/display/graph/flamegraph/adapter.go b/pkg/display/graph/flamegraph/adapter.go index d12cd640..a71c545f 100644 --- a/pkg/display/graph/flamegraph/adapter.go +++ b/pkg/display/graph/flamegraph/adapter.go @@ -63,11 +63,11 @@ func (e *traceStackElementAdapter) ParentID() string { } func (e *traceStackElementAdapter) DumpCount() int64 { - return int64(e.ProfileStackElement.Count) + return int64(e.Count) } func (e *traceStackElementAdapter) Symbol() string { - return e.ProfileStackElement.CodeSignature + return e.CodeSignature } func (e *traceStackElementAdapter) StackType() StackType { diff --git a/pkg/display/graph/flamegraph/flamegraph.go b/pkg/display/graph/flamegraph/flamegraph.go index b4afddf9..4eb1c8df 100644 --- a/pkg/display/graph/flamegraph/flamegraph.go +++ b/pkg/display/graph/flamegraph/flamegraph.go @@ -19,6 +19,7 @@ package flamegraph import ( "bytes" + "context" "fmt" "html/template" "os" @@ -28,11 +29,9 @@ import ( "github.com/apache/skywalking-cli/internal/logger" api "skywalking.apache.org/repo/goapi/query" - - "github.com/urfave/cli/v2" ) -func DisplayByTrace(ctx *cli.Context, analysis api.ProfileAnalyzation) error { +func DisplayByTrace(ctx context.Context, analysis api.ProfileAnalyzation) error { trees := make([]*ProfilingDataTree, 0) for _, tree := range analysis.Trees { elements := make([]ProfilingDataStackElement, 0) @@ -45,7 +44,7 @@ func DisplayByTrace(ctx *cli.Context, analysis api.ProfileAnalyzation) error { return display(ctx, trees) } -func DisplayByEBPF(ctx *cli.Context, analysis *api.EBPFProfilingAnalyzation) error { +func DisplayByEBPF(ctx context.Context, analysis *api.EBPFProfilingAnalyzation) error { trees := make([]*ProfilingDataTree, 0) for _, tree := range analysis.Trees { elements := make([]ProfilingDataStackElement, 0) @@ -58,7 +57,7 @@ func DisplayByEBPF(ctx *cli.Context, analysis *api.EBPFProfilingAnalyzation) err return display(ctx, trees) } -func display(_ *cli.Context, trees []*ProfilingDataTree) error { +func display(_ context.Context, trees []*ProfilingDataTree) error { if len(trees) == 0 { return fmt.Errorf("could not find the analysis data") } @@ -70,7 +69,7 @@ func display(_ *cli.Context, trees []*ProfilingDataTree) error { } // build data - data := make(map[string]interface{}) + data := make(map[string]any) elements, maxDepth := buildFlameGraphElements(trees) data["elements"] = elements data["maxDepth"] = maxDepth + 1 @@ -80,7 +79,7 @@ func display(_ *cli.Context, trees []*ProfilingDataTree) error { return renderFlameGraphAndWrite(flameGraphPath, data) } -func renderFlameGraphAndWrite(path string, data map[string]interface{}) error { +func renderFlameGraphAndWrite(path string, data map[string]any) error { // render template var b bytes.Buffer tmpl, err := template.New("flameGraphTemplate").Parse(flameGraphHTML) @@ -141,7 +140,8 @@ func buildFlameGraphElements(trees []*ProfilingDataTree) (result []*StackElement } func buildFlameGraphChildElements(renderElements []*StackElement, dataElements []ProfilingDataStackElement, - parent *StackElement, relativeLeft int64) (result []*StackElement, left int64) { + parent *StackElement, relativeLeft int64, +) (result []*StackElement, left int64) { parentID := "0" var depth int64 = 1 left = relativeLeft diff --git a/pkg/display/graph/gauge/gauge.go b/pkg/display/graph/gauge/gauge.go index e0ac6968..3e91e722 100644 --- a/pkg/display/graph/gauge/gauge.go +++ b/pkg/display/graph/gauge/gauge.go @@ -26,8 +26,7 @@ import ( api "skywalking.apache.org/repo/goapi/query" - "github.com/urfave/cli/v2" - + "github.com/apache/skywalking-cli/pkg/contextkey" "github.com/apache/skywalking-cli/pkg/graphql/dashboard" "github.com/apache/skywalking-cli/pkg/util" @@ -162,7 +161,7 @@ func MetricColumnsElement(columns []*MetricColumn) []grid.Element { columnWidthPerc = 99 } - for i := 0; i < columnNum; i++ { + for i := range columnNum { var column []grid.Element column = append(column, grid.RowHeightPerc(TitleHeight, grid.Widget(columns[i].title))) @@ -171,7 +170,7 @@ func MetricColumnsElement(columns []*MetricColumn) []grid.Element { gaugeNum := int(math.Min(MaxGaugeNum, float64(len(columns[i].gauges)))) gaugeHeight := int(math.Floor(float64(99-TitleHeight) / float64(gaugeNum))) - for j := 0; j < gaugeNum; j++ { + for j := range gaugeNum { column = append(column, grid.RowHeightPerc(gaugeHeight, grid.Widget(columns[i].gauges[j]))) } metricColumns = append(metricColumns, grid.ColWidthPerc(columnWidthPerc, column...)) @@ -194,7 +193,7 @@ func layout(columns []grid.Element) ([]container.Option, error) { return gridOpts, nil } -func Display(ctx *cli.Context, metrics [][]*api.SelectedRecord) error { +func Display(ctx context.Context, metrics [][]*api.SelectedRecord) error { t, err := termbox.New() if err != nil { return err @@ -211,7 +210,7 @@ func Display(ctx *cli.Context, metrics [][]*api.SelectedRecord) error { var columns []*MetricColumn - configs, err := dashboard.LoadTemplate(ctx.String("template")) + configs, err := dashboard.LoadTemplate(ctx.Value(contextkey.DashboardTemplate{}).(string)) if err != nil { return nil } @@ -234,7 +233,6 @@ func Display(ctx *cli.Context, metrics [][]*api.SelectedRecord) error { container.Border(linestyle.Light), container.BorderTitle("[Global Metrics]-PRESS Q TO QUIT"))..., ) - if err != nil { return err } diff --git a/pkg/display/graph/graph.go b/pkg/display/graph/graph.go index 64c850c6..09efb47e 100644 --- a/pkg/display/graph/graph.go +++ b/pkg/display/graph/graph.go @@ -18,6 +18,7 @@ package graph import ( + "context" "fmt" "reflect" @@ -25,8 +26,6 @@ import ( api "skywalking.apache.org/repo/goapi/query" - "github.com/urfave/cli/v2" - d "github.com/apache/skywalking-cli/pkg/display/displayable" db "github.com/apache/skywalking-cli/pkg/display/graph/dashboard" "github.com/apache/skywalking-cli/pkg/display/graph/gauge" @@ -60,7 +59,7 @@ var ( TraceProfilingAnalysisDataType = reflect.TypeOf(TraceProfilingAnalysis{}) ) -func Display(ctx *cli.Context, displayable *d.Displayable) error { +func Display(ctx context.Context, displayable *d.Displayable) error { data := displayable.Data switch reflect.TypeOf(data) { diff --git a/pkg/display/graph/linear/linear.go b/pkg/display/graph/linear/linear.go index ce4a29d1..78ee6399 100644 --- a/pkg/display/graph/linear/linear.go +++ b/pkg/display/graph/linear/linear.go @@ -33,8 +33,6 @@ import ( "github.com/mum4k/termdash/terminal/termbox" "github.com/mum4k/termdash/terminal/terminalapi" "github.com/mum4k/termdash/widgets/linechart" - - "github.com/urfave/cli/v2" ) const RootID = "root" @@ -95,7 +93,7 @@ func LineChartElements(lineCharts map[string]*linechart.LineChart) [][]grid.Elem charts = append(charts, lineCharts[title]) } - for r := 0; r < len(rows); r++ { + for r := range rows { var row []grid.Element for c := 0; c < cols && r*cols+c < len(lineCharts); c++ { percentage := int(math.Floor(float64(100) / float64(cols))) @@ -133,7 +131,7 @@ func layout(rows [][]grid.Element) ([]container.Option, error) { return builder.Build() } -func Display(cliCtx *cli.Context, inputs map[string]map[string]*displayable.MetricValue) error { +func Display(ctx context.Context, inputs map[string]map[string]*displayable.MetricValue) error { t, err := termbox.New() if err != nil { return err @@ -166,15 +164,15 @@ func Display(cliCtx *cli.Context, inputs map[string]map[string]*displayable.Metr err = c.Update(RootID, append( gridOpts, container.Border(linestyle.Light), - container.BorderTitle(fmt.Sprintf("[%s]-PRESS Q TO QUIT", cliCtx.String("name"))), + container.BorderTitle(fmt.Sprintf("[%s]-PRESS Q TO QUIT", ctx.Value("name").(string))), container.BorderTitleAlignLeft())..., ) - if err != nil { return err } - ctx, cancel := context.WithCancel(context.Background()) + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) quitter := func(keyboard *terminalapi.Keyboard) { if strings.EqualFold(keyboard.Key.String(), "q") { cancel() diff --git a/pkg/display/graph/tree/list.go b/pkg/display/graph/tree/list.go index 84e20606..89cd4c87 100644 --- a/pkg/display/graph/tree/list.go +++ b/pkg/display/graph/tree/list.go @@ -18,6 +18,7 @@ package tree import ( + "context" "fmt" "strings" @@ -28,17 +29,18 @@ import ( ui "github.com/gizak/termui/v3" "github.com/gizak/termui/v3/widgets" - "github.com/urfave/cli/v2" "github.com/apache/skywalking-cli/internal/logger" ) -const DefaultPageSize = 15 -const KeyMap = " Keymap " -const Detail = " Detail " -const Quit = "" +const ( + DefaultPageSize = 15 + KeyMap = " Keymap " + Detail = " Detail " + Quit = "" +) -func DisplayList(ctx *cli.Context, displayable *d.Displayable) error { +func DisplayList(ctx context.Context, displayable *d.Displayable) error { data := displayable.Data.(api.TraceBrief) condition := displayable.Condition.(*api.TraceQueryCondition) if err := ui.Init(); err != nil { @@ -84,19 +86,20 @@ func DisplayList(ctx *cli.Context, displayable *d.Displayable) error { detail.Title = Detail detail.WrapText = false - draw(list, tree, detail, help, data, ctx, condition) - listenTracesKeyboard(list, tree, data, ctx, detail, help, condition) + draw(ctx, list, tree, detail, help, data, condition) + listenTracesKeyboard(ctx, list, tree, data, detail, help, condition) return nil } -func draw(list *widgets.List, tree *widgets.Tree, detail, help *widgets.Paragraph, data api.TraceBrief, - ctx *cli.Context, _ *api.TraceQueryCondition) { +func draw(ctx context.Context, list *widgets.List, tree *widgets.Tree, detail, help *widgets.Paragraph, data api.TraceBrief, + _ *api.TraceQueryCondition, +) { x, y := ui.TerminalDimensions() if len(data.Traces) != 0 { showIndex := list.SelectedRow - var traceID = data.Traces[showIndex].TraceIds[0] + traceID := data.Traces[showIndex].TraceIds[0] list.Title = fmt.Sprintf("[%s]", traceID) nodes, serviceNames := getNodeData(ctx, traceID) tree.Title = fmt.Sprintf("[%s]", strings.Join(serviceNames, "->")) @@ -119,8 +122,9 @@ func draw(list *widgets.List, tree *widgets.Tree, detail, help *widgets.Paragrap ui.Render(list, tree, detail, help) } -func listenTracesKeyboard(list *widgets.List, tree *widgets.Tree, data api.TraceBrief, ctx *cli.Context, - detail, help *widgets.Paragraph, condition *api.TraceQueryCondition) { +func listenTracesKeyboard(ctx context.Context, list *widgets.List, tree *widgets.Tree, data api.TraceBrief, + detail, help *widgets.Paragraph, condition *api.TraceQueryCondition, +) { uiEvents := ui.PollEvents() listActive := true var err error @@ -160,7 +164,7 @@ func listenTracesKeyboard(list *widgets.List, tree *widgets.Tree, data api.Trace } } - draw(list, tree, detail, help, data, ctx, condition) + draw(ctx, list, tree, detail, help, data, condition) } } @@ -198,9 +202,8 @@ func listActions(key string, list *widgets.List, tree *widgets.Tree, listActive return f } -func getNodeData(ctx *cli.Context, traceID string) (nodes []*widgets.TreeNode, serviceNames []string) { +func getNodeData(ctx context.Context, traceID string) (nodes []*widgets.TreeNode, serviceNames []string) { data, err := trace.Trace(ctx, traceID) - if err != nil { logger.Log.Fatalln(err) } diff --git a/pkg/graphql/alarm/alarm.go b/pkg/graphql/alarm/alarm.go index 87d6ad32..1e3a93a9 100644 --- a/pkg/graphql/alarm/alarm.go +++ b/pkg/graphql/alarm/alarm.go @@ -18,13 +18,13 @@ package alarm import ( + "context" + "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" - api "skywalking.apache.org/repo/goapi/query" ) @@ -36,7 +36,7 @@ type ListAlarmCondition struct { Paging *api.Pagination } -func Alarms(ctx *cli.Context, condition *ListAlarmCondition) (api.Alarms, error) { +func Alarms(ctx context.Context, condition *ListAlarmCondition) (api.Alarms, error) { var response map[string]api.Alarms request := graphql.NewRequest(assets.Read("graphqls/alarm/alarms.graphql")) @@ -53,7 +53,7 @@ func Alarms(ctx *cli.Context, condition *ListAlarmCondition) (api.Alarms, error) return response["result"], err } -func TagAutocompleteKeys(ctx *cli.Context, duration api.Duration) ([]string, error) { +func TagAutocompleteKeys(ctx context.Context, duration api.Duration) ([]string, error) { var response map[string][]string request := graphql.NewRequest(assets.Read("graphqls/alarm/tagAutocompleteKeys.graphql")) @@ -64,7 +64,7 @@ func TagAutocompleteKeys(ctx *cli.Context, duration api.Duration) ([]string, err return response["result"], err } -func TagAutocompleteValues(ctx *cli.Context, duration api.Duration, key string) ([]string, error) { +func TagAutocompleteValues(ctx context.Context, duration api.Duration, key string) ([]string, error) { var response map[string][]string request := graphql.NewRequest(assets.Read("graphqls/alarm/tagAutocompleteValues.graphql")) diff --git a/pkg/graphql/client/client.go b/pkg/graphql/client/client.go index f265fbc2..40b49473 100644 --- a/pkg/graphql/client/client.go +++ b/pkg/graphql/client/client.go @@ -22,13 +22,13 @@ import ( "encoding/base64" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" "github.com/apache/skywalking-cli/internal/logger" + "github.com/apache/skywalking-cli/pkg/contextkey" ) -func newClient(cliCtx *cli.Context) (client *graphql.Client) { - client = graphql.NewClient(cliCtx.String("base-url")) +func newClient(ctx context.Context) (client *graphql.Client) { + client = graphql.NewClient(ctx.Value(contextkey.BaseURL{}).(string)) client.Log = func(msg string) { logger.Log.Debugln(msg) } @@ -36,10 +36,10 @@ func newClient(cliCtx *cli.Context) (client *graphql.Client) { } // ExecuteQuery executes the `request` and parse to the `response`, returning `error` if there is any. -func ExecuteQuery(cliCtx *cli.Context, request *graphql.Request, response interface{}) error { - username := cliCtx.String("username") - password := cliCtx.String("password") - authorization := cliCtx.String("authorization") +func ExecuteQuery(ctx context.Context, request *graphql.Request, response any) error { + username := ctx.Value(contextkey.Username{}).(string) + password := ctx.Value(contextkey.Password{}).(string) + authorization := ctx.Value(contextkey.Authorization{}).(string) if authorization == "" && username != "" && password != "" { authorization = "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password)) } @@ -47,8 +47,7 @@ func ExecuteQuery(cliCtx *cli.Context, request *graphql.Request, response interf request.Header.Set("Authorization", authorization) } - client := newClient(cliCtx) - ctx := context.Background() + client := newClient(ctx) err := client.Run(ctx, request, response) return err } diff --git a/pkg/graphql/common/common.go b/pkg/graphql/common/common.go index 4a17d19e..1cd4606e 100644 --- a/pkg/graphql/common/common.go +++ b/pkg/graphql/common/common.go @@ -18,15 +18,15 @@ package common import ( - "github.com/machinebox/graphql" + "context" - "github.com/urfave/cli/v2" + "github.com/machinebox/graphql" "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" ) -func Version(ctx *cli.Context) (string, error) { +func Version(ctx context.Context) (string, error) { var response map[string]string request := graphql.NewRequest(assets.Read("graphqls/common/version.graphql")) diff --git a/pkg/graphql/dashboard/global.go b/pkg/graphql/dashboard/global.go index 5b5adc58..3c9c1d16 100644 --- a/pkg/graphql/dashboard/global.go +++ b/pkg/graphql/dashboard/global.go @@ -19,10 +19,12 @@ package dashboard import ( "bytes" + "context" "os" "strings" "sync" + "github.com/apache/skywalking-cli/pkg/contextkey" "github.com/apache/skywalking-cli/pkg/display/displayable" "golang.org/x/text/cases" @@ -30,7 +32,6 @@ import ( api "skywalking.apache.org/repo/goapi/query" "github.com/spf13/viper" - "github.com/urfave/cli/v2" "gopkg.in/yaml.v2" @@ -77,8 +78,10 @@ type GlobalData struct { // Use singleton pattern to make sure to load template only once. var globalTemplate *GlobalTemplate -const templateType = "yml" -const DefaultTemplatePath = "templates/dashboard/global.yml" +const ( + templateType = "yml" + DefaultTemplatePath = "templates/dashboard/global.yml" +) // newGlobalTemplate create a new GlobalTemplate and set default values for buttons' template. func newGlobalTemplate() GlobalTemplate { @@ -131,7 +134,7 @@ func LoadTemplate(filename string) (*GlobalTemplate, error) { func getButtonTexts(byteValue []byte) ([]string, error) { var ret []string - c := make(map[string]interface{}) + c := make(map[string]any) if err := yaml.Unmarshal(byteValue, &c); err != nil { return nil, err } @@ -144,10 +147,10 @@ func getButtonTexts(byteValue []byte) ([]string, error) { return ret, nil } -func Metrics(ctx *cli.Context, duration api.Duration) ([][]*api.SelectedRecord, error) { +func Metrics(ctx context.Context, duration api.Duration) ([][]*api.SelectedRecord, error) { var ret [][]*api.SelectedRecord - template, err := LoadTemplate(ctx.String("template")) + template, err := LoadTemplate(ctx.Value(contextkey.DashboardTemplate{}).(string)) if err != nil { return nil, nil } @@ -168,8 +171,8 @@ func Metrics(ctx *cli.Context, duration api.Duration) ([][]*api.SelectedRecord, return ret, nil } -func responseLatency(ctx *cli.Context, duration api.Duration) map[string]map[string]*displayable.MetricValue { - template, err := LoadTemplate(ctx.String("template")) +func responseLatency(ctx context.Context, duration api.Duration) map[string]map[string]*displayable.MetricValue { + template, err := LoadTemplate(ctx.Value(contextkey.DashboardTemplate{}).(string)) if err != nil { return nil } @@ -185,13 +188,12 @@ func responseLatency(ctx *cli.Context, duration api.Duration) map[string]map[str relabels := strings.Split(template.ResponseLatency.Relabels, ",") responseLatency, err := metrics.MultipleLinearIntValues(ctx, template.ResponseLatency.Condition, labels, duration) - if err != nil { logger.Log.Fatalln(err) } mapping := make(map[string]string, len(labels)) - for i := 0; i < len(labels); i++ { + for i := range labels { mapping[labels[i]] = relabels[i] } @@ -199,8 +201,8 @@ func responseLatency(ctx *cli.Context, duration api.Duration) map[string]map[str return utils.MetricsValuesArrayToMap(duration, responseLatency, mapping) } -func heatMap(ctx *cli.Context, duration api.Duration) (api.HeatMap, error) { - template, err := LoadTemplate(ctx.String("template")) +func heatMap(ctx context.Context, duration api.Duration) (api.HeatMap, error) { + template, err := LoadTemplate(ctx.Value(contextkey.DashboardTemplate{}).(string)) if err != nil { return api.HeatMap{}, nil } @@ -213,9 +215,9 @@ func heatMap(ctx *cli.Context, duration api.Duration) (api.HeatMap, error) { return metrics.Thermodynamic(ctx, template.HeatMap.Condition, duration) } -func Global(ctx *cli.Context, duration api.Duration) (*GlobalData, error) { +func Global(ctx context.Context, duration api.Duration) (*GlobalData, error) { // Load template to `globalTemplate`, so the subsequent three calls can ues it directly. - _, err := LoadTemplate(ctx.String("template")) + _, err := LoadTemplate(ctx.Value(contextkey.DashboardTemplate{}).(string)) if err != nil { return nil, nil } diff --git a/pkg/graphql/dependency/dependency.go b/pkg/graphql/dependency/dependency.go index 958835ee..be3dff2b 100644 --- a/pkg/graphql/dependency/dependency.go +++ b/pkg/graphql/dependency/dependency.go @@ -18,8 +18,9 @@ package dependency import ( + "context" + "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" api "skywalking.apache.org/repo/goapi/query" @@ -27,7 +28,7 @@ import ( "github.com/apache/skywalking-cli/pkg/graphql/client" ) -func EndpointDependency(ctx *cli.Context, endpointID string, duration api.Duration) (api.EndpointTopology, error) { +func EndpointDependency(ctx context.Context, endpointID string, duration api.Duration) (api.EndpointTopology, error) { var response map[string]api.EndpointTopology request := graphql.NewRequest(assets.Read("graphqls/dependency/EndpointDependency.graphql")) @@ -39,7 +40,7 @@ func EndpointDependency(ctx *cli.Context, endpointID string, duration api.Durati return response["result"], err } -func GlobalTopology(ctx *cli.Context, layer string, duration api.Duration) (api.Topology, error) { +func GlobalTopology(ctx context.Context, layer string, duration api.Duration) (api.Topology, error) { var response map[string]api.Topology request := graphql.NewRequest(assets.Read("graphqls/dependency/GlobalTopology.graphql")) @@ -51,7 +52,7 @@ func GlobalTopology(ctx *cli.Context, layer string, duration api.Duration) (api. return response["result"], err } -func GlobalTopologyWithoutLayer(ctx *cli.Context, duration api.Duration) (api.Topology, error) { +func GlobalTopologyWithoutLayer(ctx context.Context, duration api.Duration) (api.Topology, error) { var response map[string]api.Topology request := graphql.NewRequest(assets.Read("graphqls/dependency/GlobalTopologyWithoutLayer.graphql")) @@ -62,7 +63,7 @@ func GlobalTopologyWithoutLayer(ctx *cli.Context, duration api.Duration) (api.To return response["result"], err } -func ServiceTopology(ctx *cli.Context, serviceID string, duration api.Duration) (api.Topology, error) { +func ServiceTopology(ctx context.Context, serviceID string, duration api.Duration) (api.Topology, error) { var response map[string]api.Topology request := graphql.NewRequest(assets.Read("graphqls/dependency/ServiceTopology.graphql")) @@ -74,7 +75,7 @@ func ServiceTopology(ctx *cli.Context, serviceID string, duration api.Duration) return response["result"], err } -func InstanceTopology(ctx *cli.Context, clientServiceID, serverServiceID string, duration api.Duration) (api.ServiceInstanceTopology, error) { +func InstanceTopology(ctx context.Context, clientServiceID, serverServiceID string, duration api.Duration) (api.ServiceInstanceTopology, error) { var response map[string]api.ServiceInstanceTopology request := graphql.NewRequest(assets.Read("graphqls/dependency/InstanceTopology.graphql")) @@ -87,7 +88,7 @@ func InstanceTopology(ctx *cli.Context, clientServiceID, serverServiceID string, return response["result"], err } -func ProcessTopology(ctx *cli.Context, instanceID string, duration api.Duration) (api.ProcessTopology, error) { +func ProcessTopology(ctx context.Context, instanceID string, duration api.Duration) (api.ProcessTopology, error) { var response map[string]api.ProcessTopology request := graphql.NewRequest(assets.Read("graphqls/dependency/ProcessTopology.graphql")) diff --git a/pkg/graphql/event/event.go b/pkg/graphql/event/event.go index d46b0351..04106ce5 100644 --- a/pkg/graphql/event/event.go +++ b/pkg/graphql/event/event.go @@ -18,17 +18,17 @@ package event import ( + "context" + "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" - api "skywalking.apache.org/repo/goapi/query" ) -func Events(ctx *cli.Context, condition *api.EventQueryCondition) (api.Events, error) { +func Events(ctx context.Context, condition *api.EventQueryCondition) (api.Events, error) { var response map[string]api.Events request := graphql.NewRequest(assets.Read("graphqls/event/events.graphql")) diff --git a/pkg/graphql/healthcheck/healthcheck.go b/pkg/graphql/healthcheck/healthcheck.go index a16b9e36..35f92138 100644 --- a/pkg/graphql/healthcheck/healthcheck.go +++ b/pkg/graphql/healthcheck/healthcheck.go @@ -18,8 +18,9 @@ package healthcheck import ( + "context" + "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" api "skywalking.apache.org/repo/goapi/query" @@ -28,7 +29,7 @@ import ( ) // CheckHealth intends to query the health status of OAP server -func CheckHealth(ctx *cli.Context) (api.HealthStatus, error) { +func CheckHealth(ctx context.Context) (api.HealthStatus, error) { var response map[string]api.HealthStatus request := graphql.NewRequest(assets.Read("graphqls/healthcheck/healthcheck.graphql")) diff --git a/pkg/graphql/hierarchy/hierarchy.go b/pkg/graphql/hierarchy/hierarchy.go index 52803b98..bf64ff79 100644 --- a/pkg/graphql/hierarchy/hierarchy.go +++ b/pkg/graphql/hierarchy/hierarchy.go @@ -18,17 +18,17 @@ package hierarchy import ( + "context" + "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" - api "skywalking.apache.org/repo/goapi/query" ) -func ServiceHierarchy(ctx *cli.Context, serviceID, layer string) (api.ServiceHierarchy, error) { +func ServiceHierarchy(ctx context.Context, serviceID, layer string) (api.ServiceHierarchy, error) { var response map[string]api.ServiceHierarchy request := graphql.NewRequest(assets.Read("graphqls/hierarchy/ServiceHierarchy.graphql")) @@ -40,7 +40,7 @@ func ServiceHierarchy(ctx *cli.Context, serviceID, layer string) (api.ServiceHie return response["result"], err } -func InstanceHierarchy(ctx *cli.Context, instanceID, layer string) (api.InstanceHierarchy, error) { +func InstanceHierarchy(ctx context.Context, instanceID, layer string) (api.InstanceHierarchy, error) { var response map[string]api.InstanceHierarchy request := graphql.NewRequest(assets.Read("graphqls/hierarchy/InstanceHierarchy.graphql")) @@ -52,7 +52,7 @@ func InstanceHierarchy(ctx *cli.Context, instanceID, layer string) (api.Instance return response["result"], err } -func ListLayerLevels(ctx *cli.Context) ([]api.LayerLevel, error) { +func ListLayerLevels(ctx context.Context) ([]api.LayerLevel, error) { var response map[string][]api.LayerLevel request := graphql.NewRequest(assets.Read("graphqls/hierarchy/ListLayerLevels.graphql")) diff --git a/pkg/graphql/log/log.go b/pkg/graphql/log/log.go index 76613d5b..18be0b74 100644 --- a/pkg/graphql/log/log.go +++ b/pkg/graphql/log/log.go @@ -18,17 +18,17 @@ package log import ( + "context" + "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" - api "skywalking.apache.org/repo/goapi/query" ) -func Logs(ctx *cli.Context, condition *api.LogQueryCondition) (api.Logs, error) { +func Logs(ctx context.Context, condition *api.LogQueryCondition) (api.Logs, error) { var response map[string]api.Logs request := graphql.NewRequest(assets.Read("graphqls/logs/Logs.graphql")) @@ -39,7 +39,7 @@ func Logs(ctx *cli.Context, condition *api.LogQueryCondition) (api.Logs, error) return response["result"], err } -func BrowserLogs(ctx *cli.Context, condition *api.BrowserErrorLogQueryCondition) (api.BrowserErrorLogs, error) { +func BrowserLogs(ctx context.Context, condition *api.BrowserErrorLogQueryCondition) (api.BrowserErrorLogs, error) { var response map[string]api.BrowserErrorLogs request := graphql.NewRequest(assets.Read("graphqls/logs/BrowserLogs.graphql")) diff --git a/pkg/graphql/menu/menu.go b/pkg/graphql/menu/menu.go index 614174ef..b46815cd 100644 --- a/pkg/graphql/menu/menu.go +++ b/pkg/graphql/menu/menu.go @@ -18,17 +18,17 @@ package menu import ( + "context" + "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" - api "skywalking.apache.org/repo/goapi/query" ) -func GetItems(ctx *cli.Context) ([]*api.MenuItem, error) { +func GetItems(ctx context.Context) ([]*api.MenuItem, error) { var response map[string][]*api.MenuItem request := graphql.NewRequest(assets.Read("graphqls/menu/GetItems.graphql")) diff --git a/pkg/graphql/metadata/metadata.go b/pkg/graphql/metadata/metadata.go index 85823d03..73b9b262 100644 --- a/pkg/graphql/metadata/metadata.go +++ b/pkg/graphql/metadata/metadata.go @@ -18,6 +18,7 @@ package metadata import ( + "context" "fmt" "regexp" "strconv" @@ -25,7 +26,6 @@ import ( api "skywalking.apache.org/repo/goapi/query" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" @@ -34,7 +34,7 @@ import ( var backendVersion = regexp.MustCompile(`^(?P\d+)\.(?P\d+)`) -func AllServices(cliCtx *cli.Context, duration api.Duration) ([]api.Service, error) { +func AllServices(cliCtx context.Context, duration api.Duration) ([]api.Service, error) { var response map[string][]api.Service version, err := protocolVersion(cliCtx) @@ -49,10 +49,10 @@ func AllServices(cliCtx *cli.Context, duration api.Duration) ([]api.Service, err return response["result"], err } -func SearchService(cliCtx *cli.Context, serviceCode string) (service api.Service, err error) { +func SearchService(ctx context.Context, serviceCode string) (service api.Service, err error) { var response map[string]api.Service - majorVersion, _, err := BackendVersion(cliCtx) + majorVersion, _, err := BackendVersion(ctx) if err != nil { return api.Service{}, err } @@ -65,7 +65,7 @@ func SearchService(cliCtx *cli.Context, serviceCode string) (service api.Service request.Var("serviceCode", serviceCode) } - err = client.ExecuteQuery(cliCtx, request, &response) + err = client.ExecuteQuery(ctx, request, &response) service = response["result"] @@ -76,7 +76,7 @@ func SearchService(cliCtx *cli.Context, serviceCode string) (service api.Service return service, err } -func AllBrowserServices(cliCtx *cli.Context, duration api.Duration) ([]api.Service, error) { +func AllBrowserServices(cliCtx context.Context, duration api.Duration) ([]api.Service, error) { var response map[string][]api.Service version, err := protocolVersion(cliCtx) @@ -91,7 +91,7 @@ func AllBrowserServices(cliCtx *cli.Context, duration api.Duration) ([]api.Servi return response["result"], err } -func SearchBrowserService(cliCtx *cli.Context, serviceCode string) (service api.Service, err error) { +func SearchBrowserService(cliCtx context.Context, serviceCode string) (service api.Service, err error) { var response map[string]api.Service version, err := protocolVersion(cliCtx) @@ -112,7 +112,7 @@ func SearchBrowserService(cliCtx *cli.Context, serviceCode string) (service api. return service, err } -func SearchEndpoints(cliCtx *cli.Context, serviceID, keyword string, limit int, duration *api.Duration) ([]api.Endpoint, error) { +func SearchEndpoints(cliCtx context.Context, serviceID, keyword string, limit int, duration *api.Duration) ([]api.Endpoint, error) { var response map[string][]api.Endpoint majorVersion, minorVersion, err := BackendVersion(cliCtx) @@ -142,7 +142,7 @@ func SearchEndpoints(cliCtx *cli.Context, serviceID, keyword string, limit int, return response["result"], err } -func Instances(cliCtx *cli.Context, serviceID string, duration api.Duration) ([]api.ServiceInstance, error) { +func Instances(cliCtx context.Context, serviceID string, duration api.Duration) ([]api.ServiceInstance, error) { var response map[string][]api.ServiceInstance version, err := protocolVersion(cliCtx) @@ -158,7 +158,7 @@ func Instances(cliCtx *cli.Context, serviceID string, duration api.Duration) ([] return response["result"], err } -func GetInstance(cliCtx *cli.Context, instanceID string) (api.ServiceInstance, error) { +func GetInstance(cliCtx context.Context, instanceID string) (api.ServiceInstance, error) { var response map[string]api.ServiceInstance request := graphql.NewRequest(assets.Read("graphqls/metadata/v2/GetInstance.graphql")) @@ -169,7 +169,7 @@ func GetInstance(cliCtx *cli.Context, instanceID string) (api.ServiceInstance, e return response["result"], err } -func GetEndpointInfo(cliCtx *cli.Context, endpointID string) (api.EndpointInfo, error) { +func GetEndpointInfo(cliCtx context.Context, endpointID string) (api.EndpointInfo, error) { var response map[string]api.EndpointInfo request := graphql.NewRequest(assets.Read("graphqls/metadata/v2/GetEndpointInfo.graphql")) @@ -180,7 +180,7 @@ func GetEndpointInfo(cliCtx *cli.Context, endpointID string) (api.EndpointInfo, return response["result"], err } -func Processes(cliCtx *cli.Context, instanceID string, duration api.Duration) ([]api.Process, error) { +func Processes(cliCtx context.Context, instanceID string, duration api.Duration) ([]api.Process, error) { var response map[string][]api.Process request := graphql.NewRequest(assets.Read("graphqls/metadata/v2/Processes.graphql")) @@ -192,7 +192,7 @@ func Processes(cliCtx *cli.Context, instanceID string, duration api.Duration) ([ return response["result"], err } -func GetProcess(cliCtx *cli.Context, processID string) (api.Process, error) { +func GetProcess(cliCtx context.Context, processID string) (api.Process, error) { var response map[string]api.Process request := graphql.NewRequest(assets.Read("graphqls/metadata/v2/GetProcess.graphql")) @@ -203,7 +203,7 @@ func GetProcess(cliCtx *cli.Context, processID string) (api.Process, error) { return response["result"], err } -func EstimateProcessScale(cliCtx *cli.Context, serviceID string, labels []string) (int64, error) { +func EstimateProcessScale(cliCtx context.Context, serviceID string, labels []string) (int64, error) { var response map[string]int64 request := graphql.NewRequest(assets.Read("graphqls/metadata/v2/EstimateProcessScale.graphql")) @@ -215,7 +215,7 @@ func EstimateProcessScale(cliCtx *cli.Context, serviceID string, labels []string return response["result"], err } -func ServerTimeInfo(cliCtx *cli.Context) (api.TimeInfo, error) { +func ServerTimeInfo(cliCtx context.Context) (api.TimeInfo, error) { var response map[string]api.TimeInfo request := graphql.NewRequest(assets.Read("graphqls/metadata/v2/ServerTimeInfo.graphql")) @@ -227,7 +227,7 @@ func ServerTimeInfo(cliCtx *cli.Context) (api.TimeInfo, error) { return response["result"], nil } -func ListLayers(cliCtx *cli.Context) ([]string, error) { +func ListLayers(cliCtx context.Context) ([]string, error) { var response map[string][]string request := graphql.NewRequest(assets.Read("graphqls/metadata/v2/ListLayers.graphql")) @@ -239,7 +239,7 @@ func ListLayers(cliCtx *cli.Context) ([]string, error) { return response["result"], nil } -func ListLayerService(cliCtx *cli.Context, layer string) ([]api.Service, error) { +func ListLayerService(cliCtx context.Context, layer string) ([]api.Service, error) { var response map[string][]api.Service request := graphql.NewRequest(assets.Read("graphqls/metadata/v2/ListService.graphql")) @@ -250,8 +250,8 @@ func ListLayerService(cliCtx *cli.Context, layer string) ([]api.Service, error) return response["result"], err } -func BackendVersion(cliCtx *cli.Context) (major, minor int, err error) { - version, err := common.Version(cliCtx) +func BackendVersion(ctx context.Context) (major, minor int, err error) { + version, err := common.Version(ctx) if err != nil { return 0, 0, err } @@ -274,8 +274,8 @@ func BackendVersion(cliCtx *cli.Context) (major, minor int, err error) { return major, minor, nil } -func protocolVersion(cliCtx *cli.Context) (string, error) { - if majorVersion, _, err := BackendVersion(cliCtx); err != nil { +func protocolVersion(ctx context.Context) (string, error) { + if majorVersion, _, err := BackendVersion(ctx); err != nil { return "", err } else if majorVersion >= 9 { return "v2", nil diff --git a/pkg/graphql/metrics/metrics.go b/pkg/graphql/metrics/metrics.go index 9fcae90b..3d25ef41 100644 --- a/pkg/graphql/metrics/metrics.go +++ b/pkg/graphql/metrics/metrics.go @@ -18,8 +18,9 @@ package metrics import ( + "context" + "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" @@ -27,7 +28,7 @@ import ( api "skywalking.apache.org/repo/goapi/query" ) -func IntValues(ctx *cli.Context, condition api.MetricsCondition, duration api.Duration) (int, error) { +func IntValues(ctx context.Context, condition api.MetricsCondition, duration api.Duration) (int, error) { var response map[string]int request := graphql.NewRequest(assets.Read("graphqls/metrics/MetricsValue.graphql")) @@ -40,7 +41,7 @@ func IntValues(ctx *cli.Context, condition api.MetricsCondition, duration api.Du return response["result"], err } -func NullableIntValue(ctx *cli.Context, condition api.MetricsCondition, duration api.Duration) (api.NullableValue, error) { +func NullableIntValue(ctx context.Context, condition api.MetricsCondition, duration api.Duration) (api.NullableValue, error) { var response map[string]api.NullableValue request := graphql.NewRequest(assets.Read("graphqls/metrics/NullableMetricsValue.graphql")) @@ -53,7 +54,7 @@ func NullableIntValue(ctx *cli.Context, condition api.MetricsCondition, duration return response["result"], err } -func LinearIntValues(ctx *cli.Context, condition api.MetricsCondition, duration api.Duration) (api.MetricsValues, error) { +func LinearIntValues(ctx context.Context, condition api.MetricsCondition, duration api.Duration) (api.MetricsValues, error) { var response map[string]api.MetricsValues request := graphql.NewRequest(assets.Read("graphqls/metrics/MetricsValues.graphql")) @@ -66,7 +67,12 @@ func LinearIntValues(ctx *cli.Context, condition api.MetricsCondition, duration return response["result"], err } -func MultipleLinearIntValues(ctx *cli.Context, condition api.MetricsCondition, labels []string, duration api.Duration) ([]api.MetricsValues, error) { +func MultipleLinearIntValues( + ctx context.Context, + condition api.MetricsCondition, + labels []string, + duration api.Duration, +) ([]api.MetricsValues, error) { var response map[string][]api.MetricsValues request := graphql.NewRequest(assets.Read("graphqls/metrics/LabeledMetricsValues.graphql")) @@ -80,7 +86,7 @@ func MultipleLinearIntValues(ctx *cli.Context, condition api.MetricsCondition, l return response["result"], err } -func Thermodynamic(ctx *cli.Context, condition api.MetricsCondition, duration api.Duration) (api.HeatMap, error) { +func Thermodynamic(ctx context.Context, condition api.MetricsCondition, duration api.Duration) (api.HeatMap, error) { var response map[string]api.HeatMap request := graphql.NewRequest(assets.Read("graphqls/metrics/HeatMap.graphql")) @@ -93,7 +99,7 @@ func Thermodynamic(ctx *cli.Context, condition api.MetricsCondition, duration ap return response["result"], err } -func SortMetrics(ctx *cli.Context, condition api.TopNCondition, duration api.Duration) ([]*api.SelectedRecord, error) { +func SortMetrics(ctx context.Context, condition api.TopNCondition, duration api.Duration) ([]*api.SelectedRecord, error) { var response map[string][]*api.SelectedRecord request := graphql.NewRequest(assets.Read("graphqls/metrics/SortMetrics.graphql")) @@ -105,7 +111,7 @@ func SortMetrics(ctx *cli.Context, condition api.TopNCondition, duration api.Dur return response["result"], err } -func SampledRecords(ctx *cli.Context, condition api.TopNCondition, duration api.Duration) ([]*api.SelectedRecord, error) { +func SampledRecords(ctx context.Context, condition api.TopNCondition, duration api.Duration) ([]*api.SelectedRecord, error) { var response map[string][]*api.SelectedRecord request := graphql.NewRequest(assets.Read("graphqls/metrics/SampledRecords.graphql")) @@ -117,7 +123,7 @@ func SampledRecords(ctx *cli.Context, condition api.TopNCondition, duration api. return response["result"], err } -func ReadRecords(ctx *cli.Context, condition api.RecordCondition, duration api.Duration) ([]*api.Record, error) { +func ReadRecords(ctx context.Context, condition api.RecordCondition, duration api.Duration) ([]*api.Record, error) { var response map[string][]*api.Record request := graphql.NewRequest(assets.Read("graphqls/metrics/ReadRecords.graphql")) @@ -129,7 +135,7 @@ func ReadRecords(ctx *cli.Context, condition api.RecordCondition, duration api.D return response["result"], err } -func ListMetrics(ctx *cli.Context, regex string) ([]*api.MetricDefinition, error) { +func ListMetrics(ctx context.Context, regex string) ([]*api.MetricDefinition, error) { var response map[string][]*api.MetricDefinition request := graphql.NewRequest(assets.Read("graphqls/metrics/ListMetrics.graphql")) request.Var("regex", regex) @@ -139,7 +145,7 @@ func ListMetrics(ctx *cli.Context, regex string) ([]*api.MetricDefinition, error return response["result"], err } -func Execute(ctx *cli.Context, expression string, entity *api.Entity, duration api.Duration) (api.ExpressionResult, error) { +func Execute(ctx context.Context, expression string, entity *api.Entity, duration api.Duration) (api.ExpressionResult, error) { var response map[string]api.ExpressionResult request := graphql.NewRequest(assets.Read("graphqls/metrics/ExecuteExpression.graphql")) diff --git a/pkg/graphql/profiling/asyncprofiler.go b/pkg/graphql/profiling/asyncprofiler.go index 5db697fd..34b18574 100644 --- a/pkg/graphql/profiling/asyncprofiler.go +++ b/pkg/graphql/profiling/asyncprofiler.go @@ -18,15 +18,16 @@ package profiling import ( + "context" + "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" api "skywalking.apache.org/repo/goapi/query" "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" ) -func CreateAsyncProfilerTask(ctx *cli.Context, condition *api.AsyncProfilerTaskCreationRequest) (api.AsyncProfilerTaskCreationResult, error) { +func CreateAsyncProfilerTask(ctx context.Context, condition *api.AsyncProfilerTaskCreationRequest) (api.AsyncProfilerTaskCreationResult, error) { var response map[string]api.AsyncProfilerTaskCreationResult request := graphql.NewRequest(assets.Read("graphqls/profiling/asyncprofiler/CreateTask.graphql")) @@ -37,7 +38,7 @@ func CreateAsyncProfilerTask(ctx *cli.Context, condition *api.AsyncProfilerTaskC return response["result"], err } -func GetAsyncProfilerTaskList(ctx *cli.Context, condition *api.AsyncProfilerTaskListRequest) (api.AsyncProfilerTaskListResult, error) { +func GetAsyncProfilerTaskList(ctx context.Context, condition *api.AsyncProfilerTaskListRequest) (api.AsyncProfilerTaskListResult, error) { var response map[string]api.AsyncProfilerTaskListResult request := graphql.NewRequest(assets.Read("graphqls/profiling/asyncprofiler/GetTaskList.graphql")) @@ -48,7 +49,7 @@ func GetAsyncProfilerTaskList(ctx *cli.Context, condition *api.AsyncProfilerTask return response["result"], err } -func GetAsyncProfilerTaskProgress(ctx *cli.Context, taskID string) (api.AsyncProfilerTaskProgress, error) { +func GetAsyncProfilerTaskProgress(ctx context.Context, taskID string) (api.AsyncProfilerTaskProgress, error) { var response map[string]api.AsyncProfilerTaskProgress request := graphql.NewRequest(assets.Read("graphqls/profiling/asyncprofiler/GetTaskProgress.graphql")) @@ -59,7 +60,7 @@ func GetAsyncProfilerTaskProgress(ctx *cli.Context, taskID string) (api.AsyncPro return response["result"], err } -func GetAsyncProfilerAnalyze(ctx *cli.Context, condition *api.AsyncProfilerAnalyzationRequest) (api.AsyncProfilerAnalyzation, error) { +func GetAsyncProfilerAnalyze(ctx context.Context, condition *api.AsyncProfilerAnalyzationRequest) (api.AsyncProfilerAnalyzation, error) { var response map[string]api.AsyncProfilerAnalyzation request := graphql.NewRequest(assets.Read("graphqls/profiling/asyncprofiler/GetAnalysis.graphql")) diff --git a/pkg/graphql/profiling/continuous.go b/pkg/graphql/profiling/continuous.go index 7d590ead..e31f4ee8 100644 --- a/pkg/graphql/profiling/continuous.go +++ b/pkg/graphql/profiling/continuous.go @@ -18,17 +18,17 @@ package profiling import ( + "context" + "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" - api "skywalking.apache.org/repo/goapi/query" ) -func SetContinuousProfilingPolicy(ctx *cli.Context, creation *api.ContinuousProfilingPolicyCreation) (api.ContinuousProfilingSetResult, error) { +func SetContinuousProfilingPolicy(ctx context.Context, creation *api.ContinuousProfilingPolicyCreation) (api.ContinuousProfilingSetResult, error) { var response map[string]api.ContinuousProfilingSetResult request := graphql.NewRequest(assets.Read("graphqls/profiling/continuous/SetContinuousProfilingPolicy.graphql")) @@ -39,7 +39,7 @@ func SetContinuousProfilingPolicy(ctx *cli.Context, creation *api.ContinuousProf return response["result"], err } -func QueryContinuousProfilingServiceTargets(ctx *cli.Context, serviceID string) ([]*api.ContinuousProfilingPolicyTarget, error) { +func QueryContinuousProfilingServiceTargets(ctx context.Context, serviceID string) ([]*api.ContinuousProfilingPolicyTarget, error) { var response map[string][]*api.ContinuousProfilingPolicyTarget request := graphql.NewRequest(assets.Read("graphqls/profiling/continuous/QueryContinuousProfilingServiceTargets.graphql")) @@ -50,8 +50,9 @@ func QueryContinuousProfilingServiceTargets(ctx *cli.Context, serviceID string) return response["result"], err } -func QueryContinuousProfilingMonitoringInstances(ctx *cli.Context, serviceID string, - target api.ContinuousProfilingTargetType) ([]api.ContinuousProfilingMonitoringInstance, error) { +func QueryContinuousProfilingMonitoringInstances(ctx context.Context, serviceID string, + target api.ContinuousProfilingTargetType, +) ([]api.ContinuousProfilingMonitoringInstance, error) { var response map[string][]api.ContinuousProfilingMonitoringInstance request := graphql.NewRequest(assets.Read("graphqls/profiling/continuous/QueryContinuousProfilingMonitoringInstances.graphql")) diff --git a/pkg/graphql/profiling/ebpf.go b/pkg/graphql/profiling/ebpf.go index 0cdf3d4c..a788e5db 100644 --- a/pkg/graphql/profiling/ebpf.go +++ b/pkg/graphql/profiling/ebpf.go @@ -18,18 +18,19 @@ package profiling import ( + "context" + "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" - api "skywalking.apache.org/repo/goapi/query" ) -func CreateEBPFProfilingFixedTimeTask(ctx *cli.Context, - condition *api.EBPFProfilingTaskFixedTimeCreationRequest) (api.EBPFProfilingTaskCreationResult, error) { +func CreateEBPFProfilingFixedTimeTask(ctx context.Context, + condition *api.EBPFProfilingTaskFixedTimeCreationRequest, +) (api.EBPFProfilingTaskCreationResult, error) { var response map[string]api.EBPFProfilingTaskCreationResult request := graphql.NewRequest(assets.Read("graphqls/profiling/ebpf/CreateEBPFProfilingFixedTimeTask.graphql")) @@ -40,7 +41,9 @@ func CreateEBPFProfilingFixedTimeTask(ctx *cli.Context, return response["result"], err } -func CreateEBPFNetworkProfilingTask(ctx *cli.Context, condition *api.EBPFProfilingNetworkTaskRequest) (api.EBPFProfilingTaskCreationResult, error) { +func CreateEBPFNetworkProfilingTask(ctx context.Context, + condition *api.EBPFProfilingNetworkTaskRequest, +) (api.EBPFProfilingTaskCreationResult, error) { var response map[string]api.EBPFProfilingTaskCreationResult request := graphql.NewRequest(assets.Read("graphqls/profiling/ebpf/CreateEBPFNetworkProfilingTask.graphql")) @@ -51,7 +54,7 @@ func CreateEBPFNetworkProfilingTask(ctx *cli.Context, condition *api.EBPFProfili return response["result"], err } -func QueryPrepareCreateEBPFProfilingTaskData(ctx *cli.Context, serviceID string) (*api.EBPFProfilingTaskPrepare, error) { +func QueryPrepareCreateEBPFProfilingTaskData(ctx context.Context, serviceID string) (*api.EBPFProfilingTaskPrepare, error) { var response map[string]*api.EBPFProfilingTaskPrepare request := graphql.NewRequest(assets.Read("graphqls/profiling/ebpf/QueryPrepareCreateEBPFProfilingTaskData.graphql")) @@ -62,7 +65,7 @@ func QueryPrepareCreateEBPFProfilingTaskData(ctx *cli.Context, serviceID string) return response["result"], err } -func QueryEBPFProfilingTaskList(ctx *cli.Context, serviceID string, triggerType api.EBPFProfilingTriggerType) ([]*api.EBPFProfilingTask, error) { +func QueryEBPFProfilingTaskList(ctx context.Context, serviceID string, triggerType api.EBPFProfilingTriggerType) ([]*api.EBPFProfilingTask, error) { var response map[string][]*api.EBPFProfilingTask request := graphql.NewRequest(assets.Read("graphqls/profiling/ebpf/QueryEBPFProfilingTaskList.graphql")) @@ -74,7 +77,7 @@ func QueryEBPFProfilingTaskList(ctx *cli.Context, serviceID string, triggerType return response["result"], err } -func QueryEBPFProfilingScheduleList(ctx *cli.Context, taskID string) ([]*api.EBPFProfilingSchedule, error) { +func QueryEBPFProfilingScheduleList(ctx context.Context, taskID string) ([]*api.EBPFProfilingSchedule, error) { var response map[string][]*api.EBPFProfilingSchedule request := graphql.NewRequest(assets.Read("graphqls/profiling/ebpf/QueryEBPFProfilingScheduleList.graphql")) @@ -85,8 +88,9 @@ func QueryEBPFProfilingScheduleList(ctx *cli.Context, taskID string) ([]*api.EBP return response["result"], err } -func AnalysisEBPFProfilingResult(ctx *cli.Context, scheduleIDList []string, - timeRanges []*api.EBPFProfilingAnalyzeTimeRange, aggregateType api.EBPFProfilingAnalyzeAggregateType) (*api.EBPFProfilingAnalyzation, error) { +func AnalysisEBPFProfilingResult(ctx context.Context, scheduleIDList []string, + timeRanges []*api.EBPFProfilingAnalyzeTimeRange, aggregateType api.EBPFProfilingAnalyzeAggregateType, +) (*api.EBPFProfilingAnalyzation, error) { var response map[string]*api.EBPFProfilingAnalyzation request := graphql.NewRequest(assets.Read("graphqls/profiling/ebpf/AnalysisEBPFProfilingResult.graphql")) @@ -99,7 +103,7 @@ func AnalysisEBPFProfilingResult(ctx *cli.Context, scheduleIDList []string, return response["result"], err } -func KeepNetworkProfilingTask(ctx *cli.Context, taskID string) (*api.EBPFNetworkKeepProfilingResult, error) { +func KeepNetworkProfilingTask(ctx context.Context, taskID string) (*api.EBPFNetworkKeepProfilingResult, error) { var response map[string]*api.EBPFNetworkKeepProfilingResult request := graphql.NewRequest(assets.Read("graphqls/profiling/ebpf/KeepNetworkProfilingTask.graphql")) diff --git a/pkg/graphql/profiling/trace.go b/pkg/graphql/profiling/trace.go index a1e0b479..6d9aa0d8 100644 --- a/pkg/graphql/profiling/trace.go +++ b/pkg/graphql/profiling/trace.go @@ -18,17 +18,17 @@ package profiling import ( + "context" + "github.com/apache/skywalking-cli/assets" "github.com/apache/skywalking-cli/pkg/graphql/client" "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" - api "skywalking.apache.org/repo/goapi/query" ) -func CreateTraceTask(ctx *cli.Context, condition *api.ProfileTaskCreationRequest) (api.ProfileTaskCreationResult, error) { +func CreateTraceTask(ctx context.Context, condition *api.ProfileTaskCreationRequest) (api.ProfileTaskCreationResult, error) { var response map[string]api.ProfileTaskCreationResult request := graphql.NewRequest(assets.Read("graphqls/profiling/trace/CreateTask.graphql")) @@ -39,7 +39,7 @@ func CreateTraceTask(ctx *cli.Context, condition *api.ProfileTaskCreationRequest return response["result"], err } -func GetTraceProfilingTaskList(ctx *cli.Context, serviceID, endpointName string) ([]*api.ProfileTask, error) { +func GetTraceProfilingTaskList(ctx context.Context, serviceID, endpointName string) ([]*api.ProfileTask, error) { var response map[string][]*api.ProfileTask request := graphql.NewRequest(assets.Read("graphqls/profiling/trace/GetTaskList.graphql")) @@ -51,7 +51,7 @@ func GetTraceProfilingTaskList(ctx *cli.Context, serviceID, endpointName string) return response["result"], err } -func GetTraceProfilingTaskLogList(ctx *cli.Context, taskID string) ([]*api.ProfileTaskLog, error) { +func GetTraceProfilingTaskLogList(ctx context.Context, taskID string) ([]*api.ProfileTaskLog, error) { var response map[string][]*api.ProfileTaskLog request := graphql.NewRequest(assets.Read("graphqls/profiling/trace/GetProfileTaskLogs.graphql")) @@ -62,7 +62,7 @@ func GetTraceProfilingTaskLogList(ctx *cli.Context, taskID string) ([]*api.Profi return response["result"], err } -func GetTraceProfilingTaskSegmentList(ctx *cli.Context, taskID string) ([]*api.ProfiledTraceSegments, error) { +func GetTraceProfilingTaskSegmentList(ctx context.Context, taskID string) ([]*api.ProfiledTraceSegments, error) { var response map[string][]*api.ProfiledTraceSegments request := graphql.NewRequest(assets.Read("graphqls/profiling/trace/GetTaskSegmentsList.graphql")) @@ -73,7 +73,7 @@ func GetTraceProfilingTaskSegmentList(ctx *cli.Context, taskID string) ([]*api.P return response["result"], err } -func GetTraceProfilingAnalyze(ctx *cli.Context, queries []*api.SegmentProfileAnalyzeQuery) (api.ProfileAnalyzation, error) { +func GetTraceProfilingAnalyze(ctx context.Context, queries []*api.SegmentProfileAnalyzeQuery) (api.ProfileAnalyzation, error) { var response map[string]api.ProfileAnalyzation request := graphql.NewRequest(assets.Read("graphqls/profiling/trace/GetSegmentsProfileAnalyze.graphql")) diff --git a/pkg/graphql/trace/trace.go b/pkg/graphql/trace/trace.go index 60718462..1a440603 100644 --- a/pkg/graphql/trace/trace.go +++ b/pkg/graphql/trace/trace.go @@ -18,8 +18,9 @@ package trace import ( + "context" + "github.com/machinebox/graphql" - "github.com/urfave/cli/v2" api "skywalking.apache.org/repo/goapi/query" @@ -27,7 +28,7 @@ import ( "github.com/apache/skywalking-cli/pkg/graphql/client" ) -func Trace(ctx *cli.Context, traceID string) (api.Trace, error) { +func Trace(ctx context.Context, traceID string) (api.Trace, error) { var response map[string]api.Trace request := graphql.NewRequest(assets.Read("graphqls/trace/Trace.graphql")) @@ -38,7 +39,7 @@ func Trace(ctx *cli.Context, traceID string) (api.Trace, error) { return response["result"], err } -func Traces(ctx *cli.Context, condition *api.TraceQueryCondition) (api.TraceBrief, error) { +func Traces(ctx context.Context, condition *api.TraceQueryCondition) (api.TraceBrief, error) { var response map[string]api.TraceBrief request := graphql.NewRequest(assets.Read("graphqls/trace/Traces.graphql")) diff --git a/pkg/heatmap/heatmap.go b/pkg/heatmap/heatmap.go index 74c9ff0e..a66d2d66 100644 --- a/pkg/heatmap/heatmap.go +++ b/pkg/heatmap/heatmap.go @@ -193,7 +193,7 @@ func (hp *HeatMap) drawColumns(cvs *canvas.Canvas, xd *axes.XDetails, yd *axes.Y for i, xl := range hp.XLabels { cv := hp.columns[xl] - for j := 0; j < len(cv.values); j++ { + for j := range cv.values { v := cv.values[j] startX := xd.Start.X + 1 + i*hp.opts.cellWidth