-
Notifications
You must be signed in to change notification settings - Fork 45
/
addexport.go
325 lines (279 loc) · 7.97 KB
/
addexport.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
* Copyright 2018-2019 The NATS Authors
* 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 cmd
import (
"errors"
"fmt"
"strconv"
"strings"
cli "github.com/nats-io/cliprompts/v2"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nkeys"
"github.com/nats-io/nsc/cmd/store"
"github.com/spf13/cobra"
)
func createAddExportCmd() *cobra.Command {
var params AddExportParams
cmd := &cobra.Command{
Use: "export",
Short: "Add an export",
Args: MaxArgs(0),
Example: params.longHelp(),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
return RunAction(cmd, args, ¶ms)
},
}
cmd.Flags().StringVarP(¶ms.export.Name, "name", "n", "", "export name")
cmd.Flags().StringVarP(¶ms.subject, "subject", "s", "", "subject")
cmd.Flags().BoolVarP(¶ms.service, "service", "r", false, "export type service")
cmd.Flags().BoolVarP(¶ms.private, "private", "p", false, "private export - requires an activation to access")
cmd.Flags().StringVarP(¶ms.latSubject, "latency", "", "", "latency metrics subject (services only)")
cmd.Flags().StringVarP(¶ms.latSampling, "sampling", "", "", "latency sampling percentage [1-100] or `header` (services only)")
hm := fmt.Sprintf("response type for the service [%s | %s | %s] (services only)", jwt.ResponseTypeSingleton, jwt.ResponseTypeStream, jwt.ResponseTypeChunked)
cmd.Flags().StringVarP(¶ms.responseType, "response-type", "", jwt.ResponseTypeSingleton, hm)
params.AccountContextParams.BindFlags(cmd)
return cmd
}
func init() {
addCmd.AddCommand(createAddExportCmd())
}
type AddExportParams struct {
AccountContextParams
claim *jwt.AccountClaims
export jwt.Export
private bool
service bool
SignerParams
subject string
latSubject string
latSampling string
responseType string
}
func (p *AddExportParams) longHelp() string {
s := `toolName add export -i
toolName add export --subject "a.b.c.>"
toolName add export --service --subject a.b
toolName add export --name myexport --subject a.b --service`
return strings.Replace(s, "toolName", GetToolName(), -1)
}
func (p *AddExportParams) SetDefaults(ctx ActionCtx) error {
p.AccountContextParams.SetDefaults(ctx)
p.SignerParams.SetDefaults(nkeys.PrefixByteOperator, true, ctx)
p.export.TokenReq = p.private
p.export.Subject = jwt.Subject(p.subject)
p.export.Type = jwt.Stream
if p.service {
p.export.Type = jwt.Service
p.export.ResponseType = jwt.ResponseType(p.responseType)
}
if p.export.Name == "" {
p.export.Name = p.subject
}
return nil
}
func (p *AddExportParams) PreInteractive(ctx ActionCtx) error {
var err error
if err = p.AccountContextParams.Edit(ctx); err != nil {
return err
}
choices := []string{jwt.Stream.String(), jwt.Service.String()}
i, err := cli.Select("export type", p.export.Type.String(), choices)
if err != nil {
return err
}
if i == 0 {
p.export.Type = jwt.Stream
} else {
p.export.Type = jwt.Service
}
svFn := func(s string) error {
p.export.Subject = jwt.Subject(s)
var vr jwt.ValidationResults
p.export.Validate(&vr)
if len(vr.Issues) > 0 {
return errors.New(vr.Issues[0].Description)
}
return nil
}
p.subject, err = cli.Prompt("subject", p.subject, cli.Val(svFn))
if err != nil {
return err
}
p.export.Subject = jwt.Subject(p.subject)
if p.export.Name == "" {
p.export.Name = p.subject
}
p.export.Name, err = cli.Prompt("name", p.export.Name, cli.NewLengthValidator(1))
if err != nil {
return err
}
p.export.TokenReq, err = cli.Confirm(fmt.Sprintf("private %s", p.export.Type.String()), p.export.TokenReq)
if err != nil {
return err
}
if p.export.IsService() {
ok, err := cli.Confirm("track service latency", false)
if err != nil {
return err
}
if ok {
samp, err := cli.Prompt("sampling percentage [1-100] or `header`", "", cli.Val(SamplingValidator))
if err != nil {
return err
}
p.latSampling = samp
p.latSubject, err = cli.Prompt("latency metrics subject", "", cli.Val(LatencyMetricsSubjectValidator))
if err != nil {
return err
}
}
choices := []string{jwt.ResponseTypeSingleton, jwt.ResponseTypeStream, jwt.ResponseTypeChunked}
s, err := cli.Select("service response type", string(p.export.ResponseType), choices)
if err != nil {
return err
}
p.export.ResponseType = jwt.ResponseType(choices[s])
}
if err := p.SignerParams.Edit(ctx); err != nil {
return err
}
return nil
}
func SamplingValidator(s string) error {
if strings.ToLower(s) == "header" {
return nil
}
v, err := strconv.Atoi(s)
if err != nil {
return err
}
if v < 1 || v > 100 {
return errors.New("sampling must be between 1 and 100 inclusive")
}
return nil
}
func latSamplingRate(latSampling string) jwt.SamplingRate {
samp := 0
if strings.ToLower(latSampling) == "header" {
samp = int(jwt.Headers)
} else {
// cannot fail
samp, _ = strconv.Atoi(latSampling)
}
return jwt.SamplingRate(samp)
}
func latSamplingRateToString(rate jwt.SamplingRate) string {
if rate == jwt.Headers {
return "header"
} else {
return fmt.Sprintf("%d", rate)
}
}
func LatencyMetricsSubjectValidator(s string) error {
var lat jwt.ServiceLatency
// bogus freq just to get a value into the validation
lat.Sampling = 100
lat.Results = jwt.Subject(s)
var vr jwt.ValidationResults
lat.Validate(&vr)
if len(vr.Issues) > 0 {
return errors.New(vr.Issues[0].Description)
}
return nil
}
func (p *AddExportParams) Load(ctx ActionCtx) error {
var err error
if err = p.AccountContextParams.Validate(ctx); err != nil {
return err
}
p.claim, err = ctx.StoreCtx().Store.ReadAccountClaim(p.AccountContextParams.Name)
if err != nil {
return err
}
return nil
}
func (p *AddExportParams) PostInteractive(_ ActionCtx) error {
return nil
}
func (p *AddExportParams) Validate(ctx ActionCtx) error {
var err error
if p.subject == "" {
ctx.CurrentCmd().SilenceUsage = false
return errors.New("a subject is required")
}
// get the old validation results
var vr jwt.ValidationResults
if err = p.claim.Exports.Validate(&vr); err != nil {
return err
}
// if we have a latency report subject create it
if p.latSubject != "" {
p.export.Latency = &jwt.ServiceLatency{Results: jwt.Subject(p.latSubject), Sampling: latSamplingRate(p.latSampling)}
}
// add the new export
p.claim.Exports.Add(&p.export)
var vr2 jwt.ValidationResults
if err = p.claim.Exports.Validate(&vr2); err != nil {
return err
}
// filter out all the old validations
uvr := jwt.CreateValidationResults()
if len(vr.Issues) > 0 {
for _, nis := range vr.Issues {
for _, is := range vr2.Issues {
if nis.Description == is.Description {
continue
}
}
uvr.Add(nis)
}
} else {
uvr = &vr2
}
// fail validation
if len(uvr.Issues) > 0 {
return errors.New(uvr.Issues[0].Error())
}
if p.service {
rt := jwt.ResponseType(p.responseType)
if rt != jwt.ResponseTypeSingleton &&
rt != jwt.ResponseTypeStream &&
rt != jwt.ResponseTypeChunked {
return fmt.Errorf("unknown response type %q", p.responseType)
}
p.export.ResponseType = rt
}
if err = p.SignerParams.Resolve(ctx); err != nil {
return err
}
return nil
}
func (p *AddExportParams) Run(ctx ActionCtx) (store.Status, error) {
token, err := p.claim.Encode(p.signerKP)
if err != nil {
return nil, err
}
visibility := "public"
if p.export.TokenReq {
visibility = "private"
}
r := store.NewDetailedReport(false)
StoreAccountAndUpdateStatus(ctx, token, r)
if r.HasNoErrors() {
r.AddOK("added %s %s export %q", visibility, p.export.Type, p.export.Name)
}
return r, err
}