-
Notifications
You must be signed in to change notification settings - Fork 688
/
intercept.go
429 lines (368 loc) · 11.8 KB
/
intercept.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package edgectl
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/datawire/ambassador/pkg/supervisor"
)
func (d *Daemon) interceptMessage() string {
switch {
case d.cluster == nil:
return "Not connected (use 'edgectl connect' to connect to your cluster)"
case d.trafficMgr == nil:
return "Intercept unavailable: no traffic manager"
case !d.trafficMgr.IsOkay():
if d.trafficMgr.apiErr != nil {
return d.trafficMgr.apiErr.Error()
} else {
return "Connecting to traffic manager..."
}
default:
return ""
}
}
// InterceptInfo tracks one intercept operation
type InterceptInfo struct {
Name string // Name of the intercept (user/logging)
Namespace string // Namespace in which to create the Intercept mapping
Deployment string // Name of the deployment being intercepted
Prefix string // Prefix to intercept (default /)
Patterns map[string]string
TargetHost string
TargetPort int
}
// path returns the URL path for this intercept
func (ii *InterceptInfo) path() string {
return fmt.Sprintf("intercept/%s/%s", ii.Namespace, ii.Deployment)
}
// PreviewURL returns the Service Preview URL for this intercept if it is
// configured appropriately, or the empty string otherwise.
func (ii *InterceptInfo) PreviewURL(hostname string) (url string) {
if hostname == "" || len(ii.Patterns) != 1 {
return
}
for header, token := range ii.Patterns {
if strings.ToLower(header) != "x-service-preview" {
return
}
url = fmt.Sprintf("https://%s/.ambassador/service-preview/%s/", hostname, token)
}
return
}
// Acquire an intercept from the traffic manager
func (ii *InterceptInfo) Acquire(_ *supervisor.Process, tm *TrafficManager) (int, error) {
reqPatterns := make([]map[string]string, 0, len(ii.Patterns))
for header, regex := range ii.Patterns {
pattern := map[string]string{"name": header, "regex_match": regex}
reqPatterns = append(reqPatterns, pattern)
}
request := map[string]interface{}{
"name": ii.Name,
"patterns": reqPatterns,
}
reqData, err := json.Marshal(request)
if err != nil {
return 0, err
}
result, code, err := tm.request("POST", ii.path(), reqData)
if err != nil {
return 0, errors.Wrap(err, "acquire intercept")
}
if code == 404 {
return 0, fmt.Errorf("deployment %q is not known to the traffic manager", ii.Deployment)
}
if !(200 <= code && code <= 299) {
return 0, fmt.Errorf("acquire intercept: %s: %s", http.StatusText(code), result)
}
port, err := strconv.Atoi(result)
if err != nil {
return 0, errors.Wrapf(err, "bad port number from traffic manager: %q", result)
}
return port, nil
}
// Retain the given intercept. This likely needs to be called every
// five seconds or so.
func (ii *InterceptInfo) Retain(_ *supervisor.Process, tm *TrafficManager, port int) error {
data := []byte(fmt.Sprintf("{\"port\": %d}", port))
result, code, err := tm.request("POST", ii.path(), data)
if err != nil {
return errors.Wrap(err, "retain intercept")
}
if !(200 <= code && code <= 299) {
return fmt.Errorf("retain intercept: %s: %s", http.StatusText(code), result)
}
return nil
}
// Release the given intercept.
func (ii *InterceptInfo) Release(_ *supervisor.Process, tm *TrafficManager, port int) error {
data := []byte(fmt.Sprintf("%d", port))
result, code, err := tm.request("DELETE", ii.path(), data)
if err != nil {
return errors.Wrap(err, "release intercept")
}
if !(200 <= code && code <= 299) {
return fmt.Errorf("release intercept: %s: %s", http.StatusText(code), result)
}
return nil
}
// ListIntercepts lists active intercepts
func (d *Daemon) ListIntercepts(_ *supervisor.Process, out *Emitter) error {
msg := d.interceptMessage()
if msg != "" {
out.Println(msg)
out.Send("intercept", msg)
return nil
}
var previewURL string
for idx, cept := range d.intercepts {
ii := cept.ii
url := ii.PreviewURL(d.trafficMgr.previewHost)
out.Printf("%4d. %s\n", idx+1, ii.Name)
if url != "" {
previewURL = url
out.Println(" (preview URL available)")
}
out.Send(fmt.Sprintf("local_intercept.%d", idx+1), ii.Name)
key := "local_intercept." + ii.Name
out.Printf(" Intercepting requests to %s when\n", ii.Deployment)
out.Send(key, ii.Deployment)
for k, v := range ii.Patterns {
out.Printf(" - %s: %s\n", k, v)
out.Send(key+"."+k, v)
}
out.Printf(" and redirecting them to %s:%d\n", ii.TargetHost, ii.TargetPort)
out.Send(key+".host", ii.TargetHost)
out.Send(key+".port", ii.TargetPort)
}
if previewURL != "" {
out.Println("Share a preview of your changes with anyone by visiting\n ", previewURL)
}
if len(d.intercepts) == 0 {
out.Println("No intercepts")
}
return nil
}
// AddIntercept adds one intercept
func (d *Daemon) AddIntercept(p *supervisor.Process, out *Emitter, ii *InterceptInfo) error {
msg := d.interceptMessage()
if msg != "" {
out.Println(msg)
out.Send("intercept", msg)
return nil
}
for _, cept := range d.intercepts {
if cept.ii.Name == ii.Name {
out.Printf("Intercept with name %q already exists\n", ii.Name)
out.Send("failed", "intercept name exists")
out.SendExit(1)
return nil
}
}
// Do we already have a namespace?
if ii.Namespace == "" {
// Nope. See if we have an interceptable that matches the name.
matches := make([]InterceptInfo, 0)
for _, deployment := range d.trafficMgr.interceptables {
fields := strings.SplitN(deployment, "/", 2)
appName := fields[0]
appNamespace := d.cluster.namespace
if len(fields) > 1 {
appNamespace = fields[0]
appName = fields[1]
}
if ii.Deployment == appName {
// Abuse InterceptInfo rather than defining a new tuple type.
matches = append(matches, InterceptInfo{"", appNamespace, appName, "", nil, "", 0})
}
}
switch len(matches) {
case 0:
out.Printf("No interceptable deployment matching %s found\n", ii.Deployment)
out.Send("failed", "no interceptable deployment matches")
out.SendExit(1)
return nil
case 1:
// Good to go.
ii.Namespace = matches[0].Namespace
out.Printf("Using deployment %s in namespace %s\n", ii.Deployment, ii.Namespace)
default:
out.Printf("Found more than one possible match:\n")
for idx, match := range matches {
out.Printf("%4d: %s in namespace %s\n", idx+1, match.Deployment, match.Namespace)
}
out.Send("failed", "multiple interceptable deployment matched")
out.SendExit(1)
return nil
}
}
cept, err := MakeIntercept(p, out, d.trafficMgr, d.cluster, ii)
if err != nil {
out.Printf("Failed to establish intercept: %s\n", err)
out.Send("failed", err.Error())
out.SendExit(1)
return nil
}
d.intercepts = append(d.intercepts, cept)
out.Printf("Added intercept %q\n", ii.Name)
return nil
}
// RemoveIntercept removes one intercept by name
func (d *Daemon) RemoveIntercept(p *supervisor.Process, out *Emitter, name string) error {
msg := d.interceptMessage()
for idx, cept := range d.intercepts {
if cept.ii.Name == name {
d.intercepts = append(d.intercepts[:idx], d.intercepts[idx+1:]...)
out.Printf("Removed intercept %q\n", name)
if err := cept.Close(); err != nil {
out.Printf("Error while removing intercept: %v\n", err)
out.Send("failed", err.Error())
out.SendExit(1)
}
return nil
}
}
if msg != "" {
out.Println(msg)
out.Send("intercept", msg)
return nil
}
out.Printf("Intercept named %q not found\n", name)
out.Send("failed", "not found")
out.SendExit(1)
return nil
}
// ClearIntercepts removes all intercepts
func (d *Daemon) ClearIntercepts(p *supervisor.Process) error {
for _, cept := range d.intercepts {
if err := cept.Close(); err != nil {
p.Logf("Closing intercept %q: %v", cept.ii.Name, err)
}
}
d.intercepts = d.intercepts[:0]
return nil
}
// Intercept is a Resource handle that represents a live intercept
type Intercept struct {
ii *InterceptInfo
tm *TrafficManager
cluster *KCluster
port int
crc Resource
mappingExists bool
ResourceBase
}
// removeMapping drops an Intercept's mapping if needed (and possible).
func (cept *Intercept) removeMapping(p *supervisor.Process) error {
var err error
err = nil
if cept.mappingExists {
p.Logf("%v: Deleting mapping in namespace %v", cept.ii.Name, cept.ii.Namespace)
delete := cept.cluster.GetKubectlCmd(p, "delete", "-n", cept.ii.Namespace, "mapping", fmt.Sprintf("%s-mapping", cept.ii.Name))
err = delete.Run()
p.Logf("%v: Deleted mapping in namespace %v", cept.ii.Name, cept.ii.Namespace)
}
if err != nil {
return errors.Wrap(err, "Intercept: mapping could not be deleted")
}
return nil
}
type mappingMetadata struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
}
type mappingSpec struct {
AmbassadorID []string `json:"ambassador_id"`
Prefix string `json:"prefix"`
Service string `json:"service"`
RegexHeaders map[string]string `json:"regex_headers"`
}
type interceptMapping struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Metadata mappingMetadata `json:"metadata"`
Spec mappingSpec `json:"spec"`
}
// MakeIntercept acquires an intercept and returns a Resource handle
// for it
func MakeIntercept(p *supervisor.Process, out *Emitter, tm *TrafficManager, cluster *KCluster, ii *InterceptInfo) (*Intercept, error) {
port, err := ii.Acquire(p, tm)
if err != nil {
return nil, err
}
cept := &Intercept{ii: ii, tm: tm, cluster: cluster, port: port}
cept.mappingExists = false
cept.doCheck = cept.check
cept.doQuit = cept.quit
cept.setup(p.Supervisor(), ii.Name)
p.Logf("%s: Intercepting via port %v, using namespace %v", ii.Name, port, ii.Namespace)
mapping := interceptMapping{
APIVersion: "getambassador.io/v2",
Kind: "Mapping",
Metadata: mappingMetadata{
Name: fmt.Sprintf("%s-mapping", ii.Name),
Namespace: ii.Namespace,
},
Spec: mappingSpec{
AmbassadorID: []string{fmt.Sprintf("intercept-%s", ii.Deployment)},
Prefix: ii.Prefix,
Service: fmt.Sprintf("telepresence-proxy.%s:%d", tm.namespace, port),
RegexHeaders: ii.Patterns,
},
}
manifest, err := json.MarshalIndent(&mapping, "", " ")
if err != nil {
_ = cept.Close()
return nil, errors.Wrap(err, "Intercept: mapping could not be constructed")
}
out.Printf("%s: applying intercept mapping in namespace %s\n", ii.Name, ii.Namespace)
apply := cluster.GetKubectlCmdNoNamespace(p, "apply", "-f", "-")
apply.Stdin = strings.NewReader(string(manifest))
err = apply.Run()
if err != nil {
p.Logf("%v: Intercept could not apply mapping: %v", ii.Name, err)
_ = cept.Close()
return nil, errors.Wrap(err, "Intercept: kubectl apply")
}
cept.mappingExists = true
sshCmd := []string{
"ssh", "-C", "-N", "telepresence@localhost",
"-oConnectTimeout=10", "-oExitOnForwardFailure=yes",
"-oStrictHostKeyChecking=no", "-oUserKnownHostsFile=/dev/null",
"-p", strconv.Itoa(tm.sshPort),
"-R", fmt.Sprintf("%d:%s:%d", cept.port, ii.TargetHost, ii.TargetPort),
}
p.Logf("%s: starting SSH tunnel", ii.Name)
out.Printf("%s: starting SSH tunnel\n", ii.Name)
ssh, err := CheckedRetryingCommand(p, ii.Name+"-ssh", sshCmd, nil, nil, 5*time.Second)
if err != nil {
_ = cept.Close()
return nil, err
}
cept.crc = ssh
return cept, nil
}
func (cept *Intercept) check(p *supervisor.Process) error {
return cept.ii.Retain(p, cept.tm, cept.port)
}
func (cept *Intercept) quit(p *supervisor.Process) error {
cept.done = true
p.Logf("cept.Quit removing %v", cept.ii.Name)
if err := cept.removeMapping(p); err != nil {
p.Logf("cept.Quit failed to remove %v: %+v", cept.ii.Name, err)
} else {
p.Logf("cept.Quit removed %v", cept.ii.Name)
}
if cept.crc != nil {
_ = cept.crc.Close()
}
p.Logf("cept.Quit releasing %v", cept.ii.Name)
if err := cept.ii.Release(p, cept.tm, cept.port); err != nil {
p.Log(err)
}
p.Logf("cept.Quit released %v", cept.ii.Name)
return nil
}