github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/cmn/network.go (about)

     1  // Package cmn provides common constants, types, and utilities for AIS clients
     2  // and AIStore.
     3  /*
     4   * Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
     5   */
     6  package cmn
     7  
     8  import (
     9  	"fmt"
    10  	"net"
    11  	"strconv"
    12  	"time"
    13  
    14  	"github.com/NVIDIA/aistore/cmn/cos"
    15  )
    16  
    17  const (
    18  	NetPublic       = "PUBLIC"
    19  	NetIntraControl = "INTRA-CONTROL"
    20  	NetIntraData    = "INTRA-DATA"
    21  )
    22  
    23  // http.DefaultTransport has the following defaults:
    24  // - MaxIdleConns:          100,
    25  // - MaxIdleConnsPerHost :  2 (via DefaultMaxIdleConnsPerHost)
    26  // - IdleConnTimeout:       90 * time.Second,
    27  // - WriteBufferSize:       4KB
    28  // - ReadBufferSize:        4KB
    29  // Following are the constants we use by default:
    30  const (
    31  	DefaultMaxIdleConns        = 64
    32  	DefaultMaxIdleConnsPerHost = 16
    33  	DefaultIdleConnTimeout     = 8 * time.Second
    34  	DefaultWriteBufferSize     = 64 * cos.KiB
    35  	DefaultReadBufferSize      = 64 * cos.KiB
    36  	DefaultSendRecvBufferSize  = 128 * cos.KiB
    37  )
    38  
    39  var KnownNetworks = []string{NetPublic, NetIntraControl, NetIntraData}
    40  
    41  func NetworkIsKnown(net string) bool {
    42  	return net == NetPublic || net == NetIntraControl || net == NetIntraData
    43  }
    44  
    45  func ParsePort(p string) (int, error) {
    46  	port, err := strconv.Atoi(p)
    47  	if err != nil {
    48  		return 0, err
    49  	}
    50  
    51  	return ValidatePort(port)
    52  }
    53  
    54  func ValidatePort(port int) (int, error) {
    55  	if port <= 0 || port >= (1<<16) {
    56  		return 0, fmt.Errorf("port number (%d) should be between 1 and 65535", port)
    57  	}
    58  	return port, nil
    59  }
    60  
    61  func Host2IP(host string) (net.IP, error) {
    62  	ips, err := net.LookupIP(host)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  	for _, ip := range ips {
    67  		if ip.To4() != nil {
    68  			return ip, nil
    69  		}
    70  	}
    71  	return nil, fmt.Errorf("failed to locally resolve %q (have IPs %v)", host, ips)
    72  }
    73  
    74  func ParseHost2IP(host string) (net.IP, error) {
    75  	ip := net.ParseIP(host)
    76  	if ip != nil {
    77  		return ip, nil // is a parse-able IP addr
    78  	}
    79  	return Host2IP(host)
    80  }