/
server.go
262 lines (232 loc) · 6.5 KB
/
server.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
package api
import (
"context"
"errors"
"fmt"
"net"
"net/http"
goos "os"
"time"
"connectrpc.com/grpchealth"
"github.com/rs/cors"
"github.com/sirupsen/logrus"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
kargoapi "github.com/akuity/kargo/api/v1alpha1"
"github.com/akuity/kargo/internal/api/config"
"github.com/akuity/kargo/internal/api/dex"
"github.com/akuity/kargo/internal/api/kubernetes"
"github.com/akuity/kargo/internal/api/option"
"github.com/akuity/kargo/internal/api/validation"
rollouts "github.com/akuity/kargo/internal/controller/rollouts/api/v1alpha1"
httputil "github.com/akuity/kargo/internal/http"
"github.com/akuity/kargo/internal/logging"
"github.com/akuity/kargo/pkg/api/service/v1alpha1/svcv1alpha1connect"
)
var (
_ svcv1alpha1connect.KargoServiceHandler = &server{}
)
type server struct {
cfg config.ServerConfig
client kubernetes.Client
internalClient client.Client
// The following behaviors are overridable for testing purposes:
// Common validations:
validateProjectExistsFn func(
ctx context.Context,
project string,
) error
externalValidateProjectFn func(
ctx context.Context,
client client.Client,
project string,
) error
// Common lookups:
getStageFn func(
context.Context,
client.Client,
types.NamespacedName,
) (*kargoapi.Stage, error)
getFreightByNameOrAliasFn func(
ctx context.Context,
c client.Client,
project string,
name string,
alias string,
) (*kargoapi.Freight, error)
isFreightAvailableFn func(
freight *kargoapi.Freight,
stage string,
upstreamStages []string,
) bool
// Common Promotions:
createPromotionFn func(
context.Context,
client.Object,
...client.CreateOption,
) error
// Promote subscribers:
findStageSubscribersFn func(ctx context.Context, stage *kargoapi.Stage) ([]kargoapi.Stage, error)
// QueryFreight API:
listFreightFn func(
context.Context,
client.ObjectList,
...client.ListOption,
) error
getAvailableFreightForStageFn func(
ctx context.Context,
project string,
stage string,
subs kargoapi.Subscriptions,
) ([]kargoapi.Freight, error)
getFreightFromWarehouseFn func(
ctx context.Context,
project string,
warehouse string,
) ([]kargoapi.Freight, error)
getVerifiedFreightFn func(
ctx context.Context,
project string,
stageSubs []kargoapi.StageSubscription,
) ([]kargoapi.Freight, error)
// Freight aliasing:
patchFreightAliasFn func(
ctx context.Context,
freight *kargoapi.Freight,
alias string,
) error
// Freight approval:
patchFreightStatusFn func(
ctx context.Context,
freight *kargoapi.Freight,
newStatus kargoapi.FreightStatus,
) error
// Rollouts integration:
getAnalysisTemplateFn func(
context.Context,
client.Client,
types.NamespacedName,
) (*rollouts.AnalysisTemplate, error)
getAnalysisRunFn func(
context.Context,
client.Client,
types.NamespacedName,
) (*rollouts.AnalysisRun, error)
// Special authorizations:
authorizeFn func(
ctx context.Context,
verb string,
gvr schema.GroupVersionResource,
subresource string,
key client.ObjectKey,
) error
}
type Server interface {
Serve(ctx context.Context, l net.Listener) error
}
func NewServer(
cfg config.ServerConfig,
kubeClient kubernetes.Client,
internalClient client.Client,
) Server {
s := &server{
cfg: cfg,
client: kubeClient,
internalClient: internalClient,
}
s.validateProjectExistsFn = s.validateProjectExists
s.externalValidateProjectFn = validation.ValidateProject
s.getStageFn = kargoapi.GetStage
s.getFreightByNameOrAliasFn = kargoapi.GetFreightByNameOrAlias
s.isFreightAvailableFn = kargoapi.IsFreightAvailable
s.createPromotionFn = kubeClient.Create
s.findStageSubscribersFn = s.findStageSubscribers
s.listFreightFn = kubeClient.List
s.getAvailableFreightForStageFn = s.getAvailableFreightForStage
s.getFreightFromWarehouseFn = s.getFreightFromWarehouse
s.getVerifiedFreightFn = s.getVerifiedFreight
s.patchFreightAliasFn = s.patchFreightAlias
s.patchFreightStatusFn = s.patchFreightStatus
s.authorizeFn = kubeClient.Authorize
s.getAnalysisTemplateFn = rollouts.GetAnalysisTemplate
s.getAnalysisRunFn = rollouts.GetAnalysisRun
return s
}
func (s *server) Serve(ctx context.Context, l net.Listener) error {
log := logging.LoggerFromContext(ctx)
mux := http.NewServeMux()
opts, err := option.NewHandlerOption(ctx, s.cfg, s.internalClient)
if err != nil {
return fmt.Errorf("error initializing handler options: %w", err)
}
mux.Handle(grpchealth.NewHandler(NewHealthChecker(), opts))
path, svcHandler := svcv1alpha1connect.NewKargoServiceHandler(s, opts)
mux.Handle(path, svcHandler)
mux.Handle("/", s.newDashboardRequestHandler())
if s.cfg.DexProxyConfig != nil {
dexProxyCfg := dex.ProxyConfigFromEnv()
dexProxy, err := dex.NewProxy(dexProxyCfg)
if err != nil {
return fmt.Errorf("error initializing dex proxy: %w", err)
}
mux.Handle("/dex/", dexProxy)
}
handler := h2c.NewHandler(mux, &http2.Server{})
// Sometimes a permissive CORS policy is useful during local development.
if s.cfg.PermissiveCORSPolicyEnabled {
handler = cors.New(cors.Options{
AllowCredentials: true,
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"DELETE", "GET", "POST", "PUT"},
AllowedHeaders: []string{"Authorization", "Content-Type"},
}).Handler(handler)
}
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: time.Minute,
}
errCh := make(chan error)
go func() {
if s.cfg.TLSConfig != nil {
errCh <- srv.ServeTLS(
l,
s.cfg.TLSConfig.CertPath,
s.cfg.TLSConfig.KeyPath,
)
} else {
errCh <- srv.Serve(l)
}
}()
log.WithFields(logrus.Fields{
"tls": s.cfg.TLSConfig != nil,
}).Infof("Server is listening on %q", l.Addr().String())
select {
case <-ctx.Done():
log.Info("Gracefully stopping server...")
time.Sleep(s.cfg.GracefulShutdownTimeout)
return srv.Shutdown(context.Background())
case err := <-errCh:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}
}
func (s *server) newDashboardRequestHandler() http.HandlerFunc {
fs := http.FileServer(http.Dir(s.cfg.UIDirectory))
return func(w http.ResponseWriter, req *http.Request) {
path := s.cfg.UIDirectory + req.URL.Path
info, err := goos.Stat(path)
if goos.IsNotExist(err) || info.IsDir() {
if w != nil {
httputil.SetNoCacheHeaders(w)
http.ServeFile(w, req, s.cfg.UIDirectory+"/index.html")
}
} else {
fs.ServeHTTP(w, req)
}
}
}