enhance: Kubernetes-HostPort support container port same as host (#230)

Signed-off-by: ChrisLiu <chrisliu1995@163.com>
This commit is contained in:
ChrisLiu 2025-06-06 11:49:42 +08:00 committed by GitHub
parent a64b21eab5
commit 51a82bd107
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 14 additions and 3 deletions

View File

@ -42,6 +42,7 @@ const (
//Its corresponding value format is as follows, containerName:port1/protocol1,port2/protocol2,... e.g. game-server:25565/TCP //Its corresponding value format is as follows, containerName:port1/protocol1,port2/protocol2,... e.g. game-server:25565/TCP
//When no protocol is specified, TCP is used by default //When no protocol is specified, TCP is used by default
ContainerPortsKey = "ContainerPorts" ContainerPortsKey = "ContainerPorts"
PortSameAsHost = "SameAsHost"
) )
type HostPortPlugin struct { type HostPortPlugin struct {
@ -103,6 +104,10 @@ func (hpp *HostPortPlugin) OnPodAdded(c client.Client, pod *corev1.Pod, ctx cont
if ports, ok := containerPortsMap[container.Name]; ok { if ports, ok := containerPortsMap[container.Name]; ok {
containerPorts := container.Ports containerPorts := container.Ports
for i, port := range ports { for i, port := range ports {
// -1 means same as host
if port == -1 {
port = hostPorts[numToAlloc-1]
}
containerPort := corev1.ContainerPort{ containerPort := corev1.ContainerPort{
ContainerPort: port, ContainerPort: port,
HostPort: hostPorts[numToAlloc-1], HostPort: hostPorts[numToAlloc-1],
@ -338,9 +343,15 @@ func parseConfig(conf []gamekruiseiov1alpha1.NetworkConfParams, pod *corev1.Pod)
for _, portString := range strings.Split(cpSlice[1], ",") { for _, portString := range strings.Split(cpSlice[1], ",") {
ppSlice := strings.Split(portString, "/") ppSlice := strings.Split(portString, "/")
// handle port // handle port
port, err := strconv.ParseInt(ppSlice[0], 10, 32) var port int64
if err != nil { var err error
continue if ppSlice[0] == PortSameAsHost {
port = -1
} else {
port, err = strconv.ParseInt(ppSlice[0], 10, 32)
if err != nil {
continue
}
} }
numToAlloc++ numToAlloc++
ports = append(ports, int32(port)) ports = append(ports, int32(port))