trpc.group/trpc-go/trpc-go@v1.0.3/internal/reuseport/reuseport_linux.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  //go:build linux
    15  // +build linux
    16  
    17  package reuseport
    18  
    19  import (
    20  	"bufio"
    21  	"os"
    22  	"strconv"
    23  	"strings"
    24  	"syscall"
    25  )
    26  
    27  var reusePort = 0x0F
    28  var maxConnFileName = "/proc/sys/net/core/somaxconn"
    29  
    30  func maxListenerBacklog() int {
    31  	fd, err := os.Open(maxConnFileName)
    32  	if err != nil {
    33  		return syscall.SOMAXCONN
    34  	}
    35  	defer fd.Close()
    36  
    37  	rd := bufio.NewReader(fd)
    38  	line, err := rd.ReadString('\n')
    39  	if err != nil {
    40  		return syscall.SOMAXCONN
    41  	}
    42  
    43  	f := strings.Fields(line)
    44  	if len(f) < 1 {
    45  		return syscall.SOMAXCONN
    46  	}
    47  
    48  	n, err := strconv.Atoi(f[0])
    49  	return defaultBacklog(uint32(n), err)
    50  }
    51  
    52  func defaultBacklog(n uint32, err error) int {
    53  	if n == 0 || err != nil {
    54  		return syscall.SOMAXCONN
    55  	}
    56  
    57  	// Linux stores the backlog in a uint16.
    58  	// Truncate number to avoid wrapping.
    59  	// See issue 5030.
    60  	if n > 1<<16-1 {
    61  		n = 1<<16 - 1
    62  	}
    63  	return int(n)
    64  }