/
result.go
294 lines (252 loc) · 8.87 KB
/
result.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Copyright 2023 Khulnasoft, Inc.
//
// Licensed 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 perf
import (
"encoding/json"
"fmt"
"io"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/gofrs/uuid"
"github.com/khulnasoft/meshplay/meshplayctl/internal/cli/root/config"
"github.com/khulnasoft/meshplay/meshplayctl/pkg/utils"
"github.com/khulnasoft/meshplay/server/models"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type resultStruct struct {
Name string
StartTime *time.Time
LatenciesMs *models.LatenciesMs
QPS int
URL string
UserID *uuid.UUID
Duration string
MeshplayID *uuid.UUID
LoadGenerator string
}
var (
pageNumber int
viewSingleResult bool
)
var linkDocPerfResult = map[string]string{
"link": "![perf-result-usage](/assets/img/meshplayctl/perf-result.png)",
"caption": "Usage of meshplayctl perf result",
}
var resultCmd = &cobra.Command{
Use: "result [profile-name]",
Short: "List performance test results",
Long: `List all the available test results of a performance profile`,
Args: cobra.MinimumNArgs(0),
Example: `
// List Test results (maximum 25 results)
meshplayctl perf result saturday-profile
// View other set of performance results with --page (maximum 25 results)
meshplayctl perf result saturday-profile --page 2
// View single performance result with detailed information
meshplayctl perf result saturday-profile --view
`,
Annotations: linkDocPerfResult,
RunE: func(cmd *cobra.Command, args []string) error {
// used for searching performance profile
var searchString, profileID string
// setting up for error formatting
cmdUsed = "result"
mctlCfg, err := config.GetMeshplayCtl(viper.GetViper())
if err != nil {
utils.Log.Error(err)
return nil
}
// Throw error if a profile name is not provided
if len(args) == 0 {
utils.Log.Error(ErrNoProfileName())
return nil
}
// handles spaces in args if quoted args passed
for i, arg := range args {
args[i] = strings.ReplaceAll(arg, " ", "%20")
}
// Merge args to get profile-name
searchString = strings.Join(args, "%20")
profiles, _, err := fetchPerformanceProfiles(mctlCfg.GetBaseMeshplayURL(), searchString, pageSize, pageNumber-1)
if err != nil {
utils.Log.Error(err)
return nil
}
if len(profiles) == 0 {
utils.Log.Info(ErrNoProfileFound())
return nil
}
data := profilesToStringArrays(profiles)
if len(profiles) == 1 {
// found only one profile with matching name
profileID = data[0][1]
} else {
// user prompt to select profile
selectedProfileIndex, err := userPrompt("profile", "Found multiple profiles with given name, select a profile", data)
if err != nil {
utils.Log.Error(err)
return nil
}
// ids got shifted with 1 in userPrompt()
profileID = data[selectedProfileIndex][2]
}
results, _, err := fetchPerformanceProfileResults(mctlCfg.GetBaseMeshplayURL(), profileID, pageSize, pageNumber-1)
if err != nil {
utils.Log.Error(ErrPerformanceProfileResult(err))
return nil
}
if len(data) == 0 {
utils.Log.Info("No Test Results to display")
return nil
}
// get performance results in format of string arrays and resultStruct
data, expandedData := performanceResultsToStringArrays(results)
if len(expandedData) == 0 {
utils.Log.Info("No test results to display")
return nil
}
if outputFormatFlag != "" {
body, _ := json.Marshal(results)
if outputFormatFlag == "yaml" {
body, _ = yaml.JSONToYAML(body)
} else if outputFormatFlag != "json" {
utils.Log.Error(ErrInvalidOutputChoice())
return nil
}
utils.Log.Info(string(body))
} else if !viewSingleResult { // print all results
utils.PrintToTable([]string{"NAME", "MESH", "QPS", "DURATION", "P50", "P99.9", "START-TIME"}, data)
} else {
index := 0
// if more than one result exist ask for index
if len(data) > 1 {
index, err = userPrompt("result", "Select Performance-test result to expand", data)
if err != nil {
return err
}
}
a := expandedData[index]
fmt.Printf("Name: %v\n", a.Name)
fmt.Printf("UserID: %s\n", a.UserID.String())
fmt.Printf("Endpoint: %v\n", a.URL)
fmt.Printf("QPS: %v\n", a.QPS)
fmt.Printf("Test run duration: %v\n", a.Duration)
fmt.Printf("Latencies _ms: Avg: %v, Max: %v, Min: %v, P50: %v, P90: %v, P99: %v\n", a.LatenciesMs.Average, a.LatenciesMs.Max, a.LatenciesMs.Min, a.LatenciesMs.P50, a.LatenciesMs.P90, a.LatenciesMs.P99)
fmt.Printf("Start Time: %v\n", fmt.Sprintf("%d-%d-%d %d:%d:%d", int(a.StartTime.Month()), a.StartTime.Day(), a.StartTime.Year(), a.StartTime.Hour(), a.StartTime.Minute(), a.StartTime.Second()))
fmt.Printf("Meshplay ID: %v\n", a.MeshplayID.String())
fmt.Printf("Load Generator: %v\n", a.LoadGenerator)
}
return nil
},
}
// Fetch results for a specific profile
func fetchPerformanceProfileResults(baseURL, profileID string, pageSize, pageNumber int) ([]models.PerformanceResult, []byte, error) {
var response *models.PerformanceResultsAPIResponse
url := baseURL + "/api/user/performance/profiles/" + profileID + "/results"
tempURL := fmt.Sprintf("%s?pagesize=%d&page=%d", url, pageSize, pageNumber)
req, err := utils.NewRequest("GET", tempURL, nil)
if err != nil {
return nil, nil, err
}
resp, err := utils.MakeRequest(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, errors.Wrap(err, utils.PerfError("failed to read response body"))
}
err = json.Unmarshal(body, &response)
if err != nil {
return nil, nil, ErrFailUnmarshal(err)
}
return response.Results, body, nil
}
// change performance results into string arrays(for tabular format printing) and profileStruct (to print single performance result)
func performanceResultsToStringArrays(results []models.PerformanceResult) ([][]string, []resultStruct) {
var data [][]string
var expendedData []resultStruct
// append data for single profile
for _, result := range results {
serviceMesh := "No Mesh"
p50 := ""
p99_9 := ""
var P50, P90, P99 float64
if result.Mesh != "" {
serviceMesh = result.Mesh
}
qps := fmt.Sprintf("%d", int(result.RunnerResults.QPS))
duration := result.RunnerResults.RequestedDuration
if len(result.RunnerResults.DurationHistogram.Percentiles) > 0 {
p50 = fmt.Sprintf("%.8f", result.RunnerResults.DurationHistogram.Percentiles[0].Value)
p99_9 = fmt.Sprintf("%.8f", result.RunnerResults.DurationHistogram.Percentiles[len(result.RunnerResults.DurationHistogram.Percentiles)-1].Value)
}
startTime := result.TestStartTime.Format("2006-01-02 15:04:05")
data = append(data, []string{result.Name, serviceMesh, qps, duration, p50, p99_9, startTime})
if len(result.RunnerResults.DurationHistogram.Percentiles) > 3 {
P50 = result.RunnerResults.DurationHistogram.Percentiles[0].Value
P90 = result.RunnerResults.DurationHistogram.Percentiles[2].Value
P99 = result.RunnerResults.DurationHistogram.Percentiles[3].Value
}
// append data for extended output
name := "None"
userid := uuid.Nil
meshplayid := uuid.Nil
url := "None"
loadGenerator := "None"
if result.UserID != nil {
userid = *result.UserID
}
if result.MeshplayID != nil {
meshplayid = *result.MeshplayID
}
if result.Name != "" {
name = result.Name
}
if result.RunnerResults.URL != "" {
url = result.RunnerResults.URL
}
if result.RunnerResults.LoadGenerator != "" {
loadGenerator = result.RunnerResults.LoadGenerator
}
a := resultStruct{
Name: name,
UserID: (*uuid.UUID)(userid.Bytes()),
URL: url,
QPS: int(result.RunnerResults.QPS),
Duration: result.RunnerResults.RequestedDuration,
LatenciesMs: &models.LatenciesMs{
Average: result.RunnerResults.DurationHistogram.Average,
Max: result.RunnerResults.DurationHistogram.Max,
Min: result.RunnerResults.DurationHistogram.Min,
P50: P50,
P90: P90,
P99: P99,
},
StartTime: result.TestStartTime,
MeshplayID: (*uuid.UUID)(meshplayid.Bytes()),
LoadGenerator: loadGenerator,
}
expendedData = append(expendedData, a)
}
return data, expendedData
}
func init() {
resultCmd.Flags().BoolVarP(&viewSingleResult, "view", "", false, "(optional) View single performance results with more info")
resultCmd.Flags().IntVarP(&pageNumber, "page", "p", 1, "(optional) List next set of performance results with --page (default = 1)")
}