| 1 | /* |
| 2 | Copyright 2023 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package framework |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "fmt" |
| 22 | "log" |
| 23 | "net" |
| 24 | "net/http" |
| 25 | "os" |
| 26 | "os/exec" |
| 27 | "path/filepath" |
| 28 | "strconv" |
| 29 | "sync" |
| 30 | "syscall" |
| 31 | "testing" |
| 32 | "time" |
| 33 | |
| 34 | "github.com/prometheus/client_golang/prometheus" |
| 35 | "github.com/spf13/pflag" |
| 36 | "k8s.io/apimachinery/pkg/util/wait" |
| 37 | |
| 38 | agentapp "sigs.k8s.io/apiserver-network-proxy/cmd/agent/app" |
| 39 | agentopts "sigs.k8s.io/apiserver-network-proxy/cmd/agent/app/options" |
| 40 | "sigs.k8s.io/apiserver-network-proxy/pkg/agent" |
| 41 | agentmetrics "sigs.k8s.io/apiserver-network-proxy/pkg/agent/metrics" |
| 42 | metricstest "sigs.k8s.io/apiserver-network-proxy/pkg/testing/metrics" |
| 43 | ) |
| 44 | |
| 45 | type AgentOpts struct { |
| 46 | AgentID string |
| 47 | ServerAddr string |
| 48 | } |
| 49 | |
| 50 | type AgentRunner interface { |
| 51 | Start(testing.TB, AgentOpts) (Agent, error) |
| 52 | } |
| 53 | |
| 54 | type Agent interface { |
| 55 | GetConnectedServerCount() (int, error) |
| 56 | Ready() bool |
| 57 | Drain() |
| 58 | Stop() |
| 59 | Metrics() metricstest.AgentTester |
| 60 | } |
| 61 | type InProcessAgentRunner struct{} |
| 62 | |
| 63 | func (*InProcessAgentRunner) Start(t testing.TB, opts AgentOpts) (Agent, error) { |
| 64 | a := &agentapp.Agent{} |
| 65 | o, err := agentOptions(t, opts) |
| 66 | if err != nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | |
| 70 | ctx, cancel := context.WithCancel(context.Background()) |
| 71 | drainCh := make(chan struct{}) |
| 72 | stopCh := make(chan struct{}) |
| 73 | go func() { |
| 74 | if err := a.Run(o, drainCh, stopCh); err != nil { |
| 75 | log.Printf("ERROR running agent: %v", err) |
| 76 | cancel() |
| 77 | } |
| 78 | }() |
| 79 | |
| 80 | healthAddr := net.JoinHostPort(o.HealthServerHost, strconv.Itoa(o.HealthServerPort)) |
| 81 | if err := wait.PollImmediateWithContext(ctx, 100*time.Millisecond, ForeverTestTimeout, func(context.Context) (bool, error) { |
| 82 | return checkLiveness(healthAddr), nil |
| 83 | }); err != nil { |
| 84 | close(stopCh) |
| 85 | return nil, fmt.Errorf("agent never came up: %v", err) |
| 86 | } |
| 87 | |
| 88 | pa := &inProcessAgent{ |
| 89 | client: a.ClientSet(), |
| 90 | drainCh: drainCh, |
| 91 | stopCh: stopCh, |
| 92 | healthAddr: healthAddr, |
| 93 | } |
| 94 | t.Cleanup(pa.Stop) |
| 95 | return pa, nil |
| 96 | } |
| 97 | |
| 98 | type inProcessAgent struct { |
| 99 | client *agent.ClientSet |
| 100 | |
| 101 | drainOnce sync.Once |
| 102 | drainCh chan struct{} |
| 103 | |
| 104 | stopOnce sync.Once |
| 105 | stopCh chan struct{} |
| 106 | |
| 107 | healthAddr string |
| 108 | } |
| 109 | |
| 110 | func (a *inProcessAgent) Drain() { |
| 111 | a.drainOnce.Do(func() { |
| 112 | close(a.drainCh) |
| 113 | }) |
| 114 | } |
| 115 | |
| 116 | func (a *inProcessAgent) Stop() { |
| 117 | a.stopOnce.Do(func() { |
| 118 | close(a.stopCh) |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | func (a *inProcessAgent) GetConnectedServerCount() (int, error) { |
| 123 | return a.client.HealthyClientsCount(), nil |
| 124 | } |
| 125 | |
| 126 | func (a *inProcessAgent) Ready() bool { |
| 127 | return checkReadiness(a.healthAddr) |
| 128 | } |
| 129 | |
| 130 | func (a *inProcessAgent) Metrics() metricstest.AgentTester { |
| 131 | return metricstest.DefaultTester |
| 132 | } |
| 133 | |
| 134 | type ExternalAgentRunner struct { |
| 135 | ExecutablePath string |
| 136 | } |
| 137 | |
| 138 | func (r *ExternalAgentRunner) Start(t testing.TB, opts AgentOpts) (Agent, error) { |
| 139 | o, err := agentOptions(t, opts) |
| 140 | if err != nil { |
| 141 | return nil, err |
| 142 | } |
| 143 | |
| 144 | args := []string{} |
| 145 | o.Flags().VisitAll(func(f *pflag.Flag) { |
| 146 | args = append(args, fmt.Sprintf("--%s=%s", f.Name, f.Value.String())) |
| 147 | }) |
| 148 | |
| 149 | cmd := exec.Command(r.ExecutablePath, args...) |
| 150 | cmd.Stdout = os.Stdout // Forward stdout & stderr |
| 151 | cmd.Stderr = os.Stderr |
| 152 | if err := cmd.Start(); err != nil { |
| 153 | return nil, err |
| 154 | } |
| 155 | |
| 156 | healthAddr := net.JoinHostPort(o.HealthServerHost, strconv.Itoa(o.HealthServerPort)) |
| 157 | a := &externalAgent{ |
| 158 | cmd: cmd, |
| 159 | healthAddr: healthAddr, |
| 160 | adminAddr: net.JoinHostPort(o.AdminBindAddress, strconv.Itoa(o.AdminServerPort)), |
| 161 | agentID: opts.AgentID, |
| 162 | metrics: &metricstest.Tester{Endpoint: fmt.Sprintf("http://%s/metrics", healthAddr)}, |
| 163 | } |
| 164 | t.Cleanup(a.Stop) |
| 165 | |
| 166 | a.waitForLiveness() |
| 167 | return a, nil |
| 168 | } |
| 169 | |
| 170 | type externalAgent struct { |
| 171 | healthAddr, adminAddr string |
| 172 | agentID string |
| 173 | cmd *exec.Cmd |
| 174 | metrics *metricstest.Tester |
| 175 | |
| 176 | drainOnce sync.Once |
| 177 | stopOnce sync.Once |
| 178 | } |
| 179 | |
| 180 | func (a *externalAgent) Drain() { |
| 181 | a.drainOnce.Do(func() { |
| 182 | if err := a.cmd.Process.Signal(syscall.SIGTERM); err != nil { |
| 183 | log.Fatalf("Error draining agent process: %v", err) |
| 184 | } |
| 185 | }) |
| 186 | } |
| 187 | |
| 188 | func (a *externalAgent) Stop() { |
| 189 | a.stopOnce.Do(func() { |
| 190 | if err := a.cmd.Process.Kill(); err != nil { |
| 191 | log.Fatalf("Error stopping agent process: %v", err) |
| 192 | } |
| 193 | }) |
| 194 | } |
| 195 | |
| 196 | var ( |
| 197 | agentConnectedServerCountMetric = prometheus.BuildFQName(agentmetrics.Namespace, agentmetrics.Subsystem, "open_server_connections") |
| 198 | ) |
| 199 | |
| 200 | func (a *externalAgent) GetConnectedServerCount() (int, error) { |
| 201 | return readIntGauge(a.metrics.Endpoint, agentConnectedServerCountMetric) |
| 202 | } |
| 203 | |
| 204 | func (a *externalAgent) Ready() bool { |
| 205 | resp, err := http.Get(fmt.Sprintf("http://%s/readyz", a.healthAddr)) |
| 206 | if err != nil { |
| 207 | return false |
| 208 | } |
| 209 | resp.Body.Close() |
| 210 | return resp.StatusCode == http.StatusOK |
| 211 | } |
| 212 | |
| 213 | func (a *externalAgent) Metrics() metricstest.AgentTester { |
| 214 | return a.metrics |
| 215 | } |
| 216 | |
| 217 | func (a *externalAgent) waitForLiveness() error { |
| 218 | err := wait.PollImmediate(100*time.Millisecond, ForeverTestTimeout, func() (bool, error) { |
| 219 | resp, err := http.Get(fmt.Sprintf("http://%s/healthz", a.healthAddr)) |
| 220 | if err != nil { |
| 221 | return false, nil |
| 222 | } |
| 223 | resp.Body.Close() |
| 224 | return resp.StatusCode == http.StatusOK, nil |
| 225 | }) |
| 226 | if err != nil { |
| 227 | return fmt.Errorf("timed out waiting for agent liveness check") |
| 228 | } |
| 229 | return nil |
| 230 | } |
| 231 | |
| 232 | func agentOptions(t testing.TB, opts AgentOpts) (*agentopts.GrpcProxyAgentOptions, error) { |
| 233 | t.Helper() |
| 234 | o := agentopts.NewGrpcProxyAgentOptions() |
| 235 | |
| 236 | host, port, err := net.SplitHostPort(opts.ServerAddr) |
| 237 | if err != nil { |
| 238 | return nil, fmt.Errorf("failed to parse ServerAddr: %w", err) |
| 239 | } |
| 240 | o.ProxyServerHost = host |
| 241 | if o.ProxyServerPort, err = strconv.Atoi(port); err != nil { |
| 242 | return nil, fmt.Errorf("invalid server port: %w", err) |
| 243 | } |
| 244 | |
| 245 | o.AgentID = opts.AgentID |
| 246 | o.SyncInterval = 100 * time.Millisecond |
| 247 | o.SyncIntervalCap = 1 * time.Second |
| 248 | o.ProbeInterval = 100 * time.Millisecond |
| 249 | |
| 250 | o.AgentCert = filepath.Join(CertsDir, TestAgentCertFile) |
| 251 | o.AgentKey = filepath.Join(CertsDir, TestAgentKeyFile) |
| 252 | o.CaCert = filepath.Join(CertsDir, TestCAFile) |
| 253 | |
| 254 | const localhost = "127.0.0.1" |
| 255 | o.HealthServerHost = localhost |
| 256 | o.AdminBindAddress = localhost |
| 257 | |
| 258 | ports, err := FreePorts(2) |
| 259 | if err != nil { |
| 260 | return nil, err |
| 261 | } |
| 262 | o.HealthServerPort = ports[0] |
| 263 | o.AdminServerPort = ports[1] |
| 264 | |
| 265 | return o, nil |
| 266 | } |