cephfs: fix fetchIP to support more formats

Signed-off-by: Riya Singhal <rsinghal@redhat.com>
This commit is contained in:
Riya Singhal 2023-12-15 18:37:49 +05:30 committed by mergify[bot]
parent b25a02e0df
commit bee77f7fac
2 changed files with 24 additions and 5 deletions

View File

@ -22,6 +22,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"net" "net"
"regexp"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -210,11 +211,24 @@ func (ac *activeClient) fetchIP() (string, error) {
// example: "inst": "client.4305 172.21.9.34:0/422650892", // example: "inst": "client.4305 172.21.9.34:0/422650892",
// then returning value will be 172.21.9.34 // then returning value will be 172.21.9.34
clientInfo := ac.Inst clientInfo := ac.Inst
parts := strings.Fields(clientInfo)
if len(parts) >= 2 { // Attempt to extract the IP address using a regular expression
lastColonIndex := strings.LastIndex(parts[1], ":") // the regular expression aims to match either a complete IPv6
firstPart := parts[1][:lastColonIndex] // address or a complete IPv4 address follows by any prefix (v1 or v2)
ip := net.ParseIP(firstPart) // if exists
// (?:v[0-9]+:): this allows for an optional prefix starting with "v"
// followed by one or more digits and a colon.
// The ? outside the group makes the entire prefix section optional.
// (?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}: this allows to check for
// standard IPv6 address.
// |: Alternation operator to allow matching either the IPv6 pattern
// with a prefix or the IPv4 pattern.
// '(?:\d+\.){3}\d+: This part matches a standard IPv4 address.
re := regexp.MustCompile(`(?:v[0-9]+:)?([0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}|(?:\d+\.){3}\d+)`)
ipMatches := re.FindStringSubmatch(clientInfo)
if len(ipMatches) > 0 {
ip := net.ParseIP(ipMatches[1])
if ip != nil { if ip != nil {
return ip.String(), nil return ip.String(), nil
} }

View File

@ -73,6 +73,11 @@ func TestFetchIP(t *testing.T) {
expectedIP: "2001:db8:85a3::8a2e:370:7334", expectedIP: "2001:db8:85a3::8a2e:370:7334",
expectedErr: false, expectedErr: false,
}, },
{
clientInfo: "client.24152 v1:100.64.0.7:0/3658550259",
expectedIP: "100.64.0.7",
expectedErr: false,
},
{ {
clientInfo: "", clientInfo: "",
expectedIP: "", expectedIP: "",