...
1 package entrypoint
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io/ioutil"
8 "net/http"
9 "sync/atomic"
10
11 "github.com/datawire/dlib/dhttp"
12 "github.com/datawire/dlib/dlog"
13 snapshotTypes "github.com/emissary-ingress/emissary/v3/pkg/snapshot/v1"
14 )
15
16
17 const ExternalSnapshotPort = 8005
18
19
20 func externalSnapshotServer(ctx context.Context, snapshot *atomic.Value) error {
21 mux := http.NewServeMux()
22 mux.HandleFunc("/snapshot-external", func(w http.ResponseWriter, r *http.Request) {
23 sanitizedSnap, err := sanitizeExternalSnapshot(ctx, snapshot.Load().([]byte), http.DefaultClient)
24 if err != nil {
25 w.WriteHeader(http.StatusInternalServerError)
26 return
27 }
28 w.Header().Set("content-type", "application/json")
29 _, _ = w.Write(sanitizedSnap)
30 })
31
32 s := &dhttp.ServerConfig{
33 Handler: mux,
34 }
35
36 return s.ListenAndServe(ctx, fmt.Sprintf(":%d", ExternalSnapshotPort))
37 }
38
39 func snapshotServer(ctx context.Context, snapshot *atomic.Value) error {
40 mux := http.NewServeMux()
41 mux.HandleFunc("/snapshot", func(w http.ResponseWriter, r *http.Request) {
42 _, _ = w.Write(snapshot.Load().([]byte))
43 })
44
45 s := &dhttp.ServerConfig{
46 Handler: mux,
47 }
48
49 return s.ListenAndServe(ctx, "localhost:9696")
50 }
51
52 func sanitizeExternalSnapshot(ctx context.Context, rawSnapshot []byte, client *http.Client) ([]byte, error) {
53 snapDecoded := snapshotTypes.Snapshot{}
54 err := json.Unmarshal(rawSnapshot, &snapDecoded)
55 if err != nil {
56 return nil, err
57 }
58 err = snapDecoded.Sanitize()
59 if err != nil {
60 return nil, err
61 }
62 isEdgeStack, err := IsEdgeStack()
63 if err != nil {
64 return nil, err
65 }
66 if snapDecoded.AmbassadorMeta != nil && isEdgeStack {
67 sidecarProcessInfoUrl := fmt.Sprintf("%s/process-info/", GetSidecarHost())
68 dlog.Debugf(ctx, "loading sidecar process-info using [%s]...", sidecarProcessInfoUrl)
69 resp, err := client.Get(sidecarProcessInfoUrl)
70 if err != nil {
71 dlog.Error(ctx, err.Error())
72 } else {
73 defer resp.Body.Close()
74 if resp.StatusCode == 200 {
75 bodyBytes, err := ioutil.ReadAll(resp.Body)
76 if err != nil {
77 dlog.Warnf(ctx, "error reading response body: %v", err)
78 } else {
79 snapDecoded.AmbassadorMeta.Sidecar = bodyBytes
80 }
81 } else {
82 dlog.Warnf(ctx, "unexpected status code %v", resp.StatusCode)
83 }
84 }
85 }
86
87 return json.Marshal(snapDecoded)
88 }
89
View as plain text