generated from LinuxSuRen/.github
-
Notifications
You must be signed in to change notification settings - Fork 16
/
net.go
62 lines (54 loc) · 1.34 KB
/
net.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package common
import (
"errors"
"fmt"
"net"
)
// PortIsFree checks if the port is free or not
func PortIsFree(port int) bool {
if listener, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port)); err == nil {
_ = listener.Close()
return true
}
return false
}
// FreePort is the tool to find free ports of KubeSphere
type FreePort struct {
defaultPorts []int
}
// NewFreePort creates a FreePort with a specific extra count of ports
func NewFreePort(extraCount int) *FreePort {
initPorts := []int{30880, 30180}
if extraCount > 0 {
for i := 0; i < extraCount; i++ {
initPorts = append(initPorts, initPorts[len(initPorts)-1]+1)
}
}
return &FreePort{defaultPorts: initPorts}
}
// FindFreePortsOfKubeSphere returns the free ports of KubeSphere
// The order of the ports is: console, jenkins
func (f *FreePort) FindFreePortsOfKubeSphere() ([]int, error) {
if len(f.defaultPorts) == 0 {
f.defaultPorts = []int{30880, // for KubeSphere console
30180, // for Jenkins
}
}
conflict := false
for _, port := range f.defaultPorts {
if !PortIsFree(port) {
conflict = true
break
}
}
if conflict {
for i := range f.defaultPorts {
f.defaultPorts[i]++
if f.defaultPorts[i] >= 65530 {
return nil, errors.New("no enough free ports available")
}
}
return f.FindFreePortsOfKubeSphere()
}
return f.defaultPorts, nil
}