-
Notifications
You must be signed in to change notification settings - Fork 53
/
http.go
205 lines (177 loc) · 4.97 KB
/
http.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
package gateway
import (
"context"
"crypto/tls"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/rancher/opni/pkg/config/v1beta1"
"github.com/rancher/opni/pkg/logger"
"github.com/rancher/opni/pkg/plugins"
"github.com/rancher/opni/pkg/plugins/apis/apiextensions"
"github.com/rancher/opni/pkg/plugins/hooks"
"github.com/rancher/opni/pkg/plugins/meta"
"github.com/rancher/opni/pkg/plugins/types"
"github.com/rancher/opni/pkg/util"
"github.com/rancher/opni/pkg/util/fwd"
"github.com/samber/lo"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
"go.uber.org/zap"
)
var (
httpRequestsTotal = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "opni",
Subsystem: "gateway",
Name: "http_requests_total",
Help: "Total number of HTTP requests handled by the gateway API",
})
apiCollectors = []prometheus.Collector{
httpRequestsTotal,
}
)
type GatewayHTTPServer struct {
router *gin.Engine
conf *v1beta1.GatewayConfigSpec
logger *zap.SugaredLogger
tlsConfig *tls.Config
metricsRouter *gin.Engine
metricsRegisterer prometheus.Registerer
routesMu sync.Mutex
reservedPrefixRoutes []string
}
func NewHTTPServer(
ctx context.Context,
cfg *v1beta1.GatewayConfigSpec,
lg *zap.SugaredLogger,
pl plugins.LoaderInterface,
) *GatewayHTTPServer {
lg = lg.Named("http")
router := gin.New()
router.SetTrustedProxies(cfg.TrustedProxies)
router.Use(
logger.GinLogger(lg),
gin.Recovery(),
otelgin.Middleware("gateway"),
func(c *gin.Context) {
httpRequestsTotal.Inc()
},
)
var healthz atomic.Int32
healthz.Store(http.StatusServiceUnavailable)
metricsRouter := gin.New()
metricsRouter.GET("/healthz", func(c *gin.Context) {
c.Status(int(healthz.Load()))
})
pl.Hook(hooks.OnLoadingCompleted(func(i int) {
healthz.Store(http.StatusOK)
}))
if cfg.Profiling.Path != "" {
pprof.Register(metricsRouter, cfg.Profiling.Path)
} else {
pprof.Register(metricsRouter)
}
metricsHandler := NewMetricsEndpointHandler(cfg.Metrics)
metricsRouter.GET(cfg.Metrics.GetPath(), gin.WrapH(metricsHandler.Handler()))
tlsConfig, _, err := loadTLSConfig(cfg)
if err != nil {
lg.With(
zap.Error(err),
).Panic("failed to load serving cert bundle")
}
srv := &GatewayHTTPServer{
router: router,
conf: cfg,
logger: lg,
tlsConfig: tlsConfig,
metricsRouter: metricsRouter,
metricsRegisterer: metricsHandler.reg,
reservedPrefixRoutes: []string{
cfg.Metrics.GetPath(),
"/healthz",
},
}
srv.metricsRegisterer.MustRegister(apiCollectors...)
pl.Hook(hooks.OnLoad(func(p types.MetricsPlugin) {
srv.metricsRegisterer.MustRegister(p)
}))
pl.Hook(hooks.OnLoadM(func(p types.HTTPAPIExtensionPlugin, md meta.PluginMeta) {
ctx, ca := context.WithTimeout(ctx, 10*time.Second)
defer ca()
cfg, err := p.Configure(ctx, apiextensions.NewCertConfig(cfg.Certs))
if err != nil {
lg.With(
zap.String("plugin", md.Module),
zap.Error(err),
).Error("failed to configure routes")
return
}
srv.setupPluginRoutes(cfg, md)
}))
return srv
}
func (s *GatewayHTTPServer) ListenAndServe(ctx context.Context) error {
lg := s.logger
listener, err := tls.Listen("tcp4", s.conf.HTTPListenAddress, s.tlsConfig)
if err != nil {
return err
}
metricsListener, err := net.Listen("tcp4", s.conf.MetricsListenAddress)
if err != nil {
return err
}
lg.With(
"api", listener.Addr().String(),
"metrics", metricsListener.Addr().String(),
).Info("gateway HTTP server starting")
ctx, ca := context.WithCancel(ctx)
e1 := lo.Async(func() error {
return util.ServeHandler(ctx, s.router.Handler(), listener)
})
e2 := lo.Async(func() error {
return util.ServeHandler(ctx, s.metricsRouter.Handler(), metricsListener)
})
return util.WaitAll(ctx, ca, e1, e2)
}
func (s *GatewayHTTPServer) setupPluginRoutes(
cfg *apiextensions.HTTPAPIExtensionConfig,
pluginMeta meta.PluginMeta,
) {
s.routesMu.Lock()
defer s.routesMu.Unlock()
tlsConfig := s.tlsConfig.Clone()
tlsConfig.InsecureSkipVerify = true
sampledLogger := logger.New(
logger.WithSampling(&zap.SamplingConfig{
Initial: 1,
Thereafter: 0,
}),
).Named("api")
forwarder := fwd.To(cfg.HttpAddr,
fwd.WithTLS(tlsConfig),
fwd.WithLogger(sampledLogger),
fwd.WithDestHint(pluginMeta.Filename()),
)
ROUTES:
for _, route := range cfg.Routes {
for _, reservedPrefix := range s.reservedPrefixRoutes {
if strings.HasPrefix(route.Path, reservedPrefix) {
s.logger.With(
"route", route.Method+" "+route.Path,
"plugin", pluginMeta.Module,
).Warn("skipping route for plugin as it conflicts with a reserved prefix")
continue ROUTES
}
}
s.logger.With(
"route", route.Method+" "+route.Path,
"plugin", pluginMeta.Module,
).Debug("configured route for plugin")
s.router.Handle(route.Method, route.Path, forwarder)
}
}