-
Notifications
You must be signed in to change notification settings - Fork 155
/
metadata_handlers.go
720 lines (649 loc) · 22.5 KB
/
metadata_handlers.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
// Copyright (c) 2023 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package zedrouter
import (
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"path"
"strings"
"github.com/go-chi/chi/v5"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/lf-edge/eve/pkg/pillar/zedcloud"
"github.com/lf-edge/eve/pkg/pillar/utils"
fileutils "github.com/lf-edge/eve/pkg/pillar/utils/file"
)
// Provides a json file
type networkHandler struct {
zedrouter *zedrouter
}
// Provides a LF-terminated text
type externalIPHandler struct {
zedrouter *zedrouter
}
// Provides a LF-terminated text
type hostnameHandler struct {
zedrouter *zedrouter
}
// Provides links for OpenStack metadata/userdata
type openstackHandler struct {
zedrouter *zedrouter
}
// Let's application to report various metadata back to the cloud. At the
// moment used for:
// - k3s cluster kubeconfig
// - reporting custom application status
type appInstMetaHandler struct {
zedrouter *zedrouter
maxResponseLen int
publishDataType types.AppInstMetaDataType
}
// Provides geographic location of the device.
type locationInfoHandler struct {
zedrouter *zedrouter
}
// Provides information about cellular connectivity of the device
// (modems, SIM cards, network providers, etc.).
type wwanStatusHandler struct {
zedrouter *zedrouter
}
// Provides cellular metrics (signal strength, packet counters).
type wwanMetricsHandler struct {
zedrouter *zedrouter
}
// Provides a signing service
type signerHandler struct {
zedrouter *zedrouter
zedcloudCtx *zedcloud.ZedCloudContext
}
// Provides the /opt/zededa/bin/diag output as text
type diagHandler struct {
zedrouter *zedrouter
zedcloudCtx *zedcloud.ZedCloudContext
}
// AppInfoHandler provides information about available patches for the application
type AppInfoHandler struct {
zedrouter *zedrouter
}
// AppCustomBlobsHandler serves the AppCustom binary blobs
type AppCustomBlobsHandler struct {
zedrouter *zedrouter
}
type middlewareKeys int
const (
patchEnvelopesContextKey middlewareKeys = iota
appUUIDContextKey
)
// ServeHTTP for networkHandler provides a json return
func (hdl networkHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("networkHandler.ServeHTTP")
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
externalIP, code := hdl.zedrouter.getExternalIPForApp(remoteIP)
var ipStr string
var hostname string
// Avoid returning the string <nil>
if !isEmptyIP(externalIP) {
ipStr = externalIP.String()
}
anStatus := hdl.zedrouter.lookupAppNetworkStatusByAppIP(remoteIP)
if anStatus != nil {
hostname = anStatus.UUIDandVersion.UUID.String()
}
enInfoObj, err := hdl.zedrouter.subEdgeNodeInfo.Get("global")
if err != nil {
errorLine := fmt.Sprintf("cannot fetch edge node information: %s", err)
hdl.zedrouter.log.Error(errorLine)
http.Error(w, errorLine, http.StatusInternalServerError)
return
}
enInfo := enInfoObj.(types.EdgeNodeInfo)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(code)
resp, _ := json.Marshal(map[string]interface{}{
"caller-ip": r.RemoteAddr,
"external-ipv4": ipStr,
"hostname": hostname, // Do not delete this line for backward compatibility
"app-instance-uuid": hostname,
"device-uuid": enInfo.DeviceID,
"device-name": enInfo.DeviceName,
"project-name": enInfo.ProjectName,
"project-uuid": enInfo.ProjectID,
"enterprise-name": enInfo.EnterpriseName,
"enterprise-id": enInfo.EnterpriseID,
// TBD: add public-ipv4 when controller tells us
})
w.Write(resp)
}
// ServeHTTP for externalIPHandler provides a text IP address
func (hdl externalIPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("externalIPHandler.ServeHTTP")
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
externalIP, code := hdl.zedrouter.getExternalIPForApp(remoteIP)
w.WriteHeader(code)
w.Header().Add("Content-Type", "text/plain")
// Avoid returning the string <nil>
if !isEmptyIP(externalIP) {
resp := []byte(externalIP.String() + "\n")
w.Write(resp)
}
}
// ServeHTTP for hostnameHandler returns text
func (hdl hostnameHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("hostnameHandler.ServeHTTP")
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
anStatus := hdl.zedrouter.lookupAppNetworkStatusByAppIP(remoteIP)
w.Header().Add("Content-Type", "text/plain")
if anStatus == nil {
w.WriteHeader(http.StatusNoContent)
hdl.zedrouter.log.Errorf("No AppNetworkStatus for %s",
remoteIP.String())
} else {
w.WriteHeader(http.StatusOK)
resp := []byte(anStatus.UUIDandVersion.UUID.String() + "\n")
w.Write(resp)
}
}
// ServeHTTP for openstackHandler metadata service
func (hdl openstackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("openstackHandler ServeHTTP request: %s", r.URL.String())
dirname, filename := path.Split(strings.TrimSuffix(r.URL.Path, "/"))
dirname = strings.TrimSuffix(dirname, "/")
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
anStatus := hdl.zedrouter.lookupAppNetworkStatusByAppIP(remoteIP)
var hostname string
var id string
if anStatus != nil {
hostname = anStatus.DisplayName
id = anStatus.UUIDandVersion.UUID.String()
} else {
errorLine := fmt.Sprintf("no AppNetworkStatus for %s",
remoteIP.String())
hdl.zedrouter.log.Error(errorLine)
http.Error(w, errorLine, http.StatusNotImplemented)
return
}
anConfig := hdl.zedrouter.lookupAppNetworkConfig(anStatus.Key())
if anConfig == nil {
errorLine := fmt.Sprintf("no AppNetworkConfig for %s",
anStatus.Key())
hdl.zedrouter.log.Error(errorLine)
http.Error(w, errorLine, http.StatusNotImplemented)
return
}
if anConfig.MetaDataType != types.MetaDataOpenStack {
errorLine := fmt.Sprintf("no MetaDataOpenStack for %s",
anStatus.Key())
hdl.zedrouter.log.Tracef(errorLine)
http.Error(w, errorLine, http.StatusNotFound)
return
}
switch filename {
case "openstack":
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "latest")
case "meta_data.json":
keys := hdl.zedrouter.getSSHPublicKeys(anConfig)
var keysMap []map[string]string
publicKeys := make(map[string]string)
for ind, key := range keys {
keysMap = append(keysMap, map[string]string{
"data": fmt.Sprintf("%s\n", key),
"type": "ssh",
"name": fmt.Sprintf("key-%d", ind),
})
publicKeys[fmt.Sprintf("key-%d", ind)] = fmt.Sprintf("%s\n", key)
}
resp, _ := json.Marshal(map[string]interface{}{
"uuid": id,
"hostname": hostname,
"name": hostname,
"launch_index": 0,
"keys": keysMap,
"public_keys": publicKeys,
})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(resp)
case "network_data.json":
resp, _ := json.Marshal(map[string]interface{}{
"services": []string{},
"networks": []string{},
})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(resp)
case "user_data":
userData, err := hdl.zedrouter.getCloudInitUserData(anConfig)
if err != nil {
errorLine := fmt.Sprintf("cannot get userData for %s: %v",
anStatus.Key(), err)
hdl.zedrouter.log.Error(errorLine)
http.Error(w, errorLine, http.StatusInternalServerError)
return
}
ud, err := base64.StdEncoding.DecodeString(userData)
if err != nil {
errorLine := fmt.Sprintf("cannot decode userData for %s: %v",
anStatus.Key(), err)
hdl.zedrouter.log.Error(errorLine)
http.Error(w, errorLine, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/yaml")
w.WriteHeader(http.StatusOK)
w.Write(ud)
case "vendor_data.json":
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
}
w.WriteHeader(http.StatusNotFound)
}
// ServeHTTP for kubeConfigHandler provides cluster kube config
func (hdl appInstMetaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
msg := "appInstMetaHandler: request method is not Post"
hdl.zedrouter.log.Error(msg)
http.Error(w, msg, http.StatusMethodNotAllowed)
return
}
if r.Header.Get("Content-Type") != "application/json" {
msg := "appInstMetaHandler: Content-Type header is not application/json"
hdl.zedrouter.log.Error(msg)
http.Error(w, msg, http.StatusUnsupportedMediaType)
return
}
kubeConfig, err := io.ReadAll(io.LimitReader(r.Body, AppInstMetadataResponseSizeLimitInBytes))
if err != nil {
msg := fmt.Sprintf("appInstMetaHandler: ReadAll failed: %v", err)
hdl.zedrouter.log.Errorf(msg)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if binary.Size(kubeConfig) > hdl.maxResponseLen {
msg := fmt.Sprintf("appInstMetaHandler: kubeconfig size exceeds limit. Expected <= %v, actual size: %v",
hdl.maxResponseLen, binary.Size(kubeConfig))
hdl.zedrouter.log.Errorf(msg)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
anStatus := hdl.zedrouter.lookupAppNetworkStatusByAppIP(remoteIP)
if anStatus == nil {
msg := fmt.Sprintf("appInstMetaHandler: no AppNetworkStatus for %s", remoteIP.String())
hdl.zedrouter.log.Errorf(msg)
http.Error(w, http.StatusText(http.StatusNoContent), http.StatusNoContent)
return
}
var appInstMetaData = &types.AppInstMetaData{
AppInstUUID: anStatus.UUIDandVersion.UUID,
Data: kubeConfig,
Type: hdl.publishDataType,
}
hdl.zedrouter.publishAppInstMetadata(appInstMetaData)
return
}
// ServeHTTP for locationInfoHandler provides a json return
func (hdl locationInfoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("locationInfoHandler.ServeHTTP")
locInfoObj, err := hdl.zedrouter.subLocationInfo.Get("global")
if err != nil {
http.Error(w, http.StatusText(http.StatusNoContent), http.StatusNoContent)
return
}
locInfo := locInfoObj.(types.WwanLocationInfo)
resp, err := json.Marshal(locInfo)
if err != nil {
msg := fmt.Sprintf("Failed to marshal location info: %v", err)
hdl.zedrouter.log.Errorf(msg)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(resp)
}
// ServeHTTP for wwanStatusHandler returns json output.
func (hdl wwanStatusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("wwanStatusHandler.ServeHTTP")
statusObj, err := hdl.zedrouter.subWwanStatus.Get("global")
if err != nil {
http.Error(w, http.StatusText(http.StatusNoContent), http.StatusNoContent)
return
}
status := statusObj.(types.WwanStatus)
// SIM card and modem (logical) names are not relevant to applications.
// They are generated by EVE and used in the EVE<->Controller API (ZInfoDevice)
// for reference purposes. ConfigChecksum is also cleared because it is used
// only internally by EVE microservices.
// All these fields will be completely omitted from the json output
// (all have omitempty json tag).
for i := range status.Networks {
status.Networks[i].Module.Name = ""
for j := range status.Networks[i].SimCards {
status.Networks[i].SimCards[j].Name = ""
}
}
resp, err := json.Marshal(status)
if err != nil {
msg := fmt.Sprintf("Failed to marshal WWAN status: %v", err)
hdl.zedrouter.log.Errorf(msg)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(resp)
}
// ServeHTTP for wwanMetricsHandler returns json output.
func (hdl wwanMetricsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("wwanMetricsHandler.ServeHTTP")
metricsObj, err := hdl.zedrouter.subWwanMetrics.Get("global")
if err != nil {
http.Error(w, http.StatusText(http.StatusNoContent), http.StatusNoContent)
return
}
metrics := metricsObj.(types.WwanMetrics)
resp, err := json.Marshal(metrics)
if err != nil {
msg := fmt.Sprintf("Failed to marshal WWAN metrics: %v", err)
hdl.zedrouter.log.Errorf(msg)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(resp)
}
// ServeHTTP for signerHandler returns protobuf output
func (hdl signerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("signerHandler.ServeHTTP")
if r.Method != http.MethodPost {
msg := "signerHandler: request method is not POST"
hdl.zedrouter.log.Error(msg)
http.Error(w, msg, http.StatusMethodNotAllowed)
return
}
// One larger to make sure we detect too large below.
payload, err := io.ReadAll(io.LimitReader(r.Body, SignerMaxSize+1))
if err != nil {
msg := fmt.Sprintf("signerHandler: ReadAll failed: %v", err)
hdl.zedrouter.log.Errorf(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
if binary.Size(payload) > SignerMaxSize {
msg := fmt.Sprintf("signerHandler: size exceeds limit. Expected <= %v",
SignerMaxSize)
hdl.zedrouter.log.Errorf(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
anStatus := hdl.zedrouter.lookupAppNetworkStatusByAppIP(remoteIP)
if anStatus == nil {
msg := fmt.Sprintf("signerHandler: no AppNetworkStatus for %s",
remoteIP.String())
hdl.zedrouter.log.Errorf(msg)
http.Error(w, msg, http.StatusForbidden)
return
}
resp, err := zedcloud.AddAuthentication(hdl.zedcloudCtx,
bytes.NewBuffer(payload), false)
if err != nil {
msg := fmt.Sprintf("Failed to AddAuthentication: %v", err)
hdl.zedrouter.log.Errorf(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/x-proto-binary")
w.WriteHeader(http.StatusOK)
w.Write(resp.Bytes())
}
// ServeHTTP for diagHandler returns text output
func (hdl diagHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("diagHandler.ServeHTTP")
if r.Method != http.MethodGet {
msg := "diagHandler: request method is not GET"
hdl.zedrouter.log.Error(msg)
http.Error(w, msg, http.StatusMethodNotAllowed)
return
}
// Check that request comes from a source IP for an app instance
// to avoid returning data to others.
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
anStatus := hdl.zedrouter.lookupAppNetworkStatusByAppIP(remoteIP)
if anStatus == nil {
msg := fmt.Sprintf("diagHandler: no AppNetworkStatus for %s",
remoteIP.String())
hdl.zedrouter.log.Errorf(msg)
http.Error(w, msg, http.StatusForbidden)
return
}
const diagStatefile = "/run/diag.out"
if _, err := os.Stat(diagStatefile); err != nil && os.IsNotExist(err) {
msg := "diagHandler: file not found"
hdl.zedrouter.log.Error(msg)
http.Error(w, msg, http.StatusNotFound)
return
}
b, err := fileutils.ReadWithMaxSize(hdl.zedrouter.log, diagStatefile,
DiagMaxSize+1)
if err != nil {
msg := fmt.Sprintf("diagHandler: read: %v", err)
hdl.zedrouter.log.Errorf(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
if len(b) > DiagMaxSize {
msg := fmt.Sprintf("diagHandler: size exceeds limit. Expected <= %v",
DiagMaxSize)
hdl.zedrouter.log.Errorf(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "text")
w.WriteHeader(http.StatusOK)
w.Write(b)
}
func (hdl AppInfoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hdl.zedrouter.log.Tracef("wwanAppInfoHandler.ServeHTTP")
w.Header().Add("Content-Type", "application/json")
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
anStatus := hdl.zedrouter.lookupAppNetworkStatusByAppIP(remoteIP)
if anStatus == nil {
hdl.zedrouter.log.Errorf("Could not find network instance by ip %v", remoteIP)
w.WriteHeader(http.StatusOK)
w.Write([]byte("not found"))
return
}
diskStatusList := hdl.zedrouter.lookupDiskStatusList(
anStatus.UUIDandVersion.UUID.String())
var appInfo types.AppInfo
for _, st := range diskStatusList {
if st.Devtype != "AppCustom" {
continue
}
blob := types.AppBlobsAvailable{
CustomMeta: st.CustomMeta,
DownloadURL: fmt.Sprintf("http://%s/eve/app-custom-blobs/%s",
MetaDataServerIP, st.DisplayName),
}
appInfo.AppBlobs = append(appInfo.AppBlobs, blob)
}
resp, _ := json.Marshal(appInfo)
w.WriteHeader(http.StatusOK)
w.Write(resp)
}
func (hdl AppCustomBlobsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
blobName := path.Base(r.URL.Path)
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
anStatus := hdl.zedrouter.lookupAppNetworkStatusByAppIP(remoteIP)
if anStatus == nil {
hdl.zedrouter.log.Errorf("Could not find network instance by ip %v", remoteIP)
w.WriteHeader(http.StatusOK)
w.Write([]byte("not found"))
return
}
diskStatusList := hdl.zedrouter.lookupDiskStatusList(
anStatus.UUIDandVersion.UUID.String())
var blobFileLocation string
for _, st := range diskStatusList {
if st.Devtype != "AppCustom" {
continue
}
if st.DisplayName == blobName {
blobFileLocation = st.FileLocation
break
}
}
if blobFileLocation == "" {
http.Error(w, r.RequestURI, http.StatusNotFound)
return
}
f, err := os.Open(blobFileLocation)
if err != nil {
http.Error(w, r.RequestURI, http.StatusNotFound)
return
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
http.Error(w, r.RequestURI, http.StatusNotFound)
return
}
modTime := fi.ModTime()
http.ServeContent(w, r, blobFileLocation, modTime, f)
}
// HandlePatchDescription returns Patch Envelopes available for app instance
func HandlePatchDescription(z *zedrouter) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// WithPatchEnvelopesByIP middleware returns envelopes which are more than 0
envelopes := r.Context().Value(patchEnvelopesContextKey).(types.PatchEnvelopeInfoList)
appUUID := r.Context().Value(appUUIDContextKey).(string)
for _, pe := range envelopes.Envelopes {
z.increasePatchEnvelopeStatusCounter(appUUID, pe)
}
b, err := patchEnvelopesJSONForAppInstance(envelopes)
if err != nil {
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(b)
return
}
}
func sendError(w http.ResponseWriter, code int, msg string) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(code)
w.Write([]byte(fmt.Sprintf("{\"message\": \"%s\"}", msg)))
}
// HandlePatchDownload serves binary artifacts of specified patch envelope to app
// instance. Patch envelope id is specified in URL. All artifacts are compressed to
// a zip archive
func HandlePatchDownload(z *zedrouter) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// WithPatchEnvelopesByIP middleware returns envelopes which are more than 0
envelopes := r.Context().Value(patchEnvelopesContextKey).(types.PatchEnvelopeInfoList)
appUUID := r.Context().Value(appUUIDContextKey).(string)
patchID := chi.URLParam(r, "patch")
if patchID == "" {
sendError(w, http.StatusNoContent, "patch in route is missing")
return
}
e := envelopes.FindPatchEnvelopeByID(patchID)
if e != nil {
path, err := os.MkdirTemp("", "patchEnvelopeZip")
if err != nil {
sendError(w, http.StatusInternalServerError,
fmt.Sprintf("failed to create temp dir %v", err))
return
}
zipFilename, err := utils.GetZipArchive(path, *e)
if err != nil {
sendError(w, http.StatusInternalServerError,
fmt.Sprintf("failed to archive binary blobs %v", err))
return
}
http.ServeFile(w, r, zipFilename)
z.increasePatchEnvelopeDownloadCounter(appUUID, *e)
err = os.Remove(zipFilename)
if err != nil {
sendError(w, http.StatusInternalServerError,
fmt.Sprintf("failed to delete archive %v", err))
return
}
return
}
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
}
// HandlePatchFileDownload serves binary artifact of specified patch envelope to app
// instance. Patch envelope id and file name is specified in URL.
func HandlePatchFileDownload(z *zedrouter) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// WithPatchEnvelopesByIP middleware returns envelopes which are more than 0
envelopes := r.Context().Value(patchEnvelopesContextKey).(types.PatchEnvelopeInfoList)
appUUID := r.Context().Value(appUUIDContextKey).(string)
patchID := chi.URLParam(r, "patch")
if patchID == "" {
sendError(w, http.StatusNotFound, "patch in route is missing")
return
}
fileName := chi.URLParam(r, "file")
if fileName == "" {
sendError(w, http.StatusNotFound, "file in route is missing")
return
}
e := envelopes.FindPatchEnvelopeByID(patchID)
if e != nil {
if idx := types.CompletedBinaryBlobIdxByName(e.BinaryBlobs, fileName); idx != -1 {
http.ServeFile(w, r, e.BinaryBlobs[idx].URL)
z.increasePatchEnvelopeDownloadCounter(appUUID, *e)
return
} else {
sendError(w, http.StatusNotFound, "file is not found")
return
}
}
sendError(w, http.StatusNotFound, "patch is not found")
}
}
// WithPatchEnvelopesByIP is a middleware for Patch Envelopes which adds
// to a context patchEnvelope variable containing available patch envelopes
// for given IP address (it gets resolved to app instance UUID)
// in case there is no patch envelopes available it returns StatusNoContent
func WithPatchEnvelopesByIP(z *zedrouter) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
remoteIP := net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
anStatus := z.lookupAppNetworkStatusByAppIP(remoteIP)
if anStatus == nil {
w.WriteHeader(http.StatusNoContent)
z.log.Errorf("No AppNetworkStatus for %s",
remoteIP.String())
return
}
appUUID := anStatus.UUIDandVersion.UUID
accessablePe := z.patchEnvelopes.Get(appUUID.String())
if len(accessablePe.Envelopes) == 0 {
sendError(w, http.StatusOK, fmt.Sprintf("No envelopes for %s", appUUID.String()))
}
ctx := context.WithValue(r.Context(), patchEnvelopesContextKey, accessablePe)
ctx = context.WithValue(ctx, appUUIDContextKey, appUUID.String())
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}