File: proxy_server.go

package info (click to toggle)
golang-k8s-sigs-apiserver-network-proxy 0.33.0%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,068 kB
  • sloc: makefile: 220; sh: 118
file content (171 lines) | stat: -rw-r--r-- 4,226 bytes parent folder | download
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/*
Copyright 2023 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package framework

import (
	"context"
	"fmt"
	"log"
	"net"
	"path/filepath"
	"strconv"
	"sync"
	"testing"
	"time"

	"github.com/google/uuid"
	"k8s.io/apimachinery/pkg/util/wait"
	serverapp "sigs.k8s.io/apiserver-network-proxy/cmd/server/app"
	serveropts "sigs.k8s.io/apiserver-network-proxy/cmd/server/app/options"
	"sigs.k8s.io/apiserver-network-proxy/pkg/server"
	metricstest "sigs.k8s.io/apiserver-network-proxy/pkg/testing/metrics"
)

type ProxyServerOpts struct {
	ServerCount int
	Mode        string
	AgentPort   int // Defaults to random port.
}

type ProxyServerRunner interface {
	Start(testing.TB, ProxyServerOpts) (ProxyServer, error)
}

type ProxyServer interface {
	ConnectedBackends() (int, error)
	AgentAddr() string
	FrontAddr() string
	Ready() bool
	Stop()
	Metrics() metricstest.ServerTester
}

type InProcessProxyServerRunner struct{}

func (*InProcessProxyServerRunner) Start(t testing.TB, opts ProxyServerOpts) (ProxyServer, error) {
	s := &serverapp.Proxy{}
	o, err := serverOptions(t, opts)
	if err != nil {
		return nil, fmt.Errorf("error building server options: %w", err)
	}

	ctx, cancel := context.WithCancel(context.Background())
	stopCh := make(chan struct{})
	go func() {
		if err := s.Run(o, stopCh); err != nil {
			log.Printf("ERROR running proxy server: %v", err)
			cancel()
		}
	}()

	healthAddr := net.JoinHostPort(o.HealthBindAddress, strconv.Itoa(o.HealthPort))
	if err := wait.PollImmediateWithContext(ctx, 100*time.Millisecond, ForeverTestTimeout, func(context.Context) (bool, error) {
		return checkLiveness(healthAddr), nil
	}); err != nil {
		close(stopCh)
		return nil, fmt.Errorf("server never came up: %v", err)
	}

	ps := &inProcessProxyServer{
		proxyServer: s.ProxyServer(),
		stopCh:      stopCh,
		mode:        opts.Mode,
		healthAddr:  healthAddr,
		agentAddr:   net.JoinHostPort(o.AgentBindAddress, strconv.Itoa(o.AgentPort)),
		frontAddr:   o.UdsName,
	}
	t.Cleanup(ps.Stop)
	return ps, nil
}

type inProcessProxyServer struct {
	proxyServer *server.ProxyServer

	stopOnce sync.Once
	stopCh   chan struct{}

	mode string

	healthAddr string
	agentAddr  string
	frontAddr  string
}

func (ps *inProcessProxyServer) Stop() {
	ps.stopOnce.Do(func() {
		close(ps.stopCh)
	})
}

func (ps *inProcessProxyServer) AgentAddr() string {
	return ps.agentAddr
}

func (ps *inProcessProxyServer) FrontAddr() string {
	return ps.frontAddr
}

func (ps *inProcessProxyServer) ConnectedBackends() (int, error) {
	numBackends := 0
	for _, bm := range ps.proxyServer.BackendManagers {
		numBackends += bm.NumBackends()
	}
	return numBackends, nil
}

func (ps *inProcessProxyServer) Ready() bool {
	return checkReadiness(ps.healthAddr)
}

func (ps *inProcessProxyServer) Metrics() metricstest.ServerTester {
	return metricstest.DefaultTester
}

func serverOptions(t testing.TB, opts ProxyServerOpts) (*serveropts.ProxyRunOptions, error) {
	t.Helper()
	o := serveropts.NewProxyRunOptions()

	o.ServerCount = opts.ServerCount
	o.Mode = opts.Mode

	uid := uuid.New().String()
	o.UdsName = filepath.Join(CertsDir, fmt.Sprintf("server-%s.sock", uid))
	o.ServerPort = 0 // Required for UDS

	o.ClusterCert = filepath.Join(CertsDir, TestServerCertFile)
	o.ClusterKey = filepath.Join(CertsDir, TestServerKeyFile)
	o.ClusterCaCert = filepath.Join(CertsDir, TestCAFile)

	const localhost = "127.0.0.1"
	o.AgentBindAddress = localhost
	o.HealthBindAddress = localhost
	o.AdminBindAddress = localhost

	ports, err := FreePorts(3)
	if err != nil {
		return nil, err
	}
	if opts.AgentPort != 0 {
		o.AgentPort = opts.AgentPort
	} else {
		o.AgentPort = ports[0]
	}
	o.HealthPort = ports[1]
	o.AdminPort = ports[2]

	return o, nil
}