/
rest_server.go
270 lines (233 loc) · 8.03 KB
/
rest_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
263
264
265
266
267
268
269
270
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package rest
import (
"context"
"fmt"
"net/http"
"os"
"time"
"github.com/oam-dev/kubevela/pkg/apiserver/collect"
restfulspec "github.com/emicklei/go-restful-openapi/v2"
"github.com/emicklei/go-restful/v3"
"github.com/go-openapi/spec"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/apiserver/datastore"
"github.com/oam-dev/kubevela/pkg/apiserver/datastore/kubeapi"
"github.com/oam-dev/kubevela/pkg/apiserver/datastore/mongodb"
"github.com/oam-dev/kubevela/pkg/apiserver/log"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/usecase"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/utils"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/webservice"
velasync "github.com/oam-dev/kubevela/pkg/apiserver/sync"
utils2 "github.com/oam-dev/kubevela/pkg/utils"
)
var _ APIServer = &restServer{}
// Config config for server
type Config struct {
// api server bind address
BindAddr string
// monitor metric path
MetricPath string
// Datastore config
Datastore datastore.Config
// LeaderConfig for leader election
LeaderConfig leaderConfig
// AddonCacheTime is how long between two cache operations
AddonCacheTime time.Duration
// DisableStatisticCronJob close the calculate system info cronJob
DisableStatisticCronJob bool
}
type leaderConfig struct {
ID string
LockName string
Duration time.Duration
}
// APIServer interface for call api server
type APIServer interface {
Run(context.Context) error
RegisterServices(ctx context.Context, initDatabase bool) restfulspec.Config
}
type restServer struct {
webContainer *restful.Container
cfg Config
dataStore datastore.DataStore
// usecases, we register part of the usecase instances
usecases map[string]interface{}
}
// New create restserver with config data
func New(cfg Config) (a APIServer, err error) {
var ds datastore.DataStore
switch cfg.Datastore.Type {
case "mongodb":
ds, err = mongodb.New(context.Background(), cfg.Datastore)
if err != nil {
return nil, fmt.Errorf("create mongodb datastore instance failure %w", err)
}
case "kubeapi":
ds, err = kubeapi.New(context.Background(), cfg.Datastore)
if err != nil {
return nil, fmt.Errorf("create kubeapi datastore instance failure %w", err)
}
default:
return nil, fmt.Errorf("not support datastore type %s", cfg.Datastore.Type)
}
s := &restServer{
webContainer: restful.NewContainer(),
cfg: cfg,
dataStore: ds,
}
return s, nil
}
func (s *restServer) Run(ctx context.Context) error {
s.RegisterServices(ctx, true)
l, err := s.setupLeaderElection()
if err != nil {
return err
}
go func() {
leaderelection.RunOrDie(ctx, *l)
}()
return s.startHTTP(ctx)
}
func (s *restServer) setupLeaderElection() (*leaderelection.LeaderElectionConfig, error) {
restCfg := ctrl.GetConfigOrDie()
rl, err := resourcelock.NewFromKubeconfig(resourcelock.LeasesResourceLock, types.DefaultKubeVelaNS, s.cfg.LeaderConfig.LockName, resourcelock.ResourceLockConfig{
Identity: s.cfg.LeaderConfig.ID,
}, restCfg, time.Second*10)
if err != nil {
klog.ErrorS(err, "Unable to setup the resource lock")
return nil, err
}
return &leaderelection.LeaderElectionConfig{
Lock: rl,
LeaseDuration: time.Second * 15,
RenewDeadline: time.Second * 10,
RetryPeriod: time.Second * 2,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: func(ctx context.Context) {
go velasync.Start(ctx, s.dataStore, restCfg, s.usecases)
if !s.cfg.DisableStatisticCronJob {
collect.StartCalculatingInfoCronJob(s.dataStore)
}
// this process would block the whole process, any other handler should start before this func
s.runWorkflowRecordSync(ctx, s.cfg.LeaderConfig.Duration)
},
OnStoppedLeading: func() {
klog.Infof("leader lost: %s", s.cfg.LeaderConfig.ID)
// Currently, the started goroutine will all closed by the context, so there seems no need to call os.Exit here.
// But it can be safe to stop the process as leader lost.
os.Exit(0)
},
OnNewLeader: func(identity string) {
if identity == s.cfg.LeaderConfig.ID {
return
}
klog.Infof("new leader elected: %s", identity)
},
},
ReleaseOnCancel: true,
}, nil
}
func (s *restServer) runWorkflowRecordSync(ctx context.Context, duration time.Duration) {
klog.Infof("start to syncing workflow record")
w := s.usecases["workflow"].(usecase.WorkflowUsecase)
t := time.NewTicker(duration)
defer t.Stop()
for {
select {
case <-t.C:
if err := w.SyncWorkflowRecord(ctx); err != nil {
klog.ErrorS(err, "syncWorkflowRecordError")
}
case <-ctx.Done():
return
}
}
}
// RegisterServices register web service
func (s *restServer) RegisterServices(ctx context.Context, initDatabase bool) restfulspec.Config {
s.usecases = webservice.Init(ctx, s.dataStore, s.cfg.AddonCacheTime, initDatabase)
/* ************************************************************** */
/* ************* Open API Route Group ***************** */
/* ************************************************************** */
// Add container filter to enable CORS
cors := restful.CrossOriginResourceSharing{
ExposeHeaders: []string{},
AllowedHeaders: []string{"Content-Type", "Accept", "Authorization", "RefreshToken"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
CookiesAllowed: true,
Container: s.webContainer}
s.webContainer.Filter(cors.Filter)
// Add container filter to respond to OPTIONS
s.webContainer.Filter(s.webContainer.OPTIONSFilter)
// Add request log
s.webContainer.Filter(s.requestLog)
// Register all custom webservice
for _, handler := range webservice.GetRegisteredWebService() {
s.webContainer.Add(handler.GetWebService())
}
config := restfulspec.Config{
WebServices: s.webContainer.RegisteredWebServices(), // you control what services are visible
APIPath: "/apidocs.json",
PostBuildSwaggerObjectHandler: enrichSwaggerObject}
s.webContainer.Add(restfulspec.NewOpenAPIService(config))
return config
}
func (s *restServer) requestLog(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
start := time.Now()
c := utils.NewResponseCapture(resp.ResponseWriter)
resp.ResponseWriter = c
chain.ProcessFilter(req, resp)
takeTime := time.Since(start)
log.Logger.With(
"clientIP", utils2.Sanitize(utils.ClientIP(req.Request)),
"path", utils2.Sanitize(req.Request.URL.Path),
"method", req.Request.Method,
"status", c.StatusCode(),
"time", takeTime.String(),
"responseSize", len(c.Bytes()),
).Infof("request log")
}
func enrichSwaggerObject(swo *spec.Swagger) {
swo.Info = &spec.Info{
InfoProps: spec.InfoProps{
Title: "Kubevela api doc",
Description: "Kubevela api doc",
Contact: &spec.ContactInfo{
ContactInfoProps: spec.ContactInfoProps{
Name: "kubevela",
Email: "feedback@mail.kubevela.io",
URL: "https://kubevela.io/",
},
},
License: &spec.License{
LicenseProps: spec.LicenseProps{
Name: "Apache License 2.0",
URL: "https://github.com/oam-dev/kubevela/blob/master/LICENSE",
},
},
Version: "v1beta1",
},
}
}
func (s *restServer) startHTTP(ctx context.Context) error {
// Start HTTP apiserver
log.Logger.Infof("HTTP APIs are being served on: %s, ctx: %s", s.cfg.BindAddr, ctx)
server := &http.Server{Addr: s.cfg.BindAddr, Handler: s.webContainer}
return server.ListenAndServe()
}