-
-
Notifications
You must be signed in to change notification settings - Fork 520
/
cmd_preview.go
299 lines (274 loc) · 9.34 KB
/
cmd_preview.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
package cli
import (
"bufio"
"context"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"google.golang.org/grpc"
empty "google.golang.org/protobuf/types/known/emptypb"
"github.com/telepresenceio/telepresence/rpc/v2/connector"
"github.com/telepresenceio/telepresence/rpc/v2/manager"
"github.com/telepresenceio/telepresence/v2/pkg/client/cache"
"github.com/telepresenceio/telepresence/v2/pkg/client/cli/cliutil"
"github.com/telepresenceio/telepresence/v2/pkg/client/scout"
)
// AddPreviewFlags mutates 'flags', adding flags to it such that the flags set the appropriate
// fields in the given 'spec'. If 'prefix' is given, long-flag names are prefixed with it.
func AddPreviewFlags(prefix string, flags *pflag.FlagSet, spec *manager.PreviewSpec) {
flags.BoolVarP(&spec.DisplayBanner, prefix+"banner", "b", true, "Display banner on preview page")
flags.StringToStringVarP(&spec.AddRequestHeaders, prefix+"add-request-headers", "", map[string]string{},
"Additional headers in key1=value1,key2=value2 pairs injected in every preview page request")
}
type UpdateInterceptFn func(context.Context, *manager.UpdateInterceptRequest) (*manager.InterceptInfo, error)
func clientUpdateInterceptFn(client manager.ManagerClient, opts ...grpc.CallOption) UpdateInterceptFn {
return func(ctx context.Context, req *manager.UpdateInterceptRequest) (*manager.InterceptInfo, error) {
return client.UpdateIntercept(ctx, req, opts...)
}
}
func AddPreviewDomain(ctx context.Context, reporter *scout.Reporter, updateInterceptFn UpdateInterceptFn, sess *manager.SessionInfo, iceptName string,
previewSpec *manager.PreviewSpec) (*manager.InterceptInfo, error) {
intercept, err := updateInterceptFn(ctx, &manager.UpdateInterceptRequest{
Session: sess,
Name: iceptName,
PreviewDomainAction: &manager.UpdateInterceptRequest_AddPreviewDomain{
AddPreviewDomain: previewSpec,
},
})
if err != nil {
reporter.Report(ctx, "preview_domain_create_fail", scout.Entry{Key: "error", Value: err.Error()})
err = fmt.Errorf("creating preview domain: %w", err)
return nil, err
}
reporter.SetMetadatum(ctx, "preview_url", intercept.PreviewDomain)
reporter.Report(ctx, "preview_domain_create_success")
return intercept, nil
}
func previewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "preview",
Args: OnlySubcommands,
Short: "Create or remove preview domains for existing intercepts",
RunE: RunSubcommands,
}
var createSpec manager.PreviewSpec
createCmd := &cobra.Command{
Use: "create [flags] <intercept_name>",
Args: cobra.ExactArgs(1),
Short: "Create a preview domain for an existing intercept",
RunE: func(cmd *cobra.Command, args []string) error {
return withConnector(cmd, true, nil, func(ctx context.Context, cs *connectorState) error {
if _, err := cliutil.ClientEnsureLoggedIn(cmd.Context(), "", cs.userD); err != nil {
return err
}
reporter := scout.NewReporter(ctx, "cli")
reporter.Start(ctx)
return cliutil.WithManager(ctx, func(ctx context.Context, managerClient manager.ManagerClient) error {
if createSpec.Ingress == nil {
request := manager.GetInterceptRequest{Session: cs.SessionInfo, Name: args[0]}
// Throws rpc "not found" error if intercept has not yet been created
interceptInfo, err := managerClient.GetIntercept(ctx, &request)
if err != nil {
return err
}
iis, err := cs.userD.GetIngressInfos(ctx, &empty.Empty{})
if err != nil {
return err
}
ingress, err := selectIngress(ctx, cmd.InOrStdin(), cmd.OutOrStdout(), cs.ConnectInfo, interceptInfo.Spec.Agent, interceptInfo.Spec.Namespace, iis.IngressInfos)
if err != nil {
return err
}
createSpec.Ingress = ingress
}
intercept, err := AddPreviewDomain(ctx, reporter,
clientUpdateInterceptFn(managerClient),
cs.SessionInfo,
args[0], // intercept name
&createSpec)
if err != nil {
return err
}
fmt.Println(cliutil.DescribeIntercepts([]*manager.InterceptInfo{intercept}, nil, false))
return nil
})
})
},
}
AddPreviewFlags("", createCmd.Flags(), &createSpec)
removeCmd := &cobra.Command{
Use: "remove <intercept_name>",
Args: cobra.ExactArgs(1),
Short: "Remove a preview domain from an intercept",
RunE: func(cmd *cobra.Command, args []string) error {
return withConnector(cmd, true, nil, func(ctx context.Context, cs *connectorState) error {
return cliutil.WithManager(ctx, func(ctx context.Context, managerClient manager.ManagerClient) error {
intercept, err := managerClient.UpdateIntercept(ctx, &manager.UpdateInterceptRequest{
Session: cs.SessionInfo,
Name: args[0],
PreviewDomainAction: &manager.UpdateInterceptRequest_RemovePreviewDomain{
RemovePreviewDomain: true,
},
})
if err != nil {
return err
}
fmt.Println(cliutil.DescribeIntercepts([]*manager.InterceptInfo{intercept}, nil, false))
return nil
})
})
},
}
cmd.AddCommand(createCmd, removeCmd)
return cmd
}
func selectIngress(
ctx context.Context,
in io.Reader,
out io.Writer,
connInfo *connector.ConnectInfo,
interceptName string,
interceptNamespace string,
ingressInfos []*manager.IngressInfo,
) (*manager.IngressInfo, error) {
infos, err := cache.LoadIngressesFromUserCache(ctx)
if err != nil {
return nil, err
}
key := connInfo.ClusterServer + "/" + connInfo.ClusterContext
selectOrConfirm := "Confirm"
cachedIngressInfo := infos[key]
if cachedIngressInfo == nil {
iis := ingressInfos
if len(iis) > 0 {
cachedIngressInfo = iis[0] // TODO: Better handling when there are several alternatives. Perhaps use SystemA for this?
} else {
selectOrConfirm = "Select" // Hard to confirm unless there's a default.
if interceptNamespace == "" {
interceptNamespace = "default"
}
cachedIngressInfo = &manager.IngressInfo{
// Default Settings
Host: fmt.Sprintf("%s.%s", interceptName, interceptNamespace),
Port: 80,
UseTls: false,
}
}
}
reader := bufio.NewReader(in)
fmt.Fprintf(out, "\n"+ingressDesc+"\n", selectOrConfirm)
reply := &manager.IngressInfo{}
if reply.Host, err = askForHost(ingressQ1, cachedIngressInfo.Host, reader, out); err != nil {
return nil, err
}
if reply.Port, err = askForPortNumber(cachedIngressInfo.Port, reader, out); err != nil {
return nil, err
}
if reply.UseTls, err = askForUseTLS(cachedIngressInfo.UseTls, reader, out); err != nil {
return nil, err
}
if cachedIngressInfo.L5Host == "" {
cachedIngressInfo.L5Host = reply.Host
}
if reply.L5Host, err = askForHost(ingressQ4, cachedIngressInfo.L5Host, reader, out); err != nil {
return nil, err
}
fmt.Fprintln(out)
if !ingressInfoEqual(cachedIngressInfo, reply) {
infos[key] = reply
if err = cache.SaveIngressesToUserCache(ctx, infos); err != nil {
return nil, err
}
}
return reply, nil
}
func ingressInfoEqual(a, b *manager.IngressInfo) bool {
return a.Host == b.Host && a.L5Host == b.L5Host && a.Port == b.Port && a.UseTls == b.UseTls
}
const (
ingressDesc = `To create a preview URL, telepresence needs to know how requests enter
your cluster. Please %s the ingress to use.`
ingressQ1 = `1/4: What's your ingress' IP address?
You may use an IP address or a DNS name (this is usually a
"service.namespace" DNS name).`
ingressQ2 = `2/4: What's your ingress' TCP port number?`
ingressQ3 = `3/4: Does that TCP port on your ingress use TLS (as opposed to cleartext)?`
ingressQ4 = `4/4: If required by your ingress, specify a different hostname
(TLS-SNI, HTTP "Host" header) to be used in requests.`
)
func showPrompt(out io.Writer, question string, defaultValue any) {
if reflect.ValueOf(defaultValue).IsZero() {
fmt.Fprintf(out, "\n%s\n\n [no default]: ", question)
} else {
fmt.Fprintf(out, "\n%s\n\n [default: %v]: ", question, defaultValue)
}
}
func askForHost(question, cachedHost string, reader *bufio.Reader, out io.Writer) (string, error) {
for {
showPrompt(out, question, cachedHost)
reply, err := reader.ReadString('\n')
if err != nil {
return "", err
}
reply = strings.TrimSpace(reply)
if reply == "" {
if cachedHost == "" {
continue
}
return cachedHost, nil
}
if cliutil.HostRx.MatchString(reply) {
return reply, nil
}
fmt.Fprintf(out,
"Address %q must match the regex [a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)* (e.g. 'myingress.mynamespace')\n",
reply)
}
}
func askForPortNumber(cachedPort int32, reader *bufio.Reader, out io.Writer) (int32, error) {
for {
showPrompt(out, ingressQ2, cachedPort)
reply, err := reader.ReadString('\n')
if err != nil {
return 0, err
}
reply = strings.TrimSpace(reply)
if reply == "" {
if cachedPort == 0 {
continue
}
return cachedPort, nil
}
port, err := strconv.Atoi(reply)
if err == nil && port > 0 {
return int32(port), nil
}
fmt.Fprintln(out, "port must be a positive integer")
}
}
func askForUseTLS(cachedUseTLS bool, reader *bufio.Reader, out io.Writer) (bool, error) {
yn := "n"
if cachedUseTLS {
yn = "y"
}
showPrompt(out, ingressQ3, yn)
for {
reply, err := reader.ReadString('\n')
if err != nil {
return false, err
}
switch strings.TrimSpace(reply) {
case "":
return cachedUseTLS, nil
case "n", "N":
return false, nil
case "y", "Y":
return true, nil
}
fmt.Fprintf(out, " please answer 'y' or 'n'\n [default: %v]: ", yn)
}
}