-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathportforward.go
71 lines (61 loc) · 1.41 KB
/
portforward.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
63
64
65
66
67
68
69
70
71
package test
import (
"bufio"
"fmt"
"os/exec"
"regexp"
"strconv"
"syscall"
"time"
corev1 "k8s.io/api/core/v1"
)
type PortForwardType struct {
LocalPort uint32
cmd *exec.Cmd
}
func PortForward(pod corev1.Pod, remotePort uint32) (*PortForwardType, error) {
cmd := exec.Command("oc", "port-forward", "-n", pod.Namespace, pod.Name, fmt.Sprintf(":%d", remotePort))
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
var localPort uint32
portRegex := regexp.MustCompile(`Forwarding from [^:]+:([0-9]+) -> ([0-9]+)`)
portChannel := make(chan uint32)
scanner := bufio.NewScanner(stdout)
go func() {
readPort := false
for scanner.Scan() {
line := scanner.Text()
if !readPort {
submatch := portRegex.FindStringSubmatch(line)
if submatch != nil {
i, _ := strconv.Atoi(submatch[1])
portChannel <- uint32(i)
readPort = true
}
}
}
}()
err = cmd.Start()
if err != nil {
return nil, err
}
select {
case localPort = <-portChannel:
break
case <-time.After(30 * time.Second):
cmd.Process.Signal(syscall.SIGTERM)
go cmd.Wait()
return nil, fmt.Errorf("timeout waiting for 'oc port-forward' output log local port number")
}
return &PortForwardType{
LocalPort: localPort,
cmd: cmd,
}, nil
}
func (portForward *PortForwardType) Close() error {
err := portForward.cmd.Process.Signal(syscall.SIGTERM)
go portForward.cmd.Wait()
return err
}