...

Source file src/k8s.io/kubernetes/test/images/agnhost/tcp-reset/tcp_reset.go

Documentation: k8s.io/kubernetes/test/images/agnhost/tcp-reset

     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  // A small utility to send RST on the TCP connection
    18  // Ref: https://gosamples.dev/connection-reset-by-peer/
    19  
    20  package tcpreset
    21  
    22  import (
    23  	"fmt"
    24  	"log"
    25  	"net"
    26  	"os"
    27  	"os/signal"
    28  	"syscall"
    29  
    30  	"github.com/spf13/cobra"
    31  )
    32  
    33  // CmdTCPReset is used by agnhost Cobra.
    34  var CmdTCPReset = &cobra.Command{
    35  	Use:   "tcp-reset",
    36  	Short: "Serves on a tcp port and RST the connections received",
    37  	Long:  `Serves on a tcp port and RST the connections received.`,
    38  	Args:  cobra.MaximumNArgs(0),
    39  	Run:   main,
    40  }
    41  
    42  var (
    43  	port int
    44  )
    45  
    46  func init() {
    47  	CmdTCPReset.Flags().IntVar(&port, "port", 8080, "Port number.")
    48  }
    49  
    50  func main(cmd *cobra.Command, args []string) {
    51  
    52  	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
    53  	if err != nil {
    54  		log.Fatalf("Error from net.Listen(): %s", err)
    55  	}
    56  	go func() {
    57  		for {
    58  			conn, err := listener.Accept()
    59  			if err != nil {
    60  				log.Fatalf("Error from Accept(): %s", err)
    61  			}
    62  			// if there are still data in the buffer to read
    63  			// and the connection is closed, it will send a RST.
    64  			buf := make([]byte, 1)
    65  			conn.Read(buf)
    66  			conn.Close()
    67  			log.Printf("TCP request from %s", conn.RemoteAddr().String())
    68  		}
    69  	}()
    70  
    71  	log.Printf("Serving on port %d.\n", port)
    72  	signals := make(chan os.Signal, 1)
    73  	signal.Notify(signals, syscall.SIGTERM)
    74  	sig := <-signals
    75  	log.Printf("Shutting down after receiving signal: %s.\n", sig)
    76  	log.Printf("Awaiting pod deletion.\n")
    77  
    78  }
    79  

View as plain text