How to use Ports method of wait Package

Best Testcontainers-go code snippet using wait.Ports

proxier_test.go

Source:proxier_test.go Github

copy

Full Screen

...97 if !svcInfo.IsAlive() {98 t.Fatalf("expected IsAlive() true for %s", servicePortName)99 }100 var servicePort *v1.ServicePort101 for _, port := range service.Spec.Ports {102 if port.Name == servicePortName.Port {103 servicePort = &port104 break105 }106 }107 if servicePort == nil {108 t.Errorf("failed to find service %s port with name %q", servicePortName.NamespacedName, servicePortName.Port)109 }110 if svcInfo.portal.ip.String() != service.Spec.ClusterIP || int32(svcInfo.portal.port) != servicePort.Port || svcInfo.protocol != servicePort.Protocol {111 t.Errorf("unexpected serviceInfo for %s: %#v", servicePortName, svcInfo)112 }113 // Wait for proxy socket to start up114 if err := wait.PollImmediate(50*time.Millisecond, 30*time.Second, func() (bool, error) {115 return svcInfo.IsStarted(), nil116 }); err != nil {117 t.Errorf("timed out waiting for proxy socket %s to start: %v", servicePortName, err)118 }119 return svcInfo120}121// addServiceAndWaitForInfoIndex adds the service to the proxy and waits for the122// named port to be ready123func addServiceAndWaitForInfo(t *testing.T, p *Proxier, servicePortName proxy.ServicePortName, service *v1.Service) *ServiceInfo {124 p.OnServiceAdd(service)125 return waitForServiceInfo(t, p, servicePortName, service)126}127// deleteServiceAndWait deletes the servicein the proxy and waits until it128// has been cleaned up. waitFunc will be called to wait for the service129// port's socket to close.130func deleteServiceAndWait(t *testing.T, p *Proxier, svcInfo *ServiceInfo, service *v1.Service, waitFunc func(*Proxier, int) error) {131 p.OnServiceDelete(service)132 // Wait for the port to really close.133 if err := waitFunc(p, svcInfo.proxyPort); err != nil {134 t.Fatalf(err.Error())135 }136 waitForProxyFinished(t, svcInfo)137 if svcInfo.IsAlive() {138 t.Fatalf("wrong value for IsAlive(): expected false")139 }140}141// udpEchoServer is a simple echo server in UDP, intended for testing the proxy.142type udpEchoServer struct {143 net.PacketConn144}145func newUDPEchoServer() (*udpEchoServer, error) {146 packetconn, err := net.ListenPacket("udp", ":0")147 if err != nil {148 return nil, err149 }150 return &udpEchoServer{packetconn}, nil151}152func (r *udpEchoServer) Loop() {153 var buffer [4096]byte154 for {155 n, cliAddr, err := r.ReadFrom(buffer[0:])156 if err != nil {157 fmt.Printf("ReadFrom failed: %v\n", err)158 continue159 }160 r.WriteTo(buffer[0:n], cliAddr)161 }162}163var tcpServerPort int32164var udpServerPort int32165func TestMain(m *testing.M) {166 // Don't handle panics167 runtime.ReallyCrash = true168 // TCP setup.169 tcp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {170 w.WriteHeader(http.StatusOK)171 w.Write([]byte(r.URL.Path[1:]))172 }))173 defer tcp.Close()174 u, err := url.Parse(tcp.URL)175 if err != nil {176 panic(fmt.Sprintf("failed to parse: %v", err))177 }178 _, port, err := net.SplitHostPort(u.Host)179 if err != nil {180 panic(fmt.Sprintf("failed to parse: %v", err))181 }182 tcpServerPortValue, err := strconv.Atoi(port)183 if err != nil {184 panic(fmt.Sprintf("failed to atoi(%s): %v", port, err))185 }186 tcpServerPort = int32(tcpServerPortValue)187 // UDP setup.188 udp, err := newUDPEchoServer()189 if err != nil {190 panic(fmt.Sprintf("failed to make a UDP server: %v", err))191 }192 _, port, err = net.SplitHostPort(udp.LocalAddr().String())193 if err != nil {194 panic(fmt.Sprintf("failed to parse: %v", err))195 }196 udpServerPortValue, err := strconv.Atoi(port)197 if err != nil {198 panic(fmt.Sprintf("failed to atoi(%s): %v", port, err))199 }200 udpServerPort = int32(udpServerPortValue)201 go udp.Loop()202 ret := m.Run()203 // it should be safe to call Close() multiple times.204 tcp.Close()205 os.Exit(ret)206}207func testEchoTCP(t *testing.T, address string, port int) {208 path := "aaaaa"209 res, err := http.Get("http://" + address + ":" + fmt.Sprintf("%d", port) + "/" + path)210 if err != nil {211 t.Fatalf("error connecting to server: %v", err)212 }213 defer res.Body.Close()214 data, err := ioutil.ReadAll(res.Body)215 if err != nil {216 t.Errorf("error reading data: %v %v", err, string(data))217 }218 if string(data) != path {219 t.Errorf("expected: %s, got %s", path, string(data))220 }221}222func testEchoUDP(t *testing.T, address string, port int) {223 data := "abc123"224 conn, err := net.Dial("udp", joinHostPort(address, port))225 if err != nil {226 t.Fatalf("error connecting to server: %v", err)227 }228 if _, err := conn.Write([]byte(data)); err != nil {229 t.Fatalf("error sending to server: %v", err)230 }231 var resp [1024]byte232 n, err := conn.Read(resp[0:])233 if err != nil {234 t.Errorf("error receiving data: %v", err)235 }236 if string(resp[0:n]) != data {237 t.Errorf("expected: %s, got %s", data, string(resp[0:n]))238 }239}240func waitForNumProxyClients(t *testing.T, s *ServiceInfo, want int, timeout time.Duration) {241 var got int242 now := time.Now()243 deadline := now.Add(timeout)244 for time.Now().Before(deadline) {245 s.ActiveClients.Mu.Lock()246 got = len(s.ActiveClients.Clients)247 s.ActiveClients.Mu.Unlock()248 if got == want {249 return250 }251 time.Sleep(500 * time.Millisecond)252 }253 t.Errorf("expected %d ProxyClients live, got %d", want, got)254}255func startProxier(p *Proxier, t *testing.T) {256 go func() {257 p.SyncLoop()258 }()259 p.OnServiceSynced()260 p.OnEndpointsSynced()261}262func newServiceObject(namespace, name, clusterIP string, ports []v1.ServicePort) (*v1.Service, []proxy.ServicePortName) {263 service := &v1.Service{264 ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name},265 Spec: v1.ServiceSpec{266 ClusterIP: clusterIP,267 Ports: ports,268 },269 }270 servicePorts := make([]proxy.ServicePortName, len(ports))271 for i, port := range ports {272 servicePorts[i] = proxy.ServicePortName{273 NamespacedName: types.NamespacedName{274 Namespace: namespace,275 Name: name,276 },277 Port: port.Name,278 }279 }280 return service, servicePorts281}282func TestTCPProxy(t *testing.T) {283 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 80, Protocol: "TCP"}})284 lb := NewLoadBalancerRR()285 lb.OnEndpointsAdd(&v1.Endpoints{286 ObjectMeta: service.ObjectMeta,287 Subsets: []v1.EndpointSubset{{288 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},289 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: tcpServerPort}},290 }},291 })292 fexec := makeFakeExec()293 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)294 if err != nil {295 t.Fatal(err)296 }297 startProxier(p, t)298 defer p.shutdown()299 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)300 testEchoTCP(t, "127.0.0.1", svcInfo.proxyPort)301}302func TestUDPProxy(t *testing.T) {303 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 80, Protocol: "UDP"}})304 lb := NewLoadBalancerRR()305 lb.OnEndpointsAdd(&v1.Endpoints{306 ObjectMeta: service.ObjectMeta,307 Subsets: []v1.EndpointSubset{{308 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},309 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: udpServerPort}},310 }},311 })312 fexec := makeFakeExec()313 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)314 if err != nil {315 t.Fatal(err)316 }317 startProxier(p, t)318 defer p.shutdown()319 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)320 testEchoUDP(t, "127.0.0.1", svcInfo.proxyPort)321}322func TestUDPProxyTimeout(t *testing.T) {323 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 80, Protocol: "UDP"}})324 lb := NewLoadBalancerRR()325 lb.OnEndpointsAdd(&v1.Endpoints{326 ObjectMeta: service.ObjectMeta,327 Subsets: []v1.EndpointSubset{{328 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},329 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: udpServerPort}},330 }},331 })332 fexec := makeFakeExec()333 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)334 if err != nil {335 t.Fatal(err)336 }337 startProxier(p, t)338 defer p.shutdown()339 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)340 testEchoUDP(t, "127.0.0.1", svcInfo.proxyPort)341 // When connecting to a UDP service endpoint, there should be a Conn for proxy.342 waitForNumProxyClients(t, svcInfo, 1, time.Second)343 // If conn has no activity for serviceInfo.timeout since last Read/Write, it should be closed because of timeout.344 waitForNumProxyClients(t, svcInfo, 0, 2*time.Second)345}346func TestMultiPortProxy(t *testing.T) {347 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{348 {Name: "p", Port: 80, Protocol: "TCP"},349 {Name: "q", Port: 80, Protocol: "UDP"},350 })351 lb := NewLoadBalancerRR()352 lb.OnEndpointsAdd(&v1.Endpoints{353 ObjectMeta: service.ObjectMeta,354 Subsets: []v1.EndpointSubset{{355 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},356 Ports: []v1.EndpointPort{{Name: ports[0].Port, Protocol: service.Spec.Ports[0].Protocol, Port: tcpServerPort}},357 }},358 })359 lb.OnEndpointsAdd(&v1.Endpoints{360 ObjectMeta: service.ObjectMeta,361 Subsets: []v1.EndpointSubset{{362 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},363 Ports: []v1.EndpointPort{{Name: ports[1].Port, Protocol: service.Spec.Ports[1].Protocol, Port: udpServerPort}},364 }},365 })366 fexec := makeFakeExec()367 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)368 if err != nil {369 t.Fatal(err)370 }371 startProxier(p, t)372 defer p.shutdown()373 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)374 testEchoTCP(t, "127.0.0.1", svcInfo.proxyPort)375 svcInfo = waitForServiceInfo(t, p, ports[1], service)376 testEchoUDP(t, "127.0.0.1", svcInfo.proxyPort)377}378func TestMultiPortOnServiceAdd(t *testing.T) {379 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{380 {Name: "p", Port: 80, Protocol: "TCP"},381 {Name: "q", Port: 81, Protocol: "UDP"},382 })383 lb := NewLoadBalancerRR()384 fexec := makeFakeExec()385 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)386 if err != nil {387 t.Fatal(err)388 }389 startProxier(p, t)390 defer p.shutdown()391 // ports p and q should exist392 _ = addServiceAndWaitForInfo(t, p, ports[0], service)393 _ = waitForServiceInfo(t, p, ports[1], service)394 // non-existent port x should not exist395 serviceX := proxy.ServicePortName{NamespacedName: ports[0].NamespacedName, Port: "x"}396 svcInfo, exists := p.getServiceInfo(serviceX)397 if exists {398 t.Fatalf("found unwanted serviceInfo for %s: %#v", serviceX, svcInfo)399 }400}401func TestTCPProxyStop(t *testing.T) {402 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 80, Protocol: "TCP"}})403 lb := NewLoadBalancerRR()404 lb.OnEndpointsAdd(&v1.Endpoints{405 ObjectMeta: service.ObjectMeta,406 Subsets: []v1.EndpointSubset{{407 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},408 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: tcpServerPort}},409 }},410 })411 fexec := makeFakeExec()412 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)413 if err != nil {414 t.Fatal(err)415 }416 startProxier(p, t)417 defer p.shutdown()418 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)419 conn, err := net.Dial("tcp", joinHostPort("", svcInfo.proxyPort))420 if err != nil {421 t.Fatalf("error connecting to proxy: %v", err)422 }423 conn.Close()424 // Wait for the port to really close.425 deleteServiceAndWait(t, p, svcInfo, service, waitForClosedPortTCP)426}427func TestUDPProxyStop(t *testing.T) {428 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 80, Protocol: "UDP"}})429 lb := NewLoadBalancerRR()430 lb.OnEndpointsAdd(&v1.Endpoints{431 ObjectMeta: service.ObjectMeta,432 Subsets: []v1.EndpointSubset{{433 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},434 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: udpServerPort}},435 }},436 })437 fexec := makeFakeExec()438 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)439 if err != nil {440 t.Fatal(err)441 }442 startProxier(p, t)443 defer p.shutdown()444 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)445 conn, err := net.Dial("udp", joinHostPort("", svcInfo.proxyPort))446 if err != nil {447 t.Fatalf("error connecting to proxy: %v", err)448 }449 conn.Close()450 // Wait for the port to really close.451 deleteServiceAndWait(t, p, svcInfo, service, waitForClosedPortUDP)452}453func TestTCPProxyUpdateDelete(t *testing.T) {454 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 9997, Protocol: "TCP"}})455 lb := NewLoadBalancerRR()456 lb.OnEndpointsAdd(&v1.Endpoints{457 ObjectMeta: service.ObjectMeta,458 Subsets: []v1.EndpointSubset{{459 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},460 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: tcpServerPort}},461 }},462 })463 fexec := makeFakeExec()464 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)465 if err != nil {466 t.Fatal(err)467 }468 startProxier(p, t)469 defer p.shutdown()470 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)471 conn, err := net.Dial("tcp", joinHostPort("", svcInfo.proxyPort))472 if err != nil {473 t.Fatalf("error connecting to proxy: %v", err)474 }475 conn.Close()476 // Wait for the port to really close.477 deleteServiceAndWait(t, p, svcInfo, service, waitForClosedPortTCP)478}479func TestUDPProxyUpdateDelete(t *testing.T) {480 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 9997, Protocol: "UDP"}})481 lb := NewLoadBalancerRR()482 lb.OnEndpointsAdd(&v1.Endpoints{483 ObjectMeta: service.ObjectMeta,484 Subsets: []v1.EndpointSubset{{485 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},486 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: udpServerPort}},487 }},488 })489 fexec := makeFakeExec()490 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)491 if err != nil {492 t.Fatal(err)493 }494 startProxier(p, t)495 defer p.shutdown()496 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)497 conn, err := net.Dial("udp", joinHostPort("", svcInfo.proxyPort))498 if err != nil {499 t.Fatalf("error connecting to proxy: %v", err)500 }501 conn.Close()502 // Wait for the port to really close.503 deleteServiceAndWait(t, p, svcInfo, service, waitForClosedPortUDP)504}505func TestTCPProxyUpdateDeleteUpdate(t *testing.T) {506 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 9997, Protocol: "TCP"}})507 lb := NewLoadBalancerRR()508 endpoint := &v1.Endpoints{509 ObjectMeta: service.ObjectMeta,510 Subsets: []v1.EndpointSubset{{511 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},512 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: tcpServerPort}},513 }},514 }515 lb.OnEndpointsAdd(endpoint)516 fexec := makeFakeExec()517 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)518 if err != nil {519 t.Fatal(err)520 }521 startProxier(p, t)522 defer p.shutdown()523 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)524 conn, err := net.Dial("tcp", joinHostPort("", svcInfo.proxyPort))525 if err != nil {526 t.Fatalf("error connecting to proxy: %v", err)527 }528 conn.Close()529 // Wait for the port to really close.530 deleteServiceAndWait(t, p, svcInfo, service, waitForClosedPortTCP)531 // need to add endpoint here because it got clean up during service delete532 lb.OnEndpointsAdd(endpoint)533 svcInfo = addServiceAndWaitForInfo(t, p, ports[0], service)534 testEchoTCP(t, "127.0.0.1", svcInfo.proxyPort)535}536func TestUDPProxyUpdateDeleteUpdate(t *testing.T) {537 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 9997, Protocol: "UDP"}})538 lb := NewLoadBalancerRR()539 endpoint := &v1.Endpoints{540 ObjectMeta: service.ObjectMeta,541 Subsets: []v1.EndpointSubset{{542 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},543 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: udpServerPort}},544 }},545 }546 lb.OnEndpointsAdd(endpoint)547 fexec := makeFakeExec()548 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)549 if err != nil {550 t.Fatal(err)551 }552 startProxier(p, t)553 defer p.shutdown()554 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)555 conn, err := net.Dial("udp", joinHostPort("", svcInfo.proxyPort))556 if err != nil {557 t.Fatalf("error connecting to proxy: %v", err)558 }559 conn.Close()560 // Wait for the port to really close.561 deleteServiceAndWait(t, p, svcInfo, service, waitForClosedPortUDP)562 // need to add endpoint here because it got clean up during service delete563 lb.OnEndpointsAdd(endpoint)564 svcInfo = addServiceAndWaitForInfo(t, p, ports[0], service)565 testEchoUDP(t, "127.0.0.1", svcInfo.proxyPort)566}567func TestTCPProxyUpdatePort(t *testing.T) {568 origPort := int32(99)569 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: origPort, Protocol: "TCP"}})570 lb := NewLoadBalancerRR()571 lb.OnEndpointsAdd(&v1.Endpoints{572 ObjectMeta: service.ObjectMeta,573 Subsets: []v1.EndpointSubset{{574 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},575 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: tcpServerPort}},576 }},577 })578 fexec := makeFakeExec()579 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)580 if err != nil {581 t.Fatal(err)582 }583 startProxier(p, t)584 defer p.shutdown()585 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)586 testEchoTCP(t, "127.0.0.1", svcInfo.proxyPort)587 newService := service.DeepCopy()588 newService.Spec.Ports[0].Port = 100589 p.OnServiceUpdate(service, newService)590 // Wait for the socket to actually get free.591 if err := waitForClosedPortTCP(p, int(origPort)); err != nil {592 t.Fatalf(err.Error())593 }594 waitForProxyFinished(t, svcInfo)595 svcInfo = waitForServiceInfo(t, p, ports[0], newService)596 testEchoTCP(t, "127.0.0.1", svcInfo.proxyPort)597}598func TestUDPProxyUpdatePort(t *testing.T) {599 origPort := int32(99)600 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: origPort, Protocol: "UDP"}})601 lb := NewLoadBalancerRR()602 lb.OnEndpointsAdd(&v1.Endpoints{603 ObjectMeta: service.ObjectMeta,604 Subsets: []v1.EndpointSubset{{605 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},606 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: udpServerPort}},607 }},608 })609 fexec := makeFakeExec()610 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)611 if err != nil {612 t.Fatal(err)613 }614 startProxier(p, t)615 defer p.shutdown()616 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)617 testEchoUDP(t, "127.0.0.1", svcInfo.proxyPort)618 newService := service.DeepCopy()619 newService.Spec.Ports[0].Port = 100620 p.OnServiceUpdate(service, newService)621 // Wait for the socket to actually get free.622 if err := waitForClosedPortUDP(p, int(origPort)); err != nil {623 t.Fatalf(err.Error())624 }625 waitForProxyFinished(t, svcInfo)626 svcInfo = waitForServiceInfo(t, p, ports[0], newService)627 testEchoUDP(t, "127.0.0.1", svcInfo.proxyPort)628}629func TestProxyUpdatePublicIPs(t *testing.T) {630 origPort := int32(9997)631 service, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: origPort, Protocol: "TCP"}})632 lb := NewLoadBalancerRR()633 lb.OnEndpointsAdd(&v1.Endpoints{634 ObjectMeta: service.ObjectMeta,635 Subsets: []v1.EndpointSubset{{636 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},637 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: tcpServerPort}},638 }},639 })640 fexec := makeFakeExec()641 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)642 if err != nil {643 t.Fatal(err)644 }645 startProxier(p, t)646 defer p.shutdown()647 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], service)648 testEchoTCP(t, "127.0.0.1", svcInfo.proxyPort)649 newService := service.DeepCopy()650 newService.Spec.ExternalIPs = []string{"4.3.2.1"}651 p.OnServiceUpdate(service, newService)652 // Wait for the socket to actually get free.653 if err := waitForClosedPortTCP(p, int(origPort)); err != nil {654 t.Fatalf(err.Error())655 }656 waitForProxyFinished(t, svcInfo)657 svcInfo = waitForServiceInfo(t, p, ports[0], newService)658 testEchoTCP(t, "127.0.0.1", svcInfo.proxyPort)659}660func TestProxyUpdatePortal(t *testing.T) {661 svcv0, ports := newServiceObject("testnamespace", "echo", "1.2.3.4", []v1.ServicePort{{Name: "p", Port: 9997, Protocol: "TCP"}})662 lb := NewLoadBalancerRR()663 endpoint := &v1.Endpoints{664 ObjectMeta: svcv0.ObjectMeta,665 Subsets: []v1.EndpointSubset{{666 Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}},667 Ports: []v1.EndpointPort{{Name: ports[0].Port, Port: tcpServerPort}},668 }},669 }670 lb.OnEndpointsAdd(endpoint)671 fexec := makeFakeExec()672 p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest, newProxySocket)673 if err != nil {674 t.Fatal(err)675 }676 startProxier(p, t)677 defer p.shutdown()678 svcInfo := addServiceAndWaitForInfo(t, p, ports[0], svcv0)679 testEchoTCP(t, "127.0.0.1", svcInfo.proxyPort)680 svcv1 := svcv0.DeepCopy()681 svcv1.Spec.ClusterIP = ""682 p.OnServiceUpdate(svcv0, svcv1)683 // Wait for the service to be removed because it had an empty ClusterIP684 var exists bool685 for i := 0; i < 50; i++ {686 _, exists = p.getServiceInfo(ports[0])687 if !exists {688 break689 }690 time.Sleep(50 * time.Millisecond)691 }692 if exists {693 t.Fatalf("service with empty ClusterIP should not be included in the proxy")694 }695 waitForProxyFinished(t, svcInfo)696 svcv2 := svcv0.DeepCopy()697 svcv2.Spec.ClusterIP = "None"698 p.OnServiceUpdate(svcv1, svcv2)699 _, exists = p.getServiceInfo(ports[0])700 if exists {701 t.Fatalf("service with 'None' as ClusterIP should not be included in the proxy")702 }703 // Set the ClusterIP again and make sure the proxy opens the port704 lb.OnEndpointsAdd(endpoint)705 p.OnServiceUpdate(svcv2, svcv0)706 svcInfo = waitForServiceInfo(t, p, ports[0], svcv0)707 testEchoTCP(t, "127.0.0.1", svcInfo.proxyPort)708}709type fakeRunner struct{}710// assert fakeAsyncRunner is a ProxyProvider711var _ asyncRunnerInterface = &fakeRunner{}712func (f fakeRunner) Run() {713}714func (f fakeRunner) Loop(stop <-chan struct{}) {715}716func TestOnServiceAddChangeMap(t *testing.T) {717 fexec := makeFakeExec()718 // Use long minSyncPeriod so we can test that immediate syncs work719 p, err := createProxier(NewLoadBalancerRR(), net.ParseIP("0.0.0.0"), ipttest.NewFake(), fexec, net.ParseIP("127.0.0.1"), nil, time.Minute, time.Minute, udpIdleTimeoutForTest, newProxySocket)720 if err != nil {721 t.Fatal(err)722 }723 // Fake out sync runner724 p.syncRunner = fakeRunner{}725 serviceMeta := metav1.ObjectMeta{Namespace: "testnamespace", Name: "testname"}726 service := &v1.Service{727 ObjectMeta: serviceMeta,728 Spec: v1.ServiceSpec{ClusterIP: "1.2.3.4", Ports: []v1.ServicePort{{729 Name: "p",730 Port: 99,731 Protocol: "TCP",732 }}},733 }734 serviceUpdate := &v1.Service{735 ObjectMeta: serviceMeta,736 Spec: v1.ServiceSpec{ClusterIP: "1.2.3.5", Ports: []v1.ServicePort{{737 Name: "p",738 Port: 100,739 Protocol: "TCP",740 }}},741 }742 serviceUpdate2 := &v1.Service{743 ObjectMeta: serviceMeta,744 Spec: v1.ServiceSpec{ClusterIP: "1.2.3.6", Ports: []v1.ServicePort{{745 Name: "p",746 Port: 101,747 Protocol: "TCP",748 }}},749 }750 type onServiceTest struct {751 detail string752 changes []serviceChange753 expectedChange *serviceChange754 }755 tests := []onServiceTest{756 {757 detail: "add",758 changes: []serviceChange{...

Full Screen

Full Screen

freeport_test.go

Source:freeport_test.go Github

copy

Full Screen

...117 }()118 // --------------------119 // OK: sequence it so that one Take must wait on another Take to Return.120 func() {121 mostPorts, err := Take(numTotal - 5)122 if err != nil {123 t.Fatalf("err: %v", err)124 }125 type reply struct {126 ports []int127 err error128 }129 ch := make(chan reply, 1)130 go func() {131 ports, err := Take(10)132 ch <- reply{ports: ports, err: err}133 }()134 Return(mostPorts)135 r := <-ch136 if r.err != nil {137 t.Fatalf("err: %v", r.err)138 }139 defer Return(r.ports)140 if len(r.ports) != 10 {141 t.Fatalf("expected %d ports but got %d", 10, len(r.ports))142 }143 }()144 // Reset145 numTotal = waitForStatsReset()146 // --------------------147 // ERROR: Now we end on the crazy "Ocean's 11" level port theft where we148 // orchestrate a situation where all ports are stolen and we don't find out149 // until Take.150 func() {151 // 1. Grab all of the ports.152 allPorts := peekAllFree()153 // 2. Leak all of the ports154 leaked := make([]io.Closer, 0, len(allPorts))155 defer func() {156 for _, c := range leaked {157 c.Close()158 }159 }()160 for i, port := range allPorts {161 ln, err := net.ListenTCP("tcp", tcpAddr("127.0.0.1", port))162 if err != nil {163 t.Fatalf("%d err: %v", i, err)164 }165 leaked = append(leaked, ln)166 }167 // 3. Request 1 port which will detect the leaked ports and fail.168 _, err := Take(1)169 expectError("freeport: impossible to satisfy request; there are no actual free ports in the block anymore", err)170 // 4. Wait for the block to zero out.171 newNumTotal := waitForStatsReset()172 if newNumTotal != 0 {173 t.Fatalf("expected total to drop to %d but got %d", 0, newNumTotal)174 }...

Full Screen

Full Screen

port.go

Source:port.go Github

copy

Full Screen

...52 } else {53 return p, wait.ErrWaitTimeout54 }55}56func (c *openstackCloud) ListPorts(opt ports.ListOptsBuilder) ([]ports.Port, error) {57 var p []ports.Port58 done, err := vfs.RetryWithBackoff(readBackoff, func() (bool, error) {59 allPages, err := ports.List(c.neutronClient, opt).AllPages()60 if err != nil {61 return false, fmt.Errorf("error listing ports: %v", err)62 }63 r, err := ports.ExtractPorts(allPages)64 if err != nil {65 return false, fmt.Errorf("error extracting ports from pages: %v", err)66 }67 p = r68 return true, nil69 })70 if err != nil {71 return p, err72 } else if done {73 return p, nil74 } else {75 return p, wait.ErrWaitTimeout76 }77}...

Full Screen

Full Screen

Ports

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c1 := make(chan string)4 c2 := make(chan string)5 go func() {6 time.Sleep(time.Second * 1)7 }()8 go func() {9 time.Sleep(time.Second * 2)10 }()11 for i := 0; i < 2; i++ {12 select {13 fmt.Println("received", msg1)14 fmt.Println("received", msg2)15 }16 }17}18import (19func main() {20 tick := time.Tick(100 * time.Millisecond)21 boom := time.After(500 * time.Millisecond)22 for {23 select {24 fmt.Println("tick.")25 fmt.Println("BOOM!")26 fmt.Println(" .")27 time.Sleep(50 * time.Millis

Full Screen

Full Screen

Ports

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 wg.Add(2)4 go func() {5 time.Sleep(1 * time.Second)6 fmt.Println("1st goroutine sleeping")7 wg.Done()8 }()9 go func() {10 time.Sleep(2 * time.Second)11 fmt.Println("2nd goroutine sleeping")12 wg.Done()13 }()14 fmt.Println("Waiting for goroutines to finish...")15 wg.Wait()16 fmt.Println("All goroutines finished.")17}18import (19func main() {20 wg.Add(2)21 go func() {22 time.Sleep(1 * time.Second)23 fmt.Println("1st goroutine sleeping")24 wg.Done()25 }()26 go func() {27 time.Sleep(2 * time.Second)28 fmt.Println("2nd goroutine sleeping")29 wg.Done()30 }()31 fmt.Println("Waiting for goroutines to finish...")32 wg.Wait()33 fmt.Println("All goroutines finished.")34}35import (36func main() {37 wg.Add(2)38 go func() {39 time.Sleep(1 * time.Second)40 fmt.Println("1st goroutine sleeping")41 wg.Done()42 }()43 go func() {44 time.Sleep(2 * time.Second)45 fmt.Println("2nd goroutine sleeping")46 wg.Done()47 }()48 fmt.Println("Waiting for goroutines to finish...")49 wg.Wait()50 fmt.Println("All goroutines finished.")51}52import (53func main() {54 wg.Add(2)55 go func() {56 time.Sleep(1 * time.Second)57 fmt.Println("1st goroutine sleeping")58 wg.Done()59 }()60 go func() {61 time.Sleep(2 * time.Second)62 fmt.Println("2nd goroutine

Full Screen

Full Screen

Ports

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ports := []string{"8000", "8001", "8002", "8003", "8004", "8005", "8006", "8007", "8008", "8009"}4 for _, port := range ports {5 go func(port string) {6 fmt.Println("Checking port", port)7 }(port)8 }9 time.Sleep(3 * time.Second)10}11import (12func main() {13 ports := []string{"8000", "8001", "8002", "8003", "8004", "8005", "8006", "8007", "8008", "8009"}14 for _, port := range ports {15 go func(port string) {16 fmt.Println("Checking port", port)17 }(port)18 }19 time.Sleep(3 * time.Second)20}21import

Full Screen

Full Screen

Ports

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("main() started")4 c1 := make(chan string)5 c2 := make(chan string)6 go func() {7 for {8 time.Sleep(time.Second * 2)9 }10 }()11 go func() {12 for {13 time.Sleep(time.Second * 3)14 }15 }()16 go func() {17 for {18 select {19 fmt.Println("Message", msg1)20 fmt.Println("Message", msg2)21 case <-time.After(time.Second):22 fmt.Println("timeout")23 }24 }25 }()26 fmt.Scanln(&input)27}

Full Screen

Full Screen

Ports

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 waitGroup.Add(2)4 go func() {5 defer waitGroup.Done()6 for count := 0; count < 3; count++ {7 for r := 'a'; r < 'a'+26; r++ {8 fmt.Printf("%c ", r)9 }10 fmt.Println()11 }12 }()13 go func() {14 defer waitGroup.Done()15 for count := 0; count < 3; count++ {16 for r := 'A'; r < 'A'+26; r++ {17 fmt.Printf("%c ", r)18 }19 fmt.Println()20 }21 }()22 waitGroup.Wait()23 fmt.Println("Terminating Program")24}25import (26func main() {27 waitGroup.Add(2)

Full Screen

Full Screen

Ports

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 w := wait.NewWait()4 w.Add(1)5 go func() {6 fmt.Println("Hello World")7 w.Done()8 }()9 w.Wait()10}11import (12func main() {13 w := wait.NewWait()14 w.Add(2)15 go func() {16 fmt.Println("Hello World")17 w.Done()18 }()19 go func() {20 fmt.Println("Hello World")21 w.Done()22 }()23 w.Wait()24}25import (26func main() {27 w := wait.NewWait()28 w.Add(3)29 go func() {30 fmt.Println("Hello World")31 w.Done()32 }()33 go func() {34 fmt.Println("Hello World")35 w.Done()36 }()37 go func() {38 fmt.Println("Hello World")39 w.Done()40 }()41 w.Wait()42}43import (44func main() {45 w := wait.NewWait()46 w.Add(4)47 go func() {48 fmt.Println("Hello World")49 w.Done()50 }()51 go func() {52 fmt.Println("Hello World")53 w.Done()54 }()55 go func() {56 fmt.Println("Hello World")57 w.Done()58 }()59 go func() {60 fmt.Println("Hello World")61 w.Done()62 }()63 w.Wait()64}65import (66func main() {67 w := wait.NewWait()68 w.Add(5)69 go func() {70 fmt.Println("Hello World")71 w.Done()72 }()73 go func() {

Full Screen

Full Screen

Ports

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 w := wait.New()4 p := port.New(8080, "tcp")5 w.Add(p)6 w.Start()7 time.Sleep(10 * time.Second)8 w.Stop()9 fmt.Println(w.Results())10}11import (12func main() {13 w := wait.New()14 p := port.New(8080, "tcp")15 w.Add(p)16 w.Start()17 time.Sleep(10 * time.Second)18 w.Stop()19 fmt.Println(w.Results())20}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful