-
Notifications
You must be signed in to change notification settings - Fork 18
/
move2kubeapi.go
270 lines (239 loc) · 12.5 KB
/
move2kubeapi.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 IBM Corporation 2020
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 move2kubeapi
import (
"fmt"
"io/fs"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strings"
gHandlers "github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/konveyor/move2kube-api/assets"
"github.com/konveyor/move2kube-api/internal/common"
"github.com/konveyor/move2kube-api/internal/move2kubeapi/handlers"
"github.com/sirupsen/logrus"
"github.com/spf13/cast"
)
// Serve starts the Move2Kube API server.
func Serve() error {
if err := handlers.Setup(); err != nil {
return fmt.Errorf("failed to setup the handlers. Error: %q", err)
}
router := mux.NewRouter()
router.Use(handlers.GetLoggingMiddleWare)
router.Use(handlers.GetRemoveTrailingSlashMiddleWare)
// dynamic routes
if common.Config.AuthEnabled {
router.HandleFunc(common.LOGIN_PATH, handlers.HandleLogin).Methods("GET")
router.HandleFunc(common.LOGIN_CALLBACK_PATH, handlers.HandleLoginCallback).Methods("GET")
router.HandleFunc("/auth/logout", handlers.HandleLogout).Methods("POST")
router.HandleFunc("/auth/user-profile", handlers.HandleUserProfile).Methods("GET")
}
// API routes
router.Handle("/api/v1", http.RedirectHandler("/swagger/openapi.json", http.StatusFound)).Methods("GET") // openapi v3 json
apiRouter := router.PathPrefix("/api/v1").Subrouter()
if common.Config.AuthEnabled {
apiRouter.Use(handlers.GetAuthorizationMiddleWare)
// admin
apiRouter.HandleFunc("/token", handlers.HandleGetAccessToken).Methods("POST")
// roles
apiRouter.HandleFunc("/roles", handlers.HandleListRoles).Methods("GET")
apiRouter.HandleFunc("/roles", handlers.HandleCreateRole).Methods("POST")
apiRouter.HandleFunc("/roles/{role-id}", handlers.HandleReadRole).Methods("GET")
apiRouter.HandleFunc("/roles/{role-id}", handlers.HandleUpdateRole).Methods("PUT")
apiRouter.HandleFunc("/roles/{role-id}", handlers.HandleDeleteRole).Methods("DELETE")
// role-bindings
apiRouter.HandleFunc("/idps/{idp-id}/users/{user-id}/roles", handlers.HandleListRoleBindings).Methods("GET")
apiRouter.HandleFunc("/idps/{idp-id}/users/{user-id}/roles", handlers.HandlePatchRoleBindings).Methods("PATCH")
apiRouter.HandleFunc("/idps/{idp-id}/users/{user-id}/roles/{role-id}", handlers.HandleCreateRoleBinding).Methods("PUT")
apiRouter.HandleFunc("/idps/{idp-id}/users/{user-id}/roles/{role-id}", handlers.HandleDeleteRoleBinding).Methods("DELETE")
}
// general
apiRouter.HandleFunc("/support", handlers.HandleSupport).Methods("GET")
// workspaces
apiRouter.HandleFunc("/workspaces", handlers.HandleListWorkspaces).Methods("GET")
apiRouter.HandleFunc("/workspaces", handlers.HandleCreateWorkspace).Methods("POST")
apiRouter.HandleFunc("/workspaces/{work-id}", handlers.HandleReadWorkspace).Methods("GET")
apiRouter.HandleFunc("/workspaces/{work-id}", handlers.HandleUpdateWorkspace).Methods("PUT")
apiRouter.HandleFunc("/workspaces/{work-id}", handlers.HandleDeleteWorkspace).Methods("DELETE")
// workspace inputs
apiRouter.HandleFunc("/workspaces/{work-id}/inputs", func(w http.ResponseWriter, r *http.Request) { handlers.HandleCreateProjectInput(w, r, true) }).Methods("POST")
apiRouter.HandleFunc("/workspaces/{work-id}/inputs/{input-id}", func(w http.ResponseWriter, r *http.Request) { handlers.HandleReadProjectInput(w, r, true) }).Methods("GET")
apiRouter.HandleFunc("/workspaces/{work-id}/inputs/{input-id}", func(w http.ResponseWriter, r *http.Request) { handlers.HandleDeleteProjectInput(w, r, true) }).Methods("DELETE")
// projects
apiRouter.HandleFunc("/workspaces/{work-id}/projects", handlers.HandleListProjects).Methods("GET")
apiRouter.HandleFunc("/workspaces/{work-id}/projects", handlers.HandleCreateProject).Methods("POST")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}", handlers.HandleReadProject).Methods("GET")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}", handlers.HandleUpdateProject).Methods("PUT")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}", handlers.HandleDeleteProject).Methods("DELETE")
// project inputs
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/inputs", func(w http.ResponseWriter, r *http.Request) { handlers.HandleCreateProjectInput(w, r, false) }).Methods("POST")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/inputs/{input-id}", func(w http.ResponseWriter, r *http.Request) { handlers.HandleReadProjectInput(w, r, false) }).Methods("GET")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/inputs/{input-id}", func(w http.ResponseWriter, r *http.Request) { handlers.HandleDeleteProjectInput(w, r, false) }).Methods("DELETE")
// plan
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/plan", handlers.HandleStartPlanning).Methods("POST")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/plan", handlers.HandleReadPlan).Methods("GET")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/plan", handlers.HandleUpdatePlan).Methods("PUT")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/plan", handlers.HandleDeletePlan).Methods("DELETE")
// project outputs
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/outputs", handlers.HandleStartTransformation).Methods("POST")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/outputs/{output-id}", handlers.HandleReadProjectOutput).Methods("GET")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/outputs/{output-id}", handlers.HandleDeleteProjectOutput).Methods("DELETE")
// project output graphs
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/outputs/{output-id}/graph", handlers.HandleReadProjectOutputGraph).Methods("GET")
// QA
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/outputs/{output-id}/problems/current", handlers.HandleGetQuestion).Methods("GET")
apiRouter.HandleFunc("/workspaces/{work-id}/projects/{proj-id}/outputs/{output-id}/problems/current/solution", handlers.HandlePostSolution).Methods("POST")
if common.Config.AuthEnabled {
// Reverse proxy the authorization server. Required for login.
backendURL, err := url.Parse(common.Config.AuthServer)
if err != nil {
return fmt.Errorf("failed to parse the authorization server URL as a URL. Error: %w", err)
}
logrus.Infof("reverse proxying requests to backend at: %+v", backendURL)
revProxy := httputil.NewSingleHostReverseProxy(backendURL)
oldDirector := revProxy.Director
revProxy.Director = func(req *http.Request) {
logrus.Debugf("reverse proxy, request before modification: %+v", req)
oldDirector(req)
req.Host = req.URL.Host
if req.URL.Path == backendURL.Path+"/" {
req.URL.Path = backendURL.Path
req.URL.RawPath = backendURL.Path
}
logrus.Debugf("reverse proxy, request after modification: %+v", req)
}
router.PathPrefix(common.Config.AuthServerBasePath).Handler(revProxy)
}
// static routes
// swagger UI
swaggerDir, _ := fs.Sub(assets.SwaggerUI, "swagger")
router.Handle("/swagger", http.RedirectHandler("/swagger/", http.StatusMovedPermanently))
router.PathPrefix("/swagger/").Handler(http.StripPrefix("/swagger", http.FileServer(http.FS(swaggerDir)))).Methods("GET")
// move2kube UI
staticFilesDir := common.Config.StaticFilesDir
if staticFilesDir != "" {
finfo, err := os.Stat(staticFilesDir)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("the static files directory %s does not exist", staticFilesDir)
}
return fmt.Errorf("failed to stat the static files directory at path %s . Error: %q", staticFilesDir, err)
}
if !finfo.IsDir() {
return fmt.Errorf("the path %s points to a file. Expected a directory containing static files to be served", staticFilesDir)
}
m2kUI := http.FileServer(http.Dir(staticFilesDir))
letReactRouterHandleIt := func(w http.ResponseWriter, r *http.Request) bool {
if r.Method != "GET" {
return false
}
accepting := r.Header[http.CanonicalHeaderKey("Accept")]
found := false
for _, aa := range accepting {
if strings.Contains(aa, "text/html") {
found = true
break
}
}
if !found {
return false
}
w.Header().Set(common.CONTENT_TYPE_HEADER, "text/html")
w.WriteHeader(http.StatusOK)
http.ServeFile(w, r, filepath.Join(staticFilesDir, "index.html"))
return true
}
router.PathPrefix("/").Handler(handle404(m2kUI, letReactRouterHandleIt)).Methods("GET")
}
logrus.Infof("Starting Move2Kube API server at port: %d", common.Config.Port)
if common.Config.CertPath == "" && common.Config.KeyPath == "" {
if common.Config.CorsAllowOrigin == "" {
if err := http.ListenAndServe(":"+cast.ToString(common.Config.Port), router); err != nil {
return fmt.Errorf("failed to listen and serve on port %d . Error: %w", common.Config.Port, err)
}
} else {
logrus.Infof("CORS is enabled for the origin '%s'", common.Config.CorsAllowOrigin)
originsOk := gHandlers.AllowedOrigins([]string{common.Config.CorsAllowOrigin})
methodsOk := gHandlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"})
headersOk := gHandlers.AllowedHeaders([]string{"X-Requested-With"})
routerWithCORS := gHandlers.CORS(originsOk, methodsOk, headersOk)(router)
if err := http.ListenAndServe(":"+cast.ToString(common.Config.Port), routerWithCORS); err != nil {
return fmt.Errorf("failed to listen and serve on port %d . Error: %w", common.Config.Port, err)
}
}
} else {
if common.Config.CertPath == "" {
return fmt.Errorf("HTTPS is enabled but the certificate file has not been provided")
}
if common.Config.KeyPath == "" {
return fmt.Errorf("HTTPS is enabled but the private key file has not been provided")
}
if finfo, err := os.Stat(common.Config.CertPath); err != nil {
return fmt.Errorf("failed to stat the certificate file at the path '%s' . Error: %w", common.Config.CertPath, err)
} else if finfo.IsDir() {
return fmt.Errorf("expected to find a certificate file at the path '%s'. Found a directory instead", common.Config.CertPath)
}
if finfo, err := os.Stat(common.Config.KeyPath); err != nil {
return fmt.Errorf("failed to stat the private key file at the path '%s' . Error: %w", common.Config.KeyPath, err)
} else if finfo.IsDir() {
return fmt.Errorf("expected to find a private key file at the path '%s'. Found a directory instead", common.Config.KeyPath)
}
logrus.Info("HTTPS is enabled")
if common.Config.CorsAllowOrigin == "" {
if err := http.ListenAndServeTLS(":"+cast.ToString(common.Config.Port), common.Config.CertPath, common.Config.KeyPath, router); err != nil {
return fmt.Errorf("failed to listen and serve using HTTPS on port %d . Error: %w", common.Config.Port, err)
}
} else {
logrus.Infof("CORS is enabled for the origin '%s'", common.Config.CorsAllowOrigin)
originsOk := gHandlers.AllowedOrigins([]string{common.Config.CorsAllowOrigin})
methodsOk := gHandlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"})
headersOk := gHandlers.AllowedHeaders([]string{"X-Requested-With"})
routerWithCORS := gHandlers.CORS(originsOk, methodsOk, headersOk)(router)
if err := http.ListenAndServeTLS(":"+cast.ToString(common.Config.Port), common.Config.CertPath, common.Config.KeyPath, routerWithCORS); err != nil {
return fmt.Errorf("failed to listen and serve using HTTPS on port %d . Error: %w", common.Config.Port, err)
}
}
}
return nil
}
// let react router handle unrecognized text/html GET requests
type hijack404 struct {
http.ResponseWriter
R *http.Request
Handle404 func(w http.ResponseWriter, r *http.Request) bool
}
func (h *hijack404) WriteHeader(code int) {
if code == 404 && h.Handle404(h.ResponseWriter, h.R) {
panic(h)
}
h.ResponseWriter.WriteHeader(code)
}
func handle404(handler http.Handler, handle404 func(w http.ResponseWriter, r *http.Request) bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hijack := &hijack404{ResponseWriter: w, R: r, Handle404: handle404}
defer func() {
if p := recover(); p != nil {
if p == hijack {
return
}
panic(p)
}
}()
handler.ServeHTTP(hijack, r)
})
}