Skip to content

Optimize calls to netstat by using /proc files #2826

Closed

Description

@dbwiddis

Coming from #2433:

I am curious if there has ever been any discussion about optimizing the Linux network metrics by utilizing the various /proc files rather than executing netstat and parsing its output? It looks like for the most part on Linux that netstat is parsing the /proc files itself and just reformatting it. The execution of netstat results in a noticeable latency in sampling these metrics that is not seem direct parsing of /proc files.

If it is just a matter of lack of contribution I would love to contribute in any way but don't want to tread on something that may be intentionally implemented in a particular way.

Originally posted by @jake-at-work in #2433

Activity

  1. added
    up for grabs
    performance
    on Feb 26, 2025
  2. rohan-coder02 commented on Mar 8, 2025

    @rohan-coder02
    Collaborator

    Hi @dbwiddis,

    Is it ok if I could present my analysis and code changes done to optimize calls to netstat by using /proc files?

    Below is my analysis and code changes.

    OSHI Existing Code Analysis:

    @Override
    public TcpStats getTCPv4Stats() {
        return NetStat.queryTcpStats("netstat -st4");
    }
    
    @Override
    public UdpStats getUDPv4Stats() {
        return NetStat.queryUdpStats("netstat -su4");
    }
    
    @Override
    public UdpStats getUDPv6Stats() {
        return NetStat.queryUdpStats("netstat -su6");
    }
    

    Linux /proc Analysis for Optimized Data Retrieval:

    • Instead of executing netstat, we directly read from the /proc filesystem, which provides the same information with lower latency
    • I have validated the outputs from various flavors of Linux such as Redhat, Amazon Linux 2, etc

    Sample Output of /proc/net/snmp (TCPv4 & UDPv4):

    cat /proc/net/snmp
    Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts InCsumErrors
    Tcp: 1 200 120000 -1 65229 30305 1 17865 1 2004091 2251354 1617 0 8815 0
    Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors InCsumErrors IgnoredMulti
    Udp: 249873 2 0 249940 0 0 0 0
    

    Sample Output of /proc/net/snmp6 (UDPv6):

    cat /proc/net/snmp6
    Udp6InDatagrams                 	0
    Udp6NoPorts                     	0
    Udp6InErrors                    	0
    Udp6OutDatagrams                	27155
    

    The above output of /proc/net/snmp6 is trimmed to consist of only variables that is stored in the class of UdpStats.
    Refer code in https://github.com/oshi/oshi/blob/master/oshi-core/src/main/java/oshi/software/os/InternetProtocolStats.java

    Key Observations:

    • TCP & UDPv4 statistics are in /proc/net/snmp.
    • UDPv6 statistics are in /proc/net/snmp6.
    • Parsing these files eliminates command dependency.

    Implemented Code Changes

    Added the following constants in oshi.util.platform.linux.ProcPath

    public static final String SNMP = NET + "/snmp";
    public static final String SNMP6 = NET + "/snmp6";
    

    In oshi.software.os.linux.LinuxInternetProtocolStats add the below code

    Optimized getTCPv4Stats(), getUDPv4Stats() and getUDPv6Stats() Implementation

    private final String TCP_COLON = "Tcp:";
    private final String UDP_COLON = "Udp:";
    
    public TcpStats getTCPv4Stats() {
        Map<String, Long> tcpData = new HashMap<>();
        Set<String> REQUIRED_TCP_VARIABLES = new HashSet<>(Arrays.asList(
                "CurrEstab", "ActiveOpens", "PassiveOpens", "AttemptFails",
                "EstabResets", "InSegs", "OutSegs", "RetransSegs", "InErrs", "OutRsts"
            ));
    
        try (BufferedReader reader = new BufferedReader(new FileReader(ProcPath.SNMP))) {
            String headerLine, valueLine;
            while ((headerLine = reader.readLine()) != null && (valueLine = reader.readLine()) != null) {
                if (headerLine.startsWith(TCP_COLON) && valueLine.startsWith(TCP_COLON)) {
                    String[] headers = headerLine.split("\\s+");
                    String[] values = valueLine.split("\\s+");
    
                    if (headers.length != values.length) {
                        LOG.warn("Mismatch in " + ProcPath.SNMP + " TCP headers and values");
                        continue;
                    }
    
                    // Store only required TCP stats
                    for (int i = 1; i < headers.length; i++) {
                        if (REQUIRED_TCP_VARIABLES.contains(headers[i])) {
                            tcpData.put(headers[i], Long.parseLong(values[i]));
                        }
                    }
                    break;
                }
            }
        } catch (IOException e) {
            LOG.error("Error reading " + ProcPath.SNMP + " for TCP stats", e);
        }
    
        // Construct and return TCPv4 statistics object
        return new TcpStats(
            tcpData.getOrDefault("CurrEstab", 0L),
            tcpData.getOrDefault("ActiveOpens", 0L),
            tcpData.getOrDefault("PassiveOpens", 0L),
            tcpData.getOrDefault("AttemptFails", 0L),
            tcpData.getOrDefault("EstabResets", 0L),
            tcpData.getOrDefault("OutSegs", 0L),
            tcpData.getOrDefault("InSegs", 0L),
            tcpData.getOrDefault("RetransSegs", 0L),
            tcpData.getOrDefault("InErrs", 0L),
            tcpData.getOrDefault("OutRsts", 0L)
        );
    }
    
    public UdpStats getUDPv4Stats() {
        Map<String, Long> udpData = new HashMap<>();
        Set<String> REQUIRED_UDP_VARIABLES = new HashSet<>(Arrays.asList(
                "OutDatagrams", "InDatagrams", "NoPorts", "InErrors"
            ));
    
        try (BufferedReader reader = new BufferedReader(new FileReader(ProcPath.SNMP))) {
            String headerLine, valueLine;
            while ((headerLine = reader.readLine()) != null && (valueLine = reader.readLine()) != null) {
                if (headerLine.startsWith(UDP_COLON) && valueLine.startsWith(UDP_COLON)) {
                    String[] headers = headerLine.split("\\s+");
                    String[] values = valueLine.split("\\s+");
                    
                    // Store only required UDP stats
                    for (int i = 1; i < headers.length; i++) {
                        if (REQUIRED_UDP_VARIABLES.contains(headers[i])) {
                            udpData.put(headers[i], Long.parseLong(values[i]));
                        }
                    }
                    break;
                }
            }
        } catch (IOException e) {
            LOG.error("Error reading " + ProcPath.SNMP + " for UDP stats", e);
        }
    
        // Construct and return UDPv4 statistics object
        return new UdpStats(
            udpData.getOrDefault("OutDatagrams", 0L),
            udpData.getOrDefault("InDatagrams", 0L),
            udpData.getOrDefault("NoPorts", 0L),
            udpData.getOrDefault("InErrors", 0L)
        );
    }
    
    public UdpStats getUDPv6Stats() {
        Map<String, Long> udp6Data = new HashMap<>();
        Set<String> REQUIRED_UDP6_VARIABLES = new HashSet<>(Arrays.asList(
                "Udp6OutDatagrams", "Udp6InDatagrams", "Udp6NoPorts", "Udp6InErrors"
            ));
    
        try (BufferedReader reader = new BufferedReader(new FileReader(ProcPath.SNMP6))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("\\s+");
    
                // Store only required UDP stats
                if (parts.length > 1 && REQUIRED_UDP6_VARIABLES.contains(parts[0])) {
                    udp6Data.put(parts[0], Long.parseLong(parts[1]));
                }
            }
        } catch (IOException e) {
            LOG.error("Error reading " + ProcPath.SNMP6 + " for UDPv6 stats", e);
        }
    
        // Construct and return UDPv6 statistics object
        return new UdpStats(
            udp6Data.getOrDefault("Udp6OutDatagrams", 0L),
            udp6Data.getOrDefault("Udp6InDatagrams", 0L),
            udp6Data.getOrDefault("Udp6NoPorts", 0L),
            udp6Data.getOrDefault("Udp6InErrors", 0L)
        );
    }
    

    Testing & Integration

    Build Verification:

    • mvn test executed successfully.
    • OSHI built without errors, generating oshi-core-6.7.1-SNAPSHOT.jar.

    Integration in Java Application:

    • Successfully loaded OSHI library.
    • Correctly retrieved and printed TCP/UDP statistics.

    Below is the simple Java App

    import oshi.software.os.InternetProtocolStats;
    import oshi.software.os.linux.LinuxInternetProtocolStats;
    
    public class Main {
    
    public static void main(String[] args) {
            testOSHI();
        }
    public static void testOSHI() {
            LinuxInternetProtocolStats linuxInternetProtocolStats = new LinuxInternetProtocolStats();
            // Get TCP and UDP statistics
            InternetProtocolStats.TcpStats tcpv4Stats = linuxInternetProtocolStats.getTCPv4Stats();
            InternetProtocolStats.UdpStats udpv4Stats = linuxInternetProtocolStats.getUDPv4Stats();
            InternetProtocolStats.UdpStats udpv6Stats = linuxInternetProtocolStats.getUDPv6Stats();
    
            // Print TCP stats
            System.out.println("TCP v4 Stats:");
            System.out.println("Connections Established: " + tcpv4Stats.getConnectionsEstablished());
            System.out.println("Connections Active: " + tcpv4Stats.getConnectionsActive());
            System.out.println("Connections Passive: " + tcpv4Stats.getConnectionsPassive());
            System.out.println("Segments Sent: " + tcpv4Stats.getSegmentsSent());
            System.out.println("Segments Received: " + tcpv4Stats.getSegmentsReceived());
            System.out.println("Segments Retransmitted: " + tcpv4Stats.getSegmentsRetransmitted());
    
            // Print UDP v4 stats
            System.out.println("\nUDP v4 Stats:");
            System.out.println("Datagrams Sent: " + udpv4Stats.getDatagramsSent());
            System.out.println("Datagrams Received: " + udpv4Stats.getDatagramsReceived());
            System.out.println("Datagrams No Port: " + udpv4Stats.getDatagramsNoPort());
            System.out.println("Datagrams Received Errors: " + udpv4Stats.getDatagramsReceivedErrors());
    
            // Print UDP v6 stats
            System.out.println("\nUDP v6 Stats:");
            System.out.println("Datagrams Sent: " + udpv6Stats.getDatagramsSent());
            System.out.println("Datagrams Received: " + udpv6Stats.getDatagramsReceived());
            System.out.println("Datagrams No Port: " + udpv6Stats.getDatagramsNoPort());
            System.out.println("Datagrams Received Errors: " + udpv6Stats.getDatagramsReceivedErrors());
        }
    }
    

    Sample Output:

    java -jar TestOSHI.jar
    
    TCP v4 Stats:
    Connections Established: 1
    Connections Active: 9123
    Connections Passive: 15
    Segments Sent: 250269
    Segments Received: 341830
    Segments Retransmitted: 290
    
    UDP v4 Stats:
    Datagrams Sent: 38795
    Datagrams Received: 38762
    Datagrams No Port: 16
    Datagrams Received Errors: 0
    
    UDP v6 Stats:
    Datagrams Sent: 0
    Datagrams Received: 0
    Datagrams No Port: 0
    Datagrams Received Errors: 0
    

    Please let me know if any queries/issues regarding the above.

  3. dbwiddis commented on Mar 8, 2025

    @dbwiddis
    MemberAuthor

    This looks great! Can you submit a PR with these changes?

    Only change I'd suggest is eliminating the duplication of the string constants (they are in both a HashSet and HashMap). You might consider using an enum (and thus EnumMap). See ParseUtil.stringToEnumMap() and various implementations using it: https://github.com/search?q=repo%3Aoshi%2Foshi%20stringtoenummap&type=code

  4. dbwiddis commented on Mar 8, 2025

    @dbwiddis
    MemberAuthor

    Also your BufferedReader code can be replaced by FileUtil.readAllBytes().

  5. rohan-coder02 commented on Mar 9, 2025

    @rohan-coder02
    Collaborator

    Hi @dbwiddis

    Thanks for your feedback.

    I've incorporated your suggestions and updated the code accordingly. The PR has been raised here: #2846.

    Please let me know if you have any questions or require further changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    performanceup for grabs

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions