-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathstatic_handler.go
228 lines (198 loc) · 7.22 KB
/
static_handler.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
// Copyright (c) 2019 The Jaeger Authors.
// Copyright (c) 2017 Uber Technologies, Inc.
// SPDX-License-Identifier: Apache-2.0
package app
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"sync/atomic"
"github.com/gorilla/mux"
"go.uber.org/zap"
"github.com/jaegertracing/jaeger/cmd/query/app/querysvc"
"github.com/jaegertracing/jaeger/cmd/query/app/ui"
"github.com/jaegertracing/jaeger/pkg/fswatcher"
"github.com/jaegertracing/jaeger/pkg/version"
)
var (
// The following patterns are searched and replaced in the index.html as a way of customizing the UI.
configPattern = regexp.MustCompile("JAEGER_CONFIG *= *DEFAULT_CONFIG;")
configJsPattern = regexp.MustCompile(`(?im)^\s*\/\/\s*JAEGER_CONFIG_JS.*\n.*`)
versionPattern = regexp.MustCompile("JAEGER_VERSION *= *DEFAULT_VERSION;")
compabilityPattern = regexp.MustCompile("JAEGER_STORAGE_CAPABILITIES *= *DEFAULT_STORAGE_CAPABILITIES;")
basePathPattern = regexp.MustCompile(`<base href="/"`) // Note: tag is not closed
)
// RegisterStaticHandler adds handler for static assets to the router.
func RegisterStaticHandler(r *mux.Router, logger *zap.Logger, qOpts *QueryOptions, qCapabilities querysvc.StorageCapabilities) io.Closer {
staticHandler, err := NewStaticAssetsHandler(qOpts.UIConfig.AssetsPath, StaticAssetsHandlerOptions{
UIConfig: qOpts.UIConfig,
BasePath: qOpts.BasePath,
StorageCapabilities: qCapabilities,
Logger: logger,
})
if err != nil {
logger.Panic("Could not create static assets handler", zap.Error(err))
}
staticHandler.RegisterRoutes(r)
return staticHandler
}
// StaticAssetsHandler handles static assets
type StaticAssetsHandler struct {
options StaticAssetsHandlerOptions
indexHTML atomic.Value // stores []byte
assetsFS http.FileSystem
watcher *fswatcher.FSWatcher
}
// StaticAssetsHandlerOptions defines options for NewStaticAssetsHandler
type StaticAssetsHandlerOptions struct {
UIConfig
BasePath string
StorageCapabilities querysvc.StorageCapabilities
Logger *zap.Logger
}
type loadedConfig struct {
regexp *regexp.Regexp
config []byte
}
// NewStaticAssetsHandler returns a StaticAssetsHandler
func NewStaticAssetsHandler(staticAssetsRoot string, options StaticAssetsHandlerOptions) (*StaticAssetsHandler, error) {
assetsFS := ui.GetStaticFiles(options.Logger)
if staticAssetsRoot != "" {
assetsFS = http.Dir(staticAssetsRoot)
}
h := &StaticAssetsHandler{
options: options,
assetsFS: assetsFS,
}
indexHTML, err := h.loadAndEnrichIndexHTML(assetsFS.Open)
if err != nil {
return nil, err
}
options.Logger.Info("Using UI configuration", zap.String("path", options.ConfigFile))
watcher, err := fswatcher.New([]string{options.ConfigFile}, h.reloadUIConfig, h.options.Logger)
if err != nil {
return nil, err
}
h.watcher = watcher
h.indexHTML.Store(indexHTML)
return h, nil
}
func (sH *StaticAssetsHandler) loadAndEnrichIndexHTML(open func(string) (http.File, error)) ([]byte, error) {
indexBytes, err := loadIndexHTML(open)
if err != nil {
return nil, fmt.Errorf("cannot load index.html: %w", err)
}
// replace UI config
if configObject, err := loadUIConfig(sH.options.ConfigFile); err != nil {
return nil, err
} else if configObject != nil {
indexBytes = configObject.regexp.ReplaceAll(indexBytes, configObject.config)
}
// replace storage capabilities
capabilitiesJSON, _ := json.Marshal(sH.options.StorageCapabilities)
capabilitiesString := fmt.Sprintf("JAEGER_STORAGE_CAPABILITIES = %s;", string(capabilitiesJSON))
indexBytes = compabilityPattern.ReplaceAll(indexBytes, []byte(capabilitiesString))
// replace Jaeger version
versionJSON, _ := json.Marshal(version.Get())
versionString := fmt.Sprintf("JAEGER_VERSION = %s;", string(versionJSON))
indexBytes = versionPattern.ReplaceAll(indexBytes, []byte(versionString))
// replace base path
if sH.options.BasePath == "" {
sH.options.BasePath = "/"
}
if sH.options.BasePath != "/" {
if !strings.HasPrefix(sH.options.BasePath, "/") || strings.HasSuffix(sH.options.BasePath, "/") {
return nil, fmt.Errorf("invalid base path '%s'. Must start but not end with a slash '/', e.g. '/jaeger/ui'", sH.options.BasePath)
}
indexBytes = basePathPattern.ReplaceAll(indexBytes, []byte(fmt.Sprintf(`<base href="%s/"`, sH.options.BasePath)))
}
return indexBytes, nil
}
func (sH *StaticAssetsHandler) reloadUIConfig() {
sH.options.Logger.Info("reloading UI config", zap.String("filename", sH.options.ConfigFile))
content, err := sH.loadAndEnrichIndexHTML(sH.assetsFS.Open)
if err != nil {
sH.options.Logger.Error("error while reloading the UI config", zap.Error(err))
}
sH.indexHTML.Store(content)
sH.options.Logger.Info("reloaded UI config", zap.String("filename", sH.options.ConfigFile))
}
func loadIndexHTML(open func(string) (http.File, error)) ([]byte, error) {
indexFile, err := open("/index.html")
if err != nil {
return nil, fmt.Errorf("cannot open index.html: %w", err)
}
defer indexFile.Close()
indexBytes, err := io.ReadAll(indexFile)
if err != nil {
return nil, fmt.Errorf("cannot read from index.html: %w", err)
}
return indexBytes, nil
}
func loadUIConfig(uiConfig string) (*loadedConfig, error) {
if uiConfig == "" {
return nil, nil
}
bytesConfig, err := os.ReadFile(filepath.Clean(uiConfig))
if err != nil {
return nil, fmt.Errorf("cannot read UI config file %v: %w", uiConfig, err)
}
var r []byte
ext := filepath.Ext(uiConfig)
switch strings.ToLower(ext) {
case ".json":
var c map[string]any
if err := json.Unmarshal(bytesConfig, &c); err != nil {
return nil, fmt.Errorf("cannot parse UI config file %v: %w", uiConfig, err)
}
r, _ = json.Marshal(c)
return &loadedConfig{
regexp: configPattern,
config: append([]byte("JAEGER_CONFIG = "), append(r, byte(';'))...),
}, nil
case ".js":
r = bytes.TrimSpace(bytesConfig)
re := regexp.MustCompile(`function\s+UIConfig(\s)?\(\s?\)(\s)?{`)
if !re.Match(r) {
return nil, fmt.Errorf("UI config file must define function UIConfig(): %v", uiConfig)
}
return &loadedConfig{
regexp: configJsPattern,
config: r,
}, nil
default:
return nil, fmt.Errorf("unrecognized UI config file format, expecting .js or .json file: %v", uiConfig)
}
}
func (sH *StaticAssetsHandler) loggingHandler(handler http.Handler) http.Handler {
if !sH.options.LogAccess {
return handler
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sH.options.Logger.Info("serving static asset", zap.Stringer("url", r.URL))
handler.ServeHTTP(w, r)
})
}
// RegisterRoutes registers routes for this handler on the given router
func (sH *StaticAssetsHandler) RegisterRoutes(router *mux.Router) {
fileServer := http.FileServer(sH.assetsFS)
if sH.options.BasePath != "/" {
fileServer = http.StripPrefix(sH.options.BasePath+"/", fileServer)
}
router.PathPrefix("/static/").Handler(sH.loggingHandler(fileServer))
// index.html is served by notFound handler
router.NotFoundHandler = sH.loggingHandler(http.HandlerFunc(sH.notFound))
}
func (sH *StaticAssetsHandler) notFound(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(sH.indexHTML.Load().([]byte))
}
func (sH *StaticAssetsHandler) Close() error {
return sH.watcher.Close()
}