using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace k8s.Tests.Mock.Server.Controllers { /// /// Controller for the mock Kubernetes pod-port-forward API. /// [Route("api/v1")] public class PodPortForwardController : Controller { /// /// Create a new . /// /// /// The adapter used to capture sockets accepted by the test server and provide them to the calling test. /// public PodPortForwardController(WebSocketTestAdapter webSocketTestAdapter) { if (webSocketTestAdapter == null) { throw new ArgumentNullException(nameof(webSocketTestAdapter)); } WebSocketTestAdapter = webSocketTestAdapter; } /// /// The adapter used to capture sockets accepted by the test server and provide them to the calling test. /// private WebSocketTestAdapter WebSocketTestAdapter { get; } /// /// Mock Kubernetes API: port-forward for pod. /// /// /// The target pod's containing namespace. /// /// /// The target pod's name. /// /// /// The port(s) to forward to the pod. /// [Route("namespaces/{kubeNamespace}/pods/{podName}/portforward")] public async Task Exec(string kubeNamespace, string podName, IEnumerable ports) { if (!HttpContext.WebSockets.IsWebSocketRequest) { return BadRequest("PortForward requires WebSockets"); } WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync( subProtocol: WebSocketProtocol.ChannelWebSocketProtocol).ConfigureAwait(false); WebSocketTestAdapter.AcceptedPodPortForwardV1Connection.AcceptServerSocket(webSocket); await WebSocketTestAdapter.TestCompleted.ConfigureAwait(false); return Ok(); } } }