-
Notifications
You must be signed in to change notification settings - Fork 251
/
tcproxy.go
89 lines (83 loc) · 2.46 KB
/
tcproxy.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Package tcproxy provides a simple wrapper around the tcproxy executable.
// After the generic worker is refactored into engines, plugins and a runtime,
// tcproxy will be a plugin instead.
package tcproxy
import (
"fmt"
"log"
"net"
"os"
"os/exec"
"strconv"
"sync"
"time"
tcclient "github.com/taskcluster/taskcluster/v39/clients/client-go"
)
// TaskclusterProxy provides access to a taskcluster-proxy process running on the OS.
type TaskclusterProxy struct {
mut sync.Mutex
command *exec.Cmd
HTTPPort uint16
Pid int
}
// New starts a tcproxy OS process using the executable specified, and returns
// a *TaskclusterProxy.
func New(taskclusterProxyExecutable string, httpPort uint16, rootURL string, creds *tcclient.Credentials) (*TaskclusterProxy, error) {
args := []string{
"--port", strconv.Itoa(int(httpPort)),
"--root-url", rootURL,
"--client-id", creds.ClientID,
"--access-token", creds.AccessToken,
"--ip-address", "127.0.0.1",
}
if creds.Certificate != "" {
args = append(args, "--certificate", creds.Certificate)
}
args = append(args, creds.AuthorizedScopes...)
l := &TaskclusterProxy{
command: exec.Command(taskclusterProxyExecutable, args...),
HTTPPort: httpPort,
}
l.command.Stdout = os.Stdout
l.command.Stderr = os.Stderr
err := l.command.Start()
// Note - we're assuming here that if the process fails to launch we'll get
// an error. We should test this to be sure.
if err != nil {
return nil, err
}
l.Pid = l.command.Process.Pid
log.Printf("Started taskcluster proxy process (PID %v)", l.Pid)
// Just to be safe, let's make sure the port is actually active before returning.
err = waitForPortToBeActive(httpPort)
return l, err
}
func (l *TaskclusterProxy) Terminate() error {
l.mut.Lock()
defer func() {
l.mut.Unlock()
}()
if l.command == nil {
// if process has already died by other means, mission accomplished, nothing more to do
return nil
}
defer func() {
log.Printf("Stopped taskcluster proxy process (PID %v)", l.Pid)
l.HTTPPort = 0
l.Pid = 0
l.command = nil
}()
return l.command.Process.Kill()
}
func waitForPortToBeActive(port uint16) error {
deadline := time.Now().Add(60 * time.Second)
for time.Now().Before(deadline) {
conn, err := net.DialTimeout("tcp", "localhost:"+strconv.Itoa(int(port)), 60*time.Second)
if err == nil {
_ = conn.Close()
return nil
}
time.Sleep(100 * time.Millisecond)
}
return fmt.Errorf("Timeout waiting for taskcluster-proxy port %v to be active", port)
}