Skip to content

Commit

Permalink
pods的webssh和一些相关
Browse files Browse the repository at this point in the history
  • Loading branch information
qishu321 committed Aug 30, 2023
1 parent e48f54d commit 7ddd843
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 5 deletions.
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
```bash
##k8s的多集群管理
- 目前实现的功能:
kubeconfig的管理,存储到数据库里,可以任意切换
然后根据这个实现多集群的管理
kubeconfig的管理,存储到数据库里,然后根据这个实现多集群的管理,多集群可以任意切换
web创建namespace、svc;web查看pod的日志、webssh登录pod、web获取集群监控汇总详情等
```

## 部署方法
Expand Down Expand Up @@ -81,6 +81,10 @@ git clone https://github.com/qishu321/cmdb-ops-flow.git
## 预览
<img src="https://github.com/qishu321/cmdb-ops-flow/blob/main/doc/kube-config.png?raw=true" style="zoom: 25%;" />

<img src="https://github.com/qishu321/cmdb-ops-flow/blob/main/doc/webssh_pod.png?raw=true" style="zoom: 25%;" />

<img src="https://github.com/qishu321/cmdb-ops-flow/blob/main/doc/pod_log.png?raw=true" style="zoom: 25%;" />

<img src="https://github.com/qishu321/cmdb-ops-flow/blob/main/doc/kube-dashboard.png?raw=true" style="zoom: 25%;" />


Expand Down
83 changes: 83 additions & 0 deletions api/apis_k8s/pods.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,63 @@ import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"io"
"log"
"net/http"
)

var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}

const logBufferSize = 1024 // 适当设置缓冲区大小

func GetPodLogs(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Printf("WebSocket 连接失败:%v", err)
return
}
defer conn.Close()

var data k8s.Pod
if err := c.ShouldBindQuery(&data); err != nil {
log.Printf("请求数据绑定失败:%v", err)
return
}
fmt.Println("123", data)
logsStream, err := service_k8s.GetPodLogs(data.ID, data.Namespace, data.Name, data.ContainerName)
if err != nil {
log.Printf("获取日志时出错:%v", err)
return
}

logBuffer := make([]byte, logBufferSize)
for {
n, err := logsStream.Read(logBuffer)
if err != nil && err != io.EOF {
log.Printf("读取日志时出错:%v", err)
return
}

if n > 0 {
logData := logBuffer[:n]
if err := conn.WriteMessage(websocket.TextMessage, logData); err != nil {
log.Printf("WebSocket 发送消息失败:%v", err)
return
}
}

if err == io.EOF {
break
}
}
}

func GetAllPods(c *gin.Context) {
var data struct {
ID int `json:"id"`
Expand Down Expand Up @@ -43,6 +97,35 @@ func GetPods(c *gin.Context) {
c.JSON(http.StatusOK, (&result.Result{}).Ok(code, list, msg.GetErrMsg(code)))
}

//var (
// logBufferSize = 10 * 1024 * 1024 // 10M
//)

//func GetPodLogs(c *gin.Context) {
// var data k8s.Pod
// if err := c.ShouldBindJSON(&data); err != nil {
// c.JSON(http.StatusBadRequest, (&result.Result{}).Error(http.StatusBadRequest, err.Error(), msg.GetErrMsg(msg.ERROR)))
// return
// }
//
// logsStream, err := service_k8s.GetPodLogs(data.ID, data.Namespace, data.Name, data.ContainerName)
// if err != nil {
// log.Printf("Error getting logs: %v", err)
//
// c.JSON(http.StatusInternalServerError, (&result.Result{}).Error(http.StatusInternalServerError, "Error getting logs", msg.GetErrMsg(msg.ERROR)))
// return
// }
//
// logBuffer := make([]byte, logBufferSize)
// n, err := logsStream.Read(logBuffer)
// if err != nil && err != io.EOF {
// c.JSON(http.StatusInternalServerError, (&result.Result{}).Error(http.StatusInternalServerError, "Error reading logs", msg.GetErrMsg(msg.ERROR)))
// return
// }
// c.JSON(http.StatusOK, (&result.Result{}).Ok(200, string(logBuffer[:n]), msg.GetErrMsg(200)))
//
//}

type query struct {
Id int `form:"id" binding:"required"`
Namespace string `form:"namespace" binding:"required"`
Expand Down
Binary file added doc/pod_log.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/webssh_pod.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 4 additions & 3 deletions models/k8s/pods.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ import (
)

type Pod struct {
ID int `json:"id"`
ID int `json:"id" form:"id"`

Name string `json:"name"`
Name string `json:"name" form:"name"`
PodIp string `json:"pod_ip"`
Status string `json:"status"`
Labels Labels `json:"labels"`
NodeName string `json:"node_name"`
Namespace string `json:"namespace"`
Namespace string `json:"namespace" form:"namespace"`
Containers []Container `json:"containers"`
ContainerName string `json:"container_name" form:"container_name"`
Annotations Annotations `json:"annotations"`
CreationTimestamp time.Time `json:"creation_timestamp"`
}
3 changes: 3 additions & 0 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ func InitRouter() {
adminuser.POST("/login", api.Login)
adminuser.GET("/ssh/webssh", api.VisitorWebsocketServer)
adminuser.GET("/kube/pods/SshPod", apis_k8s.SshPod)
adminuser.GET("/kube/pods/getPodLogs", apis_k8s.GetPodLogs)

}

Expand All @@ -111,6 +112,8 @@ func InitRouter() {

api_k8s.POST("/kube/pods/getallPods", apis_k8s.GetAllPods)
api_k8s.POST("/kube/pods/getPods", apis_k8s.GetPods)
api_k8s.POST("/kube/pods/getPodLogs", apis_k8s.GetPodLogs)

api_k8s.GET("/kube/pods/SshPod", apis_k8s.SshPod)

api_k8s.POST("/kube/nodes/getVersion", apis_k8s.GetVersion)
Expand Down
22 changes: 22 additions & 0 deletions service/service_k8s/pods.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"cmdb-ops-flow/models/k8s"
"context"
"fmt"
"io"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

Expand Down Expand Up @@ -79,3 +81,23 @@ func GetPods(id int, ns string) ([]k8s.Pod, error) {
//
// return req, err
//}

func GetPodLogs(id int, ns string, podName string, containerName string) (io.ReadCloser, error) {
clientset, err := k8s.GetKubeConfig(id)
if err != nil {
return nil, err
}
tailLines := int64(25) // 将100转换为int64类型

req := clientset.CoreV1().Pods(ns).GetLogs(podName, &v1.PodLogOptions{
TailLines: &tailLines, // 使用指向int64类型的指针
Container: containerName,
})
fmt.Println(req)
logsStream, err := req.Stream(context.TODO())
if err != nil {
return nil, fmt.Errorf("error opening log stream for container %s: %v", containerName, err)
}

return logsStream, nil
}

0 comments on commit 7ddd843

Please sign in to comment.