Skip to content

Commit

Permalink
bcs-webconsole 日志库统一&返回风格统一 (#2687)
Browse files Browse the repository at this point in the history
* bcs-webconsole 日志库统一&返回风格统一

* bcs-webconsole 日志库统一&返回风格统一优化

* bcs-webconsole 日志库统一&返回风格统一优化
  • Loading branch information
LidolLxf authored Oct 23, 2023
1 parent 043bdae commit b18974c
Show file tree
Hide file tree
Showing 13 changed files with 99 additions and 153 deletions.
146 changes: 41 additions & 105 deletions bcs-services/bcs-webconsole/console/api/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"bytes"
"context"
"io"
"net/http"
"net/url"
"path"
"strconv"
Expand Down Expand Up @@ -88,27 +87,19 @@ func (s service) RegisterRoute(router gin.IRoutes) {

// ListClusters 集群列表
func (s *service) ListClusters(c *gin.Context) {
authCtx := route.MustGetAuthContext(c)

projectId := c.Param("projectId")
project, err := bcs.GetProject(c.Request.Context(), config.G.BCS, projectId)
if err != nil {
APIError(c, i18n.GetMessage(c, "项目不正确"))
rest.APIError(c, i18n.GetMessage(c, "项目不正确"))
return
}

clusters, err := bcs.ListClusters(c.Request.Context(), project.ProjectId)
if err != nil {
APIError(c, i18n.GetMessage(c, err.Error()))
rest.APIError(c, i18n.GetMessage(c, err.Error()))
return
}
data := types.APIResponse{
Data: clusters,
Code: types.NoError,
Message: i18n.GetMessage(c, "获取集群成功"),
RequestID: authCtx.RequestId,
}
c.JSON(http.StatusOK, data)
rest.APIOK(c, i18n.GetMessage(c, "获取集群成功"), clusters)
}

// CreateWebConsoleSession 创建websocket session
Expand Down Expand Up @@ -143,7 +134,7 @@ func (s *service) CreateWebConsoleSession(c *gin.Context) {
return
}()
if err != nil {
APIError(c, i18n.GetMessage(c, err.Error()))
rest.APIError(c, i18n.GetMessage(c, err.Error()))
return
}

Expand All @@ -153,21 +144,15 @@ func (s *service) CreateWebConsoleSession(c *gin.Context) {

sessionId, err := sessions.NewStore().WebSocketScope().Set(c.Request.Context(), podCtx)
if err != nil {
msg := i18n.GetMessage(c, "获取session失败{}", err)
APIError(c, msg)
rest.APIError(c, i18n.GetMessage(c, "获取session失败{}", err))
return
}

data := types.APIResponse{
Data: map[string]string{
"session_id": sessionId,
"ws_url": makeWebSocketURL(sessionId, consoleQuery.Lang, false),
},
Code: types.NoError,
Message: i18n.GetMessage(c, "获取session成功"),
RequestID: authCtx.RequestId,
data := map[string]string{
"session_id": sessionId,
"ws_url": makeWebSocketURL(sessionId, consoleQuery.Lang, false),
}
c.JSON(http.StatusOK, data)
rest.APIOK(c, i18n.GetMessage(c, "获取session成功"), data)
}

// UploadHandler 上传文件
Expand All @@ -179,45 +164,45 @@ func (s *service) UploadHandler(c *gin.Context) {
sessionId := c.Param("sessionId")
data := types.APIResponse{RequestID: authCtx.RequestId}
if uploadPath == "" {
uploadErrorHandler(c, authCtx, "请先输入上传路径")
rest.APIError(c, i18n.GetMessage(c, "请先输入上传路径"))
return
}
err := checkFileExists(uploadPath, sessionId)
if err != nil {
uploadErrorHandler(c, authCtx, "目标路径不存在")
rest.APIError(c, i18n.GetMessage(c, "目标路径不存在"))
return
}
err = checkPathIsDir(uploadPath, sessionId)
if err != nil {
uploadErrorHandler(c, authCtx, "目标路径不存在")
rest.APIError(c, i18n.GetMessage(c, "目标路径不存在"))
return
}
file, err := c.FormFile("file")
if err != nil {
logger.Errorf("get file from request failed, err: %s", err.Error())
uploadErrorHandler(c, authCtx, "解析上传文件失败")
rest.APIError(c, i18n.GetMessage(c, "解析上传文件失败"))
return
}

opened, err := file.Open()
if err != nil {
logger.Errorf("open file from request failed, err: %s", err.Error())
uploadErrorHandler(c, authCtx, "解析上传文件失败")
rest.APIError(c, i18n.GetMessage(c, "解析上传文件失败"))
return
}
defer opened.Close()

podCtx, err := sessions.NewStore().WebSocketScope().Get(c.Request.Context(), sessionId)
if err != nil {
logger.Errorf("get pod context by session %s failed, err: %s", sessionId, err.Error())
uploadErrorHandler(c, authCtx, "获取pod信息失败")
rest.APIError(c, i18n.GetMessage(c, "获取pod信息失败"))
return
}
reader, writer := io.Pipe()
pe, err := podCtx.NewPodExec()
if err != nil {
logger.Errorf("new pod exec failed, err: %s", err.Error())
uploadErrorHandler(c, authCtx, "执行上传命令失败")
rest.APIError(c, i18n.GetMessage(c, "执行上传命令失败"))
return
}
errChan := make(chan error, 1)
Expand Down Expand Up @@ -258,33 +243,22 @@ func (s *service) UploadHandler(c *gin.Context) {

if err = pe.Exec(); err != nil {
logger.Errorf("pod exec failed, err: %s", err.Error())
uploadErrorHandler(c, authCtx, "执行上传命令失败")
rest.APIError(c, i18n.GetMessage(c, "执行上传命令失败"))
return
}

err, ok := <-errChan
if ok && err != nil {
logger.Errorf("writer to tar failed, err: %s", err.Error())
uploadErrorHandler(c, authCtx, "文件上传失败")
rest.APIError(c, i18n.GetMessage(c, "文件上传失败"))
return
}
data.Code = types.NoError
data.Message = i18n.GetMessage(c, "文件上传成功")
c.JSON(http.StatusOK, data)
}

// uploadErrorHandler 上传文件时,错误信息处理
func uploadErrorHandler(c *gin.Context, authCtx *route.AuthContext, msg string) {
data := types.APIResponse{RequestID: authCtx.RequestId}
data.Code = types.ApiErrorCode
data.Message = i18n.GetMessage(c, msg)
c.JSON(http.StatusOK, data)
rest.APIOK(c, i18n.GetMessage(c, "文件上传成功"), data)
}

// DownloadHandler 下载文件
func (s *service) DownloadHandler(c *gin.Context) {
authCtx := route.MustGetAuthContext(c)
data := types.APIResponse{RequestID: authCtx.RequestId}
downloadPath := c.Query("download_path")
sessionId := c.Param("sessionId")
reader, writer := io.Pipe()
Expand Down Expand Up @@ -321,9 +295,7 @@ func (s *service) DownloadHandler(c *gin.Context) {
tarReader := tar.NewReader(reader)
_, err := tarReader.Next()
if err != nil {
data.Code = types.ApiErrorCode
data.Message = i18n.GetMessage(c, "复制文件流失败")
c.JSON(http.StatusOK, data)
rest.APIError(c, i18n.GetMessage(c, "复制文件流失败"))
return
}
fileName := downloadPath[strings.LastIndex(downloadPath, "/")+1:]
Expand All @@ -344,26 +316,22 @@ func (s *service) CheckDownloadHandler(c *gin.Context) {
sessionId := c.Param("sessionId")

if err := checkFileExists(downloadPath, sessionId); err != nil {
data.Message = i18n.GetMessage(c, "目标文件不存在")
c.JSON(http.StatusOK, data)
rest.APIError(c, i18n.GetMessage(c, "目标文件不存在"))
return
}

if err := checkPathIsDir(downloadPath, sessionId); err == nil {
data.Message = i18n.GetMessage(c, "暂不支持文件夹下载")
c.JSON(http.StatusOK, data)
rest.APIError(c, i18n.GetMessage(c, "暂不支持文件夹下载"))
return
}

if err := checkFileSize(downloadPath, sessionId, FileSizeLimits*FileSizeUnitMb); err != nil {
data.Message = i18n.GetMessage(c, "文件不能超过{}MB", map[string]int{"fileLimit": FileSizeLimits})
c.JSON(http.StatusOK, data)
rest.APIError(c,
i18n.GetMessage(c, "文件不能超过{}MB", map[string]int{"fileLimit": FileSizeLimits}))
return
}

data.Code = types.NoError
data.Message = i18n.GetMessage(c, "文件可以下载")
c.JSON(http.StatusOK, data)
rest.APIOK(c, i18n.GetMessage(c, "文件可以下载"), data)
}

func checkPathIsDir(path, sessionID string) error {
Expand Down Expand Up @@ -444,32 +412,25 @@ func checkFileSize(path, sessionID string, sizeLimit int) error {
func (s *service) CreatePortalSession(c *gin.Context) {
authCtx := route.MustGetAuthContext(c)
if authCtx.BindSession == nil {
msg := i18n.GetMessage(c, "session_id不合法或已经过期")
APIError(c, msg)
rest.APIError(c, i18n.GetMessage(c, "session_id不合法或已经过期"))
return
}

podCtx := authCtx.BindSession

sessionId, err := sessions.NewStore().WebSocketScope().Set(c.Request.Context(), podCtx)
if err != nil {
msg := i18n.GetMessage(c, "获取session失败{}", err)
APIError(c, msg)
rest.APIError(c, i18n.GetMessage(c, "获取session失败{}", err))
return
}

lang := c.Query("lang")
lang = strings.TrimSuffix(lang, "/")
data := types.APIResponse{
Data: map[string]string{
"session_id": sessionId,
"ws_url": makeWebSocketURL(sessionId, lang, false),
},
Code: types.NoError,
Message: i18n.GetMessage(c, "获取session成功"),
RequestID: authCtx.RequestId,
}
c.JSON(http.StatusOK, data)
data := map[string]string{
"session_id": sessionId,
"ws_url": makeWebSocketURL(sessionId, lang, false),
}
rest.APIOK(c, i18n.GetMessage(c, "获取session成功"), data)
}

// CreateContainerPortalSession 创建 webconsole url api
Expand All @@ -480,29 +441,26 @@ func (s *service) CreateContainerPortalSession(c *gin.Context) {

err := c.BindJSON(consoleQuery)
if err != nil {
msg := i18n.GetMessage(c, "请求参数错误{}", err)
APIError(c, msg)
rest.APIError(c, i18n.GetMessage(c, "请求参数错误{}", err))
return
}

if e := consoleQuery.Validate(); e != nil {
msg := i18n.GetMessage(c, "请求参数错误{}", e)
APIError(c, msg)
rest.APIError(c, i18n.GetMessage(c, "请求参数错误{}", e))
return
}

// 自定义命令行
commands, err := consoleQuery.SplitCommand()
if err != nil {
msg := i18n.GetMessage(c, "请求参数错误, command not valid{}", err)
APIError(c, msg)
rest.APIError(
c, i18n.GetMessage(c, "请求参数错误, command not valid{}", err))
return
}

podCtx, err := podmanager.QueryOpenPodCtx(c.Request.Context(), authCtx.ClusterId, consoleQuery)
if err != nil {
msg := i18n.GetMessage(c, "请求参数错误{}", err)
APIError(c, msg)
rest.APIError(c, i18n.GetMessage(c, "请求参数错误{}", err))
return
}

Expand All @@ -519,8 +477,7 @@ func (s *service) CreateContainerPortalSession(c *gin.Context) {

sessionId, err := sessions.NewStore().OpenAPIScope().Set(c.Request.Context(), podCtx)
if err != nil {
msg := i18n.GetMessage(c, "获取session失败{}", err)
APIError(c, msg)
rest.APIError(c, i18n.GetMessage(c, "获取session失败{}", err))
return
}

Expand All @@ -533,22 +490,14 @@ func (s *service) CreateContainerPortalSession(c *gin.Context) {
if consoleQuery.WSAcquire {
wsSessionId, err := sessions.NewStore().WebSocketScope().Set(c.Request.Context(), podCtx)
if err != nil {
msg := i18n.GetMessage(c, "获取session失败{}", err)
APIError(c, msg)
rest.APIError(c, i18n.GetMessage(c, "获取session失败{}", err))
return
}

data["ws_url"] = makeWebSocketURL(wsSessionId, "", true)
}

respData := types.APIResponse{
Data: data,
Code: types.NoError,
Message: i18n.GetMessage(c, "获取session成功"),
RequestID: authCtx.RequestId,
}

c.JSON(http.StatusOK, respData)
rest.APIOK(c, i18n.GetMessage(c, "获取session成功"), data)
}

// makeWebConsoleURL webconsole 页面访问地址
Expand Down Expand Up @@ -595,18 +544,5 @@ func makeWebSocketURL(sessionId, lang string, withScheme bool) string {

// CreateClusterPortalSession 集群级别的 webconsole openapi
func (s *service) CreateClusterPortalSession(c *gin.Context) {
rest.AbortWithBadRequestError(c, errors.New("Not implemented"))
}

// APIError 简易的错误返回
func APIError(c *gin.Context, msg string) { // nolint
authCtx := route.MustGetAuthContext(c)

data := types.APIResponse{
Code: types.ApiErrorCode,
Message: msg,
RequestID: authCtx.RequestId,
}

c.AbortWithStatusJSON(http.StatusBadRequest, data)
rest.APIError(c, "Not implemented")
}
4 changes: 2 additions & 2 deletions bcs-services/bcs-webconsole/console/api/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,13 @@ func (q *wsQuery) GetTerminalSize() *types.TerminalSize {
func (s *service) BCSWebSocketHandler(c *gin.Context) { // nolint
// 还未建立 WebSocket 连接, 使用 Json 返回
if !websocket.IsWebSocketUpgrade(c.Request) {
rest.AbortWithBadRequestError(c, errors.New("invalid websocket connection"))
rest.APIError(c, "invalid websocket connection")
return
}

ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
rest.AbortWithBadRequestError(c, errors.Wrap(err, "upgrade websocket connection"))
rest.APIError(c, errors.Wrap(err, "upgrade websocket connection").Error())
return
}
defer ws.Close() // nolint
Expand Down
10 changes: 5 additions & 5 deletions bcs-services/bcs-webconsole/console/audit/record/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
"sync"
"time"

"k8s.io/klog/v2"
"github.com/Tencent/bk-bcs/bcs-common/common/blog"

"github.com/Tencent/bk-bcs/bcs-services/bcs-webconsole/console/audit/asciinema"
"github.com/Tencent/bk-bcs/bcs-services/bcs-webconsole/console/config"
Expand Down Expand Up @@ -54,7 +54,7 @@ func (c *castFile) clean() {
}

if err := os.Remove(c.absPath); err != nil {
klog.Error("remove file %s, err: %s", c.absPath, err)
blog.Error("remove file %s, err: %s", c.absPath, err)
}
}

Expand Down Expand Up @@ -184,7 +184,7 @@ func (r *ReplyRecorder) End() {
r.uploader.setState(r.cast.filePath, terminationState)

r.Writer = nil
klog.Infof("set file %s state to termination", r.cast.filePath)
blog.Infof("set file %s state to termination", r.cast.filePath)
})
}

Expand All @@ -200,7 +200,7 @@ func RecordOutputEvent(r *ReplyRecorder, p []byte) { // nolint
}

if err := r.Writer.WriteRow(p, asciinema.OutputEvent); err != nil {
klog.Errorf("session %s write replay row failed: %s", r.SessionID, err)
blog.Errorf("session %s write replay row failed: %s", r.SessionID, err)

r.End()
}
Expand All @@ -218,7 +218,7 @@ func RecordResizeEvent(r *ReplyRecorder, p []byte) { // nolint
}

if err := r.Writer.WriteRow(p, asciinema.ResizeEvent); err != nil {
klog.Errorf("Session %s write replay row failed: %s", r.SessionID, err)
blog.Errorf("Session %s write replay row failed: %s", r.SessionID, err)

r.End()
}
Expand Down
Loading

0 comments on commit b18974c

Please sign in to comment.