Skip to content

Commit

Permalink
pods的webssh和一些相关
Browse files Browse the repository at this point in the history
  • Loading branch information
qishu321 committed Aug 29, 2023
1 parent e71f1dc commit e48f54d
Show file tree
Hide file tree
Showing 9 changed files with 446 additions and 27 deletions.
35 changes: 35 additions & 0 deletions api/apis_k8s/pods.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import (
"cmdb-ops-flow/service/service_k8s"
"cmdb-ops-flow/utils/msg"
"cmdb-ops-flow/utils/result"
"cmdb-ops-flow/utils/ssh"
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
)

Expand Down Expand Up @@ -39,3 +42,35 @@ func GetPods(c *gin.Context) {
code := msg.SUCCSE
c.JSON(http.StatusOK, (&result.Result{}).Ok(code, list, msg.GetErrMsg(code)))
}

type query struct {
Id int `form:"id" binding:"required"`
Namespace string `form:"namespace" binding:"required"`
PodName string `form:"pod_name" binding:"required"`
ContainerName string `form:"container_name" binding:"required"`
Command string `form:"command" binding:"required"`
}

func SshPod(c *gin.Context) {
wsConn, err := ssh.InitWebsocket(c.Writer, c.Request)
if err != nil {
fmt.Println("InitWebsocket err", err)
wsConn.WsClose()
return
}
var r query
if err := c.ShouldBindQuery(&r); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"err": err.Error(),
})
return
}

wsConn.WsWrite(websocket.TextMessage, []byte("你已进入 命名空间:"+r.Namespace+" 容器组:"+r.ContainerName+" 容器名:"+r.ContainerName+"的终端"))

if err := ssh.StartProcess(wsConn, r.Id, r.PodName, r.Namespace, r.ContainerName, r.Command); err != nil {
fmt.Println("StartProcess err", err)
wsConn.WsClose()
return
}
}
2 changes: 2 additions & 0 deletions api/apis_k8s/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"cmdb-ops-flow/service/service_k8s"
"cmdb-ops-flow/utils/msg"
"cmdb-ops-flow/utils/result"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
Expand Down Expand Up @@ -43,6 +44,7 @@ func EditSvc(c *gin.Context) {

var data k8s.Svc
if err := c.ShouldBindJSON(&data); err != nil {
fmt.Println(err)
c.JSON(http.StatusOK, (&result.Result{}).Error(5001, err.Error(), msg.GetErrMsg(msg.ERROR)))
return
}
Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ require (
github.com/jinzhu/gorm v1.9.16
github.com/opentracing/opentracing-go v1.2.0
github.com/prometheus/client_golang v1.11.1
github.com/sirupsen/logrus v1.6.0
github.com/uber/jaeger-client-go v2.30.0+incompatible
go.etcd.io/etcd/client/v3 v3.5.9
golang.org/x/crypto v0.11.0
Expand Down Expand Up @@ -52,10 +53,12 @@ require (
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/moby/spdystream v0.2.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
Expand Down
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJY
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
Expand Down Expand Up @@ -165,6 +166,7 @@ github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa02
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
Expand All @@ -186,6 +188,8 @@ github.com/mattn/go-sqlite3 v1.14.0 h1:mLyGNKR8+Vv9CAU7PphKa2hkEqxxhn8i32J6FPj1/
github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8=
github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
Expand Down Expand Up @@ -233,6 +237,7 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
Expand Down
33 changes: 22 additions & 11 deletions models/k8s/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,29 @@ package k8s

type Selector map[string]string

// type SessionAffinityConfig map[string]string
type ClientIP struct {
TimeoutSeconds int32 `json:"timeoutSeconds"`
}

type SessionAffinityConfig struct {
ClientIP
}

type Svc struct {
ID int `json:"id"`

Name string `json:"name"`
Namespace string `json:"namespace"`
Type string `json:"type"`
ClusterIp string `json:"cluster_ip"`
Ports []string `json:"ports"`
Selector Selector `json:"selector"`
Labels Labels `json:"labels"`
Annotations Annotations `json:"annotations"`
EndPoints []string `json:"end_points"`
NodePort int32 `json:"nodePort"` // 添加了 NodePort 字段
Protocol string `json:"protocol"`
Name string `json:"name"`
Namespace string `json:"namespace"`
Type string `json:"type"`
ClusterIp string `json:"cluster_ip"`
Ports []string `json:"ports"`
Selector Selector `json:"selector"`
Labels Labels `json:"labels"`
Annotations Annotations `json:"annotations"`
EndPoints []string `json:"end_points"`
NodePort int32 `json:"nodePort"` // 添加了 NodePort 字段
Protocol string `json:"protocol"`
SessionAffinity string `json:"sessionAffinity"`
SessionAffinityConfig SessionAffinityConfig `json:"session_affinity_config"`
}
3 changes: 3 additions & 0 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ func InitRouter() {
adminuser := r.Group("/api/admin/user")
{
adminuser.POST("/login", api.Login)
adminuser.GET("/ssh/webssh", api.VisitorWebsocketServer)
adminuser.GET("/kube/pods/SshPod", apis_k8s.SshPod)

}

Expand All @@ -109,6 +111,7 @@ func InitRouter() {

api_k8s.POST("/kube/pods/getallPods", apis_k8s.GetAllPods)
api_k8s.POST("/kube/pods/getPods", apis_k8s.GetPods)
api_k8s.GET("/kube/pods/SshPod", apis_k8s.SshPod)

api_k8s.POST("/kube/nodes/getVersion", apis_k8s.GetVersion)
api_k8s.POST("/kube/nodes/getNodeMetrics", apis_k8s.GetNodeMetrics)
Expand Down
27 changes: 27 additions & 0 deletions service/service_k8s/pods.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,30 @@ func GetPods(id int, ns string) ([]k8s.Pod, error) {

return pods, err
}

//func GetPodLogs(id int, ns string) ([]k8s.Pod, error) {
// clientSet, err := k8s.GetKubeConfig(id)
// if err != nil {
// fmt.Println(err)
// }
// podList, _ := clientSet.CoreV1().Pods(ns).List(context.Background(), metav1.ListOptions{})
//
// pods := make([]k8s.Pod, 0, 20)
// for _, item := range podList.Items {
// containers := make([]k8s.Container, 0, len(item.Status.ContainerStatuses))
// for _, containerStatus := range item.Status.ContainerStatuses {
// container := k8s.Container{Name: containerStatus.Name, Ready: containerStatus.Ready, RestartCount: int(containerStatus.RestartCount),
// Image: containerStatus.Image, ImageId: containerStatus.ImageID, ContainerId: containerStatus.ContainerID}
// containers = append(containers, container)
// }
// pod := k8s.Pod{Name: item.Name, Namespace: item.Namespace, Status: string(item.Status.Phase), CreationTimestamp: item.CreationTimestamp.Time,
// Containers: containers, Labels: item.Labels, Annotations: item.Annotations, PodIp: item.Status.PodIP, NodeName: item.Spec.NodeName}
// pods = append(pods, pod)
// }
// req,err := clientSet.CoreV1().Pods(ns).GetLogs(pods[0].Name, &v1.PodLogOptions{Follow: true, Container: pods[0].Containers[0].Name}).Stream(context.TODO()) //hello 为container name
// if err != nil {
// fmt.Println(err)
// }
//
// return req, err
//}
96 changes: 80 additions & 16 deletions service/service_k8s/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,65 @@ func Getsvs(id int, ns string) ([]k8s.Svc, error) {
prots = append(prots, portStr)
}

svc := k8s.Svc{
ID: id,
Name: service.Name,
Namespace: service.Namespace,
Type: string(service.Spec.Type),
ClusterIp: service.Spec.ClusterIP,
Ports: prots,
Selector: service.Spec.Selector,
Labels: service.Labels,
Annotations: service.Annotations,
NodePort: service.Spec.Ports[0].NodePort, // Assuming there's at least one port defined
Protocol: string(service.Spec.Ports[0].Protocol), // Assuming there's at least one port defined
if service.Spec.SessionAffinity == "ClientIP" {
svc := k8s.Svc{
ID: id,
Name: service.Name,
Namespace: service.Namespace,
Type: string(service.Spec.Type),
ClusterIp: service.Spec.ClusterIP,
Ports: prots,
Selector: service.Spec.Selector,
Labels: service.Labels,
Annotations: service.Annotations,
NodePort: service.Spec.Ports[0].NodePort, // Assuming there's at least one port defined
Protocol: string(service.Spec.Ports[0].Protocol),
SessionAffinity: string(service.Spec.SessionAffinity),
SessionAffinityConfig: k8s.SessionAffinityConfig{
ClientIP: k8s.ClientIP{
TimeoutSeconds: *service.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds,
},
},
}
svcs = append(svcs, svc)
} else {
svc := k8s.Svc{
ID: id,
Name: service.Name,
Namespace: service.Namespace,
Type: string(service.Spec.Type),
ClusterIp: service.Spec.ClusterIP,
Ports: prots,
Selector: service.Spec.Selector,
Labels: service.Labels,
Annotations: service.Annotations,
NodePort: service.Spec.Ports[0].NodePort, // Assuming there's at least one port defined
Protocol: string(service.Spec.Ports[0].Protocol),
SessionAffinity: string(service.Spec.SessionAffinity),
}
//svc := k8s.Svc{
// ID: id,
// Name: service.Name,
// Namespace: service.Namespace,
// Type: string(service.Spec.Type),
// ClusterIp: service.Spec.ClusterIP,
// Ports: prots,
// Selector: service.Spec.Selector,
// Labels: service.Labels,
// Annotations: service.Annotations,
// NodePort: service.Spec.Ports[0].NodePort, // Assuming there's at least one port defined
// Protocol: string(service.Spec.Ports[0].Protocol),
// SessionAffinity: string(service.Spec.SessionAffinity),
// SessionAffinityConfig: k8s.SessionAffinityConfig{
// ClientIP:k8s.ClientIP{
// TimeoutSeconds: *service.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds,
// },
// },
//
//
//}
svcs = append(svcs, svc)
}
svcs = append(svcs, svc)
}

return svcs, nil
Expand Down Expand Up @@ -89,6 +134,13 @@ func EditSvc(id int, updatedSvc k8s.Svc) (*v1.Service, error) {
existingSvc.Spec.Ports = updatedServicePorts
existingSvc.Spec.Ports[0].NodePort = updatedSvc.NodePort

existingSvc.Spec.SessionAffinity = v1.ServiceAffinity(updatedSvc.SessionAffinity)
existingSvc.Spec.SessionAffinityConfig = &v1.SessionAffinityConfig{
ClientIP: &v1.ClientIPConfig{
TimeoutSeconds: &updatedSvc.SessionAffinityConfig.ClientIP.TimeoutSeconds,
},
}

// 其他字段根据你的需求进行更新

// 更新 Service 资源
Expand Down Expand Up @@ -128,6 +180,11 @@ func AddSvc(id int, data k8s.Svc) (*v1.Service, error) {

servicePorts = append(servicePorts, servicePort)
}
//sessionAffinityConfig := &k8s.SessionAffinityConfig{
// ClientIP: k8s.ClientIP{
// TimeoutSeconds: data.SessionAffinityConfig.ClientIP.TimeoutSeconds,
// },
//}

serviceType := v1.ServiceTypeClusterIP
if data.Type == "NodePort" {
Expand All @@ -140,11 +197,18 @@ func AddSvc(id int, data k8s.Svc) (*v1.Service, error) {
Labels: data.Labels,
},
Spec: v1.ServiceSpec{
Selector: data.Selector,
Type: serviceType,
Ports: servicePorts,
Selector: data.Selector,
Type: serviceType,
Ports: servicePorts,
SessionAffinity: v1.ServiceAffinity(data.SessionAffinity),
SessionAffinityConfig: &v1.SessionAffinityConfig{
ClientIP: &v1.ClientIPConfig{
TimeoutSeconds: &data.SessionAffinityConfig.ClientIP.TimeoutSeconds,
},
},
},
}

serviceList, err := clientSet.CoreV1().Services(data.Namespace).Create(context.TODO(), service, metav1.CreateOptions{})

return serviceList, err
Expand Down
Loading

0 comments on commit e48f54d

Please sign in to comment.