Skip to content

Commit 22f42be

Browse files
feat: autoselect node,error messaging improvement , node group and custom shell support (#2925)
* passing nodeSelector field as empty in templates * added node name in fetch terminal status api * minor code restructuring * updating template data using map interface conversion * error message improvement in case of pod termination * wrong nodename fix * pod template error fix * fix * added shell validation method * error logging added * error reason field added in UserTerminalSessionResponse * wip * validate shell api * info logs added * fix * debug stmts added * cmd args fix * added node group filed for NodeCapacityDetail obj * code debugging * node group added for k-ops and aws cluster type * fix * node group added for gcp type cluster nodes * added code comments * code restructuring * valid shell api debug * fix * added debug stmt * added shell not supported error messaging * error message fix * fix * nil ptr err fix * added shell auto selection * fix * sending shell name back in case of invalid shell * added shell validation inside updateShell api * sending shell not supported reason in API response * node grouping * json key name fix * provided validate shell functionality in terminal status api * route fix * added nodegroup name in cluster list api * shellName added * json key change * error messaging refactoring * enhanced error message * showing shell name in shell not supported message * terminate status fix and log statements added * nil ptr checks added * nil ptr checks added * sending pod status and errorReason in pod events api * fix * fix * updating terminal status in cache * pod terminate error fix * added mutex locking at some missing places * added mutex locking at some missing places * removed commented code * code review changes * added constants for keys used in manifest * removed info message and comments * removed info message and comments
1 parent a61ee4d commit 22f42be

File tree

7 files changed

+506
-80
lines changed

7 files changed

+506
-80
lines changed

api/terminal/UserTerminalAccessRestHandler.go

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,13 @@ type UserTerminalAccessRestHandler interface {
2525
DisconnectAllTerminalSessionAndRetry(w http.ResponseWriter, r *http.Request)
2626
FetchTerminalPodEvents(w http.ResponseWriter, r *http.Request)
2727
FetchTerminalPodManifest(w http.ResponseWriter, r *http.Request)
28+
ValidateShell(w http.ResponseWriter, r *http.Request)
29+
}
30+
31+
type validShellResponse struct {
32+
IsValidShell bool `json:"isValidShell"`
33+
ErrorReason string `json:"errorReason"`
34+
ShellName string `json:"shellName"`
2835
}
2936

3037
type UserTerminalAccessRestHandlerImpl struct {
@@ -45,7 +52,35 @@ func NewUserTerminalAccessRestHandlerImpl(logger *zap.SugaredLogger, userTermina
4552
validator: validator,
4653
}
4754
}
48-
55+
func (handler UserTerminalAccessRestHandlerImpl) ValidateShell(w http.ResponseWriter, r *http.Request) {
56+
userId, err := handler.UserService.GetLoggedInUser(r)
57+
if userId == 0 || err != nil {
58+
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
59+
return
60+
}
61+
vars := mux.Vars(r)
62+
podName := vars["podName"]
63+
namespace := vars["namespace"]
64+
shellName := vars["shellName"]
65+
clusterId, err := strconv.Atoi(vars["clusterId"])
66+
if err != nil {
67+
handler.Logger.Errorw("error in parsing clusterId from request", "clusterId", clusterId, "err", err)
68+
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
69+
return
70+
}
71+
token := r.Header.Get("token")
72+
if ok := handler.Enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionCreate, "*"); !ok {
73+
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
74+
return
75+
}
76+
res, shell, err := handler.UserTerminalAccessService.ValidateShell(podName, namespace, shellName, clusterId)
77+
reason := ""
78+
if err != nil {
79+
reason = err.Error()
80+
}
81+
resp := validShellResponse{IsValidShell: res, ErrorReason: reason, ShellName: shell}
82+
common.WriteJsonResp(w, nil, resp, http.StatusOK)
83+
}
4984
func (handler UserTerminalAccessRestHandlerImpl) StartTerminalSession(w http.ResponseWriter, r *http.Request) {
5085
userId, err := handler.UserService.GetLoggedInUser(r)
5186
if userId == 0 || err != nil {
@@ -161,6 +196,8 @@ func (handler UserTerminalAccessRestHandlerImpl) FetchTerminalStatus(w http.Resp
161196
}
162197
vars := mux.Vars(r)
163198
terminalAccessId, err := strconv.Atoi(vars["terminalAccessId"])
199+
namespace := vars["namespace"]
200+
shellName := vars["shellName"]
164201
if err != nil {
165202
handler.Logger.Errorw("request err, FetchTerminalStatus", "err", err)
166203
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
@@ -172,7 +209,7 @@ func (handler UserTerminalAccessRestHandlerImpl) FetchTerminalStatus(w http.Resp
172209
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
173210
return
174211
}
175-
sessionResponse, err := handler.UserTerminalAccessService.FetchTerminalStatus(r.Context(), terminalAccessId)
212+
sessionResponse, err := handler.UserTerminalAccessService.FetchTerminalStatus(r.Context(), terminalAccessId, namespace, shellName)
176213
if err != nil {
177214
handler.Logger.Errorw("service err, FetchTerminalStatus", "err", err)
178215
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
@@ -201,13 +238,13 @@ func (handler UserTerminalAccessRestHandlerImpl) FetchTerminalPodEvents(w http.R
201238
return
202239
}
203240

204-
podEvents, err := handler.UserTerminalAccessService.FetchPodEvents(r.Context(), terminalAccessId)
241+
resp, err := handler.UserTerminalAccessService.FetchPodEvents(r.Context(), terminalAccessId)
205242
if err != nil {
206243
handler.Logger.Errorw("service err, FetchTerminalPodEvents", "err", err)
207244
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
208245
return
209246
}
210-
common.WriteJsonResp(w, nil, podEvents, http.StatusOK)
247+
common.WriteJsonResp(w, nil, resp, http.StatusOK)
211248
}
212249

213250
func (handler UserTerminalAccessRestHandlerImpl) FetchTerminalPodManifest(w http.ResponseWriter, r *http.Request) {

api/terminal/UserTerminalAccessRouter.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ func (router UserTerminalAccessRouterImpl) InitTerminalAccessRouter(userTerminal
2626
userTerminalAccessRouter.Path("/start").
2727
HandlerFunc(router.userTerminalAccessRestHandler.StartTerminalSession).Methods("POST")
2828
userTerminalAccessRouter.Path("/get").
29-
HandlerFunc(router.userTerminalAccessRestHandler.FetchTerminalStatus).Queries("terminalAccessId", "{terminalAccessId}").Methods("GET")
29+
HandlerFunc(router.userTerminalAccessRestHandler.FetchTerminalStatus).Queries("terminalAccessId", "{terminalAccessId}", "namespace", "{namespace}", "shellName", "{shellName}").Methods("GET")
3030
userTerminalAccessRouter.Path("/pod/events").
3131
HandlerFunc(router.userTerminalAccessRestHandler.FetchTerminalPodEvents).Queries("terminalAccessId", "{terminalAccessId}").Methods("GET")
3232
userTerminalAccessRouter.Path("/pod/manifest").
@@ -37,6 +37,7 @@ func (router UserTerminalAccessRouterImpl) InitTerminalAccessRouter(userTerminal
3737
HandlerFunc(router.userTerminalAccessRestHandler.StopTerminalSession).Queries("terminalAccessId", "{terminalAccessId}").Methods("PUT")
3838
userTerminalAccessRouter.Path("/disconnectAndRetry").
3939
HandlerFunc(router.userTerminalAccessRestHandler.DisconnectAllTerminalSessionAndRetry).Methods("POST")
40+
userTerminalAccessRouter.Path("/validateShell").Queries("podName", "{podName}", "namespace", "{namespace}", "shellName", "{shellName}", "clusterId", "{clusterId}").HandlerFunc(router.userTerminalAccessRestHandler.ValidateShell)
4041

4142
//TODO fetch all user running/starting pods
4243
//TODO fetch all running/starting pods also include sessionIds if session exists

internal/sql/models/UserTerminalSession.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,14 @@ type UserTerminalSessionRequest struct {
1212
type UserTerminalShellSessionRequest struct {
1313
TerminalAccessId int `json:"terminalAccessId" validate:"number,gt=0"`
1414
ShellName string `json:"shellName" validate:"required,min=1"`
15+
NameSpace string `json:"namespace" validate:"required,min=1"`
1516
}
1617

18+
type UserTerminalPodEvents struct {
19+
Status string `json:"status"`
20+
ErrorReason string `json:"errorReason"`
21+
EventsResponse interface{} `json:"eventsResponse"`
22+
}
1723
type UserTerminalSessionConfig struct {
1824
MaxSessionPerUser int `env:"MAX_SESSION_PER_USER" envDefault:"5"`
1925
TerminalPodStatusSyncTimeInSecs int `env:"TERMINAL_POD_STATUS_SYNC_In_SECS" envDefault:"600"`
@@ -26,7 +32,11 @@ type UserTerminalSessionResponse struct {
2632
UserId int32 `json:"userId"`
2733
TerminalAccessId int `json:"terminalAccessId"`
2834
Status TerminalPodStatus `json:"status"`
35+
ErrorReason string `json:"errorReason"`
2936
PodName string `json:"podName"`
37+
NodeName string `json:"nodeName"`
38+
IsValidShell bool `json:"isValidShell"`
39+
ShellName string `json:"shellName"`
3040
}
3141

3242
const TerminalAccessPodNameTemplate = "terminal-access-" + TerminalAccessClusterIdTemplateVar + "-" + TerminalAccessUserIdTemplateVar + "-" + TerminalAccessRandomIdVar
@@ -44,6 +54,9 @@ const TerminalAccessClusterRoleBindingTemplate = TerminalAccessPodNameTemplate +
4454
const TerminalAccessServiceAccountTemplateName = "terminal-access-service-account"
4555
const TerminalAccessServiceAccountTemplate = TerminalAccessPodNameTemplate + "-sa"
4656
const MaxSessionLimitReachedMsg = "session-limit-reached"
57+
const AUTO_SELECT_NODE string = "autoSelectNode"
58+
const ShellNotSupported string = "'%s' is not supported for the selected image"
59+
const AutoSelectShell string = "autoSelectShell"
4760

4861
type TerminalPodStatus string
4962

0 commit comments

Comments
 (0)